zitejs 0.10.0-start.21 → 0.10.0-start.22

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 (112) hide show
  1. package/dist/cjs/auth/client.d.ts +2 -2
  2. package/dist/cjs/check/start/sourceRules.js +3 -0
  3. package/dist/cjs/cli.js +6 -0
  4. package/dist/cjs/dev/index.js +15 -0
  5. package/dist/cjs/dev/signin.d.ts +16 -0
  6. package/dist/cjs/dev/signin.js +76 -0
  7. package/dist/cjs/internal/appMode.d.ts +11 -0
  8. package/dist/cjs/internal/appMode.js +4 -1
  9. package/dist/cjs/internal/appToken.d.ts +17 -0
  10. package/dist/cjs/internal/appToken.js +26 -0
  11. package/dist/cjs/internal/platformFetch.d.ts +2 -0
  12. package/dist/cjs/internal/platformFetch.js +13 -0
  13. package/dist/cjs/internal/serviceUrls.d.ts +7 -0
  14. package/dist/cjs/internal/serviceUrls.js +16 -0
  15. package/dist/cjs/runtime/index.d.ts +1 -1
  16. package/dist/cjs/start/aiUsage.d.ts +23 -0
  17. package/dist/cjs/start/aiUsage.js +151 -0
  18. package/dist/cjs/start/devApp.d.ts +1 -0
  19. package/dist/cjs/start/devApp.js +6 -0
  20. package/dist/cjs/start/entries.js +4 -0
  21. package/dist/cjs/start/provider.d.ts +24 -0
  22. package/dist/cjs/start/provider.js +159 -0
  23. package/dist/cjs/start/types.d.ts +320 -0
  24. package/dist/cjs/start/types.js +2 -0
  25. package/dist/cjs/upload/index.js +73 -22
  26. package/dist/cjs/upload/index.test.js +35 -2
  27. package/dist/esm/auth/client.d.ts +2 -2
  28. package/dist/esm/check/start/sourceRules.js +3 -0
  29. package/dist/esm/cli.js +6 -0
  30. package/dist/esm/dev/index.js +15 -0
  31. package/dist/esm/dev/signin.d.ts +16 -0
  32. package/dist/esm/dev/signin.js +72 -0
  33. package/dist/esm/internal/appMode.d.ts +11 -0
  34. package/dist/esm/internal/appMode.js +2 -0
  35. package/dist/esm/internal/appToken.d.ts +17 -0
  36. package/dist/esm/internal/appToken.js +22 -0
  37. package/dist/esm/internal/platformFetch.d.ts +2 -0
  38. package/dist/esm/internal/platformFetch.js +8 -0
  39. package/dist/esm/internal/serviceUrls.d.ts +7 -0
  40. package/dist/esm/internal/serviceUrls.js +12 -0
  41. package/dist/esm/runtime/index.d.ts +1 -1
  42. package/dist/esm/signin/conformance.d.ts +100 -0
  43. package/dist/esm/signin/conformance.js +471 -0
  44. package/dist/esm/signin/cookies.d.ts +28 -0
  45. package/dist/esm/signin/cookies.js +59 -0
  46. package/dist/esm/signin/encoding.d.ts +9 -0
  47. package/dist/esm/signin/encoding.js +39 -0
  48. package/dist/esm/signin/endpoints.d.ts +12 -0
  49. package/dist/esm/signin/endpoints.js +29 -0
  50. package/dist/esm/signin/http.d.ts +25 -0
  51. package/dist/esm/signin/http.js +69 -0
  52. package/dist/esm/signin/index.d.ts +8 -0
  53. package/dist/esm/signin/index.js +9 -0
  54. package/dist/esm/signin/keys.d.ts +39 -0
  55. package/dist/esm/signin/keys.js +80 -0
  56. package/dist/esm/signin/paths.d.ts +2 -0
  57. package/dist/esm/signin/paths.js +2 -0
  58. package/dist/esm/signin/seal.d.ts +8 -0
  59. package/dist/esm/signin/seal.js +35 -0
  60. package/dist/esm/signin/signin.d.ts +60 -0
  61. package/dist/esm/signin/signin.js +340 -0
  62. package/dist/esm/signin/transport.d.ts +111 -0
  63. package/dist/esm/signin/transport.js +1 -0
  64. package/dist/esm/signin/verify.d.ts +77 -0
  65. package/dist/esm/signin/verify.js +155 -0
  66. package/dist/esm/start/airtable/index.d.ts +1 -1
  67. package/dist/esm/start/analytics.d.ts +5 -0
  68. package/dist/esm/start/analytics.js +77 -0
  69. package/dist/esm/start/data/index.d.ts +3 -3
  70. package/dist/esm/start/data/index.js +1 -1
  71. package/dist/esm/start/devApp.d.ts +1 -0
  72. package/dist/esm/start/devApp.js +3 -0
  73. package/dist/esm/start/devSignIn.d.ts +1 -0
  74. package/dist/esm/start/devSignIn.js +3 -0
  75. package/dist/esm/start/direct.d.ts +40 -0
  76. package/dist/esm/start/direct.js +313 -0
  77. package/dist/esm/start/entries.js +4 -0
  78. package/dist/esm/start/fetch.d.ts +1 -0
  79. package/dist/esm/start/fetch.js +4 -0
  80. package/dist/esm/start/instance.js +6 -2
  81. package/dist/esm/start/localSignIn.d.ts +18 -0
  82. package/dist/esm/start/localSignIn.js +73 -0
  83. package/dist/esm/start/outbound.d.ts +10 -1
  84. package/dist/esm/start/outbound.js +132 -22
  85. package/dist/esm/start/pageHead.d.ts +36 -0
  86. package/dist/esm/start/pageHead.js +178 -0
  87. package/dist/esm/start/provider.d.ts +24 -0
  88. package/dist/esm/start/provider.js +150 -0
  89. package/dist/esm/start/router.d.ts +6 -2
  90. package/dist/esm/start/router.js +41 -2
  91. package/dist/esm/start/server.d.ts +13 -6
  92. package/dist/esm/start/server.js +173 -42
  93. package/dist/esm/start/telemetry.d.ts +10 -0
  94. package/dist/esm/start/telemetry.js +74 -0
  95. package/dist/esm/start/types.d.ts +117 -2
  96. package/dist/esm/start/uploads.d.ts +2 -0
  97. package/dist/esm/start/uploads.js +52 -0
  98. package/dist/esm/start/version.d.ts +1 -1
  99. package/dist/esm/start/version.js +1 -1
  100. package/dist/esm/start/vite.d.ts +12 -1
  101. package/dist/esm/start/vite.js +116 -4
  102. package/dist/esm/start/workspaceSchema.d.ts +1 -0
  103. package/dist/esm/start/workspaceSchema.js +3 -0
  104. package/dist/esm/upload/index.js +74 -23
  105. package/dist/esm/upload/index.test.js +35 -2
  106. package/package.json +21 -11
  107. package/dist/cjs/auth-server/index.d.ts +0 -369
  108. package/dist/cjs/auth-server/index.js +0 -119
  109. package/dist/esm/auth-server/index.d.ts +0 -369
  110. package/dist/esm/auth-server/index.js +0 -116
  111. package/dist/esm/start/problems.d.ts +0 -19
  112. package/dist/esm/start/problems.js +0 -8
