zitejs 0.10.0-start.2 → 0.10.0-start.21

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 (188) hide show
  1. package/dist/cjs/auth/actions.d.ts +28 -0
  2. package/dist/cjs/auth/actions.js +93 -0
  3. package/dist/cjs/auth/client.d.ts +357 -0
  4. package/dist/cjs/auth/client.js +66 -0
  5. package/dist/cjs/auth/index.d.ts +2 -249
  6. package/dist/cjs/auth/index.js +11 -108
  7. package/dist/cjs/auth/index.test.js +48 -0
  8. package/dist/cjs/auth/previewClaim.d.ts +7 -0
  9. package/dist/cjs/auth/previewClaim.js +16 -0
  10. package/dist/cjs/auth/profileUpdates.d.ts +9 -0
  11. package/dist/cjs/auth/profileUpdates.js +11 -0
  12. package/dist/cjs/backend/index.d.ts +121 -3
  13. package/dist/cjs/backend/index.test.js +58 -0
  14. package/dist/cjs/bundle/index.d.ts +8 -0
  15. package/dist/cjs/bundle/index.js +9 -8
  16. package/dist/cjs/check/index.d.ts +45 -1
  17. package/dist/cjs/check/index.js +198 -109
  18. package/dist/cjs/check/start/problem.d.ts +11 -0
  19. package/dist/cjs/check/start/problem.js +5 -0
  20. package/dist/cjs/check/start/routeTree.d.ts +9 -0
  21. package/dist/cjs/check/start/routeTree.js +111 -0
  22. package/dist/cjs/check/start/sourceRules.d.ts +8 -0
  23. package/dist/cjs/check/start/sourceRules.js +1159 -0
  24. package/dist/cjs/check/start/tsgo.d.ts +2 -0
  25. package/dist/cjs/check/start/tsgo.js +35 -0
  26. package/dist/cjs/cli.js +1 -1
  27. package/dist/cjs/client/index.d.ts +24 -0
  28. package/dist/cjs/dev/index.js +14 -4
  29. package/dist/cjs/integrations/rules.d.ts +13 -0
  30. package/dist/cjs/integrations/rules.js +31 -0
  31. package/dist/cjs/integrations/rules.test.js +1 -0
  32. package/dist/cjs/internal/appMode.d.ts +3 -0
  33. package/dist/cjs/internal/appMode.js +15 -0
  34. package/dist/cjs/runtime/index.d.ts +64 -25
  35. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  36. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.js +33 -0
  37. package/dist/cjs/start/entries.d.ts +10 -4
  38. package/dist/cjs/start/entries.js +23 -6
  39. package/dist/cjs/steps/index.d.ts +78 -0
  40. package/dist/cjs/steps/index.js +507 -0
  41. package/dist/cjs/steps/index.test.d.ts +1 -0
  42. package/dist/cjs/steps/index.test.js +635 -0
  43. package/dist/cjs/sync/index.js +2 -1
  44. package/dist/cjs/sync/lib.d.ts +10 -3
  45. package/dist/cjs/sync/lib.js +44 -25
  46. package/dist/cjs/sync/lib.test.js +116 -36
  47. package/dist/cjs/types/fields.d.ts +8 -1
  48. package/dist/cjs/types/fields.js +7 -1
  49. package/dist/cjs/types/tables.d.ts +16 -0
  50. package/dist/cjs/upload/index.js +12 -2
  51. package/dist/cjs/upload/index.test.js +39 -0
  52. package/dist/cjs/vite/index.js +8 -3
  53. package/dist/cjs/vite/index.test.js +10 -2
  54. package/dist/esm/auth/actions.d.ts +28 -0
  55. package/dist/esm/auth/actions.js +55 -0
  56. package/dist/esm/auth/client.d.ts +357 -0
  57. package/dist/esm/auth/client.js +62 -0
  58. package/dist/esm/auth/index.d.ts +2 -249
  59. package/dist/esm/auth/index.js +2 -103
  60. package/dist/esm/auth/index.test.js +48 -0
  61. package/dist/esm/auth/previewClaim.d.ts +7 -0
  62. package/dist/esm/auth/previewClaim.js +12 -0
  63. package/dist/esm/auth/profileUpdates.d.ts +9 -0
  64. package/dist/esm/auth/profileUpdates.js +6 -0
  65. package/dist/esm/backend/index.d.ts +121 -3
  66. package/dist/esm/backend/index.test.js +58 -0
  67. package/dist/esm/bundle/index.d.ts +8 -0
  68. package/dist/esm/bundle/index.js +8 -8
  69. package/dist/esm/check/index.d.ts +45 -1
  70. package/dist/esm/check/index.js +198 -113
  71. package/dist/esm/check/start/problem.d.ts +11 -0
  72. package/dist/esm/check/start/problem.js +1 -0
  73. package/dist/esm/check/start/routeTree.d.ts +9 -0
  74. package/dist/esm/check/start/routeTree.js +70 -0
  75. package/dist/esm/check/start/sourceRules.d.ts +8 -0
  76. package/dist/esm/check/start/sourceRules.js +1156 -0
  77. package/dist/esm/check/start/tsgo.d.ts +2 -0
  78. package/dist/esm/check/start/tsgo.js +29 -0
  79. package/dist/esm/cli.js +1 -1
  80. package/dist/esm/client/index.d.ts +24 -0
  81. package/dist/esm/dev/index.js +16 -6
  82. package/dist/esm/integrations/rules.d.ts +13 -0
  83. package/dist/esm/integrations/rules.js +31 -0
  84. package/dist/esm/integrations/rules.test.js +1 -0
  85. package/dist/esm/internal/appMode.d.ts +3 -0
  86. package/dist/esm/internal/appMode.js +10 -0
  87. package/dist/esm/runtime/index.d.ts +64 -25
  88. package/dist/esm/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  89. package/dist/esm/runtime/sendEmailParamsTypes.test-d.js +31 -0
  90. package/dist/esm/start/aiUsage.d.ts +23 -0
  91. package/dist/esm/start/aiUsage.js +146 -0
  92. package/dist/esm/start/airtable/arrayFields.d.ts +10 -0
  93. package/dist/esm/start/airtable/arrayFields.js +30 -0
  94. package/dist/esm/start/airtable/dispatch.d.ts +54 -0
  95. package/dist/esm/start/airtable/dispatch.js +483 -0
  96. package/dist/esm/start/airtable/formulas.d.ts +70 -0
  97. package/dist/esm/start/airtable/formulas.js +260 -0
  98. package/dist/esm/start/airtable/index.d.ts +8 -0
  99. package/dist/esm/start/airtable/index.js +54 -0
  100. package/dist/esm/start/authHooks.d.ts +7 -0
  101. package/dist/esm/start/authHooks.js +10 -0
  102. package/dist/esm/start/authHooksModule.d.ts +1 -0
  103. package/dist/esm/start/authHooksModule.js +3 -0
  104. package/dist/esm/start/clientErrorMessage.test.d.ts +1 -0
  105. package/dist/esm/start/clientErrorMessage.test.js +105 -0
  106. package/dist/esm/start/credentials.d.ts +2 -0
  107. package/dist/esm/start/credentials.js +2 -0
  108. package/dist/esm/start/data/baseRunner.d.ts +92 -0
  109. package/dist/esm/start/data/baseRunner.js +83 -0
  110. package/dist/esm/start/data/dispatch.d.ts +16 -0
  111. package/dist/esm/start/data/dispatch.js +198 -0
  112. package/dist/esm/start/data/index.d.ts +15 -0
  113. package/dist/esm/start/data/index.js +58 -0
  114. package/dist/esm/start/data/sqlNameMappings.d.ts +58 -0
  115. package/dist/esm/start/data/sqlNameMappings.js +92 -0
  116. package/dist/esm/start/data/transformations.d.ts +97 -0
  117. package/dist/esm/start/data/transformations.js +262 -0
  118. package/dist/esm/start/data/types.d.ts +91 -0
  119. package/dist/esm/start/data/types.js +14 -0
  120. package/dist/esm/start/describe.d.ts +42 -5
  121. package/dist/esm/start/describe.js +77 -23
  122. package/dist/esm/start/entries.d.ts +10 -4
  123. package/dist/esm/start/entries.js +21 -5
  124. package/dist/esm/start/errors.d.ts +63 -0
  125. package/dist/esm/start/errors.js +146 -0
  126. package/dist/esm/start/errors.test.d.ts +1 -0
  127. package/dist/esm/start/errors.test.js +23 -0
  128. package/dist/esm/start/factories.test-d.d.ts +2 -0
  129. package/dist/esm/start/factories.test-d.js +20 -0
  130. package/dist/esm/start/host.d.ts +2 -2
  131. package/dist/esm/start/index.d.ts +32 -27
  132. package/dist/esm/start/index.js +79 -47
  133. package/dist/esm/start/instance.d.ts +4 -4
  134. package/dist/esm/start/instance.js +54 -11
  135. package/dist/esm/start/outbound.d.ts +11 -0
  136. package/dist/esm/start/outbound.js +400 -0
  137. package/dist/esm/start/previewClaim.d.ts +7 -0
  138. package/dist/esm/start/previewClaim.js +23 -0
  139. package/dist/esm/start/problems.js +1 -1
  140. package/dist/esm/start/quiet.d.ts +2 -0
  141. package/dist/esm/start/quiet.js +27 -0
  142. package/dist/esm/start/redactSecrets.d.ts +15 -0
  143. package/dist/esm/start/redactSecrets.js +154 -0
  144. package/dist/esm/start/redactSecrets.test.d.ts +1 -0
  145. package/dist/esm/start/redactSecrets.test.js +151 -0
  146. package/dist/esm/start/registration.d.ts +13 -0
  147. package/dist/esm/start/registration.js +21 -0
  148. package/dist/esm/start/registrationHash.d.ts +22 -0
  149. package/dist/esm/start/registrationHash.js +470 -0
  150. package/dist/esm/start/router.d.ts +25 -4
  151. package/dist/esm/start/router.js +169 -11
  152. package/dist/esm/start/runLog.d.ts +7 -4
  153. package/dist/esm/start/runLog.js +64 -6
  154. package/dist/esm/start/scope.d.ts +4 -4
  155. package/dist/esm/start/server.d.ts +40 -36
  156. package/dist/esm/start/server.js +322 -49
  157. package/dist/esm/start/steps.d.ts +28 -0
  158. package/dist/esm/start/steps.js +97 -0
  159. package/dist/esm/start/types.d.ts +179 -6
  160. package/dist/esm/start/version.d.ts +1 -0
  161. package/dist/esm/start/version.js +2 -0
  162. package/dist/esm/start/vite.js +91 -14
  163. package/dist/esm/start/worker.d.ts +6 -0
  164. package/dist/esm/start/worker.js +12 -0
  165. package/dist/esm/start/workflow.d.ts +46 -12
  166. package/dist/esm/start/workflow.js +10 -3
  167. package/dist/esm/start/workflow.test-d.js +50 -8
  168. package/dist/esm/start/workflowModules.js +1 -1
  169. package/dist/esm/start/workflowRun.d.ts +26 -8
  170. package/dist/esm/start/workflowRun.js +39 -8
  171. package/dist/esm/steps/index.d.ts +78 -0
  172. package/dist/esm/steps/index.js +502 -0
  173. package/dist/esm/steps/index.test.d.ts +1 -0
  174. package/dist/esm/steps/index.test.js +633 -0
  175. package/dist/esm/sync/index.js +2 -1
  176. package/dist/esm/sync/lib.d.ts +10 -3
  177. package/dist/esm/sync/lib.js +44 -25
  178. package/dist/esm/sync/lib.test.js +116 -36
  179. package/dist/esm/types/fields.d.ts +8 -1
  180. package/dist/esm/types/fields.js +6 -0
  181. package/dist/esm/types/tables.d.ts +16 -0
  182. package/dist/esm/upload/index.js +12 -2
  183. package/dist/esm/upload/index.test.js +39 -0
  184. package/dist/esm/vite/index.js +8 -3
  185. package/dist/esm/vite/index.test.js +10 -2
  186. package/package.json +37 -16
  187. package/dist/cjs/start/problems.d.ts +0 -19
  188. package/dist/cjs/start/problems.js +0 -11
