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,34 +1,192 @@
1
- import { createElement as h } from "react";
1
+ import { createElement as h, useEffect, useState } from "react";
2
+ import { QueryClient } from "@tanstack/react-query";
2
3
  import { createRouter, Link, useRouter, } from "@tanstack/react-router";
4
+ import { setupRouterSsrQueryIntegration } from "@tanstack/react-router-ssr-query";
5
+ import { asCrossed, errorFromThrown, isSignInError, withThrownRejections } from "./errors.js";
6
+ import { carryPreviewClaim, PREVIEW_CLAIM_PARAM, previewClaim } from "./previewClaim.js";
3
7
  import { currentHost } from "./host.js";
8
+ import { keepRenderedMode } from "../internal/appMode.js";
9
+ import { onProfileUpdated } from "../auth/profileUpdates.js";
10
+ // Long enough that a page's queries don't refetch as the browser picks it up, short enough to stay fresh.
11
+ export const QUERY_STALE_TIME_MS = 30_000;
12
+ /** @internal What a page carries to the browser beside its queries: the signed-in user, and the mode it was served in. */
13
+ export const dehydrateZite = (context) => ({ user: context.user, mode: currentHost()?.mode });
14
+ /** @internal The user after a profile edit, named as the host names them: first and last name, else the email. */
15
+ export const withProfile = (user, changes) => {
16
+ const { firstName: _firstName, lastName: _lastName, ...rest } = user;
17
+ const firstName = changes.firstName !== undefined ? changes.firstName : user.firstName;
18
+ const lastName = changes.lastName !== undefined ? changes.lastName : user.lastName;
19
+ return {
20
+ ...rest,
21
+ name: [firstName, lastName].filter(Boolean).join(" ") || user.email,
22
+ ...(firstName && { firstName }),
23
+ ...(lastName && { lastName }),
24
+ };
25
+ };
26
+ /** @internal In the browser: `updateProfile` from zitejs/auth updates the router's user and reruns its guards and loaders. */
27
+ export const refreshOnProfileUpdate = (router, context) => onProfileUpdated((changes) => {
28
+ if (!context.user)
29
+ return;
30
+ context.user = withProfile(context.user, changes);
31
+ void router.invalidate();
32
+ });
33
+ /** @internal Takes in what the page carried. */
34
+ export const hydrateZite = (context, dehydrated) => {
35
+ context.user = dehydrated.user;
36
+ keepRenderedMode(dehydrated.mode);
37
+ };
38
+ const ziteWindow = () => (typeof window === "undefined" ? undefined : window);
4
39
  const box = { maxWidth: 480, margin: "15vh auto", padding: 24, fontFamily: "system-ui, sans-serif", textAlign: "center" };
40
+ /**
41
+ * @internal Tells the editor's preview the page crashed, as classic's runtime reports an emptied #root: a Start page
42
+ * has none, and an error a route's boundary catches is the crash. Being signed out isn't one.
43
+ */
44
+ export const reportCrash = (error) => {
45
+ if (!isSignInError(error))
46
+ ziteWindow()?._ziteOnCrash?.(error);
47
+ };
48
+ // As classic's crash screen: the message, "Fix it for me" in the editor, and a reload. The server renders from the
49
+ // error the router already mapped and the browser from the one that crossed, so both show the same text.
5
50
  function ZiteErrorComponent({ error }) {
6
51
  const router = useRouter();
7
- const message = error instanceof Error && error.name === "ZiteError" ? error.message : "Something went wrong.";
8
- return h("div", { role: "alert", style: box }, h("p", { style: { fontWeight: 600 } }, message), h("button", { type: "button", onClick: () => router.invalidate() }, "Try again"));
52
+ const [allowAiFix, setAllowAiFix] = useState(false);
53
+ useEffect(() => setAllowAiFix(ziteWindow()?.__ziteAllowAiFix === true), []);
54
+ useEffect(() => markReady("error"), []);
55
+ const message = error instanceof Error ? error.message : String(error);
56
+ const reload = () => {
57
+ const onReload = ziteWindow()?._ziteOnReload;
58
+ if (onReload)
59
+ onReload();
60
+ else
61
+ router.invalidate();
62
+ };
63
+ return h("div", { role: "alert", style: box }, h("p", { style: { fontWeight: 600 } }, "Something went wrong"), h("pre", { style: { whiteSpace: "pre-wrap", textAlign: "left" } }, message), allowAiFix &&
64
+ !isSignInError(error) &&
65
+ h("button", { type: "button", onClick: () => ziteWindow()?._ziteOnFixError?.(error) }, "Fix it for me"), h("button", { type: "button", onClick: reload }, "Try again"));
9
66
  }