@@ -0,0 +1,150 @@
1
+ // The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token, the
2
+ // platform's URLs and who is calling, in props. `local`: a developer's machine, with a dev token the backend minted.
3
+ import { appTokenClaims } from "../internal/appToken.js";
4
+ import { platformFetch } from "../internal/platformFetch.js";
5
+ import { devAppId } from "./devApp.js";
6
+ // A streamed answer can outlive the request's deadline, which the token's expiry follows.
7
+ const RENEW_WITHIN_MS = 30_000;
8
+ const expiresWithin = (token, ms) => {
9
+ const claims = appTokenClaims(token);
10
+ return claims !== undefined && claims.exp * 1000 - Date.now() < ms;
11
+ };
12
+ const URL_NAMES = ["baseRunner", "backend", "aiGateway", "runs", "email", "pdf", "uploads", "steps"];
13
+ // `local` may leave out the AI gateway (a call on Zite's AI key is then refused), `runs` (a preview sends no analytics,
14
+ // and `local` keeps no run detail) and each service's own URL (the backend then answers it).
15
+ const OPTIONAL_URLS = new Set(["aiGateway", "runs", "email", "pdf", "uploads", "steps"]);
16
+ const trimmed = (urls) => Object.fromEntries(URL_NAMES.flatMap((name) => (urls[name] ? [[name, urls[name].replace(/\/+$/, "")]] : [])));
17
+ export const ziteProvider = (props, session) => {
18
+ let current = props.appToken;
19
+ let renewing;
20
+ const renew = async () => {
21
+ try {
22
+ const fresh = await (await session())?.appToken?.();
23
+ return typeof fresh === "string" && fresh ? fresh : undefined;
24
+ }
25
+ catch (error) {
26
+ // A host that predates renewal: the token holds until it expires.
27
+ console.error("[zite] couldn't renew the app token", error);
28
+ return undefined;
29
+ }
30
+ };
31
+ return {
32
+ kind: "zite",
33
+ urls: props.urls && trimmed(props.urls),
34
+ user: () => props.user,
35
+ token: async () => {
36
+ if (!current || !expiresWithin(current, RENEW_WITHIN_MS))
37
+ return current;
38
+ renewing ??= renew().finally(() => (renewing = undefined));
39
+ current = (await renewing) ?? current;
40
+ return current;
41
+ },
42
+ };
43
+ };
44
+ /** What `local` reads, documented in `zitejs`'s help. */
45
+ export const LOCAL_ENV = { token: "ZITE_DEV_TOKEN", apiKey: "ZITE_DEV_API_KEY", urls: "ZITE_URLS", user: "ZITE_DEV_USER" };
46
+ const processEnv = () => globalThis.process?.env;
47
+ /** `ZITE_URLS`, or a throw saying what it must name. */
48
+ export const localUrls = (raw) => {
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(raw ?? "");
52
+ }
53
+ catch {
54
+ parsed = undefined;
55
+ }
56
+ const given = (parsed ?? {});
57
+ const isUrl = (value) => typeof value === "string" && /^https?:\/\//.test(value);
58
+ if (URL_NAMES.some((name) => (given[name] === undefined ? !OPTIONAL_URLS.has(name) : !isUrl(given[name])))) {
59
+ throw new Error(`${LOCAL_ENV.urls} must be JSON naming the baseRunner and backend URLs, and may name aiGateway, runs, email, pdf, uploads and steps`);
60
+ }
61
+ return trimmed(given);
62
+ };
63
+ const localUser = (raw) => {
64
+ if (!raw)
65
+ return null;
66
+ let given;
67
+ try {
68
+ given = JSON.parse(raw);
69
+ }
70
+ catch {
71
+ given = undefined;
72
+ }
73
+ if (typeof given?.id !== "string" || typeof given.email !== "string") {
74
+ throw new Error(`${LOCAL_ENV.user} must be JSON with the stand-in user's id and email`);
75
+ }
76
+ const roles = Array.isArray(given.roles) ? given.roles : [];
77
+ return {
78
+ id: given.id,
79
+ email: given.email,
80
+ name: typeof given.name === "string" ? given.name : given.email,
81
+ roles: roles.map((role) => (typeof role === "string" ? { id: role, name: role } : role)),
82
+ isInternal: given.isInternal === true,
83
+ };
84
+ };
85
+ const MODES = new Set(["live", "preview", "demo"]);
86
+ /** The mode a dev token names; preview for one it doesn't. */
87
+ export const localModeOf = (claims) => MODES.has(claims?.mode) ? claims?.mode : "preview";
88
+ // The backend mints them for 15 minutes.
89
+ const RENEW_DEV_TOKEN_WITHIN_MS = 60_000;
90
+ const MINT_TIMEOUT_MS = 10_000;
91
+ // Per isolate, only a minted token, never a pending mint: Workers ties a request's I/O to that request.
92
+ let held;
93
+ /** For tests: forget the minted dev token. */
94
+ export const resetDevToken = () => {
95
+ held = undefined;
96
+ };
97
+ export const mintDevToken = async (backend, appId, apiKey) => {
98
+ const response = await platformFetch(new Request(`${backend}/v1/start/apps/${encodeURIComponent(appId)}/dev-token`, {
99
+ method: "POST",
100
+ headers: { authorization: `Bearer ${apiKey}` },
101
+ signal: AbortSignal.timeout(MINT_TIMEOUT_MS),
102
+ }));
103
+ const answer = (await response.json().catch(() => null));
104
+ if (response.ok && typeof answer?.token === "string")
105
+ return answer.token;
106
+ const why = [answer?.message, answer?.error].find((text) => typeof text === "string");
107
+ throw new Error(`The backend didn't mint a dev token for app ${appId} with ${LOCAL_ENV.apiKey}: ${response.status}${why ? ` ${why}` : ""}`);
108
+ };
109
+ /** The app's dev token, minted with the developer's key, and minted again when it's about to expire. */
110
+ const mintedDevToken = (backend, appId, apiKey) => {
111
+ const key = `${backend} ${appId} ${apiKey}`;
112
+ let minting;
113
+ return async () => {
114
+ const current = held?.key === key ? held.token : undefined;
115
+ if (current && !expiresWithin(current, RENEW_DEV_TOKEN_WITHIN_MS))
116
+ return current;
117
+ minting ??= mintDevToken(backend, appId, apiKey).finally(() => (minting = undefined));
118
+ try {
119
+ const token = await minting;
120
+ held = { key, token };
121
+ return token;
122
+ }
123
+ catch (error) {
124
+ if (!current || expiresWithin(current, 0))
125
+ throw error;
126
+ console.error("[zite] couldn't renew the dev token; using the one held until it expires", error);
127
+ return current;
128
+ }
129
+ };
130
+ };
131
+ // A given dev token is used as it is. A key mints them only under `vite dev`, which knows the app's id.
132
+ const localToken = (env, appId) => {
133
+ const given = env[LOCAL_ENV.token];
134
+ if (given)
135
+ return () => async () => given;
136
+ const apiKey = env[LOCAL_ENV.apiKey];
137
+ return apiKey && appId ? (backend) => mintedDevToken(backend, appId, apiKey) : undefined;
138
+ };
139
+ /**
140
+ * `local` when the developer set a dev token, or a key to mint them with, else undefined. Throws on env it can't read,
141
+ * so a typo fails loudly rather than signing nobody in.
142
+ */
143
+ export const localPlatform = (env = processEnv() ?? {}, appId = devAppId) => {
144
+ const token = localToken(env, appId);
145
+ if (!token)
146
+ return undefined;
147
+ const urls = localUrls(env[LOCAL_ENV.urls]);
148
+ const user = localUser(env[LOCAL_ENV.user]);
149
+ return { kind: "local", urls, user: () => user, token: token(urls.backend) };
150
+ };
@@ -1,7 +1,7 @@
1
1
  import { QueryClient } from "@tanstack/react-query";
