zitejs 0.10.0-start.21 → 0.10.0-start.23

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 (128) 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 +302 -0
  24. package/dist/cjs/start/types.js +2 -0
  25. package/dist/cjs/sync/lib.js +23 -50
  26. package/dist/cjs/sync/sdkNames.d.ts +65 -7
  27. package/dist/cjs/sync/sdkNames.js +76 -12
  28. package/dist/cjs/sync/sdkNames.test.js +38 -0
  29. package/dist/cjs/upload/index.js +73 -22
  30. package/dist/cjs/upload/index.test.js +35 -2
  31. package/dist/esm/auth/client.d.ts +2 -2
  32. package/dist/esm/check/start/sourceRules.js +3 -0
  33. package/dist/esm/cli.js +6 -0
  34. package/dist/esm/dev/index.js +15 -0
  35. package/dist/esm/dev/signin.d.ts +16 -0
  36. package/dist/esm/dev/signin.js +72 -0
  37. package/dist/esm/internal/appMode.d.ts +11 -0
  38. package/dist/esm/internal/appMode.js +2 -0
  39. package/dist/esm/internal/appToken.d.ts +17 -0
  40. package/dist/esm/internal/appToken.js +22 -0
  41. package/dist/esm/internal/platformFetch.d.ts +2 -0
  42. package/dist/esm/internal/platformFetch.js +8 -0
  43. package/dist/esm/internal/serviceUrls.d.ts +7 -0
  44. package/dist/esm/internal/serviceUrls.js +12 -0
  45. package/dist/esm/runtime/index.d.ts +1 -1
  46. package/dist/esm/signin/conformance.d.ts +100 -0
  47. package/dist/esm/signin/conformance.js +471 -0
  48. package/dist/esm/signin/cookies.d.ts +28 -0
  49. package/dist/esm/signin/cookies.js +59 -0
  50. package/dist/esm/signin/encoding.d.ts +9 -0
  51. package/dist/esm/signin/encoding.js +39 -0
  52. package/dist/esm/signin/endpoints.d.ts +12 -0
  53. package/dist/esm/signin/endpoints.js +29 -0
  54. package/dist/esm/signin/http.d.ts +25 -0
  55. package/dist/esm/signin/http.js +69 -0
  56. package/dist/esm/signin/index.d.ts +8 -0
  57. package/dist/esm/signin/index.js +9 -0
  58. package/dist/esm/signin/keys.d.ts +39 -0
  59. package/dist/esm/signin/keys.js +80 -0
  60. package/dist/esm/signin/paths.d.ts +2 -0
  61. package/dist/esm/signin/paths.js +2 -0
  62. package/dist/esm/signin/seal.d.ts +8 -0
  63. package/dist/esm/signin/seal.js +35 -0
  64. package/dist/esm/signin/signin.d.ts +60 -0
  65. package/dist/esm/signin/signin.js +340 -0
  66. package/dist/esm/signin/transport.d.ts +111 -0
  67. package/dist/esm/signin/transport.js +1 -0
  68. package/dist/esm/signin/verify.d.ts +77 -0
  69. package/dist/esm/signin/verify.js +155 -0
  70. package/dist/esm/start/airtable/built.d.ts +2 -0
  71. package/dist/esm/start/airtable/built.js +3 -0
  72. package/dist/esm/start/airtable/index.d.ts +3 -5
  73. package/dist/esm/start/airtable/index.js +4 -25
  74. package/dist/esm/start/airtable/settings.d.ts +31 -0
  75. package/dist/esm/start/airtable/settings.js +110 -0
  76. package/dist/esm/start/analytics.d.ts +5 -0
  77. package/dist/esm/start/analytics.js +77 -0
  78. package/dist/esm/start/data/index.d.ts +21 -9
  79. package/dist/esm/start/data/index.js +26 -20
  80. package/dist/esm/start/data/names.d.ts +7 -0
  81. package/dist/esm/start/data/names.js +15 -0
  82. package/dist/esm/start/data/types.d.ts +4 -1
  83. package/dist/esm/start/devApp.d.ts +1 -0
  84. package/dist/esm/start/devApp.js +3 -0
  85. package/dist/esm/start/devSignIn.d.ts +1 -0
  86. package/dist/esm/start/devSignIn.js +3 -0
  87. package/dist/esm/start/direct.d.ts +44 -0
  88. package/dist/esm/start/direct.js +442 -0
  89. package/dist/esm/start/entries.js +4 -0
  90. package/dist/esm/start/fetch.d.ts +1 -0
  91. package/dist/esm/start/fetch.js +4 -0
  92. package/dist/esm/start/instance.js +6 -2
  93. package/dist/esm/start/localSignIn.d.ts +18 -0
  94. package/dist/esm/start/localSignIn.js +73 -0
  95. package/dist/esm/start/outbound.d.ts +9 -1
  96. package/dist/esm/start/outbound.js +130 -31
  97. package/dist/esm/start/pageHead.d.ts +36 -0
  98. package/dist/esm/start/pageHead.js +178 -0
  99. package/dist/esm/start/provider.d.ts +24 -0
  100. package/dist/esm/start/provider.js +150 -0
  101. package/dist/esm/start/router.d.ts +6 -2
  102. package/dist/esm/start/router.js +41 -2
  103. package/dist/esm/start/server.d.ts +23 -12
  104. package/dist/esm/start/server.js +185 -56
  105. package/dist/esm/start/telemetry.d.ts +13 -0
  106. package/dist/esm/start/telemetry.js +71 -0
  107. package/dist/esm/start/types.d.ts +141 -44
  108. package/dist/esm/start/uploads.d.ts +2 -0
  109. package/dist/esm/start/uploads.js +52 -0
  110. package/dist/esm/start/version.d.ts +1 -1
  111. package/dist/esm/start/version.js +1 -1
  112. package/dist/esm/start/vite.d.ts +18 -1
  113. package/dist/esm/start/vite.js +163 -4
  114. package/dist/esm/start/workspaceSchema.d.ts +2 -0
  115. package/dist/esm/start/workspaceSchema.js +3 -0
  116. package/dist/esm/sync/lib.js +23 -50
  117. package/dist/esm/sync/sdkNames.d.ts +65 -7
  118. package/dist/esm/sync/sdkNames.js +73 -11
  119. package/dist/esm/sync/sdkNames.test.js +38 -0
  120. package/dist/esm/upload/index.js +74 -23
  121. package/dist/esm/upload/index.test.js +35 -2
  122. package/package.json +22 -12
  123. package/dist/cjs/auth-server/index.d.ts +0 -369
  124. package/dist/cjs/auth-server/index.js +0 -119
  125. package/dist/esm/auth-server/index.d.ts +0 -369
  126. package/dist/esm/auth-server/index.js +0 -116
  127. package/dist/esm/start/problems.d.ts +0 -19
  128. package/dist/esm/start/problems.js +0 -8
