@vistagenic/vista 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/bin/vista.js +79 -109
  2. package/dist/ai/embeddings.d.ts +11 -11
  3. package/dist/ai/embeddings.js +71 -71
  4. package/dist/ai/index.d.ts +10 -10
  5. package/dist/ai/index.js +26 -26
  6. package/dist/ai/providers/base.js +85 -85
  7. package/dist/ai/react/react-server.d.ts +1 -1
  8. package/dist/ai/react/react-server.js +17 -17
  9. package/dist/ai/react/use-agent.js +138 -138
  10. package/dist/auth/core.d.ts +140 -140
  11. package/dist/auth/core.js +165 -165
  12. package/dist/auth/index.d.ts +20 -20
  13. package/dist/auth/index.js +369 -369
  14. package/dist/auth/react-server.d.ts +1 -1
  15. package/dist/auth/react-server.js +10 -10
  16. package/dist/auth/react.d.ts +18 -18
  17. package/dist/auth/react.js +71 -71
  18. package/dist/bin/build-rsc-flashpack.js +6 -0
  19. package/dist/bin/build-rsc.js +555 -492
  20. package/dist/bin/build.js +365 -353
  21. package/dist/bin/generate.js +513 -510
  22. package/dist/bin/webpack.config.d.ts +3 -1
  23. package/dist/bin/webpack.config.js +7 -4
  24. package/dist/build/manifest.d.ts +169 -169
  25. package/dist/build/manifest.js +423 -423
  26. package/dist/build/rsc/client-manifest.d.ts +62 -62
  27. package/dist/build/rsc/client-manifest.js +295 -295
  28. package/dist/build/rsc/compiler.d.ts +3 -1
  29. package/dist/build/rsc/compiler.js +12 -7
  30. package/dist/build/rsc/native-scanner.d.ts +135 -135
  31. package/dist/build/rsc/native-scanner.js +203 -203
  32. package/dist/build/rsc/react-client-reference-manifest.d.ts +35 -28
  33. package/dist/build/rsc/react-client-reference-manifest.js +366 -240
  34. package/dist/build/standalone.js +260 -254
  35. package/dist/client/dynamic.react-server.d.ts +2 -2
  36. package/dist/client/dynamic.react-server.js +23 -23
  37. package/dist/client/link.js +1 -1
  38. package/dist/client/link.react-server.d.ts +2 -2
  39. package/dist/client/link.react-server.js +11 -11
  40. package/dist/client/navigation.js +2 -2
  41. package/dist/client/navigation.react-server.d.ts +1 -1
  42. package/dist/client/navigation.react-server.js +17 -17
  43. package/dist/client/router.react-server.d.ts +1 -1
  44. package/dist/client/router.react-server.js +17 -17
  45. package/dist/client/rsc-router.d.ts +1 -3
  46. package/dist/client/rsc-router.js +98 -45
  47. package/dist/client/rsc-router.react-server.d.ts +1 -1
  48. package/dist/client/rsc-router.react-server.js +17 -17
  49. package/dist/client/script.react-server.d.ts +2 -2
  50. package/dist/client/script.react-server.js +23 -23
  51. package/dist/config.d.ts +1 -1
  52. package/dist/config.js +1 -7
  53. package/dist/deploy/adapters/cloudflare.js +42 -41
  54. package/dist/deploy/adapters/docker.d.ts +1 -0
  55. package/dist/deploy/adapters/docker.js +5 -4
  56. package/dist/deploy/adapters/netlify.js +60 -27
  57. package/dist/deploy/adapters/vercel.js +80 -50
  58. package/dist/deploy/preflight.js +4 -3
  59. package/dist/deploy/runtime-pack.d.ts +11 -0
  60. package/dist/deploy/runtime-pack.js +300 -0
  61. package/dist/deploy/utils.d.ts +7 -1
  62. package/dist/deploy/utils.js +95 -3
  63. package/dist/flashpack/command.js +1 -0
  64. package/dist/flashpack/runtime.js +2 -1
  65. package/dist/image/get-img-props.js +21 -11
  66. package/dist/image/image-config.d.ts +2 -0
  67. package/dist/image/image-config.js +17 -0
  68. package/dist/image/index.d.ts +18 -3
  69. package/dist/image/index.js +1 -1
  70. package/dist/image/react-server.d.ts +1 -2
  71. package/dist/image/react-server.js +1 -1
  72. package/dist/index.d.ts +23 -23
  73. package/dist/index.js +61 -61
  74. package/dist/server/app-dir.d.ts +22 -0
  75. package/dist/server/app-dir.js +77 -0
  76. package/dist/server/app-router-runtime.d.ts +1 -0
  77. package/dist/server/app-router-runtime.js +34 -9
  78. package/dist/server/cookie-parse.d.ts +4 -4
  79. package/dist/server/cookie-parse.js +14 -14
  80. package/dist/server/engine.js +5 -5
  81. package/dist/server/hydration-chunks.d.ts +7 -0
  82. package/dist/server/hydration-chunks.js +49 -0
  83. package/dist/server/image-optimizer.js +2 -1
  84. package/dist/server/index.d.ts +109 -109
  85. package/dist/server/index.js +315 -315
  86. package/dist/server/middleware-runner.d.ts +125 -125
  87. package/dist/server/middleware-runner.js +607 -615
  88. package/dist/server/middleware-security.d.ts +36 -36
  89. package/dist/server/middleware-security.js +183 -183
  90. package/dist/server/module-compile-hook.js +706 -695
  91. package/dist/server/root-resolver.js +6 -5
  92. package/dist/server/rsc-engine-flashpack.d.ts +3 -1
  93. package/dist/server/rsc-engine-flashpack.js +12 -1
  94. package/dist/server/rsc-engine.d.ts +6 -1
  95. package/dist/server/rsc-engine.js +217 -280
  96. package/dist/server/rsc-upstream.js +900 -892
  97. package/dist/server/ssr-webpack-shim.d.ts +6 -0
  98. package/dist/server/ssr-webpack-shim.js +29 -0
  99. package/dist/server/static-generator.d.ts +2 -0
  100. package/dist/server/static-generator.js +33 -32
  101. package/dist/server/structure-validator.js +2 -1
  102. package/dist/server/structure-watch.js +2 -0
  103. package/dist/server/typed-api-runtime.js +639 -635
  104. package/dist/server/vista-import-map.js +134 -134
  105. package/dist/stack/index.d.ts +34 -34
  106. package/dist/stack/index.js +49 -49
  107. package/dist/stack/server/caller.d.ts +13 -13
  108. package/dist/stack/server/caller.js +42 -42
  109. package/dist/stack/server/executor.d.ts +40 -40
  110. package/dist/stack/server/executor.js +222 -222
  111. package/dist/stack/server/index.d.ts +11 -11
  112. package/dist/stack/server/index.js +24 -24
  113. package/dist/stack/server/procedure.d.ts +20 -20
  114. package/dist/stack/server/procedure.js +66 -66
  115. package/dist/stack/server/types.d.ts +113 -113
  116. package/dist/theme/react-server.d.ts +10 -10
  117. package/dist/theme/react-server.js +16 -16
  118. package/package.json +1 -1