2
2
  import { type AnyRoute, type RouterConstructorOptions, type RouterHistory } from "@tanstack/react-router";
3
3
  import { type ProfileChanges } from "../auth/profileUpdates.js";
4
- import type { HostMode, User } from "./types.js";
4
+ import type { HostMode, PlatformHead, User } from "./types.js";
5
5
  export declare const QUERY_STALE_TIME_MS = 30000;
6
6
  /** The router context every Zite app's root route declares: `createRootRouteWithContext<ZiteRouterContext>()`. */
7
7
  export type ZiteRouterContext = {
@@ -11,8 +11,12 @@ export type ZiteRouterContext = {
11
11
  type Dehydrated = {
12
12
  user: User | null;
13
13
  mode?: HostMode;
14
+ head?: PlatformHead;
14
15
  };
15
- /** @internal What a page carries to the browser beside its queries: the signed-in user, and the mode it was served in. */
16
+ /**
17
+ * @internal What a page carries to the browser beside its queries: the signed-in user, the mode it was served in, and
18
+ * the platform's head entries, which the browser renders again as it navigates.
19
+ */
16
20
  export declare const dehydrateZite: (context: ZiteRouterContext) => Dehydrated;
17
21
  /** @internal The user after a profile edit, named as the host names them: first and last name, else the email. */
18
22
  export declare const withProfile: (user: User, changes: ProfileChanges) => User;
@@ -7,10 +7,17 @@ import { carryPreviewClaim, PREVIEW_CLAIM_PARAM, previewClaim } from "./previewC
7
7
  import { currentHost } from "./host.js";
8
8
  import { keepRenderedMode } from "../internal/appMode.js";
9
9
  import { onProfileUpdated } from "../auth/profileUpdates.js";
10
+ import { rootHead, routeHead } from "./pageHead.js";
10
11
  // Long enough that a page's queries don't refetch as the browser picks it up, short enough to stay fresh.
11
12
  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 });
