@vistagenic/vista 0.3.2 → 0.3.3

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 (98) 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 +537 -492
  20. package/dist/bin/build.js +355 -353
  21. package/dist/bin/generate.js +513 -510
  22. package/dist/bin/webpack.config.js +4 -3
  23. package/dist/build/manifest.d.ts +169 -169
  24. package/dist/build/manifest.js +423 -423
  25. package/dist/build/rsc/client-manifest.d.ts +62 -62
  26. package/dist/build/rsc/client-manifest.js +295 -295
  27. package/dist/build/rsc/compiler.js +5 -4
  28. package/dist/build/rsc/native-scanner.d.ts +135 -135
  29. package/dist/build/rsc/native-scanner.js +203 -203
  30. package/dist/build/rsc/react-client-reference-manifest.d.ts +28 -28
  31. package/dist/build/rsc/react-client-reference-manifest.js +240 -240
  32. package/dist/build/standalone.js +260 -254
  33. package/dist/client/dynamic.react-server.d.ts +2 -2
  34. package/dist/client/dynamic.react-server.js +23 -23
  35. package/dist/client/link.react-server.d.ts +2 -2
  36. package/dist/client/link.react-server.js +11 -11
  37. package/dist/client/navigation.react-server.d.ts +1 -1
  38. package/dist/client/navigation.react-server.js +17 -17
  39. package/dist/client/router.react-server.d.ts +1 -1
  40. package/dist/client/router.react-server.js +17 -17
  41. package/dist/client/rsc-router.react-server.d.ts +1 -1
  42. package/dist/client/rsc-router.react-server.js +17 -17
  43. package/dist/client/script.react-server.d.ts +2 -2
  44. package/dist/client/script.react-server.js +23 -23
  45. package/dist/config.d.ts +1 -1
  46. package/dist/config.js +1 -7
  47. package/dist/deploy/adapters/cloudflare.js +43 -19
  48. package/dist/deploy/adapters/docker.d.ts +1 -0
  49. package/dist/deploy/adapters/docker.js +5 -4
  50. package/dist/deploy/adapters/netlify.js +62 -17
  51. package/dist/deploy/adapters/vercel.js +80 -50
  52. package/dist/deploy/preflight.js +4 -3
  53. package/dist/deploy/runtime-pack.d.ts +11 -0
  54. package/dist/deploy/runtime-pack.js +300 -0
  55. package/dist/deploy/utils.d.ts +1 -1
  56. package/dist/deploy/utils.js +31 -2
  57. package/dist/flashpack/command.js +1 -0
  58. package/dist/flashpack/runtime.js +2 -1
  59. package/dist/index.d.ts +23 -23
  60. package/dist/index.js +61 -61
  61. package/dist/server/app-dir.d.ts +22 -0
  62. package/dist/server/app-dir.js +77 -0
  63. package/dist/server/cookie-parse.d.ts +4 -4
  64. package/dist/server/cookie-parse.js +14 -14
  65. package/dist/server/engine.js +5 -5
  66. package/dist/server/image-optimizer.js +2 -1
  67. package/dist/server/index.d.ts +109 -109
  68. package/dist/server/index.js +315 -315
  69. package/dist/server/middleware-runner.d.ts +125 -125
  70. package/dist/server/middleware-runner.js +607 -615
  71. package/dist/server/middleware-security.d.ts +36 -36
  72. package/dist/server/middleware-security.js +183 -183
  73. package/dist/server/module-compile-hook.js +695 -695
  74. package/dist/server/root-resolver.js +6 -5
  75. package/dist/server/rsc-engine-flashpack.d.ts +3 -1
  76. package/dist/server/rsc-engine-flashpack.js +12 -1
  77. package/dist/server/rsc-engine.d.ts +6 -1
  78. package/dist/server/rsc-engine.js +203 -219
  79. package/dist/server/rsc-upstream.js +893 -892
  80. package/dist/server/static-generator.js +4 -3
  81. package/dist/server/structure-validator.js +2 -1
  82. package/dist/server/structure-watch.js +2 -0
  83. package/dist/server/typed-api-runtime.js +639 -635
  84. package/dist/server/vista-import-map.js +134 -134
  85. package/dist/stack/index.d.ts +34 -34
  86. package/dist/stack/index.js +49 -49
  87. package/dist/stack/server/caller.d.ts +13 -13
  88. package/dist/stack/server/caller.js +42 -42
  89. package/dist/stack/server/executor.d.ts +40 -40
  90. package/dist/stack/server/executor.js +222 -222
  91. package/dist/stack/server/index.d.ts +11 -11
  92. package/dist/stack/server/index.js +24 -24
  93. package/dist/stack/server/procedure.d.ts +20 -20
  94. package/dist/stack/server/procedure.js +66 -66
  95. package/dist/stack/server/types.d.ts +113 -113
  96. package/dist/theme/react-server.d.ts +10 -10
  97. package/dist/theme/react-server.js +16 -16
  98. package/package.json +1 -1