@@ -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,22 +1,31 @@
1
- import type { HostProps, PlatformBinding, HostRequestState } from "./types.js";
1
+ import type { HostProps, 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, PlatformProvider, 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, and only inside an access scope. The access kind
8
+ * travels with the call so the platform can record what a page read and
9
+ * narrow anonymous reads. A request with no token or URLs fails each call
10
+ * that would leave the app loudly: there is nowhere else for it to go. What
11
+ * props already answer, integrations.get and ZiteMeta.getWorkspace, needs none.
10
12
  */
11
13
  export declare function installPlatformTransport(): void;
12
14
  /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
13
15
  export declare function hostContextFromProps(request: Request, props: HostProps): HostRequestState;
14
16
  /**
15
17
  * 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.
18
+ * host can set props, so without them a build answers warm and describe, nobody is signed in and nothing reaches the
19
+ * platform. An entry that passes its own provider (tests) owns its requests: it may say who is calling in `x-zite-*`
20
+ * headers, and its provider's token and URLs reach the platform.
18
21
  */
19
- export declare function hostContextFromRequest(request: Request, platform?: PlatformBinding): HostRequestState;
22
+ export declare function hostContextFromRequest(request: Request, provider?: PlatformProvider): HostRequestState;
23
+ /**
24
+ * A request under `vite dev` with the `local` provider: the developer's dev token reaches the platform, and the
25
+ * stand-in user is signed in. Headers still invoke only warm and describe. Its token's mode, base and app URL come
26
+ * once the token does, with `loadLocal`.
27
+ */
28
+ export declare function hostContextFromLocal(request: Request, provider: PlatformProvider): HostRequestState;
20
29
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
21
30
  export declare const builtFunctionIds: () => string[];
22
31
  /** Each server function's `description` option, written in by `zite()` at build. */
@@ -33,7 +42,8 @@ export type ZiteServerOptions = {
33
42
  fetch(request: Request, ...rest: unknown[]): Promise<Response> | Response;
34
43
  };
35
44
  getRouter: () => unknown;
36
- platform?: PlatformBinding;
45
+ /** A test entry's own platform, for the requests no host dispatched; see `hostContextFromRequest`. */
46
+ provider?: PlatformProvider;
37
47
  /** The app's start instance, which a test run of a server function runs under. */
38
48
  startInstance: {
39
49
  getOptions: () => unknown;
@@ -44,9 +54,10 @@ export type ZiteHandlers = {
44
54
  };
45
55
  /**
46
56
  * 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.
57
+ * carries its identity, app token and platform URLs in props. Without props, a
58
+ * developer's dev token or API key in env selects the `local` provider;
59
+ * anything else (describe under `vite preview`, tests) reads `x-zite-*`
60
+ * headers and uses `provider` if one is given.
50
61
  */
51
62
  export declare function createZiteHandlers(options: ZiteServerOptions): ZiteHandlers;
52
63
  /** The fetch handler alone, for the Node entry. */
@@ -2,26 +2,39 @@
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";
9
9
  import { errorOf, preview } from "./runLog.js";
10
- import { DATA_INTEGRATION_ID, dataContextOf, runDataCall } from "./data/index.js";
10
+ import { DATA_INTEGRATION_ID, 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 { connectionsOnToken, directAccess, directCall, directDataFetch, localPagePlan, NoPlatformError } 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 { workspaceSchemaNames } 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";
20
31
  /**
21
32
  * 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.
33
+ * platform on its app token, and only inside an access scope. The access kind
34
+ * travels with the call so the platform can record what a page read and
35
+ * narrow anonymous reads. A request with no token or URLs fails each call
36
+ * that would leave the app loudly: there is nowhere else for it to go. What
37
+ * props already answer, integrations.get and ZiteMeta.getWorkspace, needs none.
25
38
  */
26
39
  export function installPlatformTransport() {
27
40
  const sdkCall = async (integrationId, className, methodName, params) => {
@@ -29,22 +42,27 @@ export function installPlatformTransport() {
29
42
  const host = getHost();
30
43
  const getsConnection = integrationId === INTEGRATIONS_PLATFORM_ID && methodName === "get";
31
44
  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;
45
+ if (!host)
46
+ throw new NoPlatformError();
37
47
  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));
48
+ const access = await directAccess(host);
49
+ if (!access)
50
+ throw new NoPlatformError();
51
+ const target = { baseId: host.baseId ?? appTokenClaims(access.token)?.base ?? null, names: workspaceSchemaNames };
52
+ return recordCall(host, { integrationId, className, methodName, params }, () => runDataCall({ dataFetch: directDataFetch(host) }, target, host.mode, methodName, params));
40
53
  }
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
- }
54
+ const airtable = integrationId.startsWith("__") ? undefined : airtableSettingsOf(integrationId);
55
+ if (airtable) {
56
+ const connectionOf = () => directCall(host, {
57
+ integrationId: INTEGRATIONS_PLATFORM_ID,
58
+ className: "Connections",
59
+ methodName: "get",
60
+ params: { name: integrationId },
61
+ access: scope.kind,
62
+ });
63
+ return recordCall(host, { integrationId, className, methodName, params }, () => runAirtableCall(host, connectionOf, integrationId, airtable, methodName, params));
46
64
  }
47
- const result = await session.call({ integrationId, className, methodName, params, access: scope.kind });
65
+ const result = await directCall(host, { integrationId, className, methodName, params, access: scope.kind });
48
66
  if (getsConnection)
49
67
  return connectionAnswer(host, name, result);
50
68
  if ("value" in result)
@@ -58,8 +76,9 @@ export function installPlatformTransport() {
58
76
  /** `integrations.get`'s answer, whose values then name the calls made with them. */
59
77
  const connectionAnswer = (host, name, result) => {
60
78
  if ("value" in result) {
61
- rememberConnection(host, name, result.value);
62
- return result.value;
79
+ const value = withAiGatewayUrl(host, withRefreshedTokens(result.value));
80
+ rememberConnection(host, name, value);
81
+ return value;
63
82
  }
64
83
  const { code, message, userFacingMessage } = result.error;
65
84
  throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
@@ -85,23 +104,13 @@ const recordCall = async (host, call, run) => {
85
104
  throw error;
86
105
  }
87
106
  };
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
107
  const decodeUser = (value) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0))));