13
+ /**
14
+ * @internal What a page carries to the browser beside its queries: the signed-in user, the mode it was served in, and
15
+ * the platform's head entries, which the browser renders again as it navigates.
16
+ */
17
+ export const dehydrateZite = (context) => {
18
+ const host = currentHost();
19
+ return { user: context.user, mode: host?.mode, ...(host?.head && { head: host.head }) };
20
+ };
14
21
  /** @internal The user after a profile edit, named as the host names them: first and last name, else the email. */
15
22
  export const withProfile = (user, changes) => {
16
23
  const { firstName: _firstName, lastName: _lastName, ...rest } = user;
@@ -30,10 +37,14 @@ export const refreshOnProfileUpdate = (router, context) => onProfileUpdated((cha
30
37
  context.user = withProfile(context.user, changes);
31
38
  void router.invalidate();
32
39
  });
40
+ // The browser's, from the page it hydrated; the server's is the request's own.
41
+ let hydratedHead;
42
+ const platformHead = () => (typeof window === "undefined" ? currentHost()?.head : hydratedHead);
33
43
  /** @internal Takes in what the page carried. */
34
44
  export const hydrateZite = (context, dehydrated) => {
35
45
  context.user = dehydrated.user;
36
46
  keepRenderedMode(dehydrated.mode);
47
+ hydratedHead = dehydrated.head;
37
48
  };
38
49
  const ziteWindow = () => (typeof window === "undefined" ? undefined : window);
39
50
  const box = { maxWidth: 480, margin: "15vh auto", padding: 24, fontFamily: "system-ui, sans-serif", textAlign: "center" };
@@ -121,6 +132,33 @@ const failWithErrors = (routes) => {
121
132
  });
122
133
  }
123
134
  };
135
+ // The platform's entries go under the root's own, replace what the app's settings set, and follow a deeper route's
136
+ // title, on any request whose host left its head to zitejs. Routes outlive a request's router, so each is wrapped once and asks for the request's entries.
137
+ const headed = new WeakSet();
138
+ const withPlatformHead = (routes) => {
139
+ for (const route of routes) {
140
+ const own = route.options.head;
141
+ if (headed.has(route) || (!route.isRoot && !own))
142
+ continue;
143
+ headed.add(route);
144
+ route.update({
145
+ head: async (ctx) => {
146
+ const head = platformHead();
147
+ if (!head)
148
+ return own?.(ctx);
149
+ let result;
150
+ try {
151
+ result = await own?.(ctx);
152
+ }
153
+ catch (error) {
154
+ // TanStack would drop the route's whole head; the runtime and badge still belong on the page.
155
+ console.error(error);
156
+ }
157
+ return route.isRoot ? rootHead(result, head) : routeHead(result, head, ctx.matches.slice(0, ctx.matches.indexOf(ctx.match)));
158
+ },
159
+ });
160
+ }
161
+ };
124
162
  // The claim stays on every URL the router writes, and the app's own routes never see it.