67
+ /**
68
+ * `<html data-zite-ready>`: what the platform's screenshots wait for. `1` once
69
+ * the page has rendered with nothing loading, `error` when the error screen did.
70
+ */
71
+ const markReady = (state) => {
72
+ if (typeof document !== "undefined")
73
+ document.documentElement.dataset.ziteReady = state;
74
+ };
75
+ const watchReady = (router) => () => {
76
+ const { status, isLoading, matches } = router.state;
77
+ if (status !== "idle" || isLoading || matches.some((match) => match.status === "pending"))
78
+ return;
79
+ markReady(matches.some((match) => match.status === "error") ? "error" : "1");
80
+ };
10
81
  function ZiteNotFound() {
11
82
  return h("div", { style: box }, h("p", { style: { fontWeight: 600 } }, "Page not found"), h(Link, { to: "/" }, "Go home"));
12
83
  }
84
+ function ZitePending() {
85
+ return h("div", { "aria-busy": true, style: { ...box, color: "#888" } }, "Loading…");
86
+ }
87
+ const rejectingWithErrors = (load) => (...args) => {
88
+ const out = load(...args);
89
+ return out instanceof Promise ? out.then(withThrownRejections) : withThrownRejections(out);
90
+ };
91
+ // A loader's error crosses to the browser as thrown, and so does a deferred value's rejection; only an Error goes
92
+ // through the zite-error adapter. A route's onError may replace its error; routes outlive a request's router, so each
93
+ // is wrapped once.
94
+ const wrapped = new WeakSet();
95
+ const failWithErrors = (routes) => {
96
+ for (const route of routes) {
97
+ if (wrapped.has(route))
98
+ continue;
99
+ wrapped.add(route);
100
+ const own = route.options.onError;
101
+ const loader = route.options.loader;
102
+ route.update({
103
+ onError: (error) => {
104
+ let failure = error;
105
+ try {
106
+ own?.(error);
107
+ }
108
+ catch (replaced) {
109
+ failure = replaced;
110
+ }
111
+ const normalized = errorFromThrown(failure);
112
+ // The server renders a failed route's error component in-process.
113
+ if (typeof window === "undefined" && normalized instanceof Error)
114
+ throw asCrossed(normalized);
115
+ if (normalized !== error)
116
+ throw normalized;
117
+ },
118
+ ...(loader && {
119
+ loader: typeof loader === "function" ? rejectingWithErrors(loader) : { ...loader, handler: rejectingWithErrors(loader.handler) },
120
+ }),
121
+ });
122
+ }
123
+ };
124
+ // The claim stays on every URL the router writes, and the app's own routes never see it.
125
+ const keepPreviewClaim = (claim, own) => ({
126
+ input: ({ url }) => {
127
+ url.searchParams.delete(PREVIEW_CLAIM_PARAM);
128
+ return own?.input?.({ url }) ?? url;
129
+ },
130
+ output: ({ url }) => {
131
+ const rewritten = own?.output?.({ url }) ?? url;
132
+ const out = new URL(rewritten.toString(), url);
133
+ out.searchParams.set(PREVIEW_CLAIM_PARAM, claim);
134
+ return out;
135
+ },
136
+ });
13
137
  /**
14
- * The router for `src/router.tsx`. The signed-in user is in `context.user`: on
15
- * the server from the platform, in the browser from the page it rendered, so
16
- * no request asks for it again.
138
+ * The router for `src/router.tsx`. The signed-in user is in `context.user`: on the server from the platform, in the
139
+ * browser from the page it rendered, so no request asks for it again. `context.queryClient` is new for each request
140
+ * on the server, so a page never renders with another visitor's cached queries, and its queries reach the browser
141
+ * with the page.
17
142
  */
