@zenithbuild/cli 0.7.5 → 0.7.7

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 (68) hide show
  1. package/dist/adapters/adapter-netlify.js +0 -8
  2. package/dist/adapters/adapter-vercel.js +6 -14
  3. package/dist/adapters/copy-hosted-page-runtime.js +2 -1
  4. package/dist/build/hoisted-code-transforms.d.ts +4 -1
  5. package/dist/build/hoisted-code-transforms.js +5 -3
  6. package/dist/build/page-ir-normalization.d.ts +1 -1
  7. package/dist/build/page-ir-normalization.js +33 -3
  8. package/dist/build/page-loop.js +46 -2
  9. package/dist/dev-build-session/helpers.d.ts +29 -0
  10. package/dist/dev-build-session/helpers.js +223 -0
  11. package/dist/dev-build-session/session.d.ts +24 -0
  12. package/dist/dev-build-session/session.js +204 -0
  13. package/dist/dev-build-session/state.d.ts +37 -0
  14. package/dist/dev-build-session/state.js +17 -0
  15. package/dist/dev-build-session.d.ts +1 -24
  16. package/dist/dev-build-session.js +1 -434
  17. package/dist/dev-server/css-state.d.ts +7 -0
  18. package/dist/dev-server/css-state.js +92 -0
  19. package/dist/dev-server/not-found.d.ts +23 -0
  20. package/dist/dev-server/not-found.js +129 -0
  21. package/dist/dev-server/request-handler.d.ts +1 -0
  22. package/dist/dev-server/request-handler.js +376 -0
  23. package/dist/dev-server/route-check.d.ts +9 -0
  24. package/dist/dev-server/route-check.js +100 -0
  25. package/dist/dev-server/watcher.d.ts +5 -0
  26. package/dist/dev-server/watcher.js +216 -0
  27. package/dist/dev-server.js +123 -924
  28. package/dist/images/payload.js +4 -0
  29. package/dist/manifest.js +46 -1
  30. package/dist/preview/create-preview-server.d.ts +18 -0
  31. package/dist/preview/create-preview-server.js +71 -0
  32. package/dist/preview/manifest.d.ts +42 -0
  33. package/dist/preview/manifest.js +57 -0
  34. package/dist/preview/paths.d.ts +3 -0
  35. package/dist/preview/paths.js +38 -0
  36. package/dist/preview/payload.d.ts +6 -0
  37. package/dist/preview/payload.js +34 -0
  38. package/dist/preview/request-handler.d.ts +1 -0
  39. package/dist/preview/request-handler.js +300 -0
  40. package/dist/preview/server-runner.d.ts +49 -0
  41. package/dist/preview/server-runner.js +220 -0
  42. package/dist/preview/server-script-runner-template.d.ts +1 -0
  43. package/dist/preview/server-script-runner-template.js +425 -0
  44. package/dist/preview.d.ts +5 -112
  45. package/dist/preview.js +7 -1119
  46. package/dist/resource-response.d.ts +15 -0
  47. package/dist/resource-response.js +91 -2
  48. package/dist/server-contract/constants.d.ts +5 -0
  49. package/dist/server-contract/constants.js +5 -0
  50. package/dist/server-contract/export-validation.d.ts +5 -0
  51. package/dist/server-contract/export-validation.js +59 -0
  52. package/dist/server-contract/json-serializable.d.ts +1 -0
  53. package/dist/server-contract/json-serializable.js +52 -0
  54. package/dist/server-contract/resolve.d.ts +15 -0
  55. package/dist/server-contract/resolve.js +271 -0
  56. package/dist/server-contract/result-helpers.d.ts +51 -0
  57. package/dist/server-contract/result-helpers.js +59 -0
  58. package/dist/server-contract/route-result-validation.d.ts +2 -0
  59. package/dist/server-contract/route-result-validation.js +73 -0
  60. package/dist/server-contract/stage.d.ts +6 -0
  61. package/dist/server-contract/stage.js +22 -0
  62. package/dist/server-contract.d.ts +6 -62
  63. package/dist/server-contract.js +9 -493
  64. package/dist/server-middleware.d.ts +10 -0
  65. package/dist/server-middleware.js +30 -0
  66. package/dist/server-output.js +13 -1
  67. package/dist/server-runtime/node-server.js +25 -3
  68. package/package.json +3 -3
