@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,423 +1,423 @@
1
- "use strict";
2
- /**
3
- * Vista Build Utilities
4
- *
5
- * Generates build manifests, BUILD_ID, and manages .vista output structure.
6
- */
7
- var __importDefault = (this && this.__importDefault) || function (mod) {
8
- return (mod && mod.__esModule) ? mod : { "default": mod };
9
- };
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.generateBuildId = generateBuildId;
12
- exports.getBuildId = getBuildId;
13
- exports.createVistaDirectories = createVistaDirectories;
14
- exports.generateBuildManifest = generateBuildManifest;
15
- exports.generateAppPathRoutesManifest = generateAppPathRoutesManifest;
16
- exports.writeVistaTypes = writeVistaTypes;
17
- exports.writeVistaTrace = writeVistaTrace;
18
- exports.generatePrerenderManifest = generatePrerenderManifest;
19
- exports.generateRequiredServerFilesManifest = generateRequiredServerFilesManifest;
20
- exports.ensureJsonFile = ensureJsonFile;
21
- exports.writeArtifactManifest = writeArtifactManifest;
22
- exports.writeCanonicalVistaArtifacts = writeCanonicalVistaArtifacts;
23
- exports.writeReservedVistaArtifacts = writeReservedVistaArtifacts;
24
- exports.generateRoutesManifest = generateRoutesManifest;
25
- exports.generateClientComponentsManifest = generateClientComponentsManifest;
26
- exports.generateServerComponentsManifest = generateServerComponentsManifest;
27
- exports.getWebpackCacheConfig = getWebpackCacheConfig;
28
- exports.cleanOldCache = cleanOldCache;
29
- exports.pruneEmptyVistaDirectories = pruneEmptyVistaDirectories;
30
- const fs_1 = __importDefault(require("fs"));
31
- const path_1 = __importDefault(require("path"));
32
- const crypto_1 = __importDefault(require("crypto"));
33
- const constants_1 = require("../constants");
34
- const integrity_1 = require("../integrity");
35
- // ============================================================================
36
- // BUILD_ID Generation
37
- // ============================================================================
38
- /**
39
- * Generate a unique build ID based on timestamp and random bytes.
40
- */
41
- function generateBuildId() {
42
- const timestamp = Date.now().toString(36);
43
- const random = crypto_1.default.randomBytes(4).toString('hex');
44
- return `${timestamp}-${random}`;
45
- }
46
- /**
47
- * Read existing BUILD_ID or generate a new one.
48
- */
49
- function getBuildId(vistaDir, forceNew = false) {
50
- const buildIdPath = path_1.default.join(vistaDir, 'BUILD_ID');
51
- if (!forceNew && fs_1.default.existsSync(buildIdPath)) {
52
- return fs_1.default.readFileSync(buildIdPath, 'utf-8').trim();
53
- }
54
- const buildId = generateBuildId();
55
- fs_1.default.mkdirSync(vistaDir, { recursive: true });
56
- fs_1.default.writeFileSync(buildIdPath, buildId);
57
- return buildId;
58
- }
59
- /**
60
- * Create the .vista directory structure.
61
- * In legacy mode, only creates root (no empty server/static dirs).
62
- * In RSC mode, creates the full structure for server/client bundles.
63
- */
64
- function createVistaDirectories(cwd, mode = 'legacy') {
65
- const root = path_1.default.join(cwd, constants_1.BUILD_DIR);
66
- const dirs = {
67
- root,
68
- cache: path_1.default.join(root, 'cache'),
69
- imageCache: path_1.default.join(root, 'cache', 'images'),
70
- server: path_1.default.join(root, 'server'),
71
- static: path_1.default.join(root, 'static'),
72
- chunks: path_1.default.join(root, 'static', 'chunks'),
73
- css: path_1.default.join(root, 'static', 'css'),
74
- media: path_1.default.join(root, 'static', 'media'),
75
- types: path_1.default.join(root, 'types'),
76
- };
77
- // Always create root
78
- fs_1.default.mkdirSync(root, { recursive: true });
79
- if (mode === 'rsc') {
80
- [dirs.root, dirs.cache, dirs.imageCache, dirs.server, dirs.static, dirs.chunks, dirs.media, dirs.types].forEach((dir) => {
81
- fs_1.default.mkdirSync(dir, { recursive: true });
82
- });
83
- }
84
- // Legacy mode: only root dir is created — webpack outputs directly into .vista/
85
- return dirs;
86
- }
87
- /**
88
- * Generate build-manifest.json
89
- */
90
- function generateBuildManifest(vistaDir, buildId, pages = {}) {
91
- const manifest = {
92
- buildId,
93
- polyfillFiles: [],
94
- devFiles: [],
95
- lowPriorityFiles: [],
96
- rootMainFiles: [`${constants_1.STATIC_CHUNKS_PATH}webpack.js`, `${constants_1.STATIC_CHUNKS_PATH}main.js`],
97
- pages,
98
- };
99
- const manifestPath = path_1.default.join(vistaDir, 'build-manifest.json');
100
- fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
101
- return manifest;
102
- }
103
- function toRegexFromPattern(pattern) {
104
- if (pattern === '/') {
105
- return '^/$';
106
- }
107
- const normalized = pattern.startsWith('/') ? pattern.slice(1) : pattern;
108
- const parts = normalized.split('/').filter(Boolean);
109
- const regexParts = parts.map((part) => {
110
- if (!part.startsWith(':')) {
111
- return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
112
- }
113
- const dynamicMatch = /^:([a-zA-Z0-9_]+)(\*)?(\?)?$/.exec(part);
114
- if (!dynamicMatch) {
115
- return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
116
- }
117
- const [, paramName, isCatchAll, isOptional] = dynamicMatch;
118
- if (isCatchAll && isOptional) {
119
- return `(?<${paramName}>.*)`;
120
- }
121
- if (isCatchAll) {
122
- return `(?<${paramName}>.+)`;
123
- }
124
- return `(?<${paramName}>[^/]+)`;
125
- });
126
- return `^/${regexParts.join('/')}$`;
127
- }
128
- function toRouteHandlerInfo(handler) {
129
- return {
130
- page: handler.filePath,
131
- regex: toRegexFromPattern(handler.pattern),
132
- namedRegex: toRegexFromPattern(handler.pattern),
133
- routeKeys: {},
134
- methods: handler.methods || [],
135
- ...(handler.runtime ? { runtime: handler.runtime } : {}),
136
- };
137
- }
138
- function toRouteInfo(route) {
139
- return {
140
- page: route.pagePath,
141
- regex: toRegexFromPattern(route.pattern),
142
- routeKeys: {},
143
- namedRegex: toRegexFromPattern(route.pattern),
144
- };
145
- }
146
- function generateAppPathRoutesManifest(vistaDir, routes = [], routeHandlers = []) {
147
- const manifest = {};
148
- routes.forEach((route) => {
149
- manifest[route.pattern] = route.pagePath;
150
- });
151
- // A page and a route handler cannot both own a URL. Pages win, so a stray
152
- // `route.ts` next to a `page.tsx` cannot silently take over the route.
153
- routeHandlers.forEach((handler) => {
154
- if (!(handler.pattern in manifest)) {
155
- manifest[handler.pattern] = handler.filePath;
156
- }
157
- });
158
- fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'app-path-routes-manifest.json'), JSON.stringify(manifest, null, 2));
159
- return manifest;
160
- }
161
- function quoteRouteLiteral(route) {
162
- return `'${route.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
163
- }
164
- function writeVistaTypes(vistaDir, routes = []) {
165
- const typesDir = path_1.default.join(vistaDir, 'types');
166
- fs_1.default.mkdirSync(typesDir, { recursive: true });
167
- const uniqueRoutes = [...new Set(routes.filter(Boolean))].sort();
168
- const union = uniqueRoutes.length
169
- ? uniqueRoutes.map((route) => ` | ${quoteRouteLiteral(route)}`).join('\n')
170
- : ' | never';
171
- const source = [
172
- '// Generated by `vista build`. Do not edit.',
173
- '// Mirrors Next.js `.next/types` route unions for editor tooling.',
174
- '',
175
- 'export type VistaAppRoute =',
176
- union,
177
- '',
178
- 'export type VistaRoutePath = VistaAppRoute;',
179
- '',
180
- ].join('\n');
181
- fs_1.default.writeFileSync(path_1.default.join(typesDir, 'routes.d.ts'), source);
182
- fs_1.default.writeFileSync(path_1.default.join(typesDir, 'package.json'), JSON.stringify({ type: 'module' }, null, 2));
183
- }
184
- function writeVistaTrace(vistaDir, fileTrace = {}) {
185
- const payload = {
186
- schemaVersion: 1,
187
- source: 'server/file-trace.json',
188
- generatedAt: fileTrace.generatedAt || new Date().toISOString(),
189
- copiedFiles: Array.isArray(fileTrace.copiedFiles) ? fileTrace.copiedFiles.length : 0,
190
- };
191
- fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'trace'), JSON.stringify(payload, null, 2));
192
- }
193
- function generatePrerenderManifest(vistaDir) {
194
- const manifest = {
195
- version: 1,
196
- routes: {},
197
- dynamicRoutes: {},
198
- notFoundRoutes: [],
199
- preview: {
200
- previewModeId: '',
201
- previewModeSigningKey: '',
202
- previewModeEncryptionKey: '',
203
- },
204
- };
205
- fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'prerender-manifest.json'), JSON.stringify(manifest, null, 2));
206
- }
207
- function generateRequiredServerFilesManifest(cwd, vistaDir, extraFiles = [], appDir = cwd) {
208
- const files = Array.from(new Set([
209
- `${constants_1.BUILD_DIR}/BUILD_ID`,
210
- `${constants_1.BUILD_DIR}/build-manifest.json`,
211
- `${constants_1.BUILD_DIR}/routes-manifest.json`,
212
- `${constants_1.BUILD_DIR}/app-path-routes-manifest.json`,
213
- `${constants_1.BUILD_DIR}/server/server-manifest.json`,
214
- ...extraFiles,
215
- ]));
216
- const manifest = {
217
- version: 1,
218
- config: {},
219
- appDir,
220
- relativeAppDir: path_1.default.relative(cwd, appDir) || '.',
221
- files,
222
- };
223
- fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'required-server-files.json'), JSON.stringify(manifest, null, 2));
224
- }
225
- function ensureJsonFile(vistaDir, relativePath, fallback = {}) {
226
- const absolutePath = path_1.default.join(vistaDir, relativePath);
227
- if (!fs_1.default.existsSync(absolutePath)) {
228
- fs_1.default.writeFileSync(absolutePath, JSON.stringify(fallback, null, 2));
229
- }
230
- }
231
- function writeArtifactManifest(vistaDir, buildId, extraManifestEntries = {}) {
232
- const artifactManifest = {
233
- schemaVersion: 1,
234
- buildId,
235
- generatedAt: new Date().toISOString(),
236
- __integrity: (0, integrity_1.generateBuildWatermark)(),
237
- manifests: {
238
- buildManifest: 'build-manifest.json',
239
- routesManifest: 'routes-manifest.json',
240
- appPathRoutesManifest: 'app-path-routes-manifest.json',
241
- prerenderManifest: 'prerender-manifest.json',
242
- requiredServerFiles: 'required-server-files.json',
243
- reactClientManifest: 'react-client-manifest.json',
244
- reactServerManifest: 'react-server-manifest.json',
245
- ...extraManifestEntries,
246
- },
247
- };
248
- fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'artifact-manifest.json'), JSON.stringify(artifactManifest, null, 2));
249
- return artifactManifest;
250
- }
251
- function writeCanonicalVistaArtifacts(cwd, vistaDir, buildId, routes = [], routeHandlers = []) {
252
- const staticRoutes = routes.filter((route) => route.type === 'static').map(toRouteInfo);
253
- const dynamicRoutes = routes.filter((route) => route.type !== 'static').map(toRouteInfo);
254
- generateBuildManifest(vistaDir, buildId);
255
- generateRoutesManifest(vistaDir, staticRoutes, dynamicRoutes, routeHandlers);
256
- const appPaths = generateAppPathRoutesManifest(vistaDir, routes, routeHandlers);
257
- generatePrerenderManifest(vistaDir);
258
- generateRequiredServerFilesManifest(cwd, vistaDir);
259
- writeVistaTypes(vistaDir, Object.keys(appPaths));
260
- // Keep canonical React manifest filenames present for validation consistency.
261
- ensureJsonFile(vistaDir, 'react-client-manifest.json', {});
262
- ensureJsonFile(vistaDir, 'react-server-manifest.json', {});
263
- return writeArtifactManifest(vistaDir, buildId, {
264
- types: 'types/routes.d.ts',
265
- });
266
- }
267
- function writeReservedVistaArtifacts(vistaDir, options) {
268
- const engineVariant = options.engineVariant || 'default';
269
- const generatedAt = new Date().toISOString();
270
- const cacheDir = path_1.default.join(vistaDir, 'cache');
271
- const imageCacheDir = path_1.default.join(cacheDir, 'images');
272
- const mediaDir = path_1.default.join(vistaDir, 'static', 'media');
273
- fs_1.default.mkdirSync(cacheDir, { recursive: true });
274
- fs_1.default.mkdirSync(imageCacheDir, { recursive: true });
275
- fs_1.default.mkdirSync(mediaDir, { recursive: true });
276
- fs_1.default.writeFileSync(path_1.default.join(cacheDir, 'cache-manifest.json'), JSON.stringify({
277
- schemaVersion: 1,
278
- buildId: options.buildId,
279
- generatedAt,
280
- engine: engineVariant,
281
- activeCacheRoot: engineVariant === 'flashpack' ? '.flash/cache' : '.vista/cache/webpack',
282
- directories: {
283
- localCache: '.vista/cache',
284
- webpack: engineVariant === 'flashpack' ? '.flash/cache/webpack' : '.vista/cache/webpack',
285
- images: '.vista/cache/images',
286
- },
287
- notes: [
288
- engineVariant === 'flashpack'
289
- ? 'Flashpack stores its hot build cache in .flash while .vista/cache keeps framework metadata.'
290
- : 'Default engine stores framework metadata here and may add webpack cache artifacts during rebuilds.',
291
- ],
292
- }, null, 2));
293
- fs_1.default.writeFileSync(path_1.default.join(imageCacheDir, 'manifest.json'), JSON.stringify({
294
- schemaVersion: 1,
295
- buildId: options.buildId,
296
- generatedAt,
297
- endpoint: constants_1.IMAGE_ENDPOINT,
298
- cacheDirectory: '.vista/cache/images',
299
- config: options.imagesConfig || {},
300
- behavior: {
301
- optimization: 'on-demand',
302
- staticImportsEmitInto: '.vista/static/media',
303
- publicReferencesStayIn: 'public/',
304
- },
305
- }, null, 2));
306
- const emittedMedia = fs_1.default
307
- .readdirSync(mediaDir, { withFileTypes: true })
308
- .filter((entry) => entry.isFile() && entry.name !== 'media-manifest.json')
309
- .map((entry) => entry.name)
310
- .sort();
311
- fs_1.default.writeFileSync(path_1.default.join(mediaDir, 'media-manifest.json'), JSON.stringify({
312
- schemaVersion: 1,
313
- buildId: options.buildId,
314
- generatedAt,
315
- mediaDirectory: '.vista/static/media',
316
- emittedFiles: emittedMedia,
317
- note: 'This directory is reserved for emitted media assets. Public file references are served from public/ and may leave this list empty.',
318
- }, null, 2));
319
- }
320
- /**
321
- * Generate routes-manifest.json from route tree.
322
- */
323
- function generateRoutesManifest(vistaDir, staticRoutes = [], dynamicRoutes = [], routeHandlers = []) {
324
- const manifest = {
325
- version: 1,
326
- basePath: '',
327
- redirects: [],
328
- rewrites: [],
329
- headers: [],
330
- staticRoutes,
331
- dynamicRoutes,
332
- routeHandlers: routeHandlers.map(toRouteHandlerInfo),
333
- };
334
- const manifestPath = path_1.default.join(vistaDir, 'routes-manifest.json');
335
- fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
336
- return manifest;
337
- }
338
- /**
339
- * Generate manifest of client components (files with 'use client').
340
- */
341
- function generateClientComponentsManifest(vistaDir, buildId, clientModules = {}) {
342
- const manifest = {
343
- buildId,
344
- clientModules,
345
- };
346
- const manifestPath = path_1.default.join(vistaDir, 'client-components-manifest.json');
347
- fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
348
- return manifest;
349
- }
350
- /**
351
- * Generate manifest of server components.
352
- */
353
- function generateServerComponentsManifest(vistaDir, serverModules = {}) {
354
- const manifest = {
355
- serverModules,
356
- };
357
- const manifestPath = path_1.default.join(vistaDir, 'server', 'server-components-manifest.json');
358
- fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
359
- }
360
- // ============================================================================
361
- // Cache Utilities
362
- // ============================================================================
363
- /**
364
- * Get Webpack cache configuration for persistent caching.
365
- */
366
- function getWebpackCacheConfig(vistaDir, buildId, name, engineVariant = 'default', cwd = process.cwd()) {
367
- const cacheDirectory = engineVariant === 'flashpack'
368
- ? path_1.default.join(cwd, constants_1.FLASH_DIR, 'cache', 'webpack')
369
- : path_1.default.join(vistaDir, 'cache', 'webpack');
370
- return {
371
- type: 'filesystem',
372
- version: buildId,
373
- cacheDirectory,
374
- name: name,
375
- buildDependencies: {
376
- config: [__filename],
377
- },
378
- };
379
- }
380
- /**
381
- * Clean old cache entries (keeps last N builds).
382
- */
383
- function cleanOldCache(vistaDir, keepBuilds = 5) {
384
- const cacheDir = path_1.default.join(vistaDir, 'cache', 'webpack');
385
- if (!fs_1.default.existsSync(cacheDir))
386
- return;
387
- const entries = fs_1.default
388
- .readdirSync(cacheDir)
389
- .map((name) => ({
390
- name,
391
- path: path_1.default.join(cacheDir, name),
392
- stat: fs_1.default.statSync(path_1.default.join(cacheDir, name)),
393
- }))
394
- .filter((e) => e.stat.isDirectory())
395
- .sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
396
- // Remove old cache directories
397
- entries.slice(keepBuilds).forEach((entry) => {
398
- fs_1.default.rmSync(entry.path, { recursive: true, force: true });
399
- });
400
- }
401
- function pruneEmptyVistaDirectories(vistaDir) {
402
- if (!fs_1.default.existsSync(vistaDir))
403
- return;
404
- const prune = (absolutePath) => {
405
- const entries = fs_1.default.readdirSync(absolutePath, { withFileTypes: true });
406
- for (const entry of entries) {
407
- if (!entry.isDirectory())
408
- continue;
409
- const childPath = path_1.default.join(absolutePath, entry.name);
410
- prune(childPath);
411
- }
412
- // Never remove the root .vista directory itself.
413
- if (absolutePath === vistaDir)
414
- return false;
415
- const remaining = fs_1.default.readdirSync(absolutePath);
416
- if (remaining.length === 0) {
417
- fs_1.default.rmdirSync(absolutePath);
418
- return true;
419
- }
420
- return false;
421
- };
422
- prune(vistaDir);
423
- }
1
+ "use strict";
2
+ /**
3
+ * Vista Build Utilities
4
+ *
5
+ * Generates build manifests, BUILD_ID, and manages .vista output structure.
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.generateBuildId = generateBuildId;
12
+ exports.getBuildId = getBuildId;
13
+ exports.createVistaDirectories = createVistaDirectories;
14
+ exports.generateBuildManifest = generateBuildManifest;
15
+ exports.generateAppPathRoutesManifest = generateAppPathRoutesManifest;
16
+ exports.writeVistaTypes = writeVistaTypes;
17
+ exports.writeVistaTrace = writeVistaTrace;
18
+ exports.generatePrerenderManifest = generatePrerenderManifest;
19
+ exports.generateRequiredServerFilesManifest = generateRequiredServerFilesManifest;
20
+ exports.ensureJsonFile = ensureJsonFile;
21
+ exports.writeArtifactManifest = writeArtifactManifest;
22
+ exports.writeCanonicalVistaArtifacts = writeCanonicalVistaArtifacts;
23
+ exports.writeReservedVistaArtifacts = writeReservedVistaArtifacts;
24
+ exports.generateRoutesManifest = generateRoutesManifest;
25
+ exports.generateClientComponentsManifest = generateClientComponentsManifest;
26
+ exports.generateServerComponentsManifest = generateServerComponentsManifest;
27
+ exports.getWebpackCacheConfig = getWebpackCacheConfig;
28
+ exports.cleanOldCache = cleanOldCache;
29
+ exports.pruneEmptyVistaDirectories = pruneEmptyVistaDirectories;
30
+ const fs_1 = __importDefault(require("fs"));
31
+ const path_1 = __importDefault(require("path"));
32
+ const crypto_1 = __importDefault(require("crypto"));
33
+ const constants_1 = require("../constants");
34
+ const integrity_1 = require("../integrity");
35
+ // ============================================================================
36
+ // BUILD_ID Generation
37
+ // ============================================================================
38
+ /**
39
+ * Generate a unique build ID based on timestamp and random bytes.
40
+ */
41
+ function generateBuildId() {
42
+ const timestamp = Date.now().toString(36);
43
+ const random = crypto_1.default.randomBytes(4).toString('hex');
44
+ return `${timestamp}-${random}`;
45
+ }
46
+ /**
47
+ * Read existing BUILD_ID or generate a new one.
48
+ */
49
+ function getBuildId(vistaDir, forceNew = false) {
50
+ const buildIdPath = path_1.default.join(vistaDir, 'BUILD_ID');
51
+ if (!forceNew && fs_1.default.existsSync(buildIdPath)) {
52
+ return fs_1.default.readFileSync(buildIdPath, 'utf-8').trim();
53
+ }
54
+ const buildId = generateBuildId();
55
+ fs_1.default.mkdirSync(vistaDir, { recursive: true });
56
+ fs_1.default.writeFileSync(buildIdPath, buildId);
57
+ return buildId;
58
+ }
59
+ /**
60
+ * Create the .vista directory structure.
61
+ * In legacy mode, only creates root (no empty server/static dirs).
62
+ * In RSC mode, creates the full structure for server/client bundles.
63
+ */
64
+ function createVistaDirectories(cwd, mode = 'legacy') {
65
+ const root = path_1.default.join(cwd, constants_1.BUILD_DIR);
66
+ const dirs = {
67
+ root,
68
+ cache: path_1.default.join(root, 'cache'),
69
+ imageCache: path_1.default.join(root, 'cache', 'images'),
70
+ server: path_1.default.join(root, 'server'),
71
+ static: path_1.default.join(root, 'static'),
72
+ chunks: path_1.default.join(root, 'static', 'chunks'),
73
+ css: path_1.default.join(root, 'static', 'css'),
74
+ media: path_1.default.join(root, 'static', 'media'),
75
+ types: path_1.default.join(root, 'types'),
76
+ };
77
+ // Always create root
78
+ fs_1.default.mkdirSync(root, { recursive: true });
79
+ if (mode === 'rsc') {
80
+ [dirs.root, dirs.cache, dirs.imageCache, dirs.server, dirs.static, dirs.chunks, dirs.media, dirs.types].forEach((dir) => {
81
+ fs_1.default.mkdirSync(dir, { recursive: true });
82
+ });
83
+ }
84
+ // Legacy mode: only root dir is created — webpack outputs directly into .vista/
85
+ return dirs;
86
+ }
87
+ /**
88
+ * Generate build-manifest.json
89
+ */
90
+ function generateBuildManifest(vistaDir, buildId, pages = {}) {
91
+ const manifest = {
92
+ buildId,
93
+ polyfillFiles: [],
94
+ devFiles: [],
95
+ lowPriorityFiles: [],
96
+ rootMainFiles: [`${constants_1.STATIC_CHUNKS_PATH}webpack.js`, `${constants_1.STATIC_CHUNKS_PATH}main.js`],
97
+ pages,
98
+ };
99
+ const manifestPath = path_1.default.join(vistaDir, 'build-manifest.json');
100
+ fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
101
+ return manifest;
102
+ }
103
+ function toRegexFromPattern(pattern) {
104
+ if (pattern === '/') {
105
+ return '^/$';
106
+ }
107
+ const normalized = pattern.startsWith('/') ? pattern.slice(1) : pattern;
108
+ const parts = normalized.split('/').filter(Boolean);
109
+ const regexParts = parts.map((part) => {
110
+ if (!part.startsWith(':')) {
111
+ return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
112
+ }
113
+ const dynamicMatch = /^:([a-zA-Z0-9_]+)(\*)?(\?)?$/.exec(part);
114
+ if (!dynamicMatch) {
115
+ return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
116
+ }
117
+ const [, paramName, isCatchAll, isOptional] = dynamicMatch;
118
+ if (isCatchAll && isOptional) {
119
+ return `(?<${paramName}>.*)`;
120
+ }
121
+ if (isCatchAll) {
122
+ return `(?<${paramName}>.+)`;
123
+ }
124
+ return `(?<${paramName}>[^/]+)`;
125
+ });
126
+ return `^/${regexParts.join('/')}$`;
127
+ }
128
+ function toRouteHandlerInfo(handler) {
129
+ return {
130
+ page: handler.filePath,
131
+ regex: toRegexFromPattern(handler.pattern),
132
+ namedRegex: toRegexFromPattern(handler.pattern),
133
+ routeKeys: {},
134
+ methods: handler.methods || [],
135
+ ...(handler.runtime ? { runtime: handler.runtime } : {}),
136
+ };
137
+ }
138
+ function toRouteInfo(route) {
139
+ return {
140
+ page: route.pagePath,
141
+ regex: toRegexFromPattern(route.pattern),
142
+ routeKeys: {},
143
+ namedRegex: toRegexFromPattern(route.pattern),
144
+ };
145
+ }
146
+ function generateAppPathRoutesManifest(vistaDir, routes = [], routeHandlers = []) {
147
+ const manifest = {};
148
+ routes.forEach((route) => {
149
+ manifest[route.pattern] = route.pagePath;
150
+ });
151
+ // A page and a route handler cannot both own a URL. Pages win, so a stray
152
+ // `route.ts` next to a `page.tsx` cannot silently take over the route.
153
+ routeHandlers.forEach((handler) => {
154
+ if (!(handler.pattern in manifest)) {
155
+ manifest[handler.pattern] = handler.filePath;
156
+ }
157
+ });
158
+ fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'app-path-routes-manifest.json'), JSON.stringify(manifest, null, 2));
159
+ return manifest;
160
+ }
161
+ function quoteRouteLiteral(route) {
162
+ return `'${route.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
163
+ }
164
+ function writeVistaTypes(vistaDir, routes = []) {
165
+ const typesDir = path_1.default.join(vistaDir, 'types');
166
+ fs_1.default.mkdirSync(typesDir, { recursive: true });
167
+ const uniqueRoutes = [...new Set(routes.filter(Boolean))].sort();
168
+ const union = uniqueRoutes.length
169
+ ? uniqueRoutes.map((route) => ` | ${quoteRouteLiteral(route)}`).join('\n')
170
+ : ' | never';
171
+ const source = [
172
+ '// Generated by `vista build`. Do not edit.',
173
+ '// Mirrors Next.js `.next/types` route unions for editor tooling.',
174
+ '',
175
+ 'export type VistaAppRoute =',
176
+ union,
177
+ '',
178
+ 'export type VistaRoutePath = VistaAppRoute;',
179
+ '',
180
+ ].join('\n');
181
+ fs_1.default.writeFileSync(path_1.default.join(typesDir, 'routes.d.ts'), source);
182
+ fs_1.default.writeFileSync(path_1.default.join(typesDir, 'package.json'), JSON.stringify({ type: 'module' }, null, 2));
183
+ }
184
+ function writeVistaTrace(vistaDir, fileTrace = {}) {
185
+ const payload = {
186
+ schemaVersion: 1,
187
+ source: 'server/file-trace.json',
188
+ generatedAt: fileTrace.generatedAt || new Date().toISOString(),
189
+ copiedFiles: Array.isArray(fileTrace.copiedFiles) ? fileTrace.copiedFiles.length : 0,
190
+ };
191
+ fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'trace'), JSON.stringify(payload, null, 2));
192
+ }
193
+ function generatePrerenderManifest(vistaDir) {
194
+ const manifest = {
195
+ version: 1,
196
+ routes: {},
197
+ dynamicRoutes: {},
198
+ notFoundRoutes: [],
199
+ preview: {
200
+ previewModeId: '',
201
+ previewModeSigningKey: '',
202
+ previewModeEncryptionKey: '',
203
+ },
204
+ };
205
+ fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'prerender-manifest.json'), JSON.stringify(manifest, null, 2));
206
+ }
207
+ function generateRequiredServerFilesManifest(cwd, vistaDir, extraFiles = [], appDir = cwd) {
208
+ const files = Array.from(new Set([
209
+ `${constants_1.BUILD_DIR}/BUILD_ID`,
210
+ `${constants_1.BUILD_DIR}/build-manifest.json`,
211
+ `${constants_1.BUILD_DIR}/routes-manifest.json`,
212
+ `${constants_1.BUILD_DIR}/app-path-routes-manifest.json`,
213
+ `${constants_1.BUILD_DIR}/server/server-manifest.json`,
214
+ ...extraFiles,
215
+ ]));
216
+ const manifest = {
217
+ version: 1,
218
+ config: {},
219
+ appDir,
220
+ relativeAppDir: path_1.default.relative(cwd, appDir) || '.',
221
+ files,
222
+ };
223
+ fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'required-server-files.json'), JSON.stringify(manifest, null, 2));
224
+ }
225
+ function ensureJsonFile(vistaDir, relativePath, fallback = {}) {
226
+ const absolutePath = path_1.default.join(vistaDir, relativePath);
227
+ if (!fs_1.default.existsSync(absolutePath)) {
228
+ fs_1.default.writeFileSync(absolutePath, JSON.stringify(fallback, null, 2));
229
+ }
230
+ }
231
+ function writeArtifactManifest(vistaDir, buildId, extraManifestEntries = {}) {
232
+ const artifactManifest = {
233
+ schemaVersion: 1,
234
+ buildId,
235
+ generatedAt: new Date().toISOString(),
236
+ __integrity: (0, integrity_1.generateBuildWatermark)(),
237
+ manifests: {
238
+ buildManifest: 'build-manifest.json',
239
+ routesManifest: 'routes-manifest.json',
240
+ appPathRoutesManifest: 'app-path-routes-manifest.json',
241
+ prerenderManifest: 'prerender-manifest.json',
242
+ requiredServerFiles: 'required-server-files.json',
243
+ reactClientManifest: 'react-client-manifest.json',
244
+ reactServerManifest: 'react-server-manifest.json',
245
+ ...extraManifestEntries,
246
+ },
247
+ };
248
+ fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'artifact-manifest.json'), JSON.stringify(artifactManifest, null, 2));
249
+ return artifactManifest;
250
+ }
251
+ function writeCanonicalVistaArtifacts(cwd, vistaDir, buildId, routes = [], routeHandlers = []) {
252
+ const staticRoutes = routes.filter((route) => route.type === 'static').map(toRouteInfo);
253
+ const dynamicRoutes = routes.filter((route) => route.type !== 'static').map(toRouteInfo);
254
+ generateBuildManifest(vistaDir, buildId);
255
+ generateRoutesManifest(vistaDir, staticRoutes, dynamicRoutes, routeHandlers);
256
+ const appPaths = generateAppPathRoutesManifest(vistaDir, routes, routeHandlers);
257
+ generatePrerenderManifest(vistaDir);
258
+ generateRequiredServerFilesManifest(cwd, vistaDir);
259
+ writeVistaTypes(vistaDir, Object.keys(appPaths));
260
+ // Keep canonical React manifest filenames present for validation consistency.
261
+ ensureJsonFile(vistaDir, 'react-client-manifest.json', {});
262
+ ensureJsonFile(vistaDir, 'react-server-manifest.json', {});
263
+ return writeArtifactManifest(vistaDir, buildId, {
264
+ types: 'types/routes.d.ts',
265
+ });
266
+ }
267
+ function writeReservedVistaArtifacts(vistaDir, options) {
268
+ const engineVariant = options.engineVariant || 'default';
269
+ const generatedAt = new Date().toISOString();
270
+ const cacheDir = path_1.default.join(vistaDir, 'cache');
271
+ const imageCacheDir = path_1.default.join(cacheDir, 'images');
272
+ const mediaDir = path_1.default.join(vistaDir, 'static', 'media');
273
+ fs_1.default.mkdirSync(cacheDir, { recursive: true });
274
+ fs_1.default.mkdirSync(imageCacheDir, { recursive: true });
275
+ fs_1.default.mkdirSync(mediaDir, { recursive: true });
276
+ fs_1.default.writeFileSync(path_1.default.join(cacheDir, 'cache-manifest.json'), JSON.stringify({
277
+ schemaVersion: 1,
278
+ buildId: options.buildId,
279
+ generatedAt,
280
+ engine: engineVariant,
281
+ activeCacheRoot: engineVariant === 'flashpack' ? '.flash/cache' : '.vista/cache/webpack',
282
+ directories: {
283
+ localCache: '.vista/cache',
284
+ webpack: engineVariant === 'flashpack' ? '.flash/cache/webpack' : '.vista/cache/webpack',
285
+ images: '.vista/cache/images',
286
+ },
287
+ notes: [
288
+ engineVariant === 'flashpack'
289
+ ? 'Flashpack stores its hot build cache in .flash while .vista/cache keeps framework metadata.'
290
+ : 'Default engine stores framework metadata here and may add webpack cache artifacts during rebuilds.',
291
+ ],
292
+ }, null, 2));
293
+ fs_1.default.writeFileSync(path_1.default.join(imageCacheDir, 'manifest.json'), JSON.stringify({
294
+ schemaVersion: 1,
295
+ buildId: options.buildId,
296
+ generatedAt,
297
+ endpoint: constants_1.IMAGE_ENDPOINT,
298
+ cacheDirectory: '.vista/cache/images',
299
+ config: options.imagesConfig || {},
300
+ behavior: {
301
+ optimization: 'on-demand',
302
+ staticImportsEmitInto: '.vista/static/media',
303
+ publicReferencesStayIn: 'public/',
304
+ },
305
+ }, null, 2));
306
+ const emittedMedia = fs_1.default
307
+ .readdirSync(mediaDir, { withFileTypes: true })
308
+ .filter((entry) => entry.isFile() && entry.name !== 'media-manifest.json')
309
+ .map((entry) => entry.name)
310
+ .sort();
311
+ fs_1.default.writeFileSync(path_1.default.join(mediaDir, 'media-manifest.json'), JSON.stringify({
312
+ schemaVersion: 1,
313
+ buildId: options.buildId,
314
+ generatedAt,
315
+ mediaDirectory: '.vista/static/media',
316
+ emittedFiles: emittedMedia,
317
+ note: 'This directory is reserved for emitted media assets. Public file references are served from public/ and may leave this list empty.',
318
+ }, null, 2));
319
+ }
320
+ /**
321
+ * Generate routes-manifest.json from route tree.
322
+ */
323
+ function generateRoutesManifest(vistaDir, staticRoutes = [], dynamicRoutes = [], routeHandlers = []) {
324
+ const manifest = {
325
+ version: 1,
326
+ basePath: '',
327
+ redirects: [],
328
+ rewrites: [],
329
+ headers: [],
330
+ staticRoutes,
331
+ dynamicRoutes,
332
+ routeHandlers: routeHandlers.map(toRouteHandlerInfo),
333
+ };
334
+ const manifestPath = path_1.default.join(vistaDir, 'routes-manifest.json');
335
+ fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
336
+ return manifest;
337
+ }
338
+ /**
339
+ * Generate manifest of client components (files with 'use client').
340
+ */
341
+ function generateClientComponentsManifest(vistaDir, buildId, clientModules = {}) {
342
+ const manifest = {
343
+ buildId,
344
+ clientModules,
345
+ };
346
+ const manifestPath = path_1.default.join(vistaDir, 'client-components-manifest.json');
347
+ fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
348
+ return manifest;
349
+ }
350
+ /**
351
+ * Generate manifest of server components.
352
+ */
353
+ function generateServerComponentsManifest(vistaDir, serverModules = {}) {
354
+ const manifest = {
355
+ serverModules,
356
+ };
357
+ const manifestPath = path_1.default.join(vistaDir, 'server', 'server-components-manifest.json');
358
+ fs_1.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
359
+ }
360
+ // ============================================================================
361
+ // Cache Utilities
362
+ // ============================================================================
363
+ /**
364
+ * Get Webpack cache configuration for persistent caching.
365
+ */
366
+ function getWebpackCacheConfig(vistaDir, buildId, name, engineVariant = 'default', cwd = process.cwd()) {
367
+ const cacheDirectory = engineVariant === 'flashpack'
368
+ ? path_1.default.join(cwd, constants_1.FLASH_DIR, 'cache', 'webpack')
369
+ : path_1.default.join(vistaDir, 'cache', 'webpack');
370
+ return {
371
+ type: 'filesystem',
372
+ version: buildId,
373
+ cacheDirectory,
374
+ name: name,
375
+ buildDependencies: {
376
+ config: [__filename],
377
+ },
378
+ };
379
+ }
380
+ /**
381
+ * Clean old cache entries (keeps last N builds).
382
+ */
383
+ function cleanOldCache(vistaDir, keepBuilds = 5) {
384
+ const cacheDir = path_1.default.join(vistaDir, 'cache', 'webpack');
385
+ if (!fs_1.default.existsSync(cacheDir))
386
+ return;
387
+ const entries = fs_1.default
388
+ .readdirSync(cacheDir)
389
+ .map((name) => ({
390
+ name,
391
+ path: path_1.default.join(cacheDir, name),
392
+ stat: fs_1.default.statSync(path_1.default.join(cacheDir, name)),
393
+ }))
394
+ .filter((e) => e.stat.isDirectory())
395
+ .sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
396
+ // Remove old cache directories
397
+ entries.slice(keepBuilds).forEach((entry) => {
398
+ fs_1.default.rmSync(entry.path, { recursive: true, force: true });
399
+ });
400
+ }
401
+ function pruneEmptyVistaDirectories(vistaDir) {
402
+ if (!fs_1.default.existsSync(vistaDir))
403
+ return;
404
+ const prune = (absolutePath) => {
405
+ const entries = fs_1.default.readdirSync(absolutePath, { withFileTypes: true });
406
+ for (const entry of entries) {
407
+ if (!entry.isDirectory())
408
+ continue;
409
+ const childPath = path_1.default.join(absolutePath, entry.name);
410
+ prune(childPath);
411
+ }
412
+ // Never remove the root .vista directory itself.
413
+ if (absolutePath === vistaDir)
414
+ return false;
415
+ const remaining = fs_1.default.readdirSync(absolutePath);
416
+ if (remaining.length === 0) {
417
+ fs_1.default.rmdirSync(absolutePath);
418
+ return true;
419
+ }
420
+ return false;
421
+ };
422
+ prune(vistaDir);
423
+ }