18
143
  export function createZiteRouter(options) {
19
- const context = { user: currentHost()?.user ?? null };
144
+ const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: QUERY_STALE_TIME_MS } } });
145
+ const claim = previewClaim();
146
+ if (claim)
147
+ carryPreviewClaim(claim);
148
+ const context = { user: currentHost()?.user ?? null, queryClient };
20
149
  const router = createRouter({
21
150
  defaultPreload: "intent",
22
151
  defaultPreloadStaleTime: 0,
23
152
  scrollRestoration: true,
24
153
  defaultErrorComponent: ZiteErrorComponent,
25
154
  defaultNotFoundComponent: ZiteNotFound,
155
+ defaultPendingComponent: ZitePending,
26
156
  ...options,
27
- context,
28
- dehydrate: () => ({ user: context.user }),
29
- hydrate: (dehydrated) => {
30
- context.user = dehydrated.user;
157
+ ...(claim && { rewrite: keepPreviewClaim(claim, options.rewrite) }),
158
+ // Whichever screen shows it: a route may have its own.
159
+ defaultOnCatch: (error, info) => {
160
+ markReady("error");
161
+ reportCrash(error);
162
+ options.defaultOnCatch?.(error, info);
31
163
  },
164
+ context,
165
+ dehydrate: () => dehydrateZite(context),
166
+ hydrate: (dehydrated) => hydrateZite(context, dehydrated),
32
167
  });
168
+ failWithErrors(Object.values(router.routesById));
169
+ setupRouterSsrQueryIntegration({ router, queryClient });
170
+ const mark = watchReady(router);
171
+ router.subscribe("onResolved", mark);
172
+ router.subscribe("onRendered", mark);
173
+ const host = currentHost();
174
+ if (host)
175
+ host.router = router;
176
+ if (typeof window === "undefined")
177
+ refuseOtherRequests(router, host);
178
+ else
179
+ refreshOnProfileUpdate(router, context);
33
180
  return router;
34
181
  }
182
+ // A router built once for the isolate would render the first visitor's user and cached queries into every
183
+ // later visitor's page, and its guards would treat everyone as that visitor.
184
+ const refuseOtherRequests = (router, builtFor) => {
185
+ const load = router.load.bind(router);
186
+ router.load = async (...args) => {
187
+ if (currentHost() !== builtFor) {
188
+ throw new Error("This router was built for another request. Call createZiteRouter inside getRouter, so each request gets its own.");
189
+ }
190
+ return load(...args);
191
+ };
192
+ };
@@ -1,5 +1,8 @@
1
+ import type { RunRecord, HostRequestState } from "./types.js";
1
2
  export declare const preview: (value: unknown) => string | undefined;