99
108
  const INVOKE_KINDS = new Set(["webhook", "describe", "workflow", "register", "warm", "authHook", "function"]);
100
109
  // What a request without props may ask for: neither runs app code on anyone's behalf.
101
110
  const UNHOSTED_INVOKE_KINDS = new Set(["warm", "describe"]);
102
111
  /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
103
112
  export function hostContextFromProps(request, props) {
104
- return {
113
+ const host = {
105
114
  requestId: props.requestId,
106
115
  url: request.url,
107
116
  user: props.user,
@@ -112,10 +121,16 @@ export function hostContextFromProps(request, props) {
112
121
  previewClaim: props.previewClaim,
113
122
  env: props.env,
114
123
  envConnections: props.envConnections,
124
+ connectionServices: props.connectionServices,
115
125
  runRoot: props.runRoot,
116
126
  runs: [],
117
- platform: props.platform,
127
+ workspace: props.workspace,
128
+ connections: props.connections,
129
+ provider: ziteProvider(props),
118
130
  };
131
+ if (props.page)
132
+ host.head = platformHeadOf(props.page, { url: request.url, mode: props.mode, token: props.appToken });
133
+ return host;
119
134
  }
120
135
  // Classic sets these per run. Node and workerd both refuse getters on process.env, so each request writes what the
121
136
  // host sent, which is the same for every request a build serves: the live URL even on a demo.
@@ -142,25 +157,84 @@ const setRequestEnv = ({ appUrl, baseId, env: connectionEnv }) => {
142
157
  };
143
158
  /**
144
159
  * 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.
160
+ * host can set props, so without them a build answers warm and describe, nobody is signed in and nothing reaches the
161
+ * platform. An entry that passes its own provider (tests) owns its requests: it may say who is calling in `x-zite-*`
162
+ * headers, and its provider's token and URLs reach the platform.
147
163
  */
148
- export function hostContextFromRequest(request, platform) {
164
+ export function hostContextFromRequest(request, provider) {
149
165
  const { headers } = request;
150
- const trusted = platform !== undefined;
166
+ const trusted = provider !== undefined;
151
167
  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
168
  return {
155
169
  requestId: (trusted && headers.get("x-zite-request-id")) || crypto.randomUUID(),
156
170
  url: request.url,
157
171
  user: user ? decodeUser(user) : null,
158
172
  mode: "live",
159
- invoke: kinds.has(kind) ? { kind: kind, name } : null,
173
+ invoke: invokeOf(headers, trusted ? INVOKE_KINDS : UNHOSTED_INVOKE_KINDS),
160
174
  runs: [],
161
- platform,
175
+ provider,
162
176
  };
163
177
  }
178
+ const invokeOf = (headers, kinds) => {
179
+ const [kind, name = ""] = headers.get("x-zite-invoke")?.split(":") ?? [];
180
+ return kinds.has(kind) ? { kind: kind, name } : null;
181
+ };
182
+ /**
183
+ * A request under `vite dev` with the `local` provider: the developer's dev token reaches the platform, and the
184
+ * stand-in user is signed in. Headers still invoke only warm and describe. Its token's mode, base and app URL come
185
+ * once the token does, with `loadLocal`.
186
+ */
187
+ export function hostContextFromLocal(request, provider) {
188
+ return {
189
+ requestId: crypto.randomUUID(),
190
+ url: request.url,
191
+ user: provider.user(),
192
+ mode: "preview",
193
+ invoke: invokeOf(request.headers, UNHOSTED_INVOKE_KINDS),
194
+ runs: [],
195
+ provider,
196
+ };
197
+ }
198
+ // A browser opening a page, the only request whose head is rendered.
199
+ const opensPage = (request) => (request.method === "GET" || request.method === "HEAD") && (request.headers.get("accept") ?? "").includes("text/html");
200
+ /** As the dispatcher answers a caller an internal app turns away: a server function, a page, or a call. */
201
+ const signInRequired = (request) => {
202
+ const url = new URL(request.url);
203
+ if (url.pathname.startsWith("/_serverFn/") || request.headers.has("x-tsr-serverfn")) {
204
+ return new Response(SIGN_IN_REQUIRED, { status: 401, headers: { "content-type": "text/plain; charset=utf-8" } });
205
+ }
206
+ if (!opensPage(request))
207
+ return Response.json({ error: "SIGN_IN_REQUIRED" }, { status: 401 });
208
+ const login = new URL("/auth/login", url);
209
+ login.searchParams.set("redirectUrl", url.href);
210
+ return new Response(null, { status: 302, headers: { location: login.pathname + login.search } });
211
+ };
212
+ // No host hands `local` what its token grants, its connections' env or its page settings, so it reads them before app
213
+ // code runs. A dev token the backend won't mint fails the request, saying why.
214
+ const loadLocal = async (host, request) => {
215
+ const access = await directAccess(host);
216
+ const claims = access ? appTokenClaims(access.token) : undefined;
217
+ host.mode = localModeOf(claims);
218
+ host.appUrl = claims?.appUrl ?? undefined;
219
+ host.baseId = claims?.base ?? undefined;
220
+ if (!access)
221
+ return;
222
+ const [connections, plan] = await Promise.all([
223
+ connectionsOnToken(access).catch((error) => {
224
+ console.error("[zite] couldn't load the app's connections", error);
225
+ return undefined;
226
+ }),
227
+ opensPage(request) ? localPagePlan(access) : null,
228
+ ]);
229
+ if (connections) {
230
+ host.env = connections.env;
231
+ host.envConnections = connections.envConnections;
232
+ }
233
+ // The backend serves the platform's runtime, wherever `local` points it.
234
+ if (plan) {
235
+ host.head = platformHeadOf({ plan, runtimeUrl: `${access.urls.backend}/runtime/app-runtime.js` }, { url: host.url, mode: host.mode, token: access.token });
236
+ }
237
+ };
164
238
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
165
239
  export const builtFunctionIds = () => "__ZITE_FN_IDS__".split(",").filter((id) => id && !id.startsWith("__ZITE"));
166
240
  const parseBuiltJson = (json) => {
@@ -324,19 +398,42 @@ const pageStatus = (host) => {
324
398
  };
325
399
  /**
326
400
  * 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.
401
+ * carries its identity, app token and platform URLs in props. Without props, a
402
+ * developer's dev token or API key in env selects the `local` provider;
403
+ * anything else (describe under `vite preview`, tests) reads `x-zite-*`
404
+ * headers and uses `provider` if one is given.
330
405
  */
331
406
  export function createZiteHandlers(options) {
332
407
  installPlatformTransport();
333
408
  // Loaded on first use, so a page request never pays for importing workflow modules.
334
409
  let workflows;
335
410
  const loadedWorkflows = () => (workflows ??= loadWorkflows());
336
- const serve = async (request, ctx) => {
411
+ const serve = async (incoming, ctx) => {
412
+ const local = ctx?.props?.platform ? undefined : localPlatform();
413
+ const mounted = local ? await signInLocally(incoming, local) : undefined;
414
+ if (mounted && "answered" in mounted)
415
+ return mounted.answered;
416
+ const request = mounted?.request ?? incoming;
337
417
  const host = ctx?.props?.platform
338
418
  ? hostContextFromProps(request, ctx.props)
339
- : hostContextFromRequest(request, options.platform);
419
+ : local
420
+ ? hostContextFromLocal(request, local)
421
+ : hostContextFromRequest(request, options.provider);
422
+ if (mounted)
423
+ host.user = userOfIdentity(mounted.signedIn.user);
424
+ // The platform walls internal apps before dispatch; this is the same wall again, before any app code.
425
+ if (ctx?.props?.platform && ctx.props.accessMode === "internal" && host.invoke === null && !host.user)
426
+ return signInRequired(request);
427
+ if (ctx?.waitUntil)
428
+ host.waitUntil = (promise) => ctx.waitUntil(promise);
429
+ // The platform's, before any app route could answer them.
430
+ const { pathname } = new URL(request.url);
431
+ if (host.invoke === null && pathname === ANALYTICS_PATH)
432
+ return takeAnalytics(request, host);
433
+ if (host.invoke === null && pathname === UPLOAD_SESSION_PATH)
434
+ return takeUploadSession(request, host);
435
+ if (local && host.invoke === null)
436
+ await loadLocal(host, request);
340
437
  setRequestEnv(host);
341
438
  // Starting this isolate was the point: the platform warms a build before its
342
439
  // first visitors, and no app code runs.
@@ -366,25 +463,20 @@ export function createZiteHandlers(options) {
366
463
  const status = response.status === 500 ? pageStatus(host) : undefined;
367
464
  if (status)
368
465
  response = new Response(response.body, { status, headers: response.headers });
466
+ if (mounted)
467
+ response = withSetCookies(response, mounted.signedIn.setCookies);
369
468
  return onBodyEnd(response, () => {
370
- const { platform } = host;
371
- if ((!host.runs.length && !host.calls?.length && !host.fetches?.length && !host.pending?.length) || !platform)
469
+ if (!host.runs.length && !host.calls?.length && !host.fetches?.length && !host.pending?.length)
372
470
  return;
373
- // On the request's session when it has one: one call, not another binding round trip.
374
471
  const flushed = (async () => {
375
472
  await Promise.all(host.pending ?? []);
376
473
  if (!host.runs.length && !host.calls?.length && !host.fetches?.length)
377
474
  return;
378
- const batch = {
475
+ await sendRunReport(host, {
379
476
  runs: host.runs,
380
477
  ...(host.calls?.length && { calls: host.calls }),
381
478
  ...(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));
479
+ });
388
480
  })().catch((error) => {
389
481
  console.error("[zite] couldn't record runs", error);
390
482
  });
@@ -393,6 +485,43 @@ export function createZiteHandlers(options) {
393
485
  };
394
486
  return { fetch: (request, ...rest) => serve(request, rest[1]) };
395
487
  }
488
+ // The app reads the request without the module's cookies, and the response carries what the module set.
489
+ const withCookie = (request, cookie) => {
490
+ const headers = new Headers(request.headers);
491
+ if (cookie)
492
+ headers.set("cookie", cookie);
493
+ else
494
+ headers.delete("cookie");
495
+ return new Request(request, { headers });
496
+ };
497
+ const withSetCookies = (response, cookies) => {
498
+ if (cookies.length === 0)
499
+ return response;
500
+ const headers = new Headers(response.headers);
501
+ for (const cookie of cookies)
502
+ headers.append("set-cookie", cookie);
503
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
504
+ };
505
+ /**
506
+ * Off Zite with an issuer configured: the sign-in module answers its own paths and nothing else under them reaches the
507
+ * app, then says who is calling. Undefined when it isn't mounted or has answered.
508
+ */
509
+ const signInLocally = async (request, local) => {
510
+ const pathname = new URL(request.url).pathname;
511
+ if (!local.urls || invokeOf(request.headers, UNHOSTED_INVOKE_KINDS) || pathname === ANALYTICS_PATH || pathname === UPLOAD_SESSION_PATH) {
512
+ return undefined;
513
+ }
514
+ const signIn = await localSignIn(globalThis.process?.env ?? {}, local.urls, request);
515
+ if (!signIn)
516
+ return undefined;
517
+ const answered = await signIn.handle(request);
518
+ if (answered)
519
+ return { answered };
520
+ if (isSignInPath(pathname))
521
+ return { answered: new Response("Not found", { status: 404 }) };
522
+ const signedIn = await signIn.resolve(request);
523
+ return { request: withCookie(request, signedIn.cookie), signedIn };
524
+ };
396
525
  /** The fetch handler alone, for the Node entry. */
397
526
  export function createZiteFetch(options) {
398
527
  return createZiteHandlers(options).fetch;
@@ -0,0 +1,13 @@
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
+ /**
10
+ * One report of the request's run; the caller keeps it going past the response with `waitUntil`. A request the host
11
+ * dispatched without a runs URL or a token has nowhere to send it, which the throw says.
12
+ */
13
+ export declare const sendRunReport: (host: HostRequestState, report: RunReport) => Promise<void>;
@@ -0,0 +1,71 @@
1
+ // What a request reports of its own run: what ran, the platform calls it made and its outbound fetches with what its
2
+ // own AI keys used. On the app token to the platform's runs service, which stamps the org, app and request from the
3
+ // token, never from the report. `local` keeps none: only the platform writes a run's row, and a dev token names no
4
+ // request of its own.
5
+ import { platformFetch } from "../internal/platformFetch.js";
6
+ // Half of what the runs service reads in one send; each record is capped far below it.
7
+ const MAX_SEND_BYTES = 512 * 1024;
8
+ const RUNS_TIMEOUT_MS = 10_000;
9
+ const encoder = new TextEncoder();
10
+ const emptySend = () => ({ runs: [], calls: [], fetches: [] });
11
+ const asReport = ({ runs, calls, fetches }) => ({
12
+ runs,
13
+ ...(calls.length > 0 && { calls }),
14
+ ...(fetches.length > 0 && { fetches }),
15
+ });
16
+ /** The report in as few sends as fit under the runs service's limit, each record whole. */
17
+ export const reportSends = (report) => {
18
+ const sends = [];
19
+ let send = emptySend();
20
+ let bytes = 0;
21
+ const place = (record, add) => {
22
+ const size = encoder.encode(JSON.stringify(record)).byteLength;
23
+ if (bytes > 0 && bytes + size > MAX_SEND_BYTES) {
24
+ sends.push(asReport(send));
25
+ send = emptySend();
26
+ bytes = 0;
27
+ }
28
+ add(send);
29
+ bytes += size;
30
+ };
31
+ for (const run of report.runs)
32
+ place(run, (into) => into.runs.push(run));
33
+ for (const call of report.calls ?? [])
34
+ place(call, (into) => into.calls.push(call));
35
+ for (const fetched of report.fetches ?? [])
36
+ place(fetched, (into) => into.fetches.push(fetched));
37
+ if (bytes > 0)
38
+ sends.push(asReport(send));
39
+ return sends;
40
+ };
41
+ const toRunsService = async (host, runs, token, report) => {
42
+ const answers = await Promise.all(reportSends(report).map((send) => platformFetch(new Request(`${runs}/ingest`, {
43
+ method: "POST",
44
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
45
+ body: JSON.stringify({
46
+ kind: "events",
47
+ ...send,
48
+ // Names the integration call events its fetches become.
49
+ ...(send.fetches?.length && host.connectionServices && { services: host.connectionServices }),
50
+ }),
51
+ signal: AbortSignal.timeout(RUNS_TIMEOUT_MS),
52
+ }))));
53
+ const refused = answers.find((answer) => !answer.ok);
54
+ await Promise.all(answers.map((answer) => answer.body?.cancel()));
55
+ if (refused)
56
+ throw new Error(`the runs service answered ${refused.status}`);
57
+ };
58
+ /**
59
+ * One report of the request's run; the caller keeps it going past the response with `waitUntil`. A request the host
60
+ * dispatched without a runs URL or a token has nowhere to send it, which the throw says.
61
+ */
62
+ export const sendRunReport = async (host, report) => {
63
+ const { provider } = host;
64
+ if (!provider || provider.kind === "local")
65
+ return;
66
+ const runs = provider.urls?.runs;
67
+ const token = runs ? await provider.token() : undefined;
68
+ if (!runs || !token)
69
+ throw new Error("This request has no runs URL or app token to send its run's detail with");
70
+ return toRunsService(host, runs, token, report);
71
+ };