@@ -1,892 +1,900 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const express_1 = __importDefault(require("express"));
7
- const fs_1 = __importDefault(require("fs"));
8
- const path_1 = __importDefault(require("path"));
9
- const react_1 = __importDefault(require("react"));
10
- const stream_1 = require("stream");
11
- const url_1 = require("url");
12
- const react_client_reference_manifest_1 = require("../build/rsc/react-client-reference-manifest");
13
- const root_resolver_1 = require("./root-resolver");
14
- const constants_1 = require("../constants");
15
- const module_compile_hook_1 = require("./module-compile-hook");
16
- const request_context_1 = require("./request-context");
17
- const runtime_actions_1 = require("./runtime-actions");
18
- const app_router_runtime_1 = require("./app-router-runtime");
19
- const fetch_policy_1 = require("./fetch-policy");
20
- const runtime_artifacts_1 = require("./runtime-artifacts");
21
- const config_1 = require("../config");
22
- const vista_import_map_1 = require("./vista-import-map");
23
- const project_alias_resolver_1 = require("./project-alias-resolver");
24
- // NOTE: RouteErrorBoundary and RouteSuspense are 'use client' components.
25
- // Under --conditions react-server, React.Component is not available, so we
26
- // must NOT import them at the top level. Instead we lazy-require them after
27
- // the client-load hook has been installed (which turns them into Flight
28
- // client references automatically).
29
- let _RouteErrorBoundary = null;
30
- let _RouteSuspense = null;
31
- function getRouteErrorBoundary() {
32
- if (!_RouteErrorBoundary) {
33
- _RouteErrorBoundary = require('../components/error-boundary').RouteErrorBoundary;
34
- }
35
- return _RouteErrorBoundary;
36
- }
37
- function getRouteSuspense() {
38
- if (!_RouteSuspense) {
39
- _RouteSuspense = require('../components/route-suspense').RouteSuspense;
40
- }
41
- return _RouteSuspense;
42
- }
43
- const CjsModule = require('module');
44
- // Support CSS imports on server runtime
45
- require.extensions['.css'] = (m, filename) => {
46
- if (filename.endsWith('.module.css')) {
47
- m.exports = {};
48
- }
49
- };
50
- let installedClientLoadHook = false;
51
- let originalCompile = null;
52
- let reactResolutionInstalled = false;
53
- let originalResolveFilename = null;
54
- const clientDirectiveCache = new Map();
55
- function resolveVistaInternalRequest(request) {
56
- return (0, vista_import_map_1.resolveVistaSourceRequest)(request, path_1.default.resolve(__dirname, '..'));
57
- }
58
- function parseCliArg(flag) {
59
- const index = process.argv.indexOf(flag);
60
- if (index === -1)
61
- return undefined;
62
- return process.argv[index + 1];
63
- }
64
- function resolvePort(defaultPort) {
65
- const raw = parseCliArg('--port') ?? process.env.RSC_UPSTREAM_PORT ?? String(defaultPort);
66
- const port = Number(raw);
67
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
68
- throw new Error(`Invalid upstream port: ${raw}`);
69
- }
70
- return port;
71
- }
72
- function resolveFromWorkspace(specifier, cwd) {
73
- const searchRoots = [
74
- cwd,
75
- path_1.default.resolve(cwd, '..'),
76
- path_1.default.resolve(cwd, '..', '..'),
77
- path_1.default.resolve(cwd, '..', '..', 'rsc'),
78
- path_1.default.resolve(cwd, '..', '..', '..'),
79
- path_1.default.resolve(cwd, '..', '..', '..', 'rsc'),
80
- ];
81
- for (const root of searchRoots) {
82
- try {
83
- return require.resolve(specifier, { paths: [root] });
84
- }
85
- catch {
86
- // continue
87
- }
88
- }
89
- return require.resolve(specifier);
90
- }
91
- function normalizeModulePath(filePath) {
92
- return filePath.replace(/\\/g, '/').toLowerCase();
93
- }
94
- function shouldInvalidateDevModule(modulePath, cwd) {
95
- const normalized = normalizeModulePath(modulePath);
96
- const rootPrefix = normalizeModulePath(`${cwd}${path_1.default.sep}`);
97
- if (!normalized.startsWith(rootPrefix))
98
- return false;
99
- if (normalized.includes('/node_modules/'))
100
- return false;
101
- if (normalized.includes(`/${constants_1.BUILD_DIR.toLowerCase()}/`))
102
- return false;
103
- return /\.(?:[cm]?[jt]sx?|json)$/i.test(normalized);
104
- }
105
- function clearProjectRequireCache(cwd) {
106
- for (const key of Object.keys(require.cache)) {
107
- if (!shouldInvalidateDevModule(key, cwd))
108
- continue;
109
- delete require.cache[key];
110
- clientDirectiveCache.delete(key);
111
- }
112
- }
113
- function setupTypeScriptRuntime(cwd) {
114
- try {
115
- const swcRegisterPath = resolveFromWorkspace('@swc-node/register/register', cwd);
116
- const typescriptPath = resolveFromWorkspace('typescript', cwd);
117
- const { register } = require(swcRegisterPath);
118
- const ts = require(typescriptPath);
119
- register({
120
- module: ts.ModuleKind.CommonJS,
121
- jsx: ts.JsxEmit.ReactJSX,
122
- moduleResolution: ts.ModuleResolutionKind.Node16,
123
- esModuleInterop: true,
124
- allowJs: true,
125
- });
126
- return;
127
- }
128
- catch {
129
- // fallback
130
- }
131
- try {
132
- const tsNodePath = resolveFromWorkspace('ts-node', cwd);
133
- require(tsNodePath).register({
134
- transpileOnly: true,
135
- compilerOptions: {
136
- module: 'commonjs',
137
- jsx: 'react-jsx',
138
- moduleResolution: 'node16',
139
- esModuleInterop: true,
140
- allowJs: true,
141
- },
142
- });
143
- return;
144
- }
145
- catch {
146
- // fallback
147
- }
148
- try {
149
- const tsxPath = resolveFromWorkspace('tsx/cjs', cwd);
150
- // tsx/cjs registers the TypeScript loader for require()
151
- require(tsxPath);
152
- return;
153
- }
154
- catch {
155
- throw new Error('No TypeScript compiler available for RSC upstream runtime. Install one of: @swc-node/register, ts-node, or tsx');
156
- }
157
- }
158
- function hasClientBoundaryDirective(source) {
159
- let trimmed = source;
160
- while (true) {
161
- trimmed = trimmed.trimStart();
162
- if (trimmed.startsWith('//')) {
163
- const newlineIndex = trimmed.indexOf('\n');
164
- trimmed = newlineIndex === -1 ? '' : trimmed.slice(newlineIndex + 1);
165
- continue;
166
- }
167
- if (trimmed.startsWith('/*')) {
168
- const commentEndIndex = trimmed.indexOf('*/');
169
- if (commentEndIndex === -1) {
170
- break;
171
- }
172
- trimmed = trimmed.slice(commentEndIndex + 2);
173
- continue;
174
- }
175
- break;
176
- }
177
- return trimmed.startsWith("'use client'") || trimmed.startsWith('"use client"');
178
- }
179
- function isClientBoundaryFile(filename, transpiledSource) {
180
- const cached = clientDirectiveCache.get(filename);
181
- if (cached !== undefined)
182
- return cached;
183
- let isClient = false;
184
- try {
185
- const originalSource = fs_1.default.readFileSync(filename, 'utf-8');
186
- isClient = hasClientBoundaryDirective(originalSource);
187
- }
188
- catch {
189
- isClient = hasClientBoundaryDirective(transpiledSource);
190
- }
191
- clientDirectiveCache.set(filename, isClient);
192
- return isClient;
193
- }
194
- function installSingleReactResolution(cwd) {
195
- if (reactResolutionInstalled)
196
- return;
197
- let reactPath;
198
- let reactDomPath;
199
- try {
200
- reactPath = require.resolve('react');
201
- reactDomPath = require.resolve('react-dom');
202
- }
203
- catch {
204
- return;
205
- }
206
- originalResolveFilename = CjsModule._resolveFilename;
207
- const projectAliasResolver = (0, project_alias_resolver_1.createProjectAliasResolver)(cwd, resolveFromWorkspace);
208
- CjsModule._resolveFilename = function (request, parent, isMain, options) {
209
- const vistaResolvedPath = resolveVistaInternalRequest(request);
210
- if (vistaResolvedPath)
211
- return vistaResolvedPath;
212
- const aliasResolvedPath = projectAliasResolver?.resolve(request);
213
- if (aliasResolvedPath) {
214
- return originalResolveFilename.call(this, aliasResolvedPath, parent, isMain, options);
215
- }
216
- if (request === 'react')
217
- return reactPath;
218
- if (request === 'react-dom')
219
- return reactDomPath;
220
- if (request.startsWith('react/')) {
221
- const subPath = request.slice('react/'.length);
222
- try {
223
- return require.resolve(`react/${subPath}`, { paths: [path_1.default.dirname(reactPath)] });
224
- }
225
- catch {
226
- // fall through
227
- }
228
- }
229
- if (request.startsWith('react-dom/')) {
230
- const subPath = request.slice('react-dom/'.length);
231
- try {
232
- return require.resolve(`react-dom/${subPath}`, { paths: [path_1.default.dirname(reactDomPath)] });
233
- }
234
- catch {
235
- // fall through
236
- }
237
- }
238
- return originalResolveFilename.call(this, request, parent, isMain, options);
239
- };
240
- reactResolutionInstalled = true;
241
- }
242
- function installClientLoadHook(cwd, createClientModuleProxy) {
243
- if (installedClientLoadHook)
244
- return;
245
- const cacheComponentsConfig = (0, config_1.resolveCacheComponentsConfig)((0, config_1.loadConfig)(cwd));
246
- (0, module_compile_hook_1.installModuleCompileHook)({
247
- cwd,
248
- createClientModuleProxy,
249
- cacheComponentsEnabled: cacheComponentsConfig.enabled,
250
- });
251
- installedClientLoadHook = true;
252
- }
253
- function matchPattern(pathname, pattern) {
254
- const patternParts = pattern.split('/').filter(Boolean);
255
- const pathParts = pathname.split('/').filter(Boolean);
256
- if (patternParts.length === 0 && pathParts.length === 0)
257
- return true;
258
- for (let i = 0; i < patternParts.length; i++) {
259
- const patternPart = patternParts[i];
260
- const pathPart = pathParts[i];
261
- // Optional catch-all: matches zero or more segments
262
- if (patternPart.endsWith('*?')) {
263
- return true;
264
- }
265
- // Required catch-all: matches one or more remaining segments
266
- if (patternPart.endsWith('*')) {
267
- return pathParts.length >= i + 1;
268
- }
269
- if (patternPart.startsWith(':')) {
270
- if (!pathPart)
271
- return false;
272
- continue;
273
- }
274
- if (patternPart !== pathPart)
275
- return false;
276
- }
277
- return patternParts.length === pathParts.length;
278
- }
279
- function matchRoute(pathname, routes) {
280
- const sorted = [...routes].sort((a, b) => {
281
- const aOptional = a.pattern.includes('*?');
282
- const bOptional = b.pattern.includes('*?');
283
- if (aOptional && !bOptional)
284
- return 1;
285
- if (!aOptional && bOptional)
286
- return -1;
287
- return b.pattern.split('/').length - a.pattern.split('/').length;
288
- });
289
- for (const route of sorted) {
290
- if (matchPattern(pathname, route.pattern))
291
- return route;
292
- }
293
- return null;
294
- }
295
- function extractParams(pathname, route) {
296
- const params = {};
297
- const patternParts = route.pattern.split('/').filter(Boolean);
298
- const pathParts = pathname.split('/').filter(Boolean);
299
- for (let i = 0; i < patternParts.length; i++) {
300
- const patternPart = patternParts[i];
301
- if (!patternPart.startsWith(':'))
302
- continue;
303
- const name = patternPart.slice(1).replace(/\*\??/, '');
304
- if (patternPart.endsWith('*?') || patternPart.endsWith('*')) {
305
- params[name] = pathParts.slice(i).join('/');
306
- }
307
- else {
308
- params[name] = pathParts[i] || '';
309
- }
310
- }
311
- return params;
312
- }
313
- async function createRenderableRouteModuleElement(modulePath, context, options = {}) {
314
- const { params, searchParams, req } = context;
315
- const RouteModule = require(modulePath);
316
- const RouteComponent = RouteModule.default;
317
- if (!RouteComponent) {
318
- throw new Error(`Route module does not export default component: ${modulePath}`);
319
- }
320
- if (options.evaluateMetadata && typeof RouteModule.generateMetadata === 'function') {
321
- await RouteModule.generateMetadata({ params, searchParams }, RouteModule.metadata ?? {});
322
- }
323
- const routeProps = typeof RouteModule.getServerProps === 'function'
324
- ? await RouteModule.getServerProps({ query: req.query, params, req })
325
- : {};
326
- const moduleStem = path_1.default.basename(modulePath).replace(/\.[jt]sx?$/, '');
327
- if (moduleStem === 'default' || moduleStem === 'not-found') {
328
- const eagerResult = await RouteComponent({
329
- ...routeProps,
330
- params,
331
- searchParams,
332
- });
333
- return react_1.default.isValidElement(eagerResult)
334
- ? eagerResult
335
- : react_1.default.createElement(react_1.default.Fragment, null, eagerResult);
336
- }
337
- return react_1.default.createElement(RouteComponent, {
338
- ...routeProps,
339
- params,
340
- searchParams,
341
- });
342
- }
343
- function applySegmentBoundaries(dir, element) {
344
- const loadingPath = (0, app_router_runtime_1.resolveConventionModule)(dir, 'loading');
345
- const errorPath = (0, app_router_runtime_1.resolveConventionModule)(dir, 'error');
346
- const loadingComponent = loadingPath
347
- ? (() => {
348
- try {
349
- return require(loadingPath).default;
350
- }
351
- catch {
352
- return undefined;
353
- }
354
- })()
355
- : undefined;
356
- const errorComponent = errorPath
357
- ? (() => {
358
- try {
359
- return require(errorPath).default;
360
- }
361
- catch {
362
- return undefined;
363
- }
364
- })()
365
- : undefined;
366
- let wrappedElement = element;
367
- if (loadingComponent) {
368
- wrappedElement = react_1.default.createElement(getRouteSuspense(), {
369
- loadingComponent,
370
- children: wrappedElement,
371
- });
372
- }
373
- if (errorComponent) {
374
- wrappedElement = react_1.default.createElement(getRouteErrorBoundary(), {
375
- fallbackComponent: errorComponent,
376
- children: wrappedElement,
377
- });
378
- }
379
- return wrappedElement;
380
- }
381
- async function renderAppSubtreeElement(input) {
382
- const appDir = path_1.default.join(input.cwd, 'app');
383
- let element = await createRenderableRouteModuleElement(input.entryFilePath, {
384
- params: input.params,
385
- searchParams: input.searchParams,
386
- req: input.req,
387
- }, {
388
- evaluateMetadata: input.evaluateLeafMetadata,
389
- });
390
- const directoryChain = (0, app_router_runtime_1.resolveDirectoryChain)(input.subtreeRootDir, input.entryFilePath);
391
- for (let i = directoryChain.length - 1; i >= 0; i--) {
392
- const dir = directoryChain[i];
393
- element = applySegmentBoundaries(dir, element);
394
- const layoutPath = (0, app_router_runtime_1.resolveConventionModule)(dir, 'root') ?? (0, app_router_runtime_1.resolveConventionModule)(dir, 'layout');
395
- if (!layoutPath || path_1.default.resolve(layoutPath) === path_1.default.resolve(input.entryFilePath)) {
396
- continue;
397
- }
398
- const LayoutModule = require(layoutPath);
399
- const LayoutComponent = LayoutModule.default;
400
- if (!LayoutComponent) {
401
- continue;
402
- }
403
- const slotProps = {};
404
- if (!input.disableParallelSlots) {
405
- const slotMatches = (0, app_router_runtime_1.resolveParallelSlotMatches)({
406
- appDir,
407
- layoutPath,
408
- pathname: input.pathname,
409
- });
410
- for (const slotMatch of slotMatches) {
411
- slotProps[slotMatch.slotName] = await renderAppSubtreeElement({
412
- subtreeRootDir: slotMatch.slotRootDir,
413
- entryFilePath: slotMatch.filePath,
414
- pathname: input.pathname,
415
- params: {
416
- ...input.params,
417
- ...slotMatch.params,
418
- },
419
- searchParams: input.searchParams,
420
- req: input.req,
421
- cwd: input.cwd,
422
- evaluateLeafMetadata: true,
423
- });
424
- }
425
- }
426
- element = react_1.default.createElement(LayoutComponent, {
427
- params: input.params,
428
- searchParams: input.searchParams,
429
- ...slotProps,
430
- }, element);
431
- }
432
- return element;
433
- }
434
- async function createRouteElement(route, context, isDev, runtimeRoot, options = {}) {
435
- const { pathname, params, searchParams, req } = context;
436
- if (isDev) {
437
- clearProjectRequireCache(runtimeRoot);
438
- }
439
- return renderAppSubtreeElement({
440
- subtreeRootDir: path_1.default.join(runtimeRoot, 'app'),
441
- entryFilePath: route.pagePath,
442
- pathname,
443
- params,
444
- searchParams,
445
- req,
446
- cwd: runtimeRoot,
447
- evaluateLeafMetadata: true,
448
- disableParallelSlots: options.disableParallelSlots,
449
- });
450
- }
451
- async function readRawRequestBody(req) {
452
- if (typeof req.body === 'string') {
453
- return Buffer.from(req.body);
454
- }
455
- if (Buffer.isBuffer(req.body)) {
456
- return req.body;
457
- }
458
- const chunks = [];
459
- for await (const chunk of req) {
460
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
461
- }
462
- return Buffer.concat(chunks);
463
- }
464
- async function parseMultipartFormData(req, rawBody) {
465
- const request = new Request(`http://127.0.0.1${req.originalUrl || req.url || '/'}`, {
466
- method: req.method || 'POST',
467
- headers: req.headers,
468
- body: rawBody,
469
- });
470
- return request.formData();
471
- }
472
- function getSearchParamsFromRequest(req) {
473
- return Object.fromEntries(new URLSearchParams(req.query).entries());
474
- }
475
- function loadFlightManifest(flightManifestPath) {
476
- const raw = JSON.parse(fs_1.default.readFileSync(flightManifestPath, 'utf-8'));
477
- return (0, react_client_reference_manifest_1.createGuardedReactClientManifest)((0, react_client_reference_manifest_1.normalizeReactClientReferenceManifest)(raw));
478
- }
479
- function startUpstream() {
480
- const cwd = path_1.default.resolve(process.env.VISTA_ARTIFACT_ROOT || process.cwd());
481
- const runtimeRoot = (0, runtime_artifacts_1.resolveRuntimeProjectRoot)(cwd, process.env.VISTA_RUNTIME_ROOT);
482
- const isDev = process.env.NODE_ENV !== 'production';
483
- const port = resolvePort(3101);
484
- const vistaDirRoot = path_1.default.join(cwd, constants_1.BUILD_DIR);
485
- installSingleReactResolution(runtimeRoot);
486
- setupTypeScriptRuntime(runtimeRoot);
487
- const flightServerPath = resolveFromWorkspace('react-server-dom-webpack/server.node', cwd);
488
- const flightServer = require(flightServerPath);
489
- installClientLoadHook(runtimeRoot, flightServer.createClientModuleProxy);
490
- (0, fetch_policy_1.installSegmentFetchPolicyShim)();
491
- const serverManifestPath = path_1.default.join(cwd, constants_1.BUILD_DIR, 'server', 'server-manifest.json');
492
- const flightManifestPath = path_1.default.join(cwd, constants_1.BUILD_DIR, 'react-client-manifest.json');
493
- if (!fs_1.default.existsSync(serverManifestPath)) {
494
- throw new Error('Missing RSC server manifest. Run "vista build" first.');
495
- }
496
- // In dev mode the flight manifest may not exist yet (webpack-dev-middleware
497
- // hasn't completed the first compilation). Write a stub so we can start,
498
- // and reload on each request.
499
- if (!fs_1.default.existsSync(flightManifestPath)) {
500
- if (isDev) {
501
- fs_1.default.writeFileSync(flightManifestPath, '{}');
502
- }
503
- else {
504
- throw new Error('Missing RSC flight manifest. Run "vista build" first.');
505
- }
506
- }
507
- let serverManifest = JSON.parse(fs_1.default.readFileSync(serverManifestPath, 'utf-8'));
508
- let flightManifest = loadFlightManifest(flightManifestPath);
509
- const app = (0, express_1.default)();
510
- const pipeFlightModel = async (res, model, status) => {
511
- let capturedError = null;
512
- let gateResolved = false;
513
- let streamEnded = false;
514
- const gateStream = new stream_1.PassThrough();
515
- const bufferedChunks = [];
516
- const finishGate = (() => {
517
- let resolver = null;
518
- const promise = new Promise((resolve) => {
519
- resolver = () => {
520
- if (gateResolved) {
521
- return;
522
- }
523
- gateResolved = true;
524
- resolve();
525
- };
526
- });
527
- return { promise, resolve: () => resolver?.() };
528
- })();
529
- const onData = (chunk) => {
530
- bufferedChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
531
- finishGate.resolve();
532
- };
533
- gateStream.on('data', onData);
534
- gateStream.once('end', () => {
535
- streamEnded = true;
536
- finishGate.resolve();
537
- });
538
- gateStream.once('error', () => {
539
- finishGate.resolve();
540
- });
541
- const stream = flightServer.renderToPipeableStream(model, flightManifest, {
542
- onError(error) {
543
- capturedError = error;
544
- if (error?.name !== 'NotFoundError') {
545
- console.error('[vista:rsc] Upstream flight render error:', error);
546
- }
547
- finishGate.resolve();
548
- },
549
- });
550
- stream.pipe(gateStream);
551
- const gateTimer = setTimeout(() => finishGate.resolve(), 75);
552
- await finishGate.promise;
553
- clearTimeout(gateTimer);
554
- if (capturedError?.name === 'NotFoundError') {
555
- gateStream.destroy();
556
- throw capturedError;
557
- }
558
- gateStream.off('data', onData);
559
- res.status(status);
560
- res.setHeader('Content-Type', 'text/x-component');
561
- res.setHeader('Vary', 'Accept');
562
- for (const chunk of bufferedChunks) {
563
- res.write(chunk);
564
- }
565
- if (streamEnded) {
566
- res.end();
567
- return;
568
- }
569
- gateStream.pipe(res);
570
- };
571
- const drainFlightModel = async (model) => {
572
- let capturedError = null;
573
- const sink = new stream_1.PassThrough();
574
- const completion = new Promise((resolve, reject) => {
575
- sink.on('data', () => { });
576
- sink.once('end', resolve);
577
- sink.once('error', reject);
578
- });
579
- const stream = flightServer.renderToPipeableStream(model, flightManifest, {
580
- onError(error) {
581
- if (!capturedError) {
582
- capturedError = error;
583
- }
584
- },
585
- });
586
- stream.pipe(sink);
587
- await completion;
588
- if (capturedError) {
589
- throw capturedError;
590
- }
591
- };
592
- const resolveActionModulePath = (actionId) => {
593
- const hashIdx = actionId.lastIndexOf('#');
594
- const modulePath = hashIdx >= 0 ? actionId.slice(0, hashIdx) : actionId;
595
- if (!modulePath.startsWith('file://')) {
596
- return modulePath;
597
- }
598
- try {
599
- return (0, url_1.fileURLToPath)(modulePath);
600
- }
601
- catch {
602
- let fallbackPath = modulePath.replace(/^file:\/\/\//, '').replace(/^file:\/\//, '');
603
- if (process.platform === 'win32' && /^[a-zA-Z]:/.test(fallbackPath) === false) {
604
- fallbackPath = '/' + fallbackPath;
605
- }
606
- return fallbackPath;
607
- }
608
- };
609
- const primeInlineActionRegistration = async (req, actionId) => {
610
- const actionEntry = serverManifest.serverActions?.[actionId];
611
- if (!actionEntry || actionEntry.kind !== 'inline') {
612
- return undefined;
613
- }
614
- const pathname = req.path.replace(/^\/(?:_rsc|rsc)/, '') || '/';
615
- const searchParams = getSearchParamsFromRequest(req);
616
- const actionRoute = matchRoute(pathname, serverManifest.routes) ||
617
- serverManifest.routes.find((candidate) => {
618
- const targetPath = path_1.default.resolve(actionEntry.filePath);
619
- return (path_1.default.resolve(candidate.pagePath) === targetPath ||
620
- candidate.layoutPaths.some((layoutPath) => path_1.default.resolve(layoutPath) === targetPath));
621
- }) ||
622
- null;
623
- const resolvedActionPath = path_1.default.resolve(actionEntry.filePath || resolveActionModulePath(actionId));
624
- const routeParams = actionRoute ? extractParams(pathname, actionRoute) : {};
625
- if (isDev) {
626
- try {
627
- delete require.cache[require.resolve(resolvedActionPath)];
628
- }
629
- catch {
630
- // ignore missing cache entries
631
- }
632
- }
633
- const actionModule = require(resolvedActionPath);
634
- if (typeof actionModule?.default === 'function') {
635
- const probeProps = {
636
- params: routeParams,
637
- searchParams,
638
- };
639
- if (actionRoute && path_1.default.resolve(actionRoute.pagePath) !== resolvedActionPath) {
640
- probeProps.children = null;
641
- }
642
- try {
643
- await actionModule.default(probeProps);
644
- }
645
- catch {
646
- // Some components require a fuller tree to evaluate. Fall through to route priming.
647
- }
648
- const directResolution = (0, runtime_actions_1.resolveRegisteredServerReference)(actionId);
649
- if (directResolution) {
650
- return directResolution;
651
- }
652
- }
653
- if (actionRoute) {
654
- const params = routeParams;
655
- const model = await createRouteElement(actionRoute, { pathname, params, searchParams, req }, isDev, runtimeRoot);
656
- await drainFlightModel(model);
657
- return (0, runtime_actions_1.resolveRegisteredServerReference)(actionId);
658
- }
659
- return undefined;
660
- };
661
- const handleRSCRequest = async (req, res) => {
662
- const pathname = req.path.replace(/^\/(?:_rsc|rsc)/, '') || '/';
663
- await (0, request_context_1.runWithRequestContext)({
664
- req,
665
- res,
666
- cwd: runtimeRoot,
667
- vistaDirRoot,
668
- urlPath: pathname,
669
- }, async () => {
670
- try {
671
- // In dev mode, reload manifests from disk on each request so we
672
- // always pick up the latest output from ReactFlightWebpackPlugin.
673
- if (isDev) {
674
- try {
675
- serverManifest = JSON.parse(fs_1.default.readFileSync(serverManifestPath, 'utf-8'));
676
- flightManifest = loadFlightManifest(flightManifestPath);
677
- }
678
- catch {
679
- // Manifests may be mid-write; use whatever we have cached.
680
- }
681
- }
682
- const route = matchRoute(pathname, serverManifest.routes);
683
- (0, request_context_1.setCurrentSegmentConfig)(route?.segmentConfig);
684
- if (!route) {
685
- const rootLayout = (0, root_resolver_1.resolveRootLayout)(runtimeRoot, isDev);
686
- const resolvedNotFound = (0, root_resolver_1.resolveNotFoundComponent)(runtimeRoot, rootLayout, isDev);
687
- let model;
688
- if (resolvedNotFound) {
689
- const notFoundElement = react_1.default.createElement(resolvedNotFound.component, {
690
- params: {},
691
- searchParams: {},
692
- });
693
- model = react_1.default.createElement(rootLayout.component, { params: {}, searchParams: {} }, notFoundElement);
694
- }
695
- else {
696
- model = react_1.default.createElement('div', {
697
- style: {
698
- display: 'flex',
699
- flexDirection: 'column',
700
- alignItems: 'center',
701
- justifyContent: 'center',
702
- height: '100vh',
703
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
704
- background: '#0a0a0a',
705
- color: '#ededed',
706
- margin: 0,
707
- overflow: 'hidden',
708
- textAlign: 'center',
709
- userSelect: 'none',
710
- },
711
- }, react_1.default.createElement('span', {
712
- style: {
713
- fontSize: '6rem',
714
- fontWeight: 800,
715
- letterSpacing: '-0.04em',
716
- lineHeight: 1,
717
- background: 'linear-gradient(135deg, #7c3aed, #2563eb, #06b6d4)',
718
- WebkitBackgroundClip: 'text',
719
- WebkitTextFillColor: 'transparent',
720
- backgroundClip: 'text',
721
- },
722
- }, '404'), react_1.default.createElement('p', {
723
- style: {
724
- marginTop: '0.75rem',
725
- fontSize: '0.95rem',
726
- fontWeight: 400,
727
- color: '#555',
728
- letterSpacing: '0.02em',
729
- },
730
- }, "There's nothing here."));
731
- }
732
- await pipeFlightModel(res, model, 404);
733
- return;
734
- }
735
- const params = extractParams(pathname, route);
736
- const searchParams = getSearchParamsFromRequest(req);
737
- const element = await createRouteElement(route, { pathname, params, searchParams, req }, isDev, runtimeRoot);
738
- await pipeFlightModel(res, element, 200);
739
- }
740
- catch (error) {
741
- if (error?.name === 'NotFoundError') {
742
- try {
743
- const rootLayout = (0, root_resolver_1.resolveRootLayout)(runtimeRoot, isDev);
744
- const route = matchRoute(pathname, serverManifest.routes);
745
- (0, request_context_1.setCurrentSegmentConfig)(route?.segmentConfig);
746
- if (route) {
747
- const segmentNotFoundPath = (0, app_router_runtime_1.resolveNearestSegmentNotFoundPath)(path_1.default.join(runtimeRoot, 'app'), route.routeDir);
748
- if (segmentNotFoundPath) {
749
- const params = extractParams(pathname, route);
750
- const searchParams = getSearchParamsFromRequest(req);
751
- const model = await createRouteElement({
752
- ...route,
753
- pagePath: segmentNotFoundPath,
754
- }, { pathname, params, searchParams, req }, isDev, runtimeRoot, { disableParallelSlots: true });
755
- await pipeFlightModel(res, model, 404);
756
- return;
757
- }
758
- }
759
- const resolvedNotFound = (0, root_resolver_1.resolveNotFoundComponent)(runtimeRoot, rootLayout, isDev);
760
- let model;
761
- if (resolvedNotFound) {
762
- const notFoundElement = react_1.default.createElement(resolvedNotFound.component, {
763
- params: {},
764
- searchParams: {},
765
- });
766
- model = react_1.default.createElement(rootLayout.component, { params: {}, searchParams: {} }, notFoundElement);
767
- }
768
- else {
769
- model = react_1.default.createElement('h1', null, '404 - Page Not Found');
770
- }
771
- await pipeFlightModel(res, model, 404);
772
- return;
773
- }
774
- catch (notFoundError) {
775
- console.error('[vista:rsc] Failed to render NotFoundError fallback:', notFoundError);
776
- }
777
- }
778
- console.error('[vista:rsc] Upstream request failed:', error);
779
- res
780
- .status(500)
781
- .type('text/plain')
782
- .send(error.message);
783
- }
784
- });
785
- };
786
- app.get('/rsc*', handleRSCRequest);
787
- app.get('/_rsc*', handleRSCRequest);
788
- // -----------------------------------------------------------------------
789
- // Server Actions — POST handler
790
- // -----------------------------------------------------------------------
791
- app.use(express_1.default.text({ type: 'text/plain', limit: '10mb' }));
792
- const handleServerAction = async (req, res) => {
793
- const pathname = req.path.replace(/^\/(?:_rsc|rsc)/, '') || '/';
794
- await (0, request_context_1.runWithRequestContext)({
795
- req,
796
- res,
797
- cwd: runtimeRoot,
798
- vistaDirRoot,
799
- urlPath: pathname,
800
- }, async () => {
801
- try {
802
- const actionId = req.headers['rsc-action'];
803
- if (!actionId) {
804
- res.status(400).type('text/plain').send('Missing rsc-action header');
805
- return;
806
- }
807
- if (isDev) {
808
- try {
809
- serverManifest = JSON.parse(fs_1.default.readFileSync(serverManifestPath, 'utf-8'));
810
- flightManifest = loadFlightManifest(flightManifestPath);
811
- }
812
- catch {
813
- // Keep cached manifests if they're being rewritten.
814
- }
815
- }
816
- (0, request_context_1.setCurrentSegmentConfig)(matchRoute(pathname, serverManifest.routes)?.segmentConfig);
817
- let actionFn = (0, runtime_actions_1.resolveRegisteredServerReference)(actionId);
818
- if (!actionFn) {
819
- actionFn = await primeInlineActionRegistration(req, actionId);
820
- }
821
- if (!actionFn) {
822
- const hashIdx = actionId.lastIndexOf('#');
823
- const exportName = hashIdx >= 0 ? actionId.slice(hashIdx + 1) : 'default';
824
- const resolvedPath = resolveActionModulePath(actionId);
825
- if (isDev) {
826
- try {
827
- delete require.cache[require.resolve(resolvedPath)];
828
- }
829
- catch {
830
- // ignore missing cache entries
831
- }
832
- }
833
- const actionModule = require(resolvedPath);
834
- actionFn = actionModule[exportName];
835
- }
836
- if (typeof actionFn !== 'function') {
837
- res.status(404).type('text/plain').send(`Server action not found: ${actionId}`);
838
- return;
839
- }
840
- const rawBody = await readRawRequestBody(req);
841
- const contentType = String(req.headers['content-type'] || '');
842
- let result;
843
- if (contentType.includes('multipart/form-data')) {
844
- const formData = await parseMultipartFormData(req, rawBody);
845
- const boundAction = await flightServer.decodeAction(formData, flightManifest);
846
- result = await boundAction();
847
- }
848
- else {
849
- const args = (await flightServer.decodeReply(rawBody.toString('utf-8'), flightManifest));
850
- result = await actionFn(...(Array.isArray(args) ? args : [args]));
851
- }
852
- const revalidatedPaths = (0, request_context_1.consumeRevalidatedPaths)();
853
- if (revalidatedPaths.length > 0) {
854
- res.setHeader('x-vista-revalidated-paths', JSON.stringify(revalidatedPaths));
855
- }
856
- const revalidatedTags = (0, request_context_1.consumeRevalidatedTags)();
857
- if (revalidatedTags.length > 0) {
858
- res.setHeader('x-vista-revalidated-tags', JSON.stringify(revalidatedTags));
859
- }
860
- res.setHeader('Content-Type', 'text/x-component');
861
- const stream = flightServer.renderToPipeableStream(result, flightManifest, {
862
- onError(error) {
863
- console.error('[vista:rsc] Server action render error:', error);
864
- },
865
- });
866
- stream.pipe(res);
867
- }
868
- catch (error) {
869
- console.error('[vista:rsc] Server action failed:', error);
870
- res
871
- .status(500)
872
- .type('text/plain')
873
- .send(error.message);
874
- }
875
- });
876
- };
877
- app.post('/rsc*', handleServerAction);
878
- app.post('/_rsc*', handleServerAction);
879
- const server = app.listen(port, () => {
880
- console.log(`[vista:rsc:upstream] Listening on http://127.0.0.1:${port}/rsc`);
881
- });
882
- server.on('error', (error) => {
883
- if (error?.code === 'EADDRINUSE') {
884
- console.error(`[vista:server] Port ${port} is already in use.`);
885
- process.exit(1);
886
- return;
887
- }
888
- console.error('[vista:server] RSC upstream startup failed:', error);
889
- process.exit(1);
890
- });
891
- }
892
- startUpstream();
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const express_1 = __importDefault(require("express"));
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const react_1 = __importDefault(require("react"));
10
+ const stream_1 = require("stream");
11
+ const url_1 = require("url");
12
+ const react_client_reference_manifest_1 = require("../build/rsc/react-client-reference-manifest");
13
+ const root_resolver_1 = require("./root-resolver");
14
+ const constants_1 = require("../constants");
15
+ const module_compile_hook_1 = require("./module-compile-hook");
16
+ const request_context_1 = require("./request-context");
17
+ const runtime_actions_1 = require("./runtime-actions");
18
+ const app_router_runtime_1 = require("./app-router-runtime");
19
+ const fetch_policy_1 = require("./fetch-policy");
20
+ const runtime_artifacts_1 = require("./runtime-artifacts");
21
+ const config_1 = require("../config");
22
+ const vista_import_map_1 = require("./vista-import-map");
23
+ const project_alias_resolver_1 = require("./project-alias-resolver");
24
+ const app_dir_1 = require("./app-dir");
25
+ // NOTE: RouteErrorBoundary and RouteSuspense are 'use client' components.
26
+ // Under --conditions react-server, React.Component is not available, so we
27
+ // must NOT import them at the top level. Instead we lazy-require them after
28
+ // the client-load hook has been installed (which turns them into Flight
29
+ // client references automatically).
30
+ let _RouteErrorBoundary = null;
31
+ let _RouteSuspense = null;
32
+ function getRouteErrorBoundary() {
33
+ if (!_RouteErrorBoundary) {
34
+ _RouteErrorBoundary = require('../components/error-boundary').RouteErrorBoundary;
35
+ }
36
+ return _RouteErrorBoundary;
37
+ }
38
+ function getRouteSuspense() {
39
+ if (!_RouteSuspense) {
40
+ _RouteSuspense = require('../components/route-suspense').RouteSuspense;
41
+ }
42
+ return _RouteSuspense;
43
+ }
44
+ const CjsModule = require('module');
45
+ // Support CSS imports on server runtime
46
+ require.extensions['.css'] = (m, filename) => {
47
+ if (filename.endsWith('.module.css')) {
48
+ m.exports = {};
49
+ }
50
+ };
51
+ let installedClientLoadHook = false;
52
+ let originalCompile = null;
53
+ let reactResolutionInstalled = false;
54
+ let originalResolveFilename = null;
55
+ const clientDirectiveCache = new Map();
56
+ function resolveVistaInternalRequest(request) {
57
+ return (0, vista_import_map_1.resolveVistaSourceRequest)(request, path_1.default.resolve(__dirname, '..'));
58
+ }
59
+ function parseCliArg(flag) {
60
+ const index = process.argv.indexOf(flag);
61
+ if (index === -1)
62
+ return undefined;
63
+ return process.argv[index + 1];
64
+ }
65
+ function resolvePort(defaultPort) {
66
+ const raw = parseCliArg('--port') ?? process.env.RSC_UPSTREAM_PORT ?? String(defaultPort);
67
+ const port = Number(raw);
68
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
69
+ throw new Error(`Invalid upstream port: ${raw}`);
70
+ }
71
+ return port;
72
+ }
73
+ function resolveFromWorkspace(specifier, cwd) {
74
+ const searchRoots = [
75
+ cwd,
76
+ path_1.default.resolve(cwd, '..'),
77
+ path_1.default.resolve(cwd, '..', '..'),
78
+ path_1.default.resolve(cwd, '..', '..', 'rsc'),
79
+ path_1.default.resolve(cwd, '..', '..', '..'),
80
+ path_1.default.resolve(cwd, '..', '..', '..', 'rsc'),
81
+ ];
82
+ for (const root of searchRoots) {
83
+ try {
84
+ return require.resolve(specifier, { paths: [root] });
85
+ }
86
+ catch {
87
+ // continue
88
+ }
89
+ }
90
+ return require.resolve(specifier);
91
+ }
92
+ function normalizeModulePath(filePath) {
93
+ return filePath.replace(/\\/g, '/').toLowerCase();
94
+ }
95
+ function shouldInvalidateDevModule(modulePath, cwd) {
96
+ const normalized = normalizeModulePath(modulePath);
97
+ const rootPrefix = normalizeModulePath(`${cwd}${path_1.default.sep}`);
98
+ if (!normalized.startsWith(rootPrefix))
99
+ return false;
100
+ if (normalized.includes('/node_modules/'))
101
+ return false;
102
+ if (normalized.includes(`/${constants_1.BUILD_DIR.toLowerCase()}/`))
103
+ return false;
104
+ return /\.(?:[cm]?[jt]sx?|json)$/i.test(normalized);
105
+ }
106
+ function clearProjectRequireCache(cwd) {
107
+ for (const key of Object.keys(require.cache)) {
108
+ if (!shouldInvalidateDevModule(key, cwd))
109
+ continue;
110
+ delete require.cache[key];
111
+ clientDirectiveCache.delete(key);
112
+ }
113
+ }
114
+ function setupTypeScriptRuntime(cwd) {
115
+ try {
116
+ const swcRegisterPath = resolveFromWorkspace('@swc-node/register/register', cwd);
117
+ const typescriptPath = resolveFromWorkspace('typescript', cwd);
118
+ const { register } = require(swcRegisterPath);
119
+ const ts = require(typescriptPath);
120
+ register({
121
+ module: ts.ModuleKind.CommonJS,
122
+ jsx: ts.JsxEmit.ReactJSX,
123
+ moduleResolution: ts.ModuleResolutionKind.Node16,
124
+ esModuleInterop: true,
125
+ allowJs: true,
126
+ });
127
+ return;
128
+ }
129
+ catch {
130
+ // fallback
131
+ }
132
+ try {
133
+ const tsNodePath = resolveFromWorkspace('ts-node', cwd);
134
+ require(tsNodePath).register({
135
+ transpileOnly: true,
136
+ compilerOptions: {
137
+ module: 'commonjs',
138
+ jsx: 'react-jsx',
139
+ moduleResolution: 'node16',
140
+ esModuleInterop: true,
141
+ allowJs: true,
142
+ },
143
+ });
144
+ return;
145
+ }
146
+ catch {
147
+ // fallback
148
+ }
149
+ try {
150
+ const tsxPath = resolveFromWorkspace('tsx/cjs', cwd);
151
+ // tsx/cjs registers the TypeScript loader for require()
152
+ require(tsxPath);
153
+ return;
154
+ }
155
+ catch {
156
+ throw new Error('No TypeScript compiler available for RSC upstream runtime. Install one of: @swc-node/register, ts-node, or tsx');
157
+ }
158
+ }
159
+ function hasClientBoundaryDirective(source) {
160
+ let trimmed = source;
161
+ while (true) {
162
+ trimmed = trimmed.trimStart();
163
+ if (trimmed.startsWith('//')) {
164
+ const newlineIndex = trimmed.indexOf('\n');
165
+ trimmed = newlineIndex === -1 ? '' : trimmed.slice(newlineIndex + 1);
166
+ continue;
167
+ }
168
+ if (trimmed.startsWith('/*')) {
169
+ const commentEndIndex = trimmed.indexOf('*/');
170
+ if (commentEndIndex === -1) {
171
+ break;
172
+ }
173
+ trimmed = trimmed.slice(commentEndIndex + 2);
174
+ continue;
175
+ }
176
+ break;
177
+ }
178
+ return trimmed.startsWith("'use client'") || trimmed.startsWith('"use client"');
179
+ }
180
+ function isClientBoundaryFile(filename, transpiledSource) {
181
+ const cached = clientDirectiveCache.get(filename);
182
+ if (cached !== undefined)
183
+ return cached;
184
+ let isClient = false;
185
+ try {
186
+ const originalSource = fs_1.default.readFileSync(filename, 'utf-8');
187
+ isClient = hasClientBoundaryDirective(originalSource);
188
+ }
189
+ catch {
190
+ isClient = hasClientBoundaryDirective(transpiledSource);
191
+ }
192
+ clientDirectiveCache.set(filename, isClient);
193
+ return isClient;
194
+ }
195
+ function installSingleReactResolution(cwd) {
196
+ if (reactResolutionInstalled)
197
+ return;
198
+ let reactPath;
199
+ let reactDomPath;
200
+ try {
201
+ reactPath = require.resolve('react');
202
+ reactDomPath = require.resolve('react-dom');
203
+ }
204
+ catch {
205
+ return;
206
+ }
207
+ originalResolveFilename = CjsModule._resolveFilename;
208
+ const projectAliasResolver = (0, project_alias_resolver_1.createProjectAliasResolver)(cwd, resolveFromWorkspace);
209
+ CjsModule._resolveFilename = function (request, parent, isMain, options) {
210
+ const vistaResolvedPath = resolveVistaInternalRequest(request);
211
+ if (vistaResolvedPath)
212
+ return vistaResolvedPath;
213
+ const aliasResolvedPath = projectAliasResolver?.resolve(request);
214
+ if (aliasResolvedPath) {
215
+ return originalResolveFilename.call(this, aliasResolvedPath, parent, isMain, options);
216
+ }
217
+ if (request === 'react')
218
+ return reactPath;
219
+ if (request === 'react-dom')
220
+ return reactDomPath;
221
+ if (request.startsWith('react/')) {
222
+ const subPath = request.slice('react/'.length);
223
+ try {
224
+ return require.resolve(`react/${subPath}`, { paths: [path_1.default.dirname(reactPath)] });
225
+ }
226
+ catch {
227
+ // fall through
228
+ }
229
+ }
230
+ if (request.startsWith('react-dom/')) {
231
+ const subPath = request.slice('react-dom/'.length);
232
+ try {
233
+ return require.resolve(`react-dom/${subPath}`, { paths: [path_1.default.dirname(reactDomPath)] });
234
+ }
235
+ catch {
236
+ // fall through
237
+ }
238
+ }
239
+ return originalResolveFilename.call(this, request, parent, isMain, options);
240
+ };
241
+ reactResolutionInstalled = true;
242
+ }
243
+ function installClientLoadHook(cwd, createClientModuleProxy) {
244
+ if (installedClientLoadHook)
245
+ return;
246
+ const cacheComponentsConfig = (0, config_1.resolveCacheComponentsConfig)((0, config_1.loadConfig)(cwd));
247
+ (0, module_compile_hook_1.installModuleCompileHook)({
248
+ cwd,
249
+ createClientModuleProxy,
250
+ cacheComponentsEnabled: cacheComponentsConfig.enabled,
251
+ });
252
+ installedClientLoadHook = true;
253
+ }
254
+ function matchPattern(pathname, pattern) {
255
+ const patternParts = pattern.split('/').filter(Boolean);
256
+ const pathParts = pathname.split('/').filter(Boolean);
257
+ if (patternParts.length === 0 && pathParts.length === 0)
258
+ return true;
259
+ for (let i = 0; i < patternParts.length; i++) {
260
+ const patternPart = patternParts[i];
261
+ const pathPart = pathParts[i];
262
+ // Optional catch-all: matches zero or more segments
263
+ if (patternPart.endsWith('*?')) {
264
+ return true;
265
+ }
266
+ // Required catch-all: matches one or more remaining segments
267
+ if (patternPart.endsWith('*')) {
268
+ return pathParts.length >= i + 1;
269
+ }
270
+ if (patternPart.startsWith(':')) {
271
+ if (!pathPart)
272
+ return false;
273
+ continue;
274
+ }
275
+ if (patternPart !== pathPart)
276
+ return false;
277
+ }
278
+ return patternParts.length === pathParts.length;
279
+ }
280
+ function matchRoute(pathname, routes) {
281
+ const sorted = [...routes].sort((a, b) => {
282
+ const aOptional = a.pattern.includes('*?');
283
+ const bOptional = b.pattern.includes('*?');
284
+ if (aOptional && !bOptional)
285
+ return 1;
286
+ if (!aOptional && bOptional)
287
+ return -1;
288
+ return b.pattern.split('/').length - a.pattern.split('/').length;
289
+ });
290
+ for (const route of sorted) {
291
+ if (matchPattern(pathname, route.pattern))
292
+ return route;
293
+ }
294
+ return null;
295
+ }
296
+ function extractParams(pathname, route) {
297
+ const params = {};
298
+ const patternParts = route.pattern.split('/').filter(Boolean);
299
+ const pathParts = pathname.split('/').filter(Boolean);
300
+ for (let i = 0; i < patternParts.length; i++) {
301
+ const patternPart = patternParts[i];
302
+ if (!patternPart.startsWith(':'))
303
+ continue;
304
+ const name = patternPart.slice(1).replace(/\*\??/, '');
305
+ if (patternPart.endsWith('*?') || patternPart.endsWith('*')) {
306
+ params[name] = pathParts.slice(i).join('/');
307
+ }
308
+ else {
309
+ params[name] = pathParts[i] || '';
310
+ }
311
+ }
312
+ return params;
313
+ }
314
+ async function createRenderableRouteModuleElement(modulePath, context, options = {}) {
315
+ const { params, searchParams, req } = context;
316
+ const RouteModule = require(modulePath);
317
+ const RouteComponent = RouteModule.default;
318
+ if (!RouteComponent) {
319
+ throw new Error(`Route module does not export default component: ${modulePath}`);
320
+ }
321
+ if (options.evaluateMetadata && typeof RouteModule.generateMetadata === 'function') {
322
+ await RouteModule.generateMetadata({ params, searchParams }, RouteModule.metadata ?? {});
323
+ }
324
+ const routeProps = typeof RouteModule.getServerProps === 'function'
325
+ ? await RouteModule.getServerProps({ query: req.query, params, req })
326
+ : {};
327
+ const moduleStem = path_1.default.basename(modulePath).replace(/\.[jt]sx?$/, '');
328
+ if (moduleStem === 'default' || moduleStem === 'not-found') {
329
+ const eagerResult = await RouteComponent({
330
+ ...routeProps,
331
+ params,
332
+ searchParams,
333
+ });
334
+ return react_1.default.isValidElement(eagerResult)
335
+ ? eagerResult
336
+ : react_1.default.createElement(react_1.default.Fragment, null, eagerResult);
337
+ }
338
+ return react_1.default.createElement(RouteComponent, {
339
+ ...routeProps,
340
+ params,
341
+ searchParams,
342
+ });
343
+ }
344
+ function applySegmentBoundaries(dir, element) {
345
+ const loadingPath = (0, app_router_runtime_1.resolveConventionModule)(dir, 'loading');
346
+ const errorPath = (0, app_router_runtime_1.resolveConventionModule)(dir, 'error');
347
+ const loadingComponent = loadingPath
348
+ ? (() => {
349
+ try {
350
+ return require(loadingPath).default;
351
+ }
352
+ catch {
353
+ return undefined;
354
+ }
355
+ })()
356
+ : undefined;
357
+ const errorComponent = errorPath
358
+ ? (() => {
359
+ try {
360
+ return require(errorPath).default;
361
+ }
362
+ catch {
363
+ return undefined;
364
+ }
365
+ })()
366
+ : undefined;
367
+ let wrappedElement = element;
368
+ if (loadingComponent) {
369
+ wrappedElement = react_1.default.createElement(getRouteSuspense(), {
370
+ loadingComponent,
371
+ children: wrappedElement,
372
+ });
373
+ }
374
+ if (errorComponent) {
375
+ wrappedElement = react_1.default.createElement(getRouteErrorBoundary(), {
376
+ fallbackComponent: errorComponent,
377
+ children: wrappedElement,
378
+ });
379
+ }
380
+ return wrappedElement;
381
+ }
382
+ async function renderAppSubtreeElement(input) {
383
+ const appDir = (0, app_dir_1.resolveAppDir)(input.cwd);
384
+ let element = await createRenderableRouteModuleElement(input.entryFilePath, {
385
+ params: input.params,
386
+ searchParams: input.searchParams,
387
+ req: input.req,
388
+ }, {
389
+ evaluateMetadata: input.evaluateLeafMetadata,
390
+ });
391
+ const directoryChain = (0, app_router_runtime_1.resolveDirectoryChain)(input.subtreeRootDir, input.entryFilePath);
392
+ for (let i = directoryChain.length - 1; i >= 0; i--) {
393
+ element = applySegmentBoundaries(directoryChain[i], element);
394
+ }
395
+ const layoutPaths = input.layoutPaths && input.layoutPaths.length > 0
396
+ ? input.layoutPaths
397
+ : directoryChain
398
+ .map((dir) => (0, app_router_runtime_1.resolveConventionModule)(dir, 'root') ?? (0, app_router_runtime_1.resolveConventionModule)(dir, 'layout'))
399
+ .filter((layoutPath) => Boolean(layoutPath));
400
+ for (let i = layoutPaths.length - 1; i >= 0; i--) {
401
+ const layoutPath = layoutPaths[i];
402
+ if (!layoutPath || path_1.default.resolve(layoutPath) === path_1.default.resolve(input.entryFilePath)) {
403
+ continue;
404
+ }
405
+ const LayoutModule = require(layoutPath);
406
+ const LayoutComponent = LayoutModule.default;
407
+ if (!LayoutComponent) {
408
+ continue;
409
+ }
410
+ const slotProps = {};
411
+ if (!input.disableParallelSlots) {
412
+ const slotMatches = (0, app_router_runtime_1.resolveParallelSlotMatches)({
413
+ appDir,
414
+ layoutPath,
415
+ pathname: input.pathname,
416
+ });
417
+ for (const slotMatch of slotMatches) {
418
+ slotProps[slotMatch.slotName] = await renderAppSubtreeElement({
419
+ subtreeRootDir: slotMatch.slotRootDir,
420
+ entryFilePath: slotMatch.filePath,
421
+ pathname: input.pathname,
422
+ params: {
423
+ ...input.params,
424
+ ...slotMatch.params,
425
+ },
426
+ searchParams: input.searchParams,
427
+ req: input.req,
428
+ cwd: input.cwd,
429
+ evaluateLeafMetadata: true,
430
+ });
431
+ }
432
+ }
433
+ element = react_1.default.createElement(LayoutComponent, {
434
+ params: input.params,
435
+ searchParams: input.searchParams,
436
+ ...slotProps,
437
+ }, element);
438
+ }
439
+ return element;
440
+ }
441
+ async function createRouteElement(route, context, isDev, runtimeRoot, options = {}) {
442
+ const { pathname, params, searchParams, req } = context;
443
+ if (isDev) {
444
+ clearProjectRequireCache(runtimeRoot);
445
+ }
446
+ return renderAppSubtreeElement({
447
+ subtreeRootDir: (0, app_dir_1.resolveAppDir)(runtimeRoot),
448
+ entryFilePath: route.pagePath,
449
+ pathname,
450
+ params,
451
+ searchParams,
452
+ req,
453
+ cwd: runtimeRoot,
454
+ evaluateLeafMetadata: true,
455
+ disableParallelSlots: options.disableParallelSlots,
456
+ layoutPaths: route.layoutPaths,
457
+ });
458
+ }
459
+ async function readRawRequestBody(req) {
460
+ if (typeof req.body === 'string') {
461
+ return Buffer.from(req.body);
462
+ }
463
+ if (Buffer.isBuffer(req.body)) {
464
+ return req.body;
465
+ }
466
+ const chunks = [];
467
+ for await (const chunk of req) {
468
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
469
+ }
470
+ return Buffer.concat(chunks);
471
+ }
472
+ async function parseMultipartFormData(req, rawBody) {
473
+ const request = new Request(`http://127.0.0.1${req.originalUrl || req.url || '/'}`, {
474
+ method: req.method || 'POST',
475
+ headers: req.headers,
476
+ body: rawBody,
477
+ });
478
+ return request.formData();
479
+ }
480
+ function getSearchParamsFromRequest(req) {
481
+ return Object.fromEntries(new URLSearchParams(req.query).entries());
482
+ }
483
+ function loadFlightManifest(flightManifestPath) {
484
+ const raw = JSON.parse(fs_1.default.readFileSync(flightManifestPath, 'utf-8'));
485
+ return (0, react_client_reference_manifest_1.createGuardedReactClientManifest)((0, react_client_reference_manifest_1.normalizeReactClientReferenceManifest)(raw));
486
+ }
487
+ function startUpstream() {
488
+ const cwd = path_1.default.resolve(process.env.VISTA_ARTIFACT_ROOT || process.cwd());
489
+ const runtimeRoot = (0, runtime_artifacts_1.resolveRuntimeProjectRoot)(cwd, process.env.VISTA_RUNTIME_ROOT);
490
+ const isDev = process.env.NODE_ENV !== 'production';
491
+ const port = resolvePort(3101);
492
+ const vistaDirRoot = path_1.default.join(cwd, constants_1.BUILD_DIR);
493
+ installSingleReactResolution(runtimeRoot);
494
+ setupTypeScriptRuntime(runtimeRoot);
495
+ const flightServerPath = resolveFromWorkspace('react-server-dom-webpack/server.node', cwd);
496
+ const flightServer = require(flightServerPath);
497
+ installClientLoadHook(runtimeRoot, flightServer.createClientModuleProxy);
498
+ (0, fetch_policy_1.installSegmentFetchPolicyShim)();
499
+ const serverManifestPath = path_1.default.join(cwd, constants_1.BUILD_DIR, 'server', 'server-manifest.json');
500
+ const flightManifestPath = path_1.default.join(cwd, constants_1.BUILD_DIR, 'react-client-manifest.json');
501
+ if (!fs_1.default.existsSync(serverManifestPath)) {
502
+ throw new Error('Missing RSC server manifest. Run "vista build" first.');
503
+ }
504
+ // In dev mode the flight manifest may not exist yet (webpack-dev-middleware
505
+ // hasn't completed the first compilation). Write a stub so we can start,
506
+ // and reload on each request.
507
+ if (!fs_1.default.existsSync(flightManifestPath)) {
508
+ if (isDev) {
509
+ fs_1.default.writeFileSync(flightManifestPath, '{}');
510
+ }
511
+ else {
512
+ throw new Error('Missing RSC flight manifest. Run "vista build" first.');
513
+ }
514
+ }
515
+ let serverManifest = JSON.parse(fs_1.default.readFileSync(serverManifestPath, 'utf-8'));
516
+ let flightManifest = loadFlightManifest(flightManifestPath);
517
+ const app = (0, express_1.default)();
518
+ const pipeFlightModel = async (res, model, status) => {
519
+ let capturedError = null;
520
+ let gateResolved = false;
521
+ let streamEnded = false;
522
+ const gateStream = new stream_1.PassThrough();
523
+ const bufferedChunks = [];
524
+ const finishGate = (() => {
525
+ let resolver = null;
526
+ const promise = new Promise((resolve) => {
527
+ resolver = () => {
528
+ if (gateResolved) {
529
+ return;
530
+ }
531
+ gateResolved = true;
532
+ resolve();
533
+ };
534
+ });
535
+ return { promise, resolve: () => resolver?.() };
536
+ })();
537
+ const onData = (chunk) => {
538
+ bufferedChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
539
+ finishGate.resolve();
540
+ };
541
+ gateStream.on('data', onData);
542
+ gateStream.once('end', () => {
543
+ streamEnded = true;
544
+ finishGate.resolve();
545
+ });
546
+ gateStream.once('error', () => {
547
+ finishGate.resolve();
548
+ });
549
+ const stream = flightServer.renderToPipeableStream(model, flightManifest, {
550
+ onError(error) {
551
+ capturedError = error;
552
+ if (error?.name !== 'NotFoundError') {
553
+ console.error('[vista:rsc] Upstream flight render error:', error);
554
+ }
555
+ finishGate.resolve();
556
+ },
557
+ });
558
+ stream.pipe(gateStream);
559
+ const gateTimer = setTimeout(() => finishGate.resolve(), 75);
560
+ await finishGate.promise;
561
+ clearTimeout(gateTimer);
562
+ if (capturedError?.name === 'NotFoundError') {
563
+ gateStream.destroy();
564
+ throw capturedError;
565
+ }
566
+ gateStream.off('data', onData);
567
+ res.status(status);
568
+ res.setHeader('Content-Type', 'text/x-component');
569
+ res.setHeader('Vary', 'Accept');
570
+ for (const chunk of bufferedChunks) {
571
+ res.write(chunk);
572
+ }
573
+ if (streamEnded) {
574
+ res.end();
575
+ return;
576
+ }
577
+ gateStream.pipe(res);
578
+ };
579
+ const drainFlightModel = async (model) => {
580
+ let capturedError = null;
581
+ const sink = new stream_1.PassThrough();
582
+ const completion = new Promise((resolve, reject) => {
583
+ sink.on('data', () => { });
584
+ sink.once('end', resolve);
585
+ sink.once('error', reject);
586
+ });
587
+ const stream = flightServer.renderToPipeableStream(model, flightManifest, {
588
+ onError(error) {
589
+ if (!capturedError) {
590
+ capturedError = error;
591
+ }
592
+ },
593
+ });
594
+ stream.pipe(sink);
595
+ await completion;
596
+ if (capturedError) {
597
+ throw capturedError;
598
+ }
599
+ };
600
+ const resolveActionModulePath = (actionId) => {
601
+ const hashIdx = actionId.lastIndexOf('#');
602
+ const modulePath = hashIdx >= 0 ? actionId.slice(0, hashIdx) : actionId;
603
+ if (!modulePath.startsWith('file://')) {
604
+ return modulePath;
605
+ }
606
+ try {
607
+ return (0, url_1.fileURLToPath)(modulePath);
608
+ }
609
+ catch {
610
+ let fallbackPath = modulePath.replace(/^file:\/\/\//, '').replace(/^file:\/\//, '');
611
+ if (process.platform === 'win32' && /^[a-zA-Z]:/.test(fallbackPath) === false) {
612
+ fallbackPath = '/' + fallbackPath;
613
+ }
614
+ return fallbackPath;
615
+ }
616
+ };
617
+ const primeInlineActionRegistration = async (req, actionId) => {
618
+ const actionEntry = serverManifest.serverActions?.[actionId];
619
+ if (!actionEntry || actionEntry.kind !== 'inline') {
620
+ return undefined;
621
+ }
622
+ const pathname = req.path.replace(/^\/(?:_rsc|rsc)/, '') || '/';
623
+ const searchParams = getSearchParamsFromRequest(req);
624
+ const actionRoute = matchRoute(pathname, serverManifest.routes) ||
625
+ serverManifest.routes.find((candidate) => {
626
+ const targetPath = path_1.default.resolve(actionEntry.filePath);
627
+ return (path_1.default.resolve(candidate.pagePath) === targetPath ||
628
+ candidate.layoutPaths.some((layoutPath) => path_1.default.resolve(layoutPath) === targetPath));
629
+ }) ||
630
+ null;
631
+ const resolvedActionPath = path_1.default.resolve(actionEntry.filePath || resolveActionModulePath(actionId));
632
+ const routeParams = actionRoute ? extractParams(pathname, actionRoute) : {};
633
+ if (isDev) {
634
+ try {
635
+ delete require.cache[require.resolve(resolvedActionPath)];
636
+ }
637
+ catch {
638
+ // ignore missing cache entries
639
+ }
640
+ }
641
+ const actionModule = require(resolvedActionPath);
642
+ if (typeof actionModule?.default === 'function') {
643
+ const probeProps = {
644
+ params: routeParams,
645
+ searchParams,
646
+ };
647
+ if (actionRoute && path_1.default.resolve(actionRoute.pagePath) !== resolvedActionPath) {
648
+ probeProps.children = null;
649
+ }
650
+ try {
651
+ await actionModule.default(probeProps);
652
+ }
653
+ catch {
654
+ // Some components require a fuller tree to evaluate. Fall through to route priming.
655
+ }
656
+ const directResolution = (0, runtime_actions_1.resolveRegisteredServerReference)(actionId);
657
+ if (directResolution) {
658
+ return directResolution;
659
+ }
660
+ }
661
+ if (actionRoute) {
662
+ const params = routeParams;
663
+ const model = await createRouteElement(actionRoute, { pathname, params, searchParams, req }, isDev, runtimeRoot);
664
+ await drainFlightModel(model);
665
+ return (0, runtime_actions_1.resolveRegisteredServerReference)(actionId);
666
+ }
667
+ return undefined;
668
+ };
669
+ const handleRSCRequest = async (req, res) => {
670
+ const pathname = req.path.replace(/^\/(?:_rsc|rsc)/, '') || '/';
671
+ await (0, request_context_1.runWithRequestContext)({
672
+ req,
673
+ res,
674
+ cwd: runtimeRoot,
675
+ vistaDirRoot,
676
+ urlPath: pathname,
677
+ }, async () => {
678
+ try {
679
+ // In dev mode, reload manifests from disk on each request so we
680
+ // always pick up the latest output from ReactFlightWebpackPlugin.
681
+ if (isDev) {
682
+ try {
683
+ serverManifest = JSON.parse(fs_1.default.readFileSync(serverManifestPath, 'utf-8'));
684
+ flightManifest = loadFlightManifest(flightManifestPath);
685
+ }
686
+ catch {
687
+ // Manifests may be mid-write; use whatever we have cached.
688
+ }
689
+ }
690
+ const route = matchRoute(pathname, serverManifest.routes);
691
+ (0, request_context_1.setCurrentSegmentConfig)(route?.segmentConfig);
692
+ if (!route) {
693
+ const rootLayout = (0, root_resolver_1.resolveRootLayout)(runtimeRoot, isDev);
694
+ const resolvedNotFound = (0, root_resolver_1.resolveNotFoundComponent)(runtimeRoot, rootLayout, isDev);
695
+ let model;
696
+ if (resolvedNotFound) {
697
+ const notFoundElement = react_1.default.createElement(resolvedNotFound.component, {
698
+ params: {},
699
+ searchParams: {},
700
+ });
701
+ model = react_1.default.createElement(rootLayout.component, { params: {}, searchParams: {} }, notFoundElement);
702
+ }
703
+ else {
704
+ model = react_1.default.createElement('div', {
705
+ style: {
706
+ display: 'flex',
707
+ flexDirection: 'column',
708
+ alignItems: 'center',
709
+ justifyContent: 'center',
710
+ height: '100vh',
711
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
712
+ background: '#0a0a0a',
713
+ color: '#ededed',
714
+ margin: 0,
715
+ overflow: 'hidden',
716
+ textAlign: 'center',
717
+ userSelect: 'none',
718
+ },
719
+ }, react_1.default.createElement('span', {
720
+ style: {
721
+ fontSize: '6rem',
722
+ fontWeight: 800,
723
+ letterSpacing: '-0.04em',
724
+ lineHeight: 1,
725
+ background: 'linear-gradient(135deg, #7c3aed, #2563eb, #06b6d4)',
726
+ WebkitBackgroundClip: 'text',
727
+ WebkitTextFillColor: 'transparent',
728
+ backgroundClip: 'text',
729
+ },
730
+ }, '404'), react_1.default.createElement('p', {
731
+ style: {
732
+ marginTop: '0.75rem',
733
+ fontSize: '0.95rem',
734
+ fontWeight: 400,
735
+ color: '#555',
736
+ letterSpacing: '0.02em',
737
+ },
738
+ }, "There's nothing here."));
739
+ }
740
+ await pipeFlightModel(res, model, 404);
741
+ return;
742
+ }
743
+ const params = extractParams(pathname, route);
744
+ const searchParams = getSearchParamsFromRequest(req);
745
+ const element = await createRouteElement(route, { pathname, params, searchParams, req }, isDev, runtimeRoot);
746
+ await pipeFlightModel(res, element, 200);
747
+ }
748
+ catch (error) {
749
+ if (error?.name === 'NotFoundError') {
750
+ try {
751
+ const rootLayout = (0, root_resolver_1.resolveRootLayout)(runtimeRoot, isDev);
752
+ const route = matchRoute(pathname, serverManifest.routes);
753
+ (0, request_context_1.setCurrentSegmentConfig)(route?.segmentConfig);
754
+ if (route) {
755
+ const segmentNotFoundPath = (0, app_router_runtime_1.resolveNearestSegmentNotFoundPath)((0, app_dir_1.resolveAppDir)(runtimeRoot), route.routeDir);
756
+ if (segmentNotFoundPath) {
757
+ const params = extractParams(pathname, route);
758
+ const searchParams = getSearchParamsFromRequest(req);
759
+ const model = await createRouteElement({
760
+ ...route,
761
+ pagePath: segmentNotFoundPath,
762
+ }, { pathname, params, searchParams, req }, isDev, runtimeRoot, { disableParallelSlots: true });
763
+ await pipeFlightModel(res, model, 404);
764
+ return;
765
+ }
766
+ }
767
+ const resolvedNotFound = (0, root_resolver_1.resolveNotFoundComponent)(runtimeRoot, rootLayout, isDev);
768
+ let model;
769
+ if (resolvedNotFound) {
770
+ const notFoundElement = react_1.default.createElement(resolvedNotFound.component, {
771
+ params: {},
772
+ searchParams: {},
773
+ });
774
+ model = react_1.default.createElement(rootLayout.component, { params: {}, searchParams: {} }, notFoundElement);
775
+ }
776
+ else {
777
+ model = react_1.default.createElement('h1', null, '404 - Page Not Found');
778
+ }
779
+ await pipeFlightModel(res, model, 404);
780
+ return;
781
+ }
782
+ catch (notFoundError) {
783
+ console.error('[vista:rsc] Failed to render NotFoundError fallback:', notFoundError);
784
+ }
785
+ }
786
+ console.error('[vista:rsc] Upstream request failed:', error);
787
+ res
788
+ .status(500)
789
+ .type('text/plain')
790
+ .send(error.message);
791
+ }
792
+ });
793
+ };
794
+ app.get('/rsc*', handleRSCRequest);
795
+ app.get('/_rsc*', handleRSCRequest);
796
+ // -----------------------------------------------------------------------
797
+ // Server Actions — POST handler
798
+ // -----------------------------------------------------------------------
799
+ app.use(express_1.default.text({ type: 'text/plain', limit: '10mb' }));
800
+ const handleServerAction = async (req, res) => {
801
+ const pathname = req.path.replace(/^\/(?:_rsc|rsc)/, '') || '/';
802
+ await (0, request_context_1.runWithRequestContext)({
803
+ req,
804
+ res,
805
+ cwd: runtimeRoot,
806
+ vistaDirRoot,
807
+ urlPath: pathname,
808
+ }, async () => {
809
+ try {
810
+ const actionId = req.headers['rsc-action'];
811
+ if (!actionId) {
812
+ res.status(400).type('text/plain').send('Missing rsc-action header');
813
+ return;
814
+ }
815
+ if (isDev) {
816
+ try {
817
+ serverManifest = JSON.parse(fs_1.default.readFileSync(serverManifestPath, 'utf-8'));
818
+ flightManifest = loadFlightManifest(flightManifestPath);
819
+ }
820
+ catch {
821
+ // Keep cached manifests if they're being rewritten.
822
+ }
823
+ }
824
+ (0, request_context_1.setCurrentSegmentConfig)(matchRoute(pathname, serverManifest.routes)?.segmentConfig);
825
+ let actionFn = (0, runtime_actions_1.resolveRegisteredServerReference)(actionId);
826
+ if (!actionFn) {
827
+ actionFn = await primeInlineActionRegistration(req, actionId);
828
+ }
829
+ if (!actionFn) {
830
+ const hashIdx = actionId.lastIndexOf('#');
831
+ const exportName = hashIdx >= 0 ? actionId.slice(hashIdx + 1) : 'default';
832
+ const resolvedPath = resolveActionModulePath(actionId);
833
+ if (isDev) {
834
+ try {
835
+ delete require.cache[require.resolve(resolvedPath)];
836
+ }
837
+ catch {
838
+ // ignore missing cache entries
839
+ }
840
+ }
841
+ const actionModule = require(resolvedPath);
842
+ actionFn = actionModule[exportName];
843
+ }
844
+ if (typeof actionFn !== 'function') {
845
+ res.status(404).type('text/plain').send(`Server action not found: ${actionId}`);
846
+ return;
847
+ }
848
+ const rawBody = await readRawRequestBody(req);
849
+ const contentType = String(req.headers['content-type'] || '');
850
+ let result;
851
+ if (contentType.includes('multipart/form-data')) {
852
+ const formData = await parseMultipartFormData(req, rawBody);
853
+ const boundAction = await flightServer.decodeAction(formData, flightManifest);
854
+ result = await boundAction();
855
+ }
856
+ else {
857
+ const args = (await flightServer.decodeReply(rawBody.toString('utf-8'), flightManifest));
858
+ result = await actionFn(...(Array.isArray(args) ? args : [args]));
859
+ }
860
+ const revalidatedPaths = (0, request_context_1.consumeRevalidatedPaths)();
861
+ if (revalidatedPaths.length > 0) {
862
+ res.setHeader('x-vista-revalidated-paths', JSON.stringify(revalidatedPaths));
863
+ }
864
+ const revalidatedTags = (0, request_context_1.consumeRevalidatedTags)();
865
+ if (revalidatedTags.length > 0) {
866
+ res.setHeader('x-vista-revalidated-tags', JSON.stringify(revalidatedTags));
867
+ }
868
+ res.setHeader('Content-Type', 'text/x-component');
869
+ const stream = flightServer.renderToPipeableStream(result, flightManifest, {
870
+ onError(error) {
871
+ console.error('[vista:rsc] Server action render error:', error);
872
+ },
873
+ });
874
+ stream.pipe(res);
875
+ }
876
+ catch (error) {
877
+ console.error('[vista:rsc] Server action failed:', error);
878
+ res
879
+ .status(500)
880
+ .type('text/plain')
881
+ .send(error.message);
882
+ }
883
+ });
884
+ };
885
+ app.post('/rsc*', handleServerAction);
886
+ app.post('/_rsc*', handleServerAction);
887
+ const server = app.listen(port, () => {
888
+ console.log(`[vista:rsc:upstream] Listening on http://127.0.0.1:${port}/rsc`);
889
+ });
890
+ server.on('error', (error) => {
891
+ if (error?.code === 'EADDRINUSE') {
892
+ console.error(`[vista:server] Port ${port} is already in use.`);
893
+ process.exit(1);
894
+ return;
895
+ }
896
+ console.error('[vista:server] RSC upstream startup failed:', error);
897
+ process.exit(1);
898
+ });
899
+ }
900
+ startUpstream();