125
163
  const keepPreviewClaim = (claim, own) => ({
126
164
  input: ({ url }) => {
@@ -166,6 +204,7 @@ export function createZiteRouter(options) {
166
204
  hydrate: (dehydrated) => hydrateZite(context, dehydrated),
167
205
  });
168
206
  failWithErrors(Object.values(router.routesById));
207
+ withPlatformHead(Object.values(router.routesById));
169
208
  setupRouterSsrQueryIntegration({ router, queryClient });
170
209
  const mark = watchReady(router);
171
210
  router.subscribe("onResolved", mark);
@@ -1,12 +1,12 @@
1
- import type { HostProps, PlatformBinding, HostRequestState } from "./types.js";
1
+ import type { HostProps, PlatformBinding, PlatformProvider, HostRequestState } from "./types.js";
2
2
  export { runWithHost } from "./scope.js";
3
3
  export { describeApp } from "./describe.js";
4
- export type { HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult, PlatformSession, RunRecord } from "./types.js";
4
+ export type { HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult, PlatformSession, PlatformUrls, RunRecord, } from "./types.js";
5
5
  /**
6
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.
7
+ * platform, on its app token or through the host's session, and only inside an
8
+ * access scope. The access kind travels with the call so the platform can
9
+ * record what a page read and narrow anonymous reads.
10
10
  */
11
11
  export declare function installPlatformTransport(): void;
12
12
  /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
@@ -17,6 +17,12 @@ export declare function hostContextFromProps(request: Request, props: HostProps)
17
17
  * its own platform (tests, local dev) owns its requests and may say who is calling in `x-zite-*` headers.
18
18
  */
19
19
  export declare function hostContextFromRequest(request: Request, platform?: PlatformBinding): HostRequestState;
20
+ /**
21
+ * A request under `vite dev` with the `local` provider: the developer's dev token reaches the platform, and the
22
+ * stand-in user is signed in. Headers still invoke only warm and describe. Its token's mode, base and app URL come
23
+ * once the token does, with `loadLocal`.
24
+ */
25
+ export declare function hostContextFromLocal(request: Request, provider: PlatformProvider): HostRequestState;
20
26
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
21
27
  export declare const builtFunctionIds: () => string[];
22
28
  /** Each server function's `description` option, written in by `zite()` at build. */
@@ -44,7 +50,8 @@ export type ZiteHandlers = {
44
50
  };
45
51
  /**
46
52
  * 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
53
+ * carries its identity and platform in props. Without props, a developer's
54
+ * dev token or API key in env selects the `local` provider; anything else (describe under
48
55
  * `vite preview`, tests) reads `x-zite-*` headers and uses `platform` if one
49
56
  * is given.
50
57
  */
@@ -2,7 +2,7 @@
2
2
  import { createServerEntry } from "@tanstack/react-start/server";
3
3
  import { createSsrRpc } from "@tanstack/react-start/ssr-rpc";
4
4
  import { runWithStartContext } from "@tanstack/start-storage-context";
5
- import { asZiteError, isZiteErrorCode, ZiteError, ZITE_ERROR_STATUS } from "./errors.js";
5
+ import { asZiteError, isZiteErrorCode, SIGN_IN_REQUIRED, ZiteError, ZITE_ERROR_STATUS } from "./errors.js";
6
6
  import { describeApp } from "./describe.js";
7
7
  import { runRegistration } from "./registration.js";
8
8
  import { isAuthHookName, loadAuthHooks } from "./authHooks.js";
@@ -10,18 +10,35 @@ import { errorOf, preview } from "./runLog.js";
10
10
  import { DATA_INTEGRATION_ID, dataContextOf, runDataCall } from "./data/index.js";
11
11
  import { airtableSettingsOf, runAirtableCall } from "./airtable/index.js";
12
12
  import { withoutConsole } from "./quiet.js";
13
- import { createOutboundFetch, rememberConnection } from "./outbound.js";
13
+ import { rememberConnection, watchOutboundFetches, withAiGatewayUrl, withRefreshedTokens } from "./outbound.js";
14
14
  import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
15
+ import { directAccess, directCall, directDataFetch, localConnections, localPagePlan, sessionOf } from "./direct.js";
16
+ import { takeAnalytics } from "./analytics.js";
17
+ import { takeUploadSession } from "./uploads.js";
18
+ import { UPLOAD_SESSION_PATH } from "../internal/serviceUrls.js";
19
+ import { sendRunReport } from "./telemetry.js";
20
+ import { ANALYTICS_PATH, platformHeadOf } from "./pageHead.js";
21
+ import { localModeOf, localPlatform, ziteProvider } from "./provider.js";
22
+ import { localSignIn, userOfIdentity } from "./localSignIn.js";
23
+ import { isSignInPath } from "../signin/paths.js";
24
+ import { appTokenClaims } from "../internal/appToken.js";
15
25
  import { getHost, requireScope, runInScope, runWithHost } from "./scope.js";
26
+ import { workspaceNameMappings } from "./workspaceSchema.js";
16
27
  import { ZITEJS_VERSION } from "./version.js";
17
28
  import { loadUnfinishedWorkflows, loadWorkflows, loggedInput, runWorkflow } from "./workflowRun.js";
18
29
  export { runWithHost } from "./scope.js";
19
30
  export { describeApp } from "./describe.js";
31
+ const relaySession = async (host) => {
32
+ const session = await sessionOf(host);
33
+ if (!session)
34
+ throw new Error("The Zite platform binding is missing");
35
+ return session;
36
+ };
20
37
  /**
21
38
  * 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.
39
+ * platform, on its app token or through the host's session, and only inside an
40
+ * access scope. The access kind travels with the call so the platform can
41
+ * record what a page read and narrow anonymous reads.
25
42
  */
26
43
  export function installPlatformTransport() {
27
44
  const sdkCall = async (integrationId, className, methodName, params) => {
@@ -30,21 +47,26 @@ export function installPlatformTransport() {
30
47
  const getsConnection = integrationId === INTEGRATIONS_PLATFORM_ID && methodName === "get";
31
48
  const name = String(params?.name ?? "");
32
49
  // Fails closed: no platform means no platform access, never a fallback.
33
- if (!host?.platform)
50
+ if (!host?.platform && !host?.provider)
34
51
  throw new Error("The Zite platform binding is missing");
35
- host.session ??= Promise.resolve(host.platform.session());
36
- const session = await host.session;
37
52
  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));
53
+ const found = await dataContextOf({
54
+ dataContext: async () => host.provider?.kind === "local"
55
+ ? { baseId: host.baseId ?? null, nameMappings: workspaceNameMappings }
56
+ : (await relaySession(host)).dataContext(),
57
+ });
58
+ const transport = (await directAccess(host)) ? { dataFetch: directDataFetch(host) } : await relaySession(host);
59
+ return recordCall(host, { integrationId, className, methodName, params }, () => runDataCall(transport, found, host.mode, methodName, params));
40
60
  }
41
- if (!integrationId.startsWith("__")) {
42
- const airtable = await airtableSettingsOf(session, integrationId);
61
+ if (!integrationId.startsWith("__") && host.platform) {
62
+ const airtable = await airtableSettingsOf({ integrationSettings: async (id) => (await relaySession(host)).integrationSettings(id) }, integrationId);
43
63
  if (airtable) {
64
+ const session = await relaySession(host);
44
65
  return recordCall(host, { integrationId, className, methodName, params }, () => runAirtableCall(host, session, integrationId, airtable, methodName, params, scope.kind));
45
66
  }
46
67
  }
47
- const result = await session.call({ integrationId, className, methodName, params, access: scope.kind });
68
+ const input = { integrationId, className, methodName, params, access: scope.kind };
69
+ const result = (await directCall(host, input)) ?? (await (await relaySession(host)).call(input));
48
70
  if (getsConnection)
49
71
  return connectionAnswer(host, name, result);
50
72
  if ("value" in result)
@@ -58,8 +80,9 @@ export function installPlatformTransport() {
58
80
  /** `integrations.get`'s answer, whose values then name the calls made with them. */
59
81
  const connectionAnswer = (host, name, result) => {
60
82
  if ("value" in result) {
61
- rememberConnection(host, name, result.value);
62
- return result.value;
83
+ const value = withAiGatewayUrl(host, withRefreshedTokens(result.value));
84
+ rememberConnection(host, name, value);
85
+ return value;
63
86
  }
64
87
  const { code, message, userFacingMessage } = result.error;
65
88
  throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
@@ -85,23 +108,13 @@ const recordCall = async (host, call, run) => {
85
108
  throw error;
86
109
  }
87
110
  };
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
- };
98
111
  const decodeUser = (value) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0))));