@@ -1,46 +1,169 @@
1
+ // For the generated server entry only. Apps never import this.
2
+ import { createServerEntry } from "@tanstack/react-start/server";
3
+ import { createSsrRpc } from "@tanstack/react-start/ssr-rpc";
4
+ import { runWithStartContext } from "@tanstack/start-storage-context";
5
+ import { asZiteError, isZiteErrorCode, ZiteError, ZITE_ERROR_STATUS } from "./errors.js";
1
6
  import { describeApp } from "./describe.js";
2
- import { preview } from "./runLog.js";
3
- import { getHost, requireScope, runWithHost } from "./scope.js";
4
- import { loadWorkflows, loggedInput, runWorkflow } from "./workflowRun.js";
7
+ import { runRegistration } from "./registration.js";
8
+ import { isAuthHookName, loadAuthHooks } from "./authHooks.js";
9
+ import { errorOf, preview } from "./runLog.js";
10
+ import { DATA_INTEGRATION_ID, dataContextOf, runDataCall } from "./data/index.js";
11
+ import { airtableSettingsOf, runAirtableCall } from "./airtable/index.js";
12
+ import { withoutConsole } from "./quiet.js";
13
+ import { createOutboundFetch, rememberConnection } from "./outbound.js";
14
+ import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
15
+ import { getHost, requireScope, runInScope, runWithHost } from "./scope.js";
16
+ import { ZITEJS_VERSION } from "./version.js";
17
+ import { loadUnfinishedWorkflows, loadWorkflows, loggedInput, runWorkflow } from "./workflowRun.js";
5
18
  export { runWithHost } from "./scope.js";