@@ -1,695 +1,695 @@
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
- exports.installModuleCompileHook = installModuleCompileHook;
7
- const fs_1 = __importDefault(require("fs"));
8
- const path_1 = __importDefault(require("path"));
9
- const core_1 = require("@swc/core");
10
- const url_1 = require("url");
11
- const runtime_actions_1 = require("./runtime-actions");
12
- const cache_1 = require("./cache");
13
- const CjsModule = require('module');
14
- let compileHookInstalled = false;
15
- let originalCompile = null;
16
- let activeCompileRoots = [];
17
- let activeClientModuleProxyFactory = null;
18
- let activeRuntimeActionsSpecifier = require.resolve('./runtime-actions');
19
- let activeCacheRuntimeSpecifier = require.resolve('./cache');
20
- let activeCacheComponentsEnabled = false;
21
- function normalizeModulePath(filePath) {
22
- return filePath.replace(/\\/g, '/').toLowerCase();
23
- }
24
- function stripLeadingCommentsAndWhitespace(source) {
25
- let remaining = source;
26
- while (true) {
27
- const trimmed = remaining.trimStart();
28
- if (trimmed.startsWith('//')) {
29
- const newlineIndex = trimmed.indexOf('\n');
30
- remaining = newlineIndex === -1 ? '' : trimmed.slice(newlineIndex + 1);
31
- continue;
32
- }
33
- if (trimmed.startsWith('/*')) {
34
- const commentEndIndex = trimmed.indexOf('*/');
35
- if (commentEndIndex === -1) {
36
- return trimmed;
37
- }
38
- remaining = trimmed.slice(commentEndIndex + 2);
39
- continue;
40
- }
41
- return trimmed;
42
- }
43
- }
44
- function hasDirective(source, directive) {
45
- const trimmed = stripLeadingCommentsAndWhitespace(source);
46
- return trimmed.startsWith(`'${directive}'`) || trimmed.startsWith(`"${directive}"`);
47
- }
48
- function containsDirectiveLiteral(source, directive) {
49
- return source.includes(`'${directive}'`) || source.includes(`"${directive}"`);
50
- }
51
- function readOriginalSource(filename, fallback) {
52
- try {
53
- return fs_1.default.readFileSync(filename, 'utf-8');
54
- }
55
- catch {
56
- return fallback;
57
- }
58
- }
59
- function createDirectiveError(filename, message) {
60
- return new Error(`[vista:cache] ${path_1.default.basename(filename)}: ${message}`);
61
- }
62
- function isVistaFrameworkModule(filename) {
63
- const normalized = normalizeModulePath(filename);
64
- return (/\/packages\/vista\/(src|dist)\//.test(normalized) ||
65
- /\/node_modules\/vista\//.test(normalized) ||
66
- /\/node_modules\/@vistagenic\/vista\//.test(normalized));
67
- }
68
- function isProjectModule(filename, roots) {
69
- const normalized = normalizeModulePath(filename);
70
- if (!/\.[cm]?[jt]sx?$/i.test(normalized)) {
71
- return false;
72
- }
73
- const matchesRoot = roots.some((root) => {
74
- const rootPrefix = normalizeModulePath(`${root}${path_1.default.sep}`);
75
- return normalized.startsWith(rootPrefix);
76
- });
77
- const isStandaloneProjectModule = roots.some((root) => {
78
- const normalizedRoot = normalizeModulePath(root);
79
- return (normalizedRoot.includes('/.vista/standalone/') &&
80
- (normalized === normalizedRoot || normalized.startsWith(`${normalizedRoot}/`)));
81
- });
82
- if (isVistaFrameworkModule(filename)) {
83
- return true;
84
- }
85
- if (!matchesRoot && !isStandaloneProjectModule)
86
- return false;
87
- if (normalized.includes('/node_modules/'))
88
- return false;
89
- if (normalized.includes('/.vista/') && !isStandaloneProjectModule)
90
- return false;
91
- if (normalized.includes('/.flash/'))
92
- return false;
93
- return true;
94
- }
95
- function isStringDirectiveStatement(statement, directive) {
96
- return (statement?.type === 'ExpressionStatement' &&
97
- (statement.directive === directive ||
98
- (statement.expression?.type === 'StringLiteral' &&
99
- statement.expression?.value === directive)));
100
- }
101
- /**
102
- * SWC labels the body of a function/method/arrow as `FunctionBody`, while a bare
103
- * block (`{ ... }`, loop/if/try bodies) stays `BlockStatement`. Older versions
104
- * reported `BlockStatement` for both, so accept either shape here - otherwise
105
- * every function-body walk silently no-ops and inline `'use server'` /
106
- * `'use cache'` directives never get transformed.
107
- */
108
- function isFunctionBodyBlock(node) {
109
- return node?.type === 'BlockStatement' || node?.type === 'FunctionBody';
110
- }
111
- function hasServerDirectiveInFunctionLike(node) {
112
- return (isFunctionBodyBlock(node?.body) &&
113
- Array.isArray(node.body.stmts) &&
114
- node.body.stmts.length > 0 &&
115
- isStringDirectiveStatement(node.body.stmts[0], 'use server'));
116
- }
117
- function hasCacheDirectiveInFunctionLike(node) {
118
- return (isFunctionBodyBlock(node?.body) &&
119
- Array.isArray(node.body.stmts) &&
120
- node.body.stmts.length > 0 &&
121
- isStringDirectiveStatement(node.body.stmts[0], 'use cache'));
122
- }
123
- function createSpan() {
124
- return { start: 0, end: 0 };
125
- }
126
- function createIdentifier(value) {
127
- return {
128
- type: 'Identifier',
129
- value,
130
- optional: false,
131
- ctxt: 0,
132
- span: createSpan(),
133
- };
134
- }
135
- function createStringLiteral(value) {
136
- return {
137
- type: 'StringLiteral',
138
- value,
139
- raw: JSON.stringify(value),
140
- span: createSpan(),
141
- };
142
- }
143
- function createRuntimeMemberExpression(runtimeIdentifier, propertyName) {
144
- return {
145
- type: 'MemberExpression',
146
- object: createIdentifier(runtimeIdentifier),
147
- property: {
148
- type: 'Identifier',
149
- value: propertyName,
150
- span: createSpan(),
151
- },
152
- span: createSpan(),
153
- };
154
- }
155
- function createRegisterReferenceCall(targetExpression, id, exportName = 'default') {
156
- return {
157
- type: 'CallExpression',
158
- ctxt: 0,
159
- span: createSpan(),
160
- callee: createRuntimeMemberExpression('__vistaServerActionsRuntime', 'registerInlineServerReference'),
161
- arguments: [
162
- { spread: null, expression: targetExpression },
163
- { spread: null, expression: createStringLiteral(id) },
164
- { spread: null, expression: createStringLiteral(exportName) },
165
- ],
166
- typeArguments: null,
167
- };
168
- }
169
- function createRegistrationStatement(identifierName, id, exportName = 'default') {
170
- return {
171
- type: 'ExpressionStatement',
172
- span: createSpan(),
173
- expression: createRegisterReferenceCall(createIdentifier(identifierName), id, exportName),
174
- };
175
- }
176
- function createUseCacheWrapCall(targetExpression, filename, exportName) {
177
- return {
178
- type: 'CallExpression',
179
- ctxt: 0,
180
- span: createSpan(),
181
- callee: createRuntimeMemberExpression('__vistaCacheRuntime', 'wrapModuleUseCacheExport'),
182
- arguments: [
183
- { spread: null, expression: targetExpression },
184
- { spread: null, expression: createStringLiteral(filename) },
185
- { spread: null, expression: createStringLiteral(exportName) },
186
- ],
187
- typeArguments: null,
188
- };
189
- }
190
- function createUseCacheAssignmentStatement(identifierName, filename, exportName) {
191
- return {
192
- type: 'ExpressionStatement',
193
- span: createSpan(),
194
- expression: {
195
- type: 'AssignmentExpression',
196
- span: createSpan(),
197
- operator: '=',
198
- left: createIdentifier(identifierName),
199
- right: createUseCacheWrapCall(createIdentifier(identifierName), filename, exportName),
200
- },
201
- };
202
- }
203
- function createRuntimeRequireDeclaration(runtimeIdentifier, runtimeSpecifier) {
204
- return {
205
- type: 'VariableDeclaration',
206
- span: createSpan(),
207
- ctxt: 0,
208
- kind: 'const',
209
- declare: false,
210
- declarations: [
211
- {
212
- type: 'VariableDeclarator',
213
- span: createSpan(),
214
- definite: false,
215
- id: {
216
- ...createIdentifier(runtimeIdentifier),
217
- typeAnnotation: null,
218
- },
219
- init: {
220
- type: 'CallExpression',
221
- ctxt: 0,
222
- span: createSpan(),
223
- callee: createIdentifier('require'),
224
- arguments: [
225
- {
226
- spread: null,
227
- expression: createStringLiteral(runtimeSpecifier),
228
- },
229
- ],
230
- typeArguments: null,
231
- },
232
- },
233
- ],
234
- };
235
- }
236
- function processFunctionLikeDeclaration(statement, filename, state, nextStatements) {
237
- if (!isFunctionBodyBlock(statement?.body)) {
238
- // Bodyless declarations (TS overload signatures, `declare function`) still
239
- // have to survive into the emitted module.
240
- nextStatements.push(statement);
241
- return false;
242
- }
243
- statement.body.stmts = processStatementList(statement.body.stmts || [], filename, state);
244
- nextStatements.push(statement);
245
- const identifierName = statement.identifier?.value;
246
- if (identifierName && hasServerDirectiveInFunctionLike(statement)) {
247
- const actionId = (0, runtime_actions_1.createInlineServerActionId)(filename, state.nextOrdinal++, identifierName);
248
- nextStatements.push(createRegistrationStatement(identifierName, actionId, identifierName));
249
- state.serverActionsTransformed = true;
250
- }
251
- if (identifierName && hasCacheDirectiveInFunctionLike(statement)) {
252
- nextStatements.push(createUseCacheAssignmentStatement(identifierName, filename, identifierName));
253
- state.useCacheTransformed = true;
254
- }
255
- return true;
256
- }
257
- function processStatementList(statements, filename, state) {
258
- const nextStatements = [];
259
- for (const statement of statements) {
260
- if (!statement || typeof statement !== 'object') {
261
- nextStatements.push(statement);
262
- continue;
263
- }
264
- if (statement.type === 'FunctionDeclaration') {
265
- processFunctionLikeDeclaration(statement, filename, state, nextStatements);
266
- continue;
267
- }
268
- if (statement.type === 'ExportDefaultDeclaration' && statement.decl) {
269
- if (isFunctionBodyBlock(statement.decl.body)) {
270
- statement.decl.body.stmts = processStatementList(statement.decl.body.stmts || [], filename, state);
271
- }
272
- else if ((statement.decl.type === 'FunctionExpression' || statement.decl.type === 'ArrowFunctionExpression') &&
273
- isFunctionBodyBlock(statement.decl.body)) {
274
- statement.decl.body.stmts = processStatementList(statement.decl.body.stmts || [], filename, state);
275
- }
276
- if ((statement.decl.type === 'FunctionDeclaration' ||
277
- statement.decl.type === 'FunctionExpression' ||
278
- statement.decl.type === 'ArrowFunctionExpression') &&
279
- hasCacheDirectiveInFunctionLike(statement.decl)) {
280
- statement.decl = createUseCacheWrapCall(statement.decl, filename, statement.decl.identifier?.value || 'default');
281
- state.useCacheTransformed = true;
282
- }
283
- nextStatements.push(statement);
284
- continue;
285
- }
286
- if (statement.type === 'ExportDeclaration' && statement.declaration) {
287
- if (statement.declaration.type === 'FunctionDeclaration') {
288
- statement.declaration.body.stmts = processStatementList(statement.declaration.body?.stmts || [], filename, state);
289
- const identifierName = statement.declaration.identifier?.value;
290
- nextStatements.push(statement);
291
- if (identifierName && hasServerDirectiveInFunctionLike(statement.declaration)) {
292
- const actionId = (0, runtime_actions_1.createInlineServerActionId)(filename, state.nextOrdinal++, identifierName);
293
- nextStatements.push(createRegistrationStatement(identifierName, actionId, identifierName));
294
- state.serverActionsTransformed = true;
295
- }
296
- if (identifierName && hasCacheDirectiveInFunctionLike(statement.declaration)) {
297
- nextStatements.push(createUseCacheAssignmentStatement(identifierName, filename, identifierName));
298
- state.useCacheTransformed = true;
299
- }
300
- continue;
301
- }
302
- else if (statement.declaration.type === 'VariableDeclaration' &&
303
- Array.isArray(statement.declaration.declarations)) {
304
- for (const declaration of statement.declaration.declarations) {
305
- if (!declaration?.init || typeof declaration.init !== 'object') {
306
- continue;
307
- }
308
- const declaratorName = declaration.id?.type === 'Identifier'
309
- ? declaration.id.value
310
- : `anonymous_${state.nextOrdinal}`;
311
- declaration.init = processExpression(declaration.init, filename, state, declaratorName);
312
- }
313
- }
314
- nextStatements.push(statement);
315
- continue;
316
- }
317
- if (statement.type === 'VariableDeclaration' && Array.isArray(statement.declarations)) {
318
- for (const declaration of statement.declarations) {
319
- if (!declaration?.init || typeof declaration.init !== 'object') {
320
- continue;
321
- }
322
- const declaratorName = declaration.id?.type === 'Identifier'
323
- ? declaration.id.value
324
- : `anonymous_${state.nextOrdinal}`;
325
- declaration.init = processExpression(declaration.init, filename, state, declaratorName);
326
- }
327
- nextStatements.push(statement);
328
- continue;
329
- }
330
- if (statement.type === 'ExpressionStatement' && statement.expression) {
331
- statement.expression = processExpression(statement.expression, filename, state);
332
- nextStatements.push(statement);
333
- continue;
334
- }
335
- if (statement.type === 'ReturnStatement' && statement.argument) {
336
- statement.argument = processExpression(statement.argument, filename, state);
337
- nextStatements.push(statement);
338
- continue;
339
- }
340
- if (statement.type === 'BlockStatement') {
341
- statement.stmts = processStatementList(statement.stmts || [], filename, state);
342
- nextStatements.push(statement);
343
- continue;
344
- }
345
- if (statement.type === 'IfStatement') {
346
- if (statement.consequent?.type === 'BlockStatement') {
347
- statement.consequent.stmts = processStatementList(statement.consequent.stmts || [], filename, state);
348
- }
349
- if (statement.alternate?.type === 'BlockStatement') {
350
- statement.alternate.stmts = processStatementList(statement.alternate.stmts || [], filename, state);
351
- }
352
- nextStatements.push(statement);
353
- continue;
354
- }
355
- if (statement.type === 'TryStatement') {
356
- if (statement.block?.type === 'BlockStatement') {
357
- statement.block.stmts = processStatementList(statement.block.stmts || [], filename, state);
358
- }
359
- if (statement.handler?.body?.type === 'BlockStatement') {
360
- statement.handler.body.stmts = processStatementList(statement.handler.body.stmts || [], filename, state);
361
- }
362
- if (statement.finalizer?.type === 'BlockStatement') {
363
- statement.finalizer.stmts = processStatementList(statement.finalizer.stmts || [], filename, state);
364
- }
365
- nextStatements.push(statement);
366
- continue;
367
- }
368
- if (statement.type === 'SwitchStatement' && Array.isArray(statement.cases)) {
369
- for (const switchCase of statement.cases) {
370
- switchCase.consequent = processStatementList(switchCase.consequent || [], filename, state);
371
- }
372
- nextStatements.push(statement);
373
- continue;
374
- }
375
- if ((statement.type === 'WhileStatement' ||
376
- statement.type === 'DoWhileStatement' ||
377
- statement.type === 'ForStatement' ||
378
- statement.type === 'ForInStatement' ||
379
- statement.type === 'ForOfStatement') &&
380
- statement.body?.type === 'BlockStatement') {
381
- statement.body.stmts = processStatementList(statement.body.stmts || [], filename, state);
382
- nextStatements.push(statement);
383
- continue;
384
- }
385
- nextStatements.push(statement);
386
- }
387
- return nextStatements;
388
- }
389
- function processExpression(expression, filename, state, hint = 'action') {
390
- if (!expression || typeof expression !== 'object') {
391
- return expression;
392
- }
393
- if (expression.type === 'ArrowFunctionExpression' || expression.type === 'FunctionExpression') {
394
- if (isFunctionBodyBlock(expression.body)) {
395
- expression.body.stmts = processStatementList(expression.body.stmts || [], filename, state);
396
- }
397
- if (hasServerDirectiveInFunctionLike(expression)) {
398
- const actionId = (0, runtime_actions_1.createInlineServerActionId)(filename, state.nextOrdinal++, expression.identifier?.value || hint);
399
- state.serverActionsTransformed = true;
400
- return createRegisterReferenceCall(expression, actionId, expression.identifier?.value || hint);
401
- }
402
- if (hasCacheDirectiveInFunctionLike(expression)) {
403
- state.useCacheTransformed = true;
404
- return createUseCacheWrapCall(expression, filename, expression.identifier?.value || hint);
405
- }
406
- return expression;
407
- }
408
- if (expression.type === 'AssignmentExpression') {
409
- expression.left = processExpression(expression.left, filename, state, `${hint}_target`);
410
- expression.right = processExpression(expression.right, filename, state, hint);
411
- return expression;
412
- }
413
- if (expression.type === 'CallExpression') {
414
- expression.callee = processExpression(expression.callee, filename, state, `${hint}_callee`);
415
- expression.arguments = (expression.arguments || []).map((argument, index) => argument && argument.expression
416
- ? {
417
- ...argument,
418
- expression: processExpression(argument.expression, filename, state, `${hint}_${index}`),
419
- }
420
- : argument);
421
- return expression;
422
- }
423
- if (expression.type === 'NewExpression') {
424
- expression.callee = processExpression(expression.callee, filename, state, `${hint}_callee`);
425
- expression.arguments = (expression.arguments || []).map((argument, index) => argument && argument.expression
426
- ? {
427
- ...argument,
428
- expression: processExpression(argument.expression, filename, state, `${hint}_${index}`),
429
- }
430
- : argument);
431
- return expression;
432
- }
433
- if (expression.type === 'ArrayExpression') {
434
- expression.elements = (expression.elements || []).map((element, index) => element && element.expression
435
- ? {
436
- ...element,
437
- expression: processExpression(element.expression, filename, state, `${hint}_${index}`),
438
- }
439
- : element);
440
- return expression;
441
- }
442
- if (expression.type === 'MemberExpression') {
443
- expression.object = processExpression(expression.object, filename, state, `${hint}_object`);
444
- if (expression.property && expression.computed) {
445
- expression.property = processExpression(expression.property, filename, state, `${hint}_property`);
446
- }
447
- return expression;
448
- }
449
- if (expression.type === 'ObjectExpression') {
450
- expression.properties = (expression.properties || []).map((property) => {
451
- if (property?.type === 'KeyValueProperty') {
452
- property.value = processExpression(property.value, filename, state, property.key?.value || property.key?.name || hint);
453
- }
454
- return property;
455
- });
456
- return expression;
457
- }
458
- if (expression.type === 'ObjectPattern') {
459
- expression.properties = (expression.properties || []).map((property) => {
460
- if (property?.type === 'KeyValuePatternProperty' && property.value) {
461
- property.value = processExpression(property.value, filename, state, hint);
462
- }
463
- if (property?.type === 'AssignmentPatternProperty' && property.value) {
464
- property.value = processExpression(property.value, filename, state, hint);
465
- }
466
- return property;
467
- });
468
- return expression;
469
- }
470
- if (expression.type === 'ConditionalExpression') {
471
- expression.test = processExpression(expression.test, filename, state, hint);
472
- expression.consequent = processExpression(expression.consequent, filename, state, hint);
473
- expression.alternate = processExpression(expression.alternate, filename, state, hint);
474
- return expression;
475
- }
476
- if (expression.type === 'SequenceExpression') {
477
- expression.expressions = (expression.expressions || []).map((entry, index) => processExpression(entry, filename, state, `${hint}_${index}`));
478
- return expression;
479
- }
480
- if (expression.type === 'BinaryExpression' ||
481
- expression.type === 'LogicalExpression' ||
482
- expression.type === 'AssignmentPattern') {
483
- expression.left = processExpression(expression.left, filename, state, `${hint}_left`);
484
- expression.right = processExpression(expression.right, filename, state, `${hint}_right`);
485
- return expression;
486
- }
487
- if (expression.type === 'UnaryExpression' || expression.type === 'UpdateExpression') {
488
- expression.argument = processExpression(expression.argument, filename, state, hint);
489
- return expression;
490
- }
491
- if (expression.type === 'AwaitExpression' || expression.type === 'SpreadElement') {
492
- expression.argument = processExpression(expression.argument, filename, state, hint);
493
- return expression;
494
- }
495
- if (expression.type === 'YieldExpression') {
496
- if (expression.argument) {
497
- expression.argument = processExpression(expression.argument, filename, state, hint);
498
- }
499
- return expression;
500
- }
501
- if (expression.type === 'ParenExpression') {
502
- expression.expression = processExpression(expression.expression, filename, state, hint);
503
- return expression;
504
- }
505
- if (expression.type === 'TemplateLiteral') {
506
- expression.expressions = (expression.expressions || []).map((entry, index) => processExpression(entry, filename, state, `${hint}_${index}`));
507
- return expression;
508
- }
509
- if (expression.type === 'TaggedTemplateExpression') {
510
- expression.tag = processExpression(expression.tag, filename, state, `${hint}_tag`);
511
- expression.template = processExpression(expression.template, filename, state, `${hint}_template`);
512
- return expression;
513
- }
514
- return expression;
515
- }
516
- function injectRuntimeRequire(moduleAst, runtimeIdentifier, runtimeSpecifier) {
517
- const body = Array.isArray(moduleAst.body) ? moduleAst.body : [];
518
- let insertionIndex = 0;
519
- while (insertionIndex < body.length && isStringDirectiveStatement(body[insertionIndex], 'use strict')) {
520
- insertionIndex += 1;
521
- }
522
- body.splice(insertionIndex, 0, createRuntimeRequireDeclaration(runtimeIdentifier, runtimeSpecifier));
523
- moduleAst.body = body;
524
- }
525
- function getParserOptions(filename) {
526
- const extension = path_1.default.extname(filename).toLowerCase();
527
- const isTypeScript = extension === '.ts' || extension === '.tsx' || extension === '.mts' || extension === '.cts';
528
- const jsxEnabled = isTypeScript ? extension === '.tsx' : true;
529
- return {
530
- syntax: isTypeScript ? 'typescript' : 'ecmascript',
531
- tsx: isTypeScript ? jsxEnabled : undefined,
532
- jsx: !isTypeScript ? jsxEnabled : undefined,
533
- };
534
- }
535
- function transformInlineServerActions(content, filename) {
536
- if ((!content.includes("'use server'") && !content.includes('"use server"')) &&
537
- (!content.includes("'use cache'") && !content.includes('"use cache"'))) {
538
- return content;
539
- }
540
- try {
541
- const moduleAst = (0, core_1.parseSync)(content, getParserOptions(filename));
542
- const state = {
543
- serverActionsTransformed: false,
544
- useCacheTransformed: false,
545
- nextOrdinal: 0,
546
- };
547
- moduleAst.body = processStatementList(moduleAst.body || [], filename, state);
548
- if (!state.serverActionsTransformed && !state.useCacheTransformed) {
549
- return content;
550
- }
551
- if (state.serverActionsTransformed) {
552
- injectRuntimeRequire(moduleAst, '__vistaServerActionsRuntime', activeRuntimeActionsSpecifier);
553
- }
554
- if (state.useCacheTransformed) {
555
- injectRuntimeRequire(moduleAst, '__vistaCacheRuntime', activeCacheRuntimeSpecifier);
556
- }
557
- return (0, core_1.printSync)(moduleAst).code;
558
- }
559
- catch (error) {
560
- if (process.env.VISTA_DEBUG) {
561
- console.error(`[vista:compile] Inline action transform failed for ${filename}:`, error);
562
- }
563
- return content;
564
- }
565
- }
566
- function wrapUseCacheModuleExports(moduleExports, filename) {
567
- if (typeof moduleExports === 'function') {
568
- const wrappedDefault = (0, cache_1.wrapModuleUseCacheExport)(moduleExports, filename, 'default');
569
- for (const propertyName of Reflect.ownKeys(moduleExports)) {
570
- if (propertyName === 'default' ||
571
- propertyName === 'length' ||
572
- propertyName === 'name' ||
573
- propertyName === 'prototype') {
574
- continue;
575
- }
576
- const descriptor = Object.getOwnPropertyDescriptor(moduleExports, propertyName);
577
- const currentValue = descriptor && 'value' in descriptor
578
- ? descriptor.value
579
- : descriptor?.get
580
- ? descriptor.get.call(moduleExports)
581
- : moduleExports[propertyName];
582
- Object.defineProperty(wrappedDefault, propertyName, {
583
- configurable: true,
584
- enumerable: descriptor?.enumerable ?? true,
585
- writable: true,
586
- value: (0, cache_1.wrapModuleUseCacheExport)(currentValue, filename, String(propertyName)),
587
- });
588
- }
589
- return wrappedDefault;
590
- }
591
- if (!moduleExports || typeof moduleExports !== 'object') {
592
- return moduleExports;
593
- }
594
- const wrappedExports = Object.create(Object.getPrototypeOf(moduleExports));
595
- for (const exportName of Reflect.ownKeys(moduleExports)) {
596
- const descriptor = Object.getOwnPropertyDescriptor(moduleExports, exportName);
597
- if (!descriptor) {
598
- continue;
599
- }
600
- if (exportName === '__esModule') {
601
- Object.defineProperty(wrappedExports, exportName, descriptor);
602
- continue;
603
- }
604
- const currentValue = 'value' in descriptor
605
- ? descriptor.value
606
- : descriptor.get
607
- ? descriptor.get.call(moduleExports)
608
- : moduleExports[exportName];
609
- Object.defineProperty(wrappedExports, exportName, {
610
- configurable: true,
611
- enumerable: descriptor.enumerable ?? true,
612
- writable: true,
613
- value: (0, cache_1.wrapModuleUseCacheExport)(currentValue, filename, String(exportName)),
614
- });
615
- }
616
- return wrappedExports;
617
- }
618
- function transpileProjectSource(source, filename, fallback) {
619
- try {
620
- return (0, core_1.transformSync)(source, {
621
- filename,
622
- sourceMaps: 'inline',
623
- module: {
624
- type: 'commonjs',
625
- },
626
- jsc: {
627
- target: 'es2020',
628
- parser: getParserOptions(filename),
629
- transform: {
630
- react: {
631
- runtime: 'automatic',
632
- },
633
- },
634
- },
635
- }).code;
636
- }
637
- catch (error) {
638
- if (process.env.VISTA_DEBUG) {
639
- console.error(`[vista:compile] Source transpile failed for ${filename}:`, error);
640
- }
641
- return fallback;
642
- }
643
- }
644
- function installModuleCompileHook(options) {
645
- const vistaRuntimeDir = path_1.default.resolve(__dirname, '..');
646
- const vistaPackageRoot = path_1.default.resolve(__dirname, '..', '..');
647
- activeCompileRoots = Array.from(new Set([
648
- options.cwd,
649
- vistaRuntimeDir,
650
- vistaPackageRoot,
651
- path_1.default.join(vistaPackageRoot, 'src'),
652
- path_1.default.join(vistaPackageRoot, 'dist'),
653
- ].map((entry) => path_1.default.resolve(entry))));
654
- activeRuntimeActionsSpecifier = require.resolve('./runtime-actions');
655
- activeCacheRuntimeSpecifier = require.resolve('./cache');
656
- activeCacheComponentsEnabled = Boolean(options.cacheComponentsEnabled);
657
- if (options.createClientModuleProxy) {
658
- activeClientModuleProxyFactory = options.createClientModuleProxy;
659
- }
660
- if (compileHookInstalled) {
661
- return;
662
- }
663
- originalCompile = CjsModule.prototype._compile;
664
- CjsModule.prototype._compile = function compileVistaModule(content, filename) {
665
- if (!isProjectModule(filename, activeCompileRoots)) {
666
- return originalCompile.call(this, content, filename);
667
- }
668
- const originalSource = readOriginalSource(filename, content);
669
- const containsUseCacheDirective = containsDirectiveLiteral(originalSource, 'use cache');
670
- const hasTopLevelUseCacheDirective = hasDirective(originalSource, 'use cache');
671
- if (containsUseCacheDirective && !activeCacheComponentsEnabled) {
672
- throw createDirectiveError(filename, 'To use "use cache", enable experimental.cacheComponents.enabled in vista.config.*.');
673
- }
674
- if (containsUseCacheDirective && hasDirective(originalSource, 'use client')) {
675
- throw createDirectiveError(filename, '"use cache" cannot be used in a Client Component. Move the cached logic to a server-only module.');
676
- }
677
- if (activeClientModuleProxyFactory && hasDirective(originalSource, 'use client')) {
678
- const moduleId = (0, url_1.pathToFileURL)(filename).href;
679
- this.exports = activeClientModuleProxyFactory(moduleId);
680
- return;
681
- }
682
- const sourceToCompile = originalSource || content;
683
- const transformedSource = transformInlineServerActions(sourceToCompile, filename);
684
- const compiledContent = transpileProjectSource(transformedSource, filename, content);
685
- const compileResult = originalCompile.call(this, compiledContent, filename);
686
- if (hasDirective(originalSource, 'use server')) {
687
- (0, runtime_actions_1.registerServerActionModule)(this.exports, filename);
688
- }
689
- if (hasTopLevelUseCacheDirective) {
690
- this.exports = wrapUseCacheModuleExports(this.exports, filename);
691
- }
692
- return compileResult;
693
- };
694
- compileHookInstalled = true;
695
- }
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
+ exports.installModuleCompileHook = installModuleCompileHook;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const core_1 = require("@swc/core");
10
+ const url_1 = require("url");
11
+ const runtime_actions_1 = require("./runtime-actions");
12
+ const cache_1 = require("./cache");
13
+ const CjsModule = require('module');
14
+ let compileHookInstalled = false;
15
+ let originalCompile = null;
16
+ let activeCompileRoots = [];
17
+ let activeClientModuleProxyFactory = null;
18
+ let activeRuntimeActionsSpecifier = require.resolve('./runtime-actions');
19
+ let activeCacheRuntimeSpecifier = require.resolve('./cache');
20
+ let activeCacheComponentsEnabled = false;
21
+ function normalizeModulePath(filePath) {
22
+ return filePath.replace(/\\/g, '/').toLowerCase();
23
+ }
24
+ function stripLeadingCommentsAndWhitespace(source) {
25
+ let remaining = source;
26
+ while (true) {
27
+ const trimmed = remaining.trimStart();
28
+ if (trimmed.startsWith('//')) {
29
+ const newlineIndex = trimmed.indexOf('\n');
30
+ remaining = newlineIndex === -1 ? '' : trimmed.slice(newlineIndex + 1);
31
+ continue;
32
+ }
33
+ if (trimmed.startsWith('/*')) {
34
+ const commentEndIndex = trimmed.indexOf('*/');
35
+ if (commentEndIndex === -1) {
36
+ return trimmed;
37
+ }
38
+ remaining = trimmed.slice(commentEndIndex + 2);
39
+ continue;
40
+ }
41
+ return trimmed;
42
+ }
43
+ }
44
+ function hasDirective(source, directive) {
45
+ const trimmed = stripLeadingCommentsAndWhitespace(source);
46
+ return trimmed.startsWith(`'${directive}'`) || trimmed.startsWith(`"${directive}"`);
47
+ }
48
+ function containsDirectiveLiteral(source, directive) {
49
+ return source.includes(`'${directive}'`) || source.includes(`"${directive}"`);
50
+ }
51
+ function readOriginalSource(filename, fallback) {
52
+ try {
53
+ return fs_1.default.readFileSync(filename, 'utf-8');
54
+ }
55
+ catch {
56
+ return fallback;
57
+ }
58
+ }
59
+ function createDirectiveError(filename, message) {
60
+ return new Error(`[vista:cache] ${path_1.default.basename(filename)}: ${message}`);
61
+ }
62
+ function isVistaFrameworkModule(filename) {
63
+ const normalized = normalizeModulePath(filename);
64
+ return (/\/packages\/vista\/(src|dist)\//.test(normalized) ||
65
+ /\/node_modules\/vista\//.test(normalized) ||
66
+ /\/node_modules\/@vistagenic\/vista\//.test(normalized));
67
+ }
68
+ function isProjectModule(filename, roots) {
69
+ const normalized = normalizeModulePath(filename);
70
+ if (!/\.[cm]?[jt]sx?$/i.test(normalized)) {
71
+ return false;
72
+ }
73
+ const matchesRoot = roots.some((root) => {
74
+ const rootPrefix = normalizeModulePath(`${root}${path_1.default.sep}`);
75
+ return normalized.startsWith(rootPrefix);
76
+ });
77
+ const isStandaloneProjectModule = roots.some((root) => {
78
+ const normalizedRoot = normalizeModulePath(root);
79
+ return (normalizedRoot.includes('/.vista/standalone/') &&
80
+ (normalized === normalizedRoot || normalized.startsWith(`${normalizedRoot}/`)));
81
+ });
82
+ if (isVistaFrameworkModule(filename)) {
83
+ return true;
84
+ }
85
+ if (!matchesRoot && !isStandaloneProjectModule)
86
+ return false;
87
+ if (normalized.includes('/node_modules/'))
88
+ return false;
89
+ if (normalized.includes('/.vista/') && !isStandaloneProjectModule)
90
+ return false;
91
+ if (normalized.includes('/.flash/'))
92
+ return false;
93
+ return true;
94
+ }
95
+ function isStringDirectiveStatement(statement, directive) {
96
+ return (statement?.type === 'ExpressionStatement' &&
97
+ (statement.directive === directive ||
98
+ (statement.expression?.type === 'StringLiteral' &&
99
+ statement.expression?.value === directive)));
100
+ }
101
+ /**
102
+ * SWC labels the body of a function/method/arrow as `FunctionBody`, while a bare
103
+ * block (`{ ... }`, loop/if/try bodies) stays `BlockStatement`. Older versions
104
+ * reported `BlockStatement` for both, so accept either shape here - otherwise
105
+ * every function-body walk silently no-ops and inline `'use server'` /
106
+ * `'use cache'` directives never get transformed.
107
+ */
108
+ function isFunctionBodyBlock(node) {
109
+ return node?.type === 'BlockStatement' || node?.type === 'FunctionBody';
110
+ }
111
+ function hasServerDirectiveInFunctionLike(node) {
112
+ return (isFunctionBodyBlock(node?.body) &&
113
+ Array.isArray(node.body.stmts) &&
114
+ node.body.stmts.length > 0 &&
115
+ isStringDirectiveStatement(node.body.stmts[0], 'use server'));
116
+ }
117
+ function hasCacheDirectiveInFunctionLike(node) {
118
+ return (isFunctionBodyBlock(node?.body) &&
119
+ Array.isArray(node.body.stmts) &&
120
+ node.body.stmts.length > 0 &&
121
+ isStringDirectiveStatement(node.body.stmts[0], 'use cache'));
122
+ }
123
+ function createSpan() {
124
+ return { start: 0, end: 0 };
125
+ }
126
+ function createIdentifier(value) {
127
+ return {
128
+ type: 'Identifier',
129
+ value,
130
+ optional: false,
131
+ ctxt: 0,
132
+ span: createSpan(),
133
+ };
134
+ }
135
+ function createStringLiteral(value) {
136
+ return {
137
+ type: 'StringLiteral',
138
+ value,
139
+ raw: JSON.stringify(value),
140
+ span: createSpan(),
141
+ };
142
+ }
143
+ function createRuntimeMemberExpression(runtimeIdentifier, propertyName) {
144
+ return {
145
+ type: 'MemberExpression',
146
+ object: createIdentifier(runtimeIdentifier),
147
+ property: {
148
+ type: 'Identifier',
149
+ value: propertyName,
150
+ span: createSpan(),
151
+ },
152
+ span: createSpan(),
153
+ };
154
+ }
155
+ function createRegisterReferenceCall(targetExpression, id, exportName = 'default') {
156
+ return {
157
+ type: 'CallExpression',
158
+ ctxt: 0,
159
+ span: createSpan(),
160
+ callee: createRuntimeMemberExpression('__vistaServerActionsRuntime', 'registerInlineServerReference'),
161
+ arguments: [
162
+ { spread: null, expression: targetExpression },
163
+ { spread: null, expression: createStringLiteral(id) },
164
+ { spread: null, expression: createStringLiteral(exportName) },
165
+ ],
166
+ typeArguments: null,
167
+ };
168
+ }
169
+ function createRegistrationStatement(identifierName, id, exportName = 'default') {
170
+ return {
171
+ type: 'ExpressionStatement',
172
+ span: createSpan(),
173
+ expression: createRegisterReferenceCall(createIdentifier(identifierName), id, exportName),
174
+ };
175
+ }
176
+ function createUseCacheWrapCall(targetExpression, filename, exportName) {
177
+ return {
178
+ type: 'CallExpression',
179
+ ctxt: 0,
180
+ span: createSpan(),
181
+ callee: createRuntimeMemberExpression('__vistaCacheRuntime', 'wrapModuleUseCacheExport'),
182
+ arguments: [
183
+ { spread: null, expression: targetExpression },
184
+ { spread: null, expression: createStringLiteral(filename) },
185
+ { spread: null, expression: createStringLiteral(exportName) },
186
+ ],
187
+ typeArguments: null,
188
+ };
189
+ }
190
+ function createUseCacheAssignmentStatement(identifierName, filename, exportName) {
191
+ return {
192
+ type: 'ExpressionStatement',
193
+ span: createSpan(),
194
+ expression: {
195
+ type: 'AssignmentExpression',
196
+ span: createSpan(),
197
+ operator: '=',
198
+ left: createIdentifier(identifierName),
199
+ right: createUseCacheWrapCall(createIdentifier(identifierName), filename, exportName),
200
+ },
201
+ };
202
+ }
203
+ function createRuntimeRequireDeclaration(runtimeIdentifier, runtimeSpecifier) {
204
+ return {
205
+ type: 'VariableDeclaration',
206
+ span: createSpan(),
207
+ ctxt: 0,
208
+ kind: 'const',
209
+ declare: false,
210
+ declarations: [
211
+ {
212
+ type: 'VariableDeclarator',
213
+ span: createSpan(),
214
+ definite: false,
215
+ id: {
216
+ ...createIdentifier(runtimeIdentifier),
217
+ typeAnnotation: null,
218
+ },
219
+ init: {
220
+ type: 'CallExpression',
221
+ ctxt: 0,
222
+ span: createSpan(),
223
+ callee: createIdentifier('require'),
224
+ arguments: [
225
+ {
226
+ spread: null,
227
+ expression: createStringLiteral(runtimeSpecifier),
228
+ },
229
+ ],
230
+ typeArguments: null,
231
+ },
232
+ },
233
+ ],
234
+ };
235
+ }
236
+ function processFunctionLikeDeclaration(statement, filename, state, nextStatements) {
237
+ if (!isFunctionBodyBlock(statement?.body)) {
238
+ // Bodyless declarations (TS overload signatures, `declare function`) still
239
+ // have to survive into the emitted module.
240
+ nextStatements.push(statement);
241
+ return false;
242
+ }
243
+ statement.body.stmts = processStatementList(statement.body.stmts || [], filename, state);
244
+ nextStatements.push(statement);
245
+ const identifierName = statement.identifier?.value;
246
+ if (identifierName && hasServerDirectiveInFunctionLike(statement)) {
247
+ const actionId = (0, runtime_actions_1.createInlineServerActionId)(filename, state.nextOrdinal++, identifierName);
248
+ nextStatements.push(createRegistrationStatement(identifierName, actionId, identifierName));
249
+ state.serverActionsTransformed = true;
250
+ }
251
+ if (identifierName && hasCacheDirectiveInFunctionLike(statement)) {
252
+ nextStatements.push(createUseCacheAssignmentStatement(identifierName, filename, identifierName));
253
+ state.useCacheTransformed = true;
254
+ }
255
+ return true;
256
+ }
257
+ function processStatementList(statements, filename, state) {
258
+ const nextStatements = [];
259
+ for (const statement of statements) {
260
+ if (!statement || typeof statement !== 'object') {
261
+ nextStatements.push(statement);
262
+ continue;
263
+ }
264
+ if (statement.type === 'FunctionDeclaration') {
265
+ processFunctionLikeDeclaration(statement, filename, state, nextStatements);
266
+ continue;
267
+ }
268
+ if (statement.type === 'ExportDefaultDeclaration' && statement.decl) {
269
+ if (isFunctionBodyBlock(statement.decl.body)) {
270
+ statement.decl.body.stmts = processStatementList(statement.decl.body.stmts || [], filename, state);
271
+ }
272
+ else if ((statement.decl.type === 'FunctionExpression' || statement.decl.type === 'ArrowFunctionExpression') &&
273
+ isFunctionBodyBlock(statement.decl.body)) {
274
+ statement.decl.body.stmts = processStatementList(statement.decl.body.stmts || [], filename, state);
275
+ }
276
+ if ((statement.decl.type === 'FunctionDeclaration' ||
277
+ statement.decl.type === 'FunctionExpression' ||
278
+ statement.decl.type === 'ArrowFunctionExpression') &&
279
+ hasCacheDirectiveInFunctionLike(statement.decl)) {
280
+ statement.decl = createUseCacheWrapCall(statement.decl, filename, statement.decl.identifier?.value || 'default');
281
+ state.useCacheTransformed = true;
282
+ }
283
+ nextStatements.push(statement);
284
+ continue;
285
+ }
286
+ if (statement.type === 'ExportDeclaration' && statement.declaration) {
287
+ if (statement.declaration.type === 'FunctionDeclaration') {
288
+ statement.declaration.body.stmts = processStatementList(statement.declaration.body?.stmts || [], filename, state);
289
+ const identifierName = statement.declaration.identifier?.value;
290
+ nextStatements.push(statement);
291
+ if (identifierName && hasServerDirectiveInFunctionLike(statement.declaration)) {
292
+ const actionId = (0, runtime_actions_1.createInlineServerActionId)(filename, state.nextOrdinal++, identifierName);
293
+ nextStatements.push(createRegistrationStatement(identifierName, actionId, identifierName));
294
+ state.serverActionsTransformed = true;
295
+ }
296
+ if (identifierName && hasCacheDirectiveInFunctionLike(statement.declaration)) {
297
+ nextStatements.push(createUseCacheAssignmentStatement(identifierName, filename, identifierName));
298
+ state.useCacheTransformed = true;
299
+ }
300
+ continue;
301
+ }
302
+ else if (statement.declaration.type === 'VariableDeclaration' &&
303
+ Array.isArray(statement.declaration.declarations)) {
304
+ for (const declaration of statement.declaration.declarations) {
305
+ if (!declaration?.init || typeof declaration.init !== 'object') {
306
+ continue;
307
+ }
308
+ const declaratorName = declaration.id?.type === 'Identifier'
309
+ ? declaration.id.value
310
+ : `anonymous_${state.nextOrdinal}`;
311
+ declaration.init = processExpression(declaration.init, filename, state, declaratorName);
312
+ }
313
+ }
314
+ nextStatements.push(statement);
315
+ continue;
316
+ }
317
+ if (statement.type === 'VariableDeclaration' && Array.isArray(statement.declarations)) {
318
+ for (const declaration of statement.declarations) {
319
+ if (!declaration?.init || typeof declaration.init !== 'object') {
320
+ continue;
321
+ }
322
+ const declaratorName = declaration.id?.type === 'Identifier'
323
+ ? declaration.id.value
324
+ : `anonymous_${state.nextOrdinal}`;
325
+ declaration.init = processExpression(declaration.init, filename, state, declaratorName);
326
+ }
327
+ nextStatements.push(statement);
328
+ continue;
329
+ }
330
+ if (statement.type === 'ExpressionStatement' && statement.expression) {
331
+ statement.expression = processExpression(statement.expression, filename, state);
332
+ nextStatements.push(statement);
333
+ continue;
334
+ }
335
+ if (statement.type === 'ReturnStatement' && statement.argument) {
336
+ statement.argument = processExpression(statement.argument, filename, state);
337
+ nextStatements.push(statement);
338
+ continue;
339
+ }
340
+ if (statement.type === 'BlockStatement') {
341
+ statement.stmts = processStatementList(statement.stmts || [], filename, state);
342
+ nextStatements.push(statement);
343
+ continue;
344
+ }
345
+ if (statement.type === 'IfStatement') {
346
+ if (statement.consequent?.type === 'BlockStatement') {
347
+ statement.consequent.stmts = processStatementList(statement.consequent.stmts || [], filename, state);
348
+ }
349
+ if (statement.alternate?.type === 'BlockStatement') {
350
+ statement.alternate.stmts = processStatementList(statement.alternate.stmts || [], filename, state);
351
+ }
352
+ nextStatements.push(statement);
353
+ continue;
354
+ }
355
+ if (statement.type === 'TryStatement') {
356
+ if (statement.block?.type === 'BlockStatement') {
357
+ statement.block.stmts = processStatementList(statement.block.stmts || [], filename, state);
358
+ }
359
+ if (statement.handler?.body?.type === 'BlockStatement') {
360
+ statement.handler.body.stmts = processStatementList(statement.handler.body.stmts || [], filename, state);
361
+ }
362
+ if (statement.finalizer?.type === 'BlockStatement') {
363
+ statement.finalizer.stmts = processStatementList(statement.finalizer.stmts || [], filename, state);
364
+ }
365
+ nextStatements.push(statement);
366
+ continue;
367
+ }
368
+ if (statement.type === 'SwitchStatement' && Array.isArray(statement.cases)) {
369
+ for (const switchCase of statement.cases) {
370
+ switchCase.consequent = processStatementList(switchCase.consequent || [], filename, state);
371
+ }
372
+ nextStatements.push(statement);
373
+ continue;
374
+ }
375
+ if ((statement.type === 'WhileStatement' ||
376
+ statement.type === 'DoWhileStatement' ||
377
+ statement.type === 'ForStatement' ||
378
+ statement.type === 'ForInStatement' ||
379
+ statement.type === 'ForOfStatement') &&
380
+ statement.body?.type === 'BlockStatement') {
381
+ statement.body.stmts = processStatementList(statement.body.stmts || [], filename, state);
382
+ nextStatements.push(statement);
383
+ continue;
384
+ }
385
+ nextStatements.push(statement);
386
+ }
387
+ return nextStatements;
388
+ }
389
+ function processExpression(expression, filename, state, hint = 'action') {
390
+ if (!expression || typeof expression !== 'object') {
391
+ return expression;
392
+ }
393
+ if (expression.type === 'ArrowFunctionExpression' || expression.type === 'FunctionExpression') {
394
+ if (isFunctionBodyBlock(expression.body)) {
395
+ expression.body.stmts = processStatementList(expression.body.stmts || [], filename, state);
396
+ }
397
+ if (hasServerDirectiveInFunctionLike(expression)) {
398
+ const actionId = (0, runtime_actions_1.createInlineServerActionId)(filename, state.nextOrdinal++, expression.identifier?.value || hint);
399
+ state.serverActionsTransformed = true;
400
+ return createRegisterReferenceCall(expression, actionId, expression.identifier?.value || hint);
401
+ }
402
+ if (hasCacheDirectiveInFunctionLike(expression)) {
403
+ state.useCacheTransformed = true;
404
+ return createUseCacheWrapCall(expression, filename, expression.identifier?.value || hint);
405
+ }
406
+ return expression;
407
+ }
408
+ if (expression.type === 'AssignmentExpression') {
409
+ expression.left = processExpression(expression.left, filename, state, `${hint}_target`);
410
+ expression.right = processExpression(expression.right, filename, state, hint);
411
+ return expression;
412
+ }
413
+ if (expression.type === 'CallExpression') {
414
+ expression.callee = processExpression(expression.callee, filename, state, `${hint}_callee`);
415
+ expression.arguments = (expression.arguments || []).map((argument, index) => argument && argument.expression
416
+ ? {
417
+ ...argument,
418
+ expression: processExpression(argument.expression, filename, state, `${hint}_${index}`),
419
+ }
420
+ : argument);
421
+ return expression;
422
+ }
423
+ if (expression.type === 'NewExpression') {
424
+ expression.callee = processExpression(expression.callee, filename, state, `${hint}_callee`);
425
+ expression.arguments = (expression.arguments || []).map((argument, index) => argument && argument.expression
426
+ ? {
427
+ ...argument,
428
+ expression: processExpression(argument.expression, filename, state, `${hint}_${index}`),
429
+ }
430
+ : argument);
431
+ return expression;
432
+ }
433
+ if (expression.type === 'ArrayExpression') {
434
+ expression.elements = (expression.elements || []).map((element, index) => element && element.expression
435
+ ? {
436
+ ...element,
437
+ expression: processExpression(element.expression, filename, state, `${hint}_${index}`),
438
+ }
439
+ : element);
440
+ return expression;
441
+ }
442
+ if (expression.type === 'MemberExpression') {
443
+ expression.object = processExpression(expression.object, filename, state, `${hint}_object`);
444
+ if (expression.property && expression.computed) {
445
+ expression.property = processExpression(expression.property, filename, state, `${hint}_property`);
446
+ }
447
+ return expression;
448
+ }
449
+ if (expression.type === 'ObjectExpression') {
450
+ expression.properties = (expression.properties || []).map((property) => {
451
+ if (property?.type === 'KeyValueProperty') {
452
+ property.value = processExpression(property.value, filename, state, property.key?.value || property.key?.name || hint);
453
+ }
454
+ return property;
455
+ });
456
+ return expression;
457
+ }
458
+ if (expression.type === 'ObjectPattern') {
459
+ expression.properties = (expression.properties || []).map((property) => {
460
+ if (property?.type === 'KeyValuePatternProperty' && property.value) {
461
+ property.value = processExpression(property.value, filename, state, hint);
462
+ }
463
+ if (property?.type === 'AssignmentPatternProperty' && property.value) {
464
+ property.value = processExpression(property.value, filename, state, hint);
465
+ }
466
+ return property;
467
+ });
468
+ return expression;
469
+ }
470
+ if (expression.type === 'ConditionalExpression') {
471
+ expression.test = processExpression(expression.test, filename, state, hint);
472
+ expression.consequent = processExpression(expression.consequent, filename, state, hint);
473
+ expression.alternate = processExpression(expression.alternate, filename, state, hint);
474
+ return expression;
475
+ }
476
+ if (expression.type === 'SequenceExpression') {
477
+ expression.expressions = (expression.expressions || []).map((entry, index) => processExpression(entry, filename, state, `${hint}_${index}`));
478
+ return expression;
479
+ }
480
+ if (expression.type === 'BinaryExpression' ||
481
+ expression.type === 'LogicalExpression' ||
482
+ expression.type === 'AssignmentPattern') {
483
+ expression.left = processExpression(expression.left, filename, state, `${hint}_left`);
484
+ expression.right = processExpression(expression.right, filename, state, `${hint}_right`);
485
+ return expression;
486
+ }
487
+ if (expression.type === 'UnaryExpression' || expression.type === 'UpdateExpression') {
488
+ expression.argument = processExpression(expression.argument, filename, state, hint);
489
+ return expression;
490
+ }
491
+ if (expression.type === 'AwaitExpression' || expression.type === 'SpreadElement') {
492
+ expression.argument = processExpression(expression.argument, filename, state, hint);
493
+ return expression;
494
+ }
495
+ if (expression.type === 'YieldExpression') {
496
+ if (expression.argument) {
497
+ expression.argument = processExpression(expression.argument, filename, state, hint);
498
+ }
499
+ return expression;
500
+ }
501
+ if (expression.type === 'ParenExpression') {
502
+ expression.expression = processExpression(expression.expression, filename, state, hint);
503
+ return expression;
504
+ }
505
+ if (expression.type === 'TemplateLiteral') {
506
+ expression.expressions = (expression.expressions || []).map((entry, index) => processExpression(entry, filename, state, `${hint}_${index}`));
507
+ return expression;
508
+ }
509
+ if (expression.type === 'TaggedTemplateExpression') {
510
+ expression.tag = processExpression(expression.tag, filename, state, `${hint}_tag`);
511
+ expression.template = processExpression(expression.template, filename, state, `${hint}_template`);
512
+ return expression;
513
+ }
514
+ return expression;
515
+ }
516
+ function injectRuntimeRequire(moduleAst, runtimeIdentifier, runtimeSpecifier) {
517
+ const body = Array.isArray(moduleAst.body) ? moduleAst.body : [];
518
+ let insertionIndex = 0;
519
+ while (insertionIndex < body.length && isStringDirectiveStatement(body[insertionIndex], 'use strict')) {
520
+ insertionIndex += 1;
521
+ }
522
+ body.splice(insertionIndex, 0, createRuntimeRequireDeclaration(runtimeIdentifier, runtimeSpecifier));
523
+ moduleAst.body = body;
524
+ }
525
+ function getParserOptions(filename) {
526
+ const extension = path_1.default.extname(filename).toLowerCase();
527
+ const isTypeScript = extension === '.ts' || extension === '.tsx' || extension === '.mts' || extension === '.cts';
528
+ const jsxEnabled = isTypeScript ? extension === '.tsx' : true;
529
+ return {
530
+ syntax: isTypeScript ? 'typescript' : 'ecmascript',
531
+ tsx: isTypeScript ? jsxEnabled : undefined,
532
+ jsx: !isTypeScript ? jsxEnabled : undefined,
533
+ };
534
+ }
535
+ function transformInlineServerActions(content, filename) {
536
+ if ((!content.includes("'use server'") && !content.includes('"use server"')) &&
537
+ (!content.includes("'use cache'") && !content.includes('"use cache"'))) {
538
+ return content;
539
+ }
540
+ try {
541
+ const moduleAst = (0, core_1.parseSync)(content, getParserOptions(filename));
542
+ const state = {
543
+ serverActionsTransformed: false,
544
+ useCacheTransformed: false,
545
+ nextOrdinal: 0,
546
+ };
547
+ moduleAst.body = processStatementList(moduleAst.body || [], filename, state);
548
+ if (!state.serverActionsTransformed && !state.useCacheTransformed) {
549
+ return content;
550
+ }
551
+ if (state.serverActionsTransformed) {
552
+ injectRuntimeRequire(moduleAst, '__vistaServerActionsRuntime', activeRuntimeActionsSpecifier);
553
+ }
554
+ if (state.useCacheTransformed) {
555
+ injectRuntimeRequire(moduleAst, '__vistaCacheRuntime', activeCacheRuntimeSpecifier);
556
+ }
557
+ return (0, core_1.printSync)(moduleAst).code;
558
+ }
559
+ catch (error) {
560
+ if (process.env.VISTA_DEBUG) {
561
+ console.error(`[vista:compile] Inline action transform failed for ${filename}:`, error);
562
+ }
563
+ return content;
564
+ }
565
+ }
566
+ function wrapUseCacheModuleExports(moduleExports, filename) {
567
+ if (typeof moduleExports === 'function') {
568
+ const wrappedDefault = (0, cache_1.wrapModuleUseCacheExport)(moduleExports, filename, 'default');
569
+ for (const propertyName of Reflect.ownKeys(moduleExports)) {
570
+ if (propertyName === 'default' ||
571
+ propertyName === 'length' ||
572
+ propertyName === 'name' ||
573
+ propertyName === 'prototype') {
574
+ continue;
575
+ }
576
+ const descriptor = Object.getOwnPropertyDescriptor(moduleExports, propertyName);
577
+ const currentValue = descriptor && 'value' in descriptor
578
+ ? descriptor.value
579
+ : descriptor?.get
580
+ ? descriptor.get.call(moduleExports)
581
+ : moduleExports[propertyName];
582
+ Object.defineProperty(wrappedDefault, propertyName, {
583
+ configurable: true,
584
+ enumerable: descriptor?.enumerable ?? true,
585
+ writable: true,
586
+ value: (0, cache_1.wrapModuleUseCacheExport)(currentValue, filename, String(propertyName)),
587
+ });
588
+ }
589
+ return wrappedDefault;
590
+ }
591
+ if (!moduleExports || typeof moduleExports !== 'object') {
592
+ return moduleExports;
593
+ }
594
+ const wrappedExports = Object.create(Object.getPrototypeOf(moduleExports));
595
+ for (const exportName of Reflect.ownKeys(moduleExports)) {
596
+ const descriptor = Object.getOwnPropertyDescriptor(moduleExports, exportName);
597
+ if (!descriptor) {
598
+ continue;
599
+ }
600
+ if (exportName === '__esModule') {
601
+ Object.defineProperty(wrappedExports, exportName, descriptor);
602
+ continue;
603
+ }
604
+ const currentValue = 'value' in descriptor
605
+ ? descriptor.value
606
+ : descriptor.get
607
+ ? descriptor.get.call(moduleExports)
608
+ : moduleExports[exportName];
609
+ Object.defineProperty(wrappedExports, exportName, {
610
+ configurable: true,
611
+ enumerable: descriptor.enumerable ?? true,
612
+ writable: true,
613
+ value: (0, cache_1.wrapModuleUseCacheExport)(currentValue, filename, String(exportName)),
614
+ });
615
+ }
616
+ return wrappedExports;
617
+ }
618
+ function transpileProjectSource(source, filename, fallback) {
619
+ try {
620
+ return (0, core_1.transformSync)(source, {
621
+ filename,
622
+ sourceMaps: 'inline',
623
+ module: {
624
+ type: 'commonjs',
625
+ },
626
+ jsc: {
627
+ target: 'es2020',
628
+ parser: getParserOptions(filename),
629
+ transform: {
630
+ react: {
631
+ runtime: 'automatic',
632
+ },
633
+ },
634
+ },
635
+ }).code;
636
+ }
637
+ catch (error) {
638
+ if (process.env.VISTA_DEBUG) {
639
+ console.error(`[vista:compile] Source transpile failed for ${filename}:`, error);
640
+ }
641
+ return fallback;
642
+ }
643
+ }
644
+ function installModuleCompileHook(options) {
645
+ const vistaRuntimeDir = path_1.default.resolve(__dirname, '..');
646
+ const vistaPackageRoot = path_1.default.resolve(__dirname, '..', '..');
647
+ activeCompileRoots = Array.from(new Set([
648
+ options.cwd,
649
+ vistaRuntimeDir,
650
+ vistaPackageRoot,
651
+ path_1.default.join(vistaPackageRoot, 'src'),
652
+ path_1.default.join(vistaPackageRoot, 'dist'),
653
+ ].map((entry) => path_1.default.resolve(entry))));
654
+ activeRuntimeActionsSpecifier = require.resolve('./runtime-actions');
655
+ activeCacheRuntimeSpecifier = require.resolve('./cache');
656
+ activeCacheComponentsEnabled = Boolean(options.cacheComponentsEnabled);
657
+ if (options.createClientModuleProxy) {
658
+ activeClientModuleProxyFactory = options.createClientModuleProxy;
659
+ }
660
+ if (compileHookInstalled) {
661
+ return;
662
+ }
663
+ originalCompile = CjsModule.prototype._compile;
664
+ CjsModule.prototype._compile = function compileVistaModule(content, filename) {
665
+ if (!isProjectModule(filename, activeCompileRoots)) {
666
+ return originalCompile.call(this, content, filename);
667
+ }
668
+ const originalSource = readOriginalSource(filename, content);
669
+ const containsUseCacheDirective = containsDirectiveLiteral(originalSource, 'use cache');
670
+ const hasTopLevelUseCacheDirective = hasDirective(originalSource, 'use cache');
671
+ if (containsUseCacheDirective && !activeCacheComponentsEnabled) {
672
+ throw createDirectiveError(filename, 'To use "use cache", enable experimental.cacheComponents.enabled in vista.config.*.');
673
+ }
674
+ if (containsUseCacheDirective && hasDirective(originalSource, 'use client')) {
675
+ throw createDirectiveError(filename, '"use cache" cannot be used in a Client Component. Move the cached logic to a server-only module.');
676
+ }
677
+ if (activeClientModuleProxyFactory && hasDirective(originalSource, 'use client')) {
678
+ const moduleId = (0, url_1.pathToFileURL)(filename).href;
679
+ this.exports = activeClientModuleProxyFactory(moduleId);
680
+ return;
681
+ }
682
+ const sourceToCompile = originalSource || content;
683
+ const transformedSource = transformInlineServerActions(sourceToCompile, filename);
684
+ const compiledContent = transpileProjectSource(transformedSource, filename, content);
685
+ const compileResult = originalCompile.call(this, compiledContent, filename);
686
+ if (hasDirective(originalSource, 'use server')) {
687
+ (0, runtime_actions_1.registerServerActionModule)(this.exports, filename);
688
+ }
689
+ if (hasTopLevelUseCacheDirective) {
690
+ this.exports = wrapUseCacheModuleExports(this.exports, filename);
691
+ }
692
+ return compileResult;
693
+ };
694
+ compileHookInstalled = true;
695
+ }