@@ -0,0 +1,2 @@
1
+ export function isRouteResultLike(value: any): boolean;
2
+ export function assertValidRouteResultShape(value: any, where: any, allowedKinds: any): void;
@@ -0,0 +1,73 @@
1
+ import { assertValidDownloadResult } from '../download-result.js';
2
+ import { ROUTE_RESULT_KINDS } from './constants.js';
3
+ export function isRouteResultLike(value) {
4
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
5
+ return false;
6
+ }
7
+ const kind = value.kind;
8
+ return typeof kind === 'string' && ROUTE_RESULT_KINDS.has(kind);
9
+ }
10
+ export function assertValidRouteResultShape(value, where, allowedKinds) {
11
+ if (!isRouteResultLike(value)) {
12
+ throw new Error(`[Zenith] ${where}: invalid route result. Expected object with kind.`);
13
+ }
14
+ const kind = value.kind;
15
+ if (!allowedKinds.has(kind)) {
16
+ throw new Error(`[Zenith] ${where}: kind "${kind}" is not allowed here (allowed: ${Array.from(allowedKinds).join(', ')}).`);
17
+ }
18
+ if (kind === 'redirect') {
19
+ if (typeof value.location !== 'string' || value.location.length === 0) {
20
+ throw new Error(`[Zenith] ${where}: redirect requires non-empty string location.`);
21
+ }
22
+ if (value.status !== undefined && (!Number.isInteger(value.status) || value.status < 300 || value.status > 399)) {
23
+ throw new Error(`[Zenith] ${where}: redirect status must be an integer 3xx.`);
24
+ }
25
+ }
26
+ if (kind === 'deny') {
27
+ if (!Number.isInteger(value.status) ||
28
+ (value.status !== 401 && value.status !== 403 && value.status !== 404)) {
29
+ throw new Error(`[Zenith] ${where}: deny status must be 401, 403, or 404.`);
30
+ }
31
+ if (value.message !== undefined && typeof value.message !== 'string') {
32
+ throw new Error(`[Zenith] ${where}: deny message must be a string when provided.`);
33
+ }
34
+ }
35
+ if (kind === 'invalid') {
36
+ if (!Number.isInteger(value.status) || (value.status !== 400 && value.status !== 422)) {
37
+ throw new Error(`[Zenith] ${where}: invalid status must be 400 or 422.`);
38
+ }
39
+ }
40
+ if (kind === 'json' || kind === 'text') {
41
+ if (!Number.isInteger(value.status) || value.status < 200 || value.status > 599 || (value.status >= 300 && value.status <= 399)) {
42
+ throw new Error(`[Zenith] ${where}: ${kind} status must be an integer between 200-599 and may not be 3xx.`);
43
+ }
44
+ if (kind === 'text' && typeof value.body !== 'string') {
45
+ throw new Error(`[Zenith] ${where}: text body must be a string.`);
46
+ }
47
+ }
48
+ if (kind === 'download') {
49
+ assertValidDownloadResult(value, where);
50
+ }
51
+ if (kind === 'stream') {
52
+ if (!isReadableStream(value.body) && !isAsyncIterable(value.body)) {
53
+ throw new Error(`[Zenith] ${where}: stream body must be a ReadableStream or AsyncIterable.`);
54
+ }
55
+ if (value.status !== undefined && (!Number.isInteger(value.status) || value.status < 200 || value.status > 599 || (value.status >= 300 && value.status <= 399))) {
56
+ throw new Error(`[Zenith] ${where}: stream status must be an integer between 200-599 and may not be 3xx.`);
57
+ }
58
+ if (value.contentType !== undefined && typeof value.contentType !== 'string') {
59
+ throw new Error(`[Zenith] ${where}: stream contentType must be a string.`);
60
+ }
61
+ }
62
+ if (kind === 'sse') {
63
+ if (!isAsyncIterable(value.events)) {
64
+ throw new Error(`[Zenith] ${where}: sse events must be an AsyncIterable.`);
65
+ }
66
+ }
67
+ }
68
+ function isReadableStream(v) {
69
+ return v && typeof v === 'object' && typeof v.getReader === 'function' && typeof v.cancel === 'function';
70
+ }
71
+ function isAsyncIterable(v) {
72
+ return v && typeof v === 'object' && typeof v[Symbol.asyncIterator] === 'function';
73
+ }
@@ -0,0 +1,6 @@
1
+ export function invokeRouteStage({ fn, ctx, where, allowedKinds }: {
2
+ fn: any;
3
+ ctx: any;
4
+ where: any;
5
+ allowedKinds: any;
6
+ }): Promise<any>;
@@ -0,0 +1,22 @@
1
+ import { AUTH_CONTROL_FLOW_FLAG } from './constants.js';
2
+ import { assertValidRouteResultShape } from './route-result-validation.js';
3
+ function unwrapAuthControlFlow(error, where, allowedKinds) {
4
+ if (!error || typeof error !== 'object' || error[AUTH_CONTROL_FLOW_FLAG] !== true) {
5
+ return null;
6
+ }
7
+ const result = error.result;
8
+ assertValidRouteResultShape(result, where, allowedKinds);
9
+ return result;
10
+ }
11
+ export async function invokeRouteStage({ fn, ctx, where, allowedKinds }) {
12
+ try {
13
+ return await fn(ctx);
14
+ }
15
+ catch (error) {
16
+ const authResult = unwrapAuthControlFlow(error, where, allowedKinds);
17
+ if (authResult) {
18
+ return authResult;
19
+ }
20
+ throw error;
21
+ }
22
+ }
@@ -1,62 +1,6 @@
1
- export function allow(): {
2
- kind: string;
3
- };
4
- export function redirect(location: any, status?: number): {
5
- kind: string;
6
- location: string;
7
- status: number;
8
- };
9
- export function deny(status?: number, message?: undefined): {
10
- kind: string;
11
- status: number;
12
- message: undefined;
13
- };
14
- export function data(payload: any): {
15
- kind: string;
16
- data: any;
17
- };
18
- export function invalid(payload: any, status?: number): {
19
- kind: string;
20
- data: any;
21
- status: number;
22
- };
23
- export function json(payload: any, status?: number): {
24
- kind: string;
25
- data: any;
26
- status: number;
27
- };
28
- export function text(body: any, status?: number): {
29
- kind: string;
30
- body: string;
31
- status: number;
32
- };
33
- export function download(body: any, options?: {}): {
34
- kind: string;
35
- body: any;
36
- bodyEncoding: string;
37
- bodySize: number;
38
- filename: string;
39
- contentType: string;
40
- status: number;
41
- };
42
- export function validateServerExports({ exports, filePath, routeKind }: {
43
- exports: any;
44
- filePath: any;
45
- routeKind?: string | undefined;
46
- }): void;
47
- export function assertJsonSerializable(value: any, where?: string): void;
48
- export function resolveRouteResult({ exports, ctx, filePath, guardOnly, routeKind }: {
49
- exports: any;
50
- ctx: any;
51
- filePath: any;
52
- guardOnly?: boolean | undefined;
53
- routeKind?: string | undefined;
54
- }): Promise<{
55
- result: any;
56
- trace: any;
57
- }>;
58
- export function resolveServerPayload({ exports, ctx, filePath }: {
59
- exports: any;
60
- ctx: any;
61
- filePath: any;
62
- }): Promise<any>;
1
+ export { validateServerExports } from "./server-contract/export-validation.js";
2
+ export { assertJsonSerializable } from "./server-contract/json-serializable.js";
3
+ export { withMiddleware };
4
+ import { withMiddleware } from './server-middleware.js';
5
+ export { allow, redirect, deny, data, invalid, json, text, download, stream, sse } from "./server-contract/result-helpers.js";
6
+ export { resolveRouteResult, resolveServerPayload } from "./server-contract/resolve.js";
@@ -1,496 +1,12 @@
1
1
  // server-contract.js — Zenith CLI V0