6
19
  export { describeApp } from "./describe.js";
7
20
  /**
8
- * Routes every zitejs data, integration and email call through `call`, and only
9
- * inside an access scope. The access kind travels with the call so the platform
10
- * can record what a page read and, later, narrow anonymous reads.
21
+ * Routes every zitejs data, integration and email call to this request's
22
+ * platform, on one session, and only inside an access scope. The access kind
23
+ * travels with the call so the platform can record what a page read and narrow
24
+ * anonymous reads.
11
25
  */
12
- export function installPlatformTransport(call) {
13
- const sdkCall = (integrationId, className, methodName, params) => {
26
+ export function installPlatformTransport() {
27
+ const sdkCall = async (integrationId, className, methodName, params) => {
14
28
  const scope = requireScope(`${className}.${methodName}`);
15
- return call({
16
- integrationId,
17
- className,
18
- methodName,
19
- params,
20
- access: scope.kind,
21
- userId: scope.user?.id ?? null,
22
- requestId: getHost()?.requestId ?? "",
23
- });
29
+ const host = getHost();
30
+ const getsConnection = integrationId === INTEGRATIONS_PLATFORM_ID && methodName === "get";
31
+ const name = String(params?.name ?? "");
32
+ // Fails closed: no platform means no platform access, never a fallback.
33
+ if (!host?.platform)
34
+ throw new Error("The Zite platform binding is missing");
35
+ host.session ??= Promise.resolve(host.platform.session());
36
+ const session = await host.session;
37
+ if (integrationId === DATA_INTEGRATION_ID) {
38
+ const found = await dataContextOf(session);
39
+ return recordCall(host, { integrationId, className, methodName, params }, () => runDataCall(session, found, host.mode, methodName, params));
40
+ }
41
+ if (!integrationId.startsWith("__")) {
42
+ const airtable = await airtableSettingsOf(session, integrationId);
43
+ if (airtable) {
44
+ return recordCall(host, { integrationId, className, methodName, params }, () => runAirtableCall(host, session, integrationId, airtable, methodName, params, scope.kind));
45
+ }
46
+ }
47
+ const result = await session.call({ integrationId, className, methodName, params, access: scope.kind });
48
+ if (getsConnection)
49
+ return connectionAnswer(host, name, result);
50
+ if ("value" in result)
51
+ return result.value;
52
+ const { code, message, userFacingMessage } = result.error;
53
+ throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
24
54
  };
25
55
  globalThis.__wrapSdkCall = sdkCall;
56
+ watchOutboundFetches();
26
57
  }
58
+ /** `integrations.get`'s answer, whose values then name the calls made with them. */
59
+ const connectionAnswer = (host, name, result) => {
60
+ if ("value" in result) {
61
+ rememberConnection(host, name, result.value);
62
+ return result.value;
63
+ }
64
+ const { code, message, userFacingMessage } = result.error;
65
+ throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
66
+ };
67
+ /** A data call the app made itself, recorded as the host recorded the ones it made. */
68
+ const recordCall = async (host, call, run) => {
69
+ const at = Date.now();
70
+ const record = {
71
+ integrationId: call.integrationId,
72
+ className: call.className,
73
+ methodName: call.methodName,
74
+ at,
75
+ inputs: preview(call.params),
76
+ };
77
+ try {
78
+ const value = await run();
79
+ (host.calls ??= []).push({ ...record, durationMs: Date.now() - at, outputs: preview(value) });
80
+ return value;
81
+ }
82
+ catch (error) {
83
+ const { code, message } = errorOf(error);
84
+ (host.calls ??= []).push({ ...record, durationMs: Date.now() - at, error: { code, message } });
85
+ throw error;
86
+ }
87
+ };
88
+ // Keyed on globalThis so two copies of zitejs in one bundle wrap fetch once.
89
+ const WATCHED_KEY = Symbol.for("zitejs:outbound-fetch");
90
+ // Next patches fetch for the same reason: the run log must hear of each.
91
+ const watchOutboundFetches = () => {
92
+ const marks = globalThis;
93
+ if (marks[WATCHED_KEY])
94
+ return;
95
+ marks[WATCHED_KEY] = true;
96
+ globalThis.fetch = createOutboundFetch(globalThis.fetch.bind(globalThis));
97
+ };
27
98
  const decodeUser = (value) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0))));