2
- export declare const errorOf: (error: unknown) => {
3
- code: string;
4
- message: string;
5
- };
3
+ export declare const errorOf: (error: unknown) => NonNullable<RunRecord["error"]>;
4
+ /**
5
+ * A server route's run, which run capture doesn't see: its body in, and its status and body out. The bodies are
6
+ * read from copies after the fact, so the response never waits; the run log waits for them before it flushes.
7
+ */
8
+ export declare function recordRoute<T>(host: HostRequestState | undefined, request: Request, run: () => Promise<T>): Promise<T>;
@@ -1,5 +1,7 @@
1
- import { ZiteError } from "./index.js";
2
- const PREVIEW_LIMIT = 8_000;
1
+ import { asZiteError } from "./errors.js";
2
+ // Classic's per-field cap. The host caps again; this keeps a large value from crossing at all.
3
+ const RUN_FIELD_LIMIT = 50 * 1024;
4
+ const capped = (text) => (text.length > RUN_FIELD_LIMIT ? `${text.slice(0, RUN_FIELD_LIMIT)}…` : text);
3
5
  export const preview = (value) => {
4
6
  if (value === undefined)
5
7
  return undefined;
@@ -7,12 +9,68 @@ export const preview = (value) => {
7
9
  return "[stream]";
8
10
  try {
9
11
  const json = JSON.stringify(value);
10
- return json && json.length > PREVIEW_LIMIT ? `${json.slice(0, PREVIEW_LIMIT)}…` : json;
12
+ return json === undefined ? undefined : capped(json);
11
13
  }
12
14
  catch {
13
15
  return "[unserializable]";
14
16
  }
15
17
  };
16
- export const errorOf = (error) => error instanceof ZiteError
17
- ? { code: error.code, message: error.message }
18
- : { code: "INTERNAL_ERROR", message: error instanceof Error ? error.message : String(error) };
18
+ export const errorOf = (error) => ({
19
+ code: asZiteError(error)?.code ?? "INTERNAL_ERROR",
20
+ message: error instanceof Error ? error.message : String(error),
21
+ ...(error instanceof Error && error.stack ? { stack: capped(error.stack) } : {}),
22
+ });
23
+ const TEXT_BODY = /^(application\/(json|x-www-form-urlencoded)|text\/(?!event-stream))/i;
24
+ // Up to the cap of a copy of the body, so the app still reads the original. Uploads and streams aren't read.
25
+ const bodyText = async (message) => {
26
+ if (!message.body || !TEXT_BODY.test(message.headers.get("content-type") ?? ""))
27
+ return undefined;
28
+ const reader = message.clone().body.pipeThrough(new TextDecoderStream()).getReader();
29
+ let text = "";
30
+ try {
31
+ while (text.length <= RUN_FIELD_LIMIT) {
32
+ const { done, value } = await reader.read();
33
+ if (done)
34
+ break;
35
+ text += value;
36
+ }
37
+ }
38
+ finally {
39
+ reader.cancel().catch(() => { });
40
+ }
41
+ return capped(text);
42
+ };
43
+ /**
44
+ * A server route's run, which run capture doesn't see: its body in, and its status and body out. The bodies are
45
+ * read from copies after the fact, so the response never waits; the run log waits for them before it flushes.
46
+ */
47
+ export async function recordRoute(host, request, run) {
48
+ if (!host)
49
+ return run();
50
+ const startedAt = Date.now();
51
+ const path = new URL(request.url).pathname;
52
+ const input = bodyText(request).catch(() => undefined);
53
+ const record = (outcome) => {
54
+ const durationMs = Date.now() - startedAt;
55
+ const recorded = (async () => {
56
+ const fields = { input: await input, ...(await outcome) };
57
+ host.runs.push({ fn: `route:${request.method} ${path}`, name: path, nested: false, startedAt, durationMs, ...fields });
58
+ })();
59
+ (host.pending ??= []).push(recorded.catch(() => { }));
60
+ };
61
+ try {
62
+ const out = await run();
63
+ const response = out instanceof Response ? out : out?.response;
64
+ if (response instanceof Response) {
65
+ record(bodyText(response).then((body) => ({ output: preview({ status: response.status, body }) }), () => ({})));
66
+ }
67
+ else {
68
+ record(Promise.resolve({}));
69
+ }
70
+ return out;
71
+ }
72
+ catch (error) {
73
+ record(Promise.resolve({ error: errorOf(error) }));
74
+ throw error;
75
+ }
76
+ }
@@ -1,5 +1,5 @@
1
- import type { User, ZiteRequestContext } from "./types.js";
2
- export type AccessKind = "signedIn" | "anyone" | "webhook" | "workflow";
1
+ import type { AccessKind, User, HostRequestState } from "./types.js";
2
+ export type { AccessKind } from "./types.js";
3
3
  export type AccessScope = {
4
4
  kind: AccessKind;
5
5
  user: User | null;
@@ -11,5 +11,5 @@ export declare class NoAccessDecisionError extends Error {
11
11
  constructor(what: string);
12
12
  }
13
13
  export declare const requireScope: (what: string) => AccessScope;
14
- export declare const runWithHost: <T>(host: ZiteRequestContext, fn: () => T) => T;
15
- export declare const getHost: () => ZiteRequestContext | undefined;
14
+ export declare const runWithHost: <T>(host: HostRequestState, fn: () => T) => T;
15
+ export declare const getHost: () => HostRequestState | undefined;
@@ -1,49 +1,53 @@
1
- import { type AccessKind } from "./scope.js";
2
- import type { RunRecord, ZiteRequestContext } from "./types.js";
1
+ import type { HostProps, PlatformBinding, HostRequestState } from "./types.js";
3
2
  export { runWithHost } from "./scope.js";
4
3
  export { describeApp } from "./describe.js";
5
- export type { RunRecord } from "./types.js";
6
- export type PlatformCallInput = {
7
- integrationId: string;
8
- className: string;
9
- methodName: string;
10
- params: unknown;
11
- access: AccessKind;
12
- userId: string | null;
13
- requestId: string;
14
- };
15
- /** The `ZITE` service binding the host's Platform entrypoint gives every app script. */
16
- export type PlatformBinding = {
17
- call(call: PlatformCallInput): Promise<unknown>;
18
- /** One batch per request, after its response has ended. */
19
- runs(batch: {
20
- requestId: string;
21
- runs: RunRecord[];
22
- }): Promise<void>;
23
- };
4
+ export type { HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult, PlatformSession, RunRecord } from "./types.js";
5
+ /**
6
+ * Routes every zitejs data, integration and email call to this request's
7
+ * platform, on one session, and only inside an access scope. The access kind
8
+ * travels with the call so the platform can record what a page read and narrow
9
+ * anonymous reads.
10
+ */
11
+ export declare function installPlatformTransport(): void;
12
+ /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
13
+ export declare function hostContextFromProps(request: Request, props: HostProps): HostRequestState;
24
14
  /**
25
- * Routes every zitejs data, integration and email call through `call`, and only
26
- * inside an access scope. The access kind travels with the call so the platform
27
- * can record what a page read and, later, narrow anonymous reads.
15
+ * A request the host didn't dispatch: the host's warm-up, `zitejs describe` under `vite preview`, and tests. Only the
16
+ * host can set props, so without them a build answers warm and describe and nobody is signed in. An entry that passes
17
+ * its own platform (tests, local dev) owns its requests and may say who is calling in `x-zite-*` headers.
28
18
  */
29
- export declare function installPlatformTransport(call: (input: PlatformCallInput) => Promise<unknown>): void;
30
- /** The host's `x-zite-*` headers. Only the host can set them: the front strips them from public traffic. */
31
- export declare function hostContextFromRequest(request: Request): ZiteRequestContext;
19
+ export declare function hostContextFromRequest(request: Request, platform?: PlatformBinding): HostRequestState;
32
20
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
33
21
  export declare const builtFunctionIds: () => string[];
34
22
  /** Each server function's `description` option, written in by `zite()` at build. */
35
23
  export declare const builtFunctionDescriptions: () => Record<string, string>;
24
+ /** Each route's file, by route id, written in by `zite()` at build. */
25
+ export declare const builtRouteFiles: () => Record<string, string>;
26
+ /** Each provider trigger's registration hash, by automation id, written in by `zite()` at build from its source. */
27
+ export declare const builtRegistrationHashes: () => Record<string, string>;
36
28
  type Fetch = (request: Request, ...rest: unknown[]) => Promise<Response> | Response;
37
- /**
38
- * The fetch handler of a Start app's server entry. Describe calls get the app's
39
- * description; everything else runs TanStack with the host's identity in
40
- * server-only storage. Platform calls go to the `ZITE` binding from the Worker's
41
- * env, or to `platform` when a test or local dev supplies one.
42
- */
43
- export declare function createZiteFetch(options: {
29
+ /** On describe's answer: the zitejs this build's server code was bundled from. */
30
+ export declare const RUNTIME_VERSION_HEADER = "x-zitejs-version";
31
+ export type ZiteServerOptions = {
44
32
  handler: {
45
- fetch: Fetch;
33
+ fetch(request: Request, ...rest: unknown[]): Promise<Response> | Response;
46
34
  };
47
35
  getRouter: () => unknown;
48
36
  platform?: PlatformBinding;
49
- }): Fetch;
37
+ /** The app's start instance, which a test run of a server function runs under. */
38
+ startInstance: {
39
+ getOptions: () => unknown;
40
+ };
41
+ };
42
+ export type ZiteHandlers = {
43
+ fetch: Fetch;
44
+ };
45
+ /**
46
+ * The handlers of a Start app's server entry. A request the host dispatched
47
+ * carries its identity and platform in props; anything else (describe under
48
+ * `vite preview`, tests) reads `x-zite-*` headers and uses `platform` if one
49
+ * is given.
50
+ */
51
+ export declare function createZiteHandlers(options: ZiteServerOptions): ZiteHandlers;
52
+ /** The fetch handler alone, for the Node entry. */
53
+ export declare function createZiteFetch(options: ZiteServerOptions): Fetch;