2
2
  // ---------------------------------------------------------------------------
3
3
  // Shared validation and payload resolution logic for <script server> blocks.
4
- import { assertValidDownloadResult, createDownloadResult } from './download-result.js';
5
- const ALLOWED_KEYS = new Set(['data', 'load', 'guard', 'action', 'prerender', 'exportPaths', 'ssr_data', 'props', 'ssr']);
6
- const RESOURCE_ALLOWED_KEYS = new Set(['load', 'guard', 'action']);
7
- const ROUTE_RESULT_KINDS = new Set(['allow', 'redirect', 'deny', 'data', 'invalid', 'json', 'text', 'download']);
8
- const AUTH_CONTROL_FLOW_FLAG = '__zenith_auth_control_flow';
9
- const STAGED_SET_COOKIES_KEY = '__zenith_staged_set_cookies';
10
- export function allow() {
11
- return { kind: 'allow' };
12
- }
13
- export function redirect(location, status = 302) {
14
- return {
15
- kind: 'redirect',
16
- location: String(location || ''),
17
- status: Number.isInteger(status) ? status : 302
18
- };
19
- }
20
- export function deny(status = 403, message = undefined) {
21
- return {
22
- kind: 'deny',
23
- status: Number.isInteger(status) ? status : 403,
24
- message: typeof message === 'string' ? message : undefined
25
- };
26
- }
27
- export function data(payload) {
28
- return { kind: 'data', data: payload };
29
- }
30
- export function invalid(payload, status = 400) {
31
- return {
32
- kind: 'invalid',
33
- data: payload,
34
- status: Number.isInteger(status) ? status : 400
35
- };
36
- }
37
- export function json(payload, status = 200) {
38
- return {
39
- kind: 'json',
40
- data: payload,
41
- status: Number.isInteger(status) ? status : 200
42
- };
43
- }
44
- export function text(body, status = 200) {
45
- return {
46
- kind: 'text',
47
- body: typeof body === 'string' ? body : String(body ?? ''),
48
- status: Number.isInteger(status) ? status : 200
49
- };
50
- }
51
- export function download(body, options = {}) {
52
- return createDownloadResult(body, options);
53
- }
54
- function isRouteResultLike(value) {
55
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
56
- return false;
57
- }
58
- const kind = value.kind;
59
- return typeof kind === 'string' && ROUTE_RESULT_KINDS.has(kind);
60
- }
61
- function assertValidRouteResultShape(value, where, allowedKinds) {
62
- if (!isRouteResultLike(value)) {
63
- throw new Error(`[Zenith] ${where}: invalid route result. Expected object with kind.`);
64
- }
65
- const kind = value.kind;
66
- if (!allowedKinds.has(kind)) {
67
- throw new Error(`[Zenith] ${where}: kind "${kind}" is not allowed here (allowed: ${Array.from(allowedKinds).join(', ')}).`);
68
- }
69
- if (kind === 'redirect') {
70
- if (typeof value.location !== 'string' || value.location.length === 0) {
71
- throw new Error(`[Zenith] ${where}: redirect requires non-empty string location.`);
72
- }
73
- if (value.status !== undefined && (!Number.isInteger(value.status) || value.status < 300 || value.status > 399)) {
74
- throw new Error(`[Zenith] ${where}: redirect status must be an integer 3xx.`);
75
- }
76
- }
77
- if (kind === 'deny') {
78
- if (!Number.isInteger(value.status) ||
79
- (value.status !== 401 && value.status !== 403 && value.status !== 404)) {
80
- throw new Error(`[Zenith] ${where}: deny status must be 401, 403, or 404.`);
81
- }
82
- if (value.message !== undefined && typeof value.message !== 'string') {
83
- throw new Error(`[Zenith] ${where}: deny message must be a string when provided.`);
84
- }
85
- }
86
- if (kind === 'invalid') {
87
- if (!Number.isInteger(value.status) || (value.status !== 400 && value.status !== 422)) {
88
- throw new Error(`[Zenith] ${where}: invalid status must be 400 or 422.`);
89
- }
90
- }
91
- if (kind === 'json' || kind === 'text') {
92
- if (!Number.isInteger(value.status) || value.status < 200 || value.status > 599 || (value.status >= 300 && value.status <= 399)) {
93
- throw new Error(`[Zenith] ${where}: ${kind} status must be an integer between 200-599 and may not be 3xx.`);
94
- }
95
- if (kind === 'text' && typeof value.body !== 'string') {
96
- throw new Error(`[Zenith] ${where}: text body must be a string.`);
97
- }
98
- }
99
- if (kind === 'download') {
100
- assertValidDownloadResult(value, where);
101
- }
102
- }
103
- function assertOneArgRouteFunction({ filePath, exportName, value }) {
104
- if (typeof value !== 'function') {
105
- throw new Error(`[Zenith] ${filePath}: "${exportName}" must be a function.`);
106
- }
107
- if (value.length !== 1) {
108
- throw new Error(`[Zenith] ${filePath}: "${exportName}(ctx)" must take exactly 1 argument.`);
109
- }
110
- const fnStr = value.toString();
111
- const paramsMatch = fnStr.match(/^[^{=]+\(([^)]*)\)/);
112
- if (paramsMatch && paramsMatch[1].includes('...')) {
113
- throw new Error(`[Zenith] ${filePath}: "${exportName}(ctx)" must not contain rest parameters.`);
114
- }
115
- }
116
- function buildActionState(result) {
117
- if (!result || typeof result !== 'object') {
118
- return null;
119
- }
120
- if (result.kind === 'data') {
121
- return {
122
- ok: true,
123
- status: 200,
124
- data: result.data
125
- };
126
- }
127
- if (result.kind === 'invalid') {
128
- return {
129
- ok: false,
130
- status: Number.isInteger(result.status) ? result.status : 400,
131
- data: result.data
132
- };
133
- }
134
- return null;
135
- }
136
- function unwrapAuthControlFlow(error, where, allowedKinds) {
137
- if (!error || typeof error !== 'object' || error[AUTH_CONTROL_FLOW_FLAG] !== true) {
138
- return null;
139
- }
140
- const result = error.result;
141
- assertValidRouteResultShape(result, where, allowedKinds);
142
- return result;
143
- }
144
- async function invokeRouteStage({ fn, ctx, where, allowedKinds }) {
145
- try {
146
- return await fn(ctx);
147
- }
148
- catch (error) {
149
- const authResult = unwrapAuthControlFlow(error, where, allowedKinds);
150
- if (authResult) {
151
- return authResult;
152
- }
153
- throw error;
154
- }
155
- }
156
- function buildResolvedEnvelope({ result, trace, status, ctx }) {
157
- const envelope = { result, trace };
158
- if (status !== undefined) {
159
- envelope.status = status;
160
- }
161
- const setCookies = Array.isArray(ctx?.[STAGED_SET_COOKIES_KEY])
162
- ? ctx[STAGED_SET_COOKIES_KEY].slice()
163
- : [];
164
- if (setCookies.length > 0) {
165
- envelope.setCookies = setCookies;
166
- }
167
- return envelope;
168
- }
169
- export function validateServerExports({ exports, filePath, routeKind = 'page' }) {
170
- const exportKeys = Object.keys(exports);
171
- const allowedKeys = routeKind === 'resource' ? RESOURCE_ALLOWED_KEYS : ALLOWED_KEYS;
172
- const illegalKeys = exportKeys.filter(k => !allowedKeys.has(k));
173
- if (illegalKeys.length > 0) {
174
- throw new Error(`[Zenith] ${filePath}: illegal export(s): ${illegalKeys.join(', ')}`);
175
- }
176
- const hasData = 'data' in exports;
177
- const hasLoad = 'load' in exports;
178
- const hasGuard = 'guard' in exports;
179
- const hasAction = 'action' in exports;
180
- const hasNew = hasData || hasLoad || hasAction;
181
- const hasLegacy = ('ssr_data' in exports) || ('props' in exports) || ('ssr' in exports);
182
- if (routeKind === 'resource') {
183
- if (hasData) {
184
- throw new Error(`[Zenith] ${filePath}: resource routes may not export "data". Use load(ctx) or action(ctx) with ctx.json()/ctx.text().`);
185
- }
186
- if (!hasLoad && !hasAction) {
187
- throw new Error(`[Zenith] ${filePath}: resource routes must export load(ctx), action(ctx), or both.`);
188
- }
189
- }
190
- if (hasData && hasLoad) {
191
- throw new Error(`[Zenith] ${filePath}: cannot export both "data" and "load". Choose one.`);
192
- }
193
- if (routeKind === 'page' && hasNew && hasLegacy) {
194
- throw new Error(`[Zenith] ${filePath}: cannot mix new ("data"/"load") with legacy ("ssr_data"/"props"/"ssr") exports.`);
195
- }
196
- if (routeKind === 'page' && 'prerender' in exports && typeof exports.prerender !== 'boolean') {
197
- throw new Error(`[Zenith] ${filePath}: "prerender" must be a boolean.`);
198
- }
199
- if (routeKind === 'page' && 'exportPaths' in exports) {
200
- if (!Array.isArray(exports.exportPaths) || exports.exportPaths.some((value) => typeof value !== 'string')) {
201
- throw new Error(`[Zenith] ${filePath}: "exportPaths" must be an array of string pathnames.`);
202
- }
203
- }
204
- if (hasLoad) {
205
- assertOneArgRouteFunction({ filePath, exportName: 'load', value: exports.load });
206
- }
207
- if (hasGuard) {
208
- assertOneArgRouteFunction({ filePath, exportName: 'guard', value: exports.guard });
209
- }
210
- if (hasAction) {
211
- assertOneArgRouteFunction({ filePath, exportName: 'action', value: exports.action });
212
- }
213
- }
214
- export function assertJsonSerializable(value, where = 'payload') {
215
- const seen = new Set();
216
- function walk(v, path) {
217
- const t = typeof v;
218
- if (v === null)
219
- return;
220
- if (t === 'string' || t === 'number' || t === 'boolean')
221
- return;
222
- if (t === 'bigint' || t === 'function' || t === 'symbol') {
223
- throw new Error(`[Zenith] ${where}: non-serializable ${t} at ${path}`);
224
- }
225
- if (t === 'undefined') {
226
- throw new Error(`[Zenith] ${where}: undefined is not allowed at ${path}`);
227
- }
228
- if (v instanceof Date) {
229
- throw new Error(`[Zenith] ${where}: Date is not allowed at ${path} (convert to ISO string)`);
230
- }
231
- if (v instanceof Map || v instanceof Set) {
232
- throw new Error(`[Zenith] ${where}: Map/Set not allowed at ${path}`);
233
- }
234
- if (t === 'object') {
235
- if (seen.has(v))
236
- throw new Error(`[Zenith] ${where}: circular reference at ${path}`);
237
- seen.add(v);
238
- if (Array.isArray(v)) {
239
- if (path === '$') {
240
- throw new Error(`[Zenith] ${where}: top-level payload must be a plain object, not an array at ${path}`);
241
- }
242
- for (let i = 0; i < v.length; i++)
243
- walk(v[i], `${path}[${i}]`);
244
- return;
245
- }
246
- const proto = Object.getPrototypeOf(v);
247
- const isPlainObject = proto === null ||
248
- proto === Object.prototype ||
249
- (proto && proto.constructor && proto.constructor.name === 'Object');
250
- if (!isPlainObject) {
251
- throw new Error(`[Zenith] ${where}: non-plain object at ${path}`);
252
- }
253
- for (const k of Object.keys(v)) {
254
- if (k === '__proto__' || k === 'constructor' || k === 'prototype') {
255
- throw new Error(`[Zenith] ${where}: forbidden prototype pollution key "${k}" at ${path}.${k}`);
256
- }
257
- walk(v[k], `${path}.${k}`);
258
- }
259
- return;
260
- }
261
- throw new Error(`[Zenith] ${where}: unsupported type at ${path}`);
262
- }
263
- walk(value, '$');
264
- }
265
- export async function resolveRouteResult({ exports, ctx, filePath, guardOnly = false, routeKind = 'page' }) {
266
- validateServerExports({ exports, filePath, routeKind });
267
- if (routeKind === 'resource') {
268
- return resolveResourceRouteResult({ exports, ctx, filePath, guardOnly });
269
- }
270
- const trace = {
271
- guard: 'none',
272
- action: 'none',
273
- load: 'none'
274
- };
275
- let responseStatus = 200;
276
- const requestMethod = String(ctx?.method || ctx?.request?.method || 'GET').toUpperCase();
277
- const isActionRequest = !guardOnly && requestMethod === 'POST';
278
- if (ctx && typeof ctx === 'object') {
279
- ctx.action = null;
280
- }
281
- if ('guard' in exports) {
282
- const guardRaw = await invokeRouteStage({
283
- fn: exports.guard,
284
- ctx,
285
- where: `${filePath}: guard(ctx)`,
286
- allowedKinds: new Set(['allow', 'redirect', 'deny'])
287
- });
288
- const guardResult = guardRaw == null ? allow() : guardRaw;
289
- if (guardResult.kind === 'data') {
290
- throw new Error(`[Zenith] ${filePath}: guard(ctx) returned data(payload) which is a critical invariant violation. guard() can only return allow(), redirect(), or deny(). Use load(ctx) for data injection.`);
291
- }
292
- assertValidRouteResultShape(guardResult, `${filePath}: guard(ctx) return`, new Set(['allow', 'redirect', 'deny']));
293
- trace.guard = guardResult.kind;
294
- if (guardResult.kind === 'redirect' || guardResult.kind === 'deny') {
295
- return buildResolvedEnvelope({ result: guardResult, trace, ctx });
296
- }
297
- }
298
- if (guardOnly) {
299
- return buildResolvedEnvelope({ result: allow(), trace, ctx });
300
- }
301
- if (isActionRequest && 'action' in exports) {
302
- const actionRaw = await invokeRouteStage({
303
- fn: exports.action,
304
- ctx,
305
- where: `${filePath}: action(ctx)`,
306
- allowedKinds: new Set(['data', 'invalid', 'redirect', 'deny'])
307
- });
308
- let actionResult = null;
309
- if (isRouteResultLike(actionRaw)) {
310
- actionResult = actionRaw;
311
- assertValidRouteResultShape(actionResult, `${filePath}: action(ctx) return`, new Set(['data', 'invalid', 'redirect', 'deny']));
312
- if (actionResult.kind === 'data' || actionResult.kind === 'invalid') {
313
- assertJsonSerializable(actionResult.data, `${filePath}: action(ctx) return`);
314
- }
315
- }
316
- else {
317
- assertJsonSerializable(actionRaw, `${filePath}: action(ctx) return`);
318
- actionResult = data(actionRaw);
319
- }
320
- trace.action = actionResult.kind;
321
- if (actionResult.kind === 'redirect' || actionResult.kind === 'deny') {
322
- return buildResolvedEnvelope({ result: actionResult, trace, ctx });
323
- }
324
- const actionState = buildActionState(actionResult);
325
- if (ctx && typeof ctx === 'object') {
326
- ctx.action = actionState;
327
- }
328
- if (actionState && actionState.ok === false) {
329
- responseStatus = actionState.status;
330
- }
331
- }
332
- let payload;
333
- if ('load' in exports) {
334
- const loadRaw = await invokeRouteStage({
335
- fn: exports.load,
336
- ctx,
337
- where: `${filePath}: load(ctx)`,
338
- allowedKinds: new Set(['data', 'redirect', 'deny'])
339
- });
340
- let loadResult = null;
341
- if (isRouteResultLike(loadRaw)) {
342
- loadResult = loadRaw;
343
- assertValidRouteResultShape(loadResult, `${filePath}: load(ctx) return`, new Set(['data', 'redirect', 'deny']));
344
- }
345
- else {
346
- assertJsonSerializable(loadRaw, `${filePath}: load(ctx) return`);
347
- loadResult = data(loadRaw);
348
- }
349
- trace.load = loadResult.kind;
350
- return buildResolvedEnvelope({
351
- result: loadResult,
352
- trace,
353
- status: loadResult.kind === 'data' ? responseStatus : undefined,
354
- ctx
355
- });
356
- }
357
- if ('data' in exports) {
358
- payload = exports.data;
359
- assertJsonSerializable(payload, `${filePath}: data export`);
360
- trace.load = 'data';
361
- return buildResolvedEnvelope({ result: data(payload), trace, status: responseStatus, ctx });
362
- }
363
- // legacy fallback
364
- if ('ssr_data' in exports) {
365
- payload = exports.ssr_data;
366
- assertJsonSerializable(payload, `${filePath}: ssr_data export`);
367
- trace.load = 'data';
368
- return buildResolvedEnvelope({ result: data(payload), trace, status: responseStatus, ctx });
369
- }
370
- if ('props' in exports) {
371
- payload = exports.props;
372
- assertJsonSerializable(payload, `${filePath}: props export`);
373
- trace.load = 'data';
374
- return buildResolvedEnvelope({ result: data(payload), trace, status: responseStatus, ctx });
375
- }
376
- if ('ssr' in exports) {
377
- payload = exports.ssr;
378
- assertJsonSerializable(payload, `${filePath}: ssr export`);
379
- trace.load = 'data';
380
- return buildResolvedEnvelope({ result: data(payload), trace, status: responseStatus, ctx });
381
- }
382
- if (isActionRequest && ctx?.action) {
383
- trace.load = 'data';
384
- return buildResolvedEnvelope({
385
- result: data({ action: ctx.action }),
386
- trace,
387
- status: responseStatus,
388
- ctx
389
- });
390
- }
391
- return buildResolvedEnvelope({ result: data({}), trace, status: responseStatus, ctx });
392
- }
393
- async function resolveResourceRouteResult({ exports, ctx, filePath, guardOnly = false }) {
394
- const trace = {
395
- guard: 'none',
396
- action: 'none',
397
- load: 'none'
398
- };
399
- const requestMethod = String(ctx?.method || ctx?.request?.method || 'GET').toUpperCase();
400
- if (ctx && typeof ctx === 'object') {
401
- ctx.action = null;
402
- }
403
- if ('guard' in exports) {
404
- const guardRaw = await invokeRouteStage({
405
- fn: exports.guard,
406
- ctx,
407
- where: `${filePath}: guard(ctx)`,
408
- allowedKinds: new Set(['allow', 'redirect', 'deny'])
409
- });
410
- const guardResult = guardRaw == null ? allow() : guardRaw;
411
- assertValidRouteResultShape(guardResult, `${filePath}: guard(ctx) return`, new Set(['allow', 'redirect', 'deny']));
412
- trace.guard = guardResult.kind;
413
- if (guardResult.kind === 'redirect' || guardResult.kind === 'deny') {
414
- return buildResolvedEnvelope({ result: guardResult, trace, ctx });
415
- }
416
- }
417
- if (guardOnly) {
418
- return buildResolvedEnvelope({ result: allow(), trace, ctx });
419
- }
420
- if (requestMethod === 'GET' || requestMethod === 'HEAD') {
421
- if (!('load' in exports)) {
422
- trace.load = 'text';
423
- return buildResolvedEnvelope({ result: text('Method Not Allowed', 405), trace, status: 405, ctx });
424
- }
425
- const loadResult = await resolveResourceStage({
426
- exports,
427
- exportName: 'load',
428
- ctx,
429
- filePath,
430
- trace,
431
- traceKey: 'load'
432
- });
433
- return buildResolvedEnvelope({
434
- result: loadResult,
435
- trace,
436
- status: loadResult.status,
437
- ctx
438
- });
439
- }
440
- if (requestMethod === 'POST') {
441
- if (!('action' in exports)) {
442
- trace.action = 'text';
443
- return buildResolvedEnvelope({ result: text('Method Not Allowed', 405), trace, status: 405, ctx });
444
- }
445
- const actionResult = await resolveResourceStage({
446
- exports,
447
- exportName: 'action',
448
- ctx,
449
- filePath,
450
- trace,
451
- traceKey: 'action'
452
- });
453
- return buildResolvedEnvelope({
454
- result: actionResult,
455
- trace,
456
- status: actionResult.status,
457
- ctx
458
- });
459
- }
460
- return buildResolvedEnvelope({
461
- result: text('Method Not Allowed', 405),
462
- trace,
463
- status: 405,
464
- ctx
465
- });
466
- }
467
- async function resolveResourceStage({ exports, exportName, ctx, filePath, trace, traceKey }) {
468
- const raw = await invokeRouteStage({
469
- fn: exports[exportName],
470
- ctx,
471
- where: `${filePath}: ${exportName}(ctx)`,
472
- allowedKinds: new Set(['json', 'text', 'download', 'redirect', 'deny'])
473
- });
474
- if (!isRouteResultLike(raw)) {
475
- throw new Error(`[Zenith] ${filePath}: ${exportName}(ctx) on a resource route must return json(...), text(...), download(...), redirect(...), or deny(...).`);
476
- }
477
- assertValidRouteResultShape(raw, `${filePath}: ${exportName}(ctx) return`, new Set(['json', 'text', 'download', 'redirect', 'deny']));
478
- if (raw.kind === 'json') {
479
- assertJsonSerializable(raw.data, `${filePath}: ${exportName}(ctx) return`);
480
- }
481
- trace[traceKey] = raw.kind;
482
- return raw;
483
- }
484
- export async function resolveServerPayload({ exports, ctx, filePath }) {
485
- const resolved = await resolveRouteResult({ exports, ctx, filePath });
486
- if (!resolved || !resolved.result || typeof resolved.result !== 'object') {
487
- return {};
488
- }
489
- if (resolved.result.kind === 'data') {
490
- return resolved.result.data;
491
- }
492
- if (resolved.result.kind === 'allow') {
493
- return {};
494
- }
495
- throw new Error(`[Zenith] ${filePath}: resolveServerPayload() expected data but received ${resolved.result.kind}. Use resolveRouteResult() for guard/load flows.`);
496
- }
4
+ //
5
+ // This file is intentionally a thin composition/export surface.
6
+ // ---------------------------------------------------------------------------
7
+ import { withMiddleware } from './server-middleware.js';
8
+ export { allow, redirect, deny, data, invalid, json, text, download, stream, sse } from './server-contract/result-helpers.js';
9
+ export { validateServerExports } from './server-contract/export-validation.js';
10
+ export { assertJsonSerializable } from './server-contract/json-serializable.js';
11
+ export { resolveRouteResult, resolveServerPayload } from './server-contract/resolve.js';
12
+ export { withMiddleware };