28
- /** The host's `x-zite-*` headers. Only the host can set them: the front strips them from public traffic. */
29
- export function hostContextFromRequest(request) {
99
+ const INVOKE_KINDS = new Set(["webhook", "describe", "workflow", "register", "warm", "authHook", "function"]);
100
+ // What a request without props may ask for: neither runs app code on anyone's behalf.
101
+ const UNHOSTED_INVOKE_KINDS = new Set(["warm", "describe"]);
102
+ /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
103
+ export function hostContextFromProps(request, props) {
104
+ return {
105
+ requestId: props.requestId,
106
+ url: request.url,
107
+ user: props.user,
108
+ mode: props.mode,
109
+ invoke: props.invoke,
110
+ appUrl: props.appUrl,
111
+ baseId: props.baseId,
112
+ previewClaim: props.previewClaim,
113
+ env: props.env,
114
+ envConnections: props.envConnections,
115
+ runRoot: props.runRoot,
116
+ runs: [],
117
+ platform: props.platform,
118
+ };
119
+ }
120
+ // Classic sets these per run. Node and workerd both refuse getters on process.env, so each request writes what the
121
+ // host sent, which is the same for every request a build serves: the live URL even on a demo.
122
+ // The connection vars the last request set, so one gone since (an integration removed) doesn't linger.
123
+ let connectionEnvKeys = new Set();
124
+ const setRequestEnv = ({ appUrl, baseId, env: connectionEnv }) => {
125
+ const env = globalThis.process?.env;
126
+ if (!env)
127
+ return;
128
+ if (appUrl)
129
+ env.ZITE_APP_URL = appUrl;
130
+ if (baseId)
131
+ env.ZITE_BASE_ID = baseId;
132
+ if (!connectionEnv)
133
+ return;
134
+ for (const key of connectionEnvKeys)
135
+ if (!Object.hasOwn(connectionEnv, key))
136
+ delete env[key];
137
+ for (const [key, value] of Object.entries(connectionEnv)) {
138
+ if (key.startsWith("ZITE_"))
139
+ env[key] = value;
140
+ }
141
+ connectionEnvKeys = new Set(Object.keys(connectionEnv));
142
+ };
143
+ /**
144
+ * A request the host didn't dispatch: the host's warm-up, `zitejs describe` under `vite preview`, and tests. Only the
145
+ * host can set props, so without them a build answers warm and describe and nobody is signed in. An entry that passes
146
+ * its own platform (tests, local dev) owns its requests and may say who is calling in `x-zite-*` headers.
147
+ */
148
+ export function hostContextFromRequest(request, platform) {
30
149
  const { headers } = request;
31
- const user = headers.get("x-zite-user");
150
+ const trusted = platform !== undefined;
151
+ const user = trusted ? headers.get("x-zite-user") : null;
32
152
  const [kind, name = ""] = headers.get("x-zite-invoke")?.split(":") ?? [];
153
+ const kinds = trusted ? INVOKE_KINDS : UNHOSTED_INVOKE_KINDS;
33
154
  return {
34
- requestId: headers.get("x-zite-request-id") ?? crypto.randomUUID(),
155
+ requestId: (trusted && headers.get("x-zite-request-id")) || crypto.randomUUID(),
35
156
  url: request.url,
36
157
  user: user ? decodeUser(user) : null,
37
- invoke: kind === "webhook" || kind === "describe" || kind === "workflow" ? { kind, name } : null,
158
+ mode: "live",
159
+ invoke: kinds.has(kind) ? { kind: kind, name } : null,
38
160
  runs: [],
161
+ platform,
39
162
  };
40
163
  }
41
164
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
42
165
  export const builtFunctionIds = () => "__ZITE_FN_IDS__".split(",").filter((id) => id && !id.startsWith("__ZITE"));
43
- const parseDescriptions = (json) => {
166
+ const parseBuiltJson = (json) => {
44
167
  try {
45
168
  return JSON.parse(json);
46
169
  }
@@ -49,17 +172,54 @@ const parseDescriptions = (json) => {
49
172
  }
50
173
  };
51
174
  /** Each server function's `description` option, written in by `zite()` at build. */
52
- export const builtFunctionDescriptions = () => parseDescriptions("__ZITE_FN_DESCRIPTIONS__");
175
+ export const builtFunctionDescriptions = () => parseBuiltJson("__ZITE_FN_DESCRIPTIONS__");
176
+ /** Each route's file, by route id, written in by `zite()` at build. */
177
+ export const builtRouteFiles = () => parseBuiltJson("__ZITE_ROUTE_FILES__");
178
+ /** Each provider trigger's registration hash, by automation id, written in by `zite()` at build from its source. */
179
+ export const builtRegistrationHashes = () => parseBuiltJson("__ZITE_REGISTRATION_HASHES__");
53
180
  // Server functions also run while a streamed page renders, so the run log is
54
- // complete only once the body has been read to the end.
181
+ // complete only once the body ends: read to the end, cancelled by the reader or
182
+ // failed. A TransformStream's flush hears only the first.
55
183
  const onBodyEnd = (response, done) => {
56
184
  if (!response.body) {
57
185
  done();
58
186
  return response;
59
187
  }
60
- return new Response(response.body.pipeThrough(new TransformStream({ flush: done })), response);
188
+ const reader = response.body.getReader();
189
+ let ended = false;
190
+ const end = () => {
191
+ if (ended)
192
+ return;
193
+ ended = true;
194
+ done();
195
+ };
196
+ const body = new ReadableStream({
197
+ async pull(controller) {
198
+ try {
199
+ const { done: finished, value } = await reader.read();
200
+ if (finished) {
201
+ end();
202
+ controller.close();
203
+ }
204
+ else {
205
+ controller.enqueue(value);
206
+ }
207
+ }
208
+ catch (error) {
209
+ end();
210
+ controller.error(error);
211
+ }
212
+ },
213
+ cancel(reason) {
214
+ end();
215
+ return reader.cancel(reason);
216
+ },
217
+ });
218
+ return new Response(body, response);
61
219
  };
62
220
  const INVOKE_PATH = "/_zite/invoke";
221
+ /** On describe's answer: the zitejs this build's server code was bundled from. */
222
+ export const RUNTIME_VERSION_HEADER = "x-zitejs-version";
63
223
  // The host sends `{ input }`; a platform-fired run's input carries the runner's
64
224
  // `__cron`, `__poll` or `__webhook` state, exactly as for classic endpoints.
65
225
  async function invokeWorkflow(request, host, workflows) {
@@ -71,7 +231,7 @@ async function invokeWorkflow(request, host, workflows) {
71
231
  return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No workflow named ${name}` } }, { status: 404 });
72
232
  const input = (await request.json().catch(() => ({})))?.input;
73
233
  const startedAt = Date.now();
74
- const result = await runWorkflow(found.workflow, input);
234
+ const result = await runWorkflow(found.workflow, input, { resuming: host.runRoot !== undefined });
75
235
  host.runs.push({
76
236
  fn: `workflow:${found.id}`,
77
237
  name: found.id,
@@ -80,47 +240,160 @@ async function invokeWorkflow(request, host, workflows) {
80
240
  durationMs: Date.now() - startedAt,
81
241
  input: preview(loggedInput(input)),
82
242
  ...(result.ok ? { output: preview(result.output) } : { error: result.error }),
243
+ ...(result.steps ? { steps: result.steps } : {}),
244
+ ...(!result.ok && result.failedStep !== undefined ? { failedStep: result.failedStep } : {}),
83
245
  });
84
246
  return Response.json(result, { status: result.ok ? 200 : 500 });
85
247
  }
248
+ // The host sends `{ input }`, an editor's test run of a server function. It runs
249
+ // as a call from a page would on the server: its own middleware decides access
250
+ // for the user the host dispatched with, validates the input and records the run.
251
+ async function invokeFunction(request, options) {
252
+ if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
253
+ return new Response("Not found", { status: 404 });
254
+ const id = getHost()?.invoke?.name ?? "";
255
+ if (!builtFunctionIds().includes(id)) {
256
+ return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No server function ${id}` } }, { status: 404 });
257
+ }
258
+ const input = (await request.json().catch(() => ({})))?.input;
259
+ const startContext = {
260
+ request,
261
+ getRouter: options.getRouter,
262
+ startOptions: (await options.startInstance.getOptions()) ?? {},
263
+ executedRequestMiddlewares: new Set(),
264
+ contextAfterGlobalMiddlewares: {},
265
+ handlerType: "serverFn",
266
+ };
267
+ // In TanStack's request event too, which the function's own status setting reads.
268
+ return createServerEntry({
269
+ fetch: async () => {
270
+ try {
271
+ const answer = (await runWithStartContext(startContext, () => createSsrRpc(id)({ data: input, context: {} })));
272
+ if ("error" in answer)
273
+ throw answer.error;
274
+ return Response.json({ ok: true, output: answer.result ?? null });
275
+ }
276
+ catch (error) {
277
+ return Response.json({ ok: false, error: errorOf(error) }, { status: 500 });
278
+ }
279
+ },
280
+ }).fetch(request, undefined);
281
+ }
282
+ // The host sends `{ op, input }`: `subscribe` with the platform's notification
283
+ // URL and secret, or `unsubscribe` with what `subscribe` returned.
284
+ async function invokeRegistration(request, host, workflows) {
285
+ if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
286
+ return new Response("Not found", { status: 404 });
287
+ const name = host.invoke?.name ?? "";
288
+ const body = (await request.json().catch(() => null));
289
+ const result = await runRegistration(workflows, name, body?.op, body?.input);
290
+ if (!result) {
291
+ return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `${name} has no ${String(body?.op)}` } }, { status: 404 });
292
+ }
293
+ return Response.json(result, { status: result.ok ? 200 : 500 });
294
+ }
295
+ // The host sends `{ input }`, the same fields classic hooks get. A hook runs as
296
+ // a workflow does: no user, and the app's data and integrations through its platform.
297
+ async function invokeAuthHook(request, host) {
298
+ if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
299
+ return new Response("Not found", { status: 404 });
300
+ const name = host.invoke?.name ?? "";
301
+ const hook = isAuthHookName(name) ? (await loadAuthHooks())[name] : undefined;
302
+ if (!hook) {
303
+ return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No auth hook named ${name}` } }, { status: 404 });
304
+ }
305
+ const input = (await request.json().catch(() => ({})))?.input ?? {};
306
+ const startedAt = Date.now();
307
+ try {
308
+ const output = await runInScope({ kind: "workflow", user: null }, () => hook(input));
309
+ host.runs.push({ fn: `authHook:${name}`, name, nested: false, startedAt, durationMs: Date.now() - startedAt, input: preview(input), output: preview(output) });
310
+ return Response.json({ ok: true, output: output ?? null });
311
+ }
312
+ catch (error) {
313
+ const failed = errorOf(error);
314
+ host.runs.push({ fn: `authHook:${name}`, name, nested: false, startedAt, durationMs: Date.now() - startedAt, input: preview(input), error: failed });
315
+ return Response.json({ ok: false, error: failed }, { status: 500 });
316
+ }
317
+ }
318
+ // TanStack renders any loader error as a 500. A page refused with a ZiteError
319
+ // (a missing role, a record that isn't there) answers with that error's status.
320
+ const pageStatus = (host) => {
321
+ const matches = host.router?.state?.matches;
322
+ const failed = asZiteError(matches?.find((match) => match.status === "error")?.error);
323
+ return failed ? ZITE_ERROR_STATUS[failed.code] : undefined;
324
+ };
86
325
  /**
87
- * The fetch handler of a Start app's server entry. Describe calls get the app's
88
- * description; everything else runs TanStack with the host's identity in
89
- * server-only storage. Platform calls go to the `ZITE` binding from the Worker's
90
- * env, or to `platform` when a test or local dev supplies one.
326
+ * The handlers of a Start app's server entry. A request the host dispatched
327
+ * carries its identity and platform in props; anything else (describe under
328
+ * `vite preview`, tests) reads `x-zite-*` headers and uses `platform` if one
329
+ * is given.
91
330
  */
92
- export function createZiteFetch(options) {
93
- let binding = options.platform;
94
- // Fails closed: no binding means no platform access, never a fallback.
95
- const platform = () => {
96
- if (!binding)
97
- throw new Error("The Zite platform binding is missing");
98
- return binding;
99
- };
100
- installPlatformTransport((call) => platform().call(call));
331
+ export function createZiteHandlers(options) {
332
+ installPlatformTransport();
101
333
  // Loaded on first use, so a page request never pays for importing workflow modules.
102
334
  let workflows;
103
335
  const loadedWorkflows = () => (workflows ??= loadWorkflows());
104
- return async (request, ...rest) => {
105
- binding ??= rest[0]?.ZITE;
106
- if (request.headers.get("x-zite-invoke") === "describe") {
336
+ const serve = async (request, ctx) => {
337
+ const host = ctx?.props?.platform
338
+ ? hostContextFromProps(request, ctx.props)
339
+ : hostContextFromRequest(request, options.platform);
340
+ setRequestEnv(host);
341
+ // Starting this isolate was the point: the platform warms a build before its
342
+ // first visitors, and no app code runs.
343
+ if (host.invoke?.kind === "warm")
344
+ return new Response(null, { status: 204 });
345
+ if (host.invoke?.kind === "describe") {
107
346
  return Response.json(await describeApp({
108
347
  fnIds: builtFunctionIds(),
109
348
  descriptions: builtFunctionDescriptions(),
349
+ routeFiles: builtRouteFiles(),
350
+ registrationHashes: builtRegistrationHashes(),
110
351
  getRouter: options.getRouter,
111
352
  request,
112
353
  workflows: await loadedWorkflows(),
113
- }));
354
+ unfinishedWorkflows: await loadUnfinishedWorkflows(),
355
+ }), { headers: { [RUNTIME_VERSION_HEADER]: ZITEJS_VERSION } });
114
356
  }
115
- const host = hostContextFromRequest(request);
116
- const response = await runWithHost(host, async () => host.invoke?.kind === "workflow" ? invokeWorkflow(request, host, await loadedWorkflows()) : options.handler.fetch(request));
357
+ let response = await runWithHost(host, async () => host.invoke?.kind === "workflow"
358
+ ? invokeWorkflow(request, host, await loadedWorkflows())
359
+ : host.invoke?.kind === "function"
360
+ ? invokeFunction(request, options)
361
+ : host.invoke?.kind === "register"
362
+ ? withoutConsole(async () => invokeRegistration(request, host, await loadedWorkflows()))
363
+ : host.invoke?.kind === "authHook"
364
+ ? invokeAuthHook(request, host)
365
+ : options.handler.fetch(request));
366
+ const status = response.status === 500 ? pageStatus(host) : undefined;
367
+ if (status)
368
+ response = new Response(response.body, { status, headers: response.headers });
117
369
  return onBodyEnd(response, () => {
118
- if (!host.runs.length || !binding)
370
+ const { platform } = host;
371
+ if ((!host.runs.length && !host.calls?.length && !host.fetches?.length && !host.pending?.length) || !platform)
119
372
  return;
120
- const flushed = binding.runs({ requestId: host.requestId, runs: host.runs }).catch((error) => {
373
+ // On the request's session when it has one: one call, not another binding round trip.
374
+ const flushed = (async () => {
375
+ await Promise.all(host.pending ?? []);
376
+ if (!host.runs.length && !host.calls?.length && !host.fetches?.length)
377
+ return;
378
+ const batch = {
379
+ runs: host.runs,
380
+ ...(host.calls?.length && { calls: host.calls }),
381
+ ...(host.fetches?.length && { fetches: host.fetches }),
382
+ };
383
+ // Only a session takes fetches.
384
+ if (host.fetches?.length)
385
+ host.session ??= Promise.resolve(platform.session());
386
+ const session = host.session ? await host.session : undefined;
387
+ await (session ? session.runs(batch) : platform.runs(batch));
388
+ })().catch((error) => {
121
389
  console.error("[zite] couldn't record runs", error);
122
390
  });
123
- rest[1]?.waitUntil(flushed);
391
+ ctx?.waitUntil(flushed);
124
392
  });
125
393
  };
394
+ return { fetch: (request, ...rest) => serve(request, rest[1]) };
395
+ }
396
+ /** The fetch handler alone, for the Node entry. */
397
+ export function createZiteFetch(options) {
398
+ return createZiteHandlers(options).fetch;
126
399
  }
@@ -0,0 +1,28 @@
1
+ import type { ZiteStep } from "../backend/index.js";
2
+ /** What a workflow's handler gets as `step`. */
3
+ export type StartStep = Pick<ZiteStep, "run">;
4
+ export type StepLog = {
5
+ name: string;
6
+ status: "ran" | "memoized" | "failed";
7
+ durationMs?: number;
8
+ at: number;
9
+ };
10
+ type SdkCall = (integrationId: string, className: string, methodName: string, params: unknown) => Promise<unknown>;
11
+ export declare const STEP_RESULT_MAX_BYTES: number;
12
+ /**
13
+ * Each completed step's result is saved before the code after it runs, so a
14
+ * resumed run gets it back instead of running the step's side effects again.
15
+ * Only a resumed run reads saved results, once, at its first step.
16
+ */
17
+ export declare function createSteps({ call, resuming, now }: {
18
+ call: SdkCall;
19
+ resuming: boolean;
20
+ now?: () => number;
21
+ }): {
22
+ step: StartStep;
23
+ log: StepLog[];
24
+ failedStep: () => string | undefined;
25
+ /** A step that throws inside `Promise.all` ends the run while its siblings still save. */
26
+ settle: () => Promise<void>;
27
+ };
28
+ export {};
@@ -0,0 +1,97 @@
1
+ const STEPS_INTEGRATION_ID = "__steps__";
2
+ export const STEP_RESULT_MAX_BYTES = 256 * 1024;
3
+ const MAX_STEPS = 512;
4
+ const plain = (name, value) => {
5
+ let json;
6
+ try {
7
+ json = JSON.stringify(value);
8
+ }
9
+ catch (err) {
10
+ throw new Error(`step "${name}" returned a value that cannot be saved for retries: ${err instanceof Error ? err.message : String(err)}. Return plain JSON data from steps.`);
11
+ }
12
+ if (json === undefined)
13
+ return null;
14
+ if (new TextEncoder().encode(json).length > STEP_RESULT_MAX_BYTES) {
15
+ throw new Error(`step "${name}" returned more than ${STEP_RESULT_MAX_BYTES / 1024}KB. Store large data elsewhere and return a reference to it.`);
16
+ }
17
+ return JSON.parse(json);
18
+ };
19
+ /**
20
+ * Each completed step's result is saved before the code after it runs, so a
21
+ * resumed run gets it back instead of running the step's side effects again.
22
+ * Only a resumed run reads saved results, once, at its first step.
23
+ */
24
+ export function createSteps({ call, resuming, now = Date.now }) {
25
+ const seen = new Set();
26
+ const inFlight = new Set();
27
+ const log = [];
28
+ let failedStep;
29
+ let saved;
30
+ const savedResults = () => (saved ??= resuming
31
+ ? call(STEPS_INTEGRATION_ID, "Steps", "load", {}).catch((err) => {
32
+ throw new Error(`Could not read this run's saved steps (${err instanceof Error ? err.message : String(err)}); nothing ran again. Resume it once more.`);
33
+ })
34
+ : Promise.resolve(Object.create(null)));
35
+ const failed = (name, err, startedAt) => {
36
+ failedStep ??= name;
37
+ log.push({ name, status: "failed", durationMs: now() - startedAt, at: now() });
38
+ return err;
39
+ };
40
+ const body = async (name, fn) => {
41
+ const startedAt = now();
42
+ let value;
43
+ try {
44
+ value = plain(name, await fn());
45
+ }
46
+ catch (err) {
47
+ throw failed(name, err, startedAt);
48
+ }
49
+ // Awaited before the step returns: a crash after this never repeats it.
50
+ try {
51
+ await call(STEPS_INTEGRATION_ID, "Steps", "persist", { name, value, durationMs: now() - startedAt });
52
+ }
53
+ catch (err) {
54
+ throw failed(name, new Error(`Saving the result of step "${name}" failed (${err instanceof Error ? err.message : String(err)}). The step itself completed; nothing is wrong with the code — run again.`), startedAt);
55
+ }
56
+ log.push({ name, status: "ran", durationMs: now() - startedAt, at: now() });
57
+ return value;
58
+ };
59
+ const step = {
60
+ run: async (name, fn) => {
61
+ if (typeof name !== "string" || name.length === 0 || name.length > 255) {
62
+ throw new Error("step.run needs a stable name of 1 to 255 characters as its first argument");
63
+ }
64
+ if (seen.size >= MAX_STEPS)
65
+ throw new Error(`a run can take at most ${MAX_STEPS} steps — batch work inside fewer steps`);
66
+ if (typeof fn !== "function")
67
+ throw new Error(`step.run("${name}") needs a function as its second argument`);
68
+ if (seen.has(name)) {
69
+ throw new Error(`step.run was called twice with the name "${name}" in one run. Each step needs its own stable name so a retry can match saved results to steps.`);
70
+ }
71
+ seen.add(name);
72
+ const results = await savedResults();
73
+ if (Object.prototype.hasOwnProperty.call(results, name)) {
74
+ log.push({ name, status: "memoized", at: now() });
75
+ return results[name];
76
+ }
77
+ const settled = body(name, fn);
78
+ inFlight.add(settled);
79
+ try {
80
+ return (await settled);
81
+ }
82
+ finally {
83
+ inFlight.delete(settled);
84
+ }
85
+ },
86
+ };
87
+ return {
88
+ step,
89
+ log,
90
+ failedStep: () => failedStep,
91
+ /** A step that throws inside `Promise.all` ends the run while its siblings still save. */
92
+ settle: async () => {
93
+ if (inFlight.size > 0)
94
+ await Promise.allSettled([...inFlight]);
95
+ },
96
+ };
97
+ }