99
112
  const INVOKE_KINDS = new Set(["webhook", "describe", "workflow", "register", "warm", "authHook", "function"]);
100
113
  // What a request without props may ask for: neither runs app code on anyone's behalf.
101
114
  const UNHOSTED_INVOKE_KINDS = new Set(["warm", "describe"]);
102
115
  /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
103
116
  export function hostContextFromProps(request, props) {
104
- return {
117
+ const host = {
105
118
  requestId: props.requestId,
106
119
  url: request.url,
107
120
  user: props.user,
@@ -112,10 +125,15 @@ export function hostContextFromProps(request, props) {
112
125
  previewClaim: props.previewClaim,
113
126
  env: props.env,
114
127
  envConnections: props.envConnections,
128
+ connectionServices: props.connectionServices,
115
129
  runRoot: props.runRoot,
116
130
  runs: [],
117
131
  platform: props.platform,
118
132
  };
133
+ host.provider = ziteProvider(props, () => sessionOf(host));
134
+ if (props.page)
135
+ host.head = platformHeadOf(props.page, { url: request.url, mode: props.mode, token: props.appToken });
136
+ return host;
119
137
  }
120
138
  // Classic sets these per run. Node and workerd both refuse getters on process.env, so each request writes what the
121
139
  // host sent, which is the same for every request a build serves: the live URL even on a demo.
@@ -149,18 +167,76 @@ export function hostContextFromRequest(request, platform) {
149
167
  const { headers } = request;
150
168
  const trusted = platform !== undefined;
151
169
  const user = trusted ? headers.get("x-zite-user") : null;
152
- const [kind, name = ""] = headers.get("x-zite-invoke")?.split(":") ?? [];
153
- const kinds = trusted ? INVOKE_KINDS : UNHOSTED_INVOKE_KINDS;
154
170
  return {
155
171
  requestId: (trusted && headers.get("x-zite-request-id")) || crypto.randomUUID(),
156
172
  url: request.url,
157
173
  user: user ? decodeUser(user) : null,
158
174
  mode: "live",
159
- invoke: kinds.has(kind) ? { kind: kind, name } : null,
175
+ invoke: invokeOf(headers, trusted ? INVOKE_KINDS : UNHOSTED_INVOKE_KINDS),
160
176
  runs: [],
161
177
  platform,
162
178
  };
163
179
  }
180
+ const invokeOf = (headers, kinds) => {
181
+ const [kind, name = ""] = headers.get("x-zite-invoke")?.split(":") ?? [];
182
+ return kinds.has(kind) ? { kind: kind, name } : null;
183
+ };
184
+ /**
185
+ * A request under `vite dev` with the `local` provider: the developer's dev token reaches the platform, and the
186
+ * stand-in user is signed in. Headers still invoke only warm and describe. Its token's mode, base and app URL come
187
+ * once the token does, with `loadLocal`.
188
+ */
189
+ export function hostContextFromLocal(request, provider) {
190
+ return {
191
+ requestId: crypto.randomUUID(),
192
+ url: request.url,
193
+ user: provider.user(),
194
+ mode: "preview",
195
+ invoke: invokeOf(request.headers, UNHOSTED_INVOKE_KINDS),
196
+ runs: [],
197
+ provider,
198
+ };
199
+ }
200
+ // A browser opening a page, the only request whose head is rendered.
201
+ const opensPage = (request) => (request.method === "GET" || request.method === "HEAD") && (request.headers.get("accept") ?? "").includes("text/html");
202
+ /** As the dispatcher answers a caller an internal app turns away: a server function, a page, or a call. */
203
+ const signInRequired = (request) => {
204
+ const url = new URL(request.url);
205
+ if (url.pathname.startsWith("/_serverFn/") || request.headers.has("x-tsr-serverfn")) {
206
+ return new Response(SIGN_IN_REQUIRED, { status: 401, headers: { "content-type": "text/plain; charset=utf-8" } });
207
+ }
208
+ if (!opensPage(request))
209
+ return Response.json({ error: "SIGN_IN_REQUIRED" }, { status: 401 });
210
+ const login = new URL("/auth/login", url);
211
+ login.searchParams.set("redirectUrl", url.href);
212
+ return new Response(null, { status: 302, headers: { location: login.pathname + login.search } });
213
+ };
214
+ // No host hands `local` what its token grants, its connections' env or its page settings, so it reads them before app
215
+ // code runs. A dev token the backend won't mint fails the request, saying why.
216
+ const loadLocal = async (host, request) => {
217
+ const access = await directAccess(host);
218
+ const claims = access ? appTokenClaims(access.token) : undefined;
219
+ host.mode = localModeOf(claims);
220
+ host.appUrl = claims?.appUrl ?? undefined;
221
+ host.baseId = claims?.base ?? undefined;
222
+ if (!access)
223
+ return;
224
+ const [connections, plan] = await Promise.all([
225
+ localConnections(access).catch((error) => {
226
+ console.error("[zite] couldn't load the app's connections", error);
227
+ return undefined;
228
+ }),
229
+ opensPage(request) ? localPagePlan(access) : null,
230
+ ]);
231
+ if (connections) {
232
+ host.env = connections.env;
233
+ host.envConnections = connections.envConnections;
234
+ }
235
+ // The backend serves the platform's runtime, wherever `local` points it.
236
+ if (plan) {
237
+ host.head = platformHeadOf({ plan, runtimeUrl: `${access.urls.backend}/runtime/app-runtime.js` }, { url: host.url, mode: host.mode, token: access.token });
238
+ }
239
+ };
164
240
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
165
241
  export const builtFunctionIds = () => "__ZITE_FN_IDS__".split(",").filter((id) => id && !id.startsWith("__ZITE"));
166
242
  const parseBuiltJson = (json) => {
@@ -324,7 +400,8 @@ const pageStatus = (host) => {
324
400
  };
325
401
  /**
326
402
  * 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
403
+ * carries its identity and platform in props. Without props, a developer's
404
+ * dev token or API key in env selects the `local` provider; anything else (describe under
328
405
  * `vite preview`, tests) reads `x-zite-*` headers and uses `platform` if one
329
406
  * is given.
330
407
  */
@@ -333,10 +410,32 @@ export function createZiteHandlers(options) {
333
410
  // Loaded on first use, so a page request never pays for importing workflow modules.
334
411
  let workflows;
335
412
  const loadedWorkflows = () => (workflows ??= loadWorkflows());
336
- const serve = async (request, ctx) => {
413
+ const serve = async (incoming, ctx) => {
414
+ const local = ctx?.props?.platform ? undefined : localPlatform();
415
+ const mounted = local ? await signInLocally(incoming, local) : undefined;
416
+ if (mounted && "answered" in mounted)
417
+ return mounted.answered;
418
+ const request = mounted?.request ?? incoming;
337
419
  const host = ctx?.props?.platform
338
420
  ? hostContextFromProps(request, ctx.props)
339
- : hostContextFromRequest(request, options.platform);
421
+ : local
422
+ ? hostContextFromLocal(request, local)
423
+ : hostContextFromRequest(request, options.platform);
424
+ if (mounted)
425
+ host.user = userOfIdentity(mounted.signedIn.user);
426
+ // The platform walls internal apps before dispatch; this is the same wall again, before any app code.
427
+ if (ctx?.props?.platform && ctx.props.accessMode === "internal" && host.invoke === null && !host.user)
428
+ return signInRequired(request);
429
+ if (ctx?.waitUntil)
430
+ host.waitUntil = (promise) => ctx.waitUntil(promise);
431
+ // The platform's, before any app route could answer them.
432
+ const { pathname } = new URL(request.url);
433
+ if (host.invoke === null && pathname === ANALYTICS_PATH)
434
+ return takeAnalytics(request, host);
435
+ if (host.invoke === null && pathname === UPLOAD_SESSION_PATH)
436
+ return takeUploadSession(request, host);
437
+ if (local && host.invoke === null)
438
+ await loadLocal(host, request);
340
439
  setRequestEnv(host);
341
440
  // Starting this isolate was the point: the platform warms a build before its
342
441
  // first visitors, and no app code runs.
@@ -366,25 +465,20 @@ export function createZiteHandlers(options) {
366
465
  const status = response.status === 500 ? pageStatus(host) : undefined;
367
466
  if (status)
368
467
  response = new Response(response.body, { status, headers: response.headers });
468
+ if (mounted)
469
+ response = withSetCookies(response, mounted.signedIn.setCookies);
369
470
  return onBodyEnd(response, () => {
370
- const { platform } = host;
371
- if ((!host.runs.length && !host.calls?.length && !host.fetches?.length && !host.pending?.length) || !platform)
471
+ if (!host.runs.length && !host.calls?.length && !host.fetches?.length && !host.pending?.length)
372
472
  return;
373
- // On the request's session when it has one: one call, not another binding round trip.
374
473
  const flushed = (async () => {
375
474
  await Promise.all(host.pending ?? []);
376
475
  if (!host.runs.length && !host.calls?.length && !host.fetches?.length)
377
476
  return;
378
- const batch = {
477
+ await sendRunReport(host, {
379
478
  runs: host.runs,
380
479
  ...(host.calls?.length && { calls: host.calls }),
381
480
  ...(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));
481
+ });
388
482
  })().catch((error) => {
389
483
  console.error("[zite] couldn't record runs", error);
390
484
  });
@@ -393,6 +487,43 @@ export function createZiteHandlers(options) {
393
487
  };
394
488
  return { fetch: (request, ...rest) => serve(request, rest[1]) };
395
489
  }
490
+ // The app reads the request without the module's cookies, and the response carries what the module set.
491
+ const withCookie = (request, cookie) => {
492
+ const headers = new Headers(request.headers);
493
+ if (cookie)
494
+ headers.set("cookie", cookie);
495
+ else
496
+ headers.delete("cookie");
497
+ return new Request(request, { headers });
498
+ };
499
+ const withSetCookies = (response, cookies) => {
500
+ if (cookies.length === 0)
501
+ return response;
502
+ const headers = new Headers(response.headers);
503
+ for (const cookie of cookies)
504
+ headers.append("set-cookie", cookie);
505
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
506
+ };
507
+ /**
508
+ * Off Zite with an issuer configured: the sign-in module answers its own paths and nothing else under them reaches the
509
+ * app, then says who is calling. Undefined when it isn't mounted or has answered.
510
+ */
511
+ const signInLocally = async (request, local) => {
512
+ const pathname = new URL(request.url).pathname;
513
+ if (!local.urls || invokeOf(request.headers, UNHOSTED_INVOKE_KINDS) || pathname === ANALYTICS_PATH || pathname === UPLOAD_SESSION_PATH) {
514
+ return undefined;
515
+ }
516
+ const signIn = await localSignIn(globalThis.process?.env ?? {}, local.urls, request);
517
+ if (!signIn)
518
+ return undefined;
519
+ const answered = await signIn.handle(request);
520
+ if (answered)
521
+ return { answered };
522
+ if (isSignInPath(pathname))
523
+ return { answered: new Response("Not found", { status: 404 }) };
524
+ const signedIn = await signIn.resolve(request);
525
+ return { request: withCookie(request, signedIn.cookie), signedIn };
526
+ };
396
527
  /** The fetch handler alone, for the Node entry. */
397
528
  export function createZiteFetch(options) {
398
529
  return createZiteHandlers(options).fetch;
@@ -0,0 +1,10 @@
1
+ import type { CallRecord, FetchRecord, HostRequestState, RunRecord } from "./types.js";
2
+ export type RunReport = {
3
+ runs: RunRecord[];
4
+ calls?: CallRecord[];
5
+ fetches?: FetchRecord[];
6
+ };
7
+ /** The report in as few sends as fit under the runs service's limit, each record whole. */
8
+ export declare const reportSends: (report: RunReport) => RunReport[];
9
+ /** One report of the request's run; the caller keeps it going past the response with `waitUntil`. */
10
+ export declare const sendRunReport: (host: HostRequestState, report: RunReport) => Promise<void>;