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,74 @@
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; without a token or a runs URL, on the host's session as before. `local` keeps none: only
4
+ // the platform writes a run's row, and a dev token names no 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
+ /** One report of the request's run; the caller keeps it going past the response with `waitUntil`. */
59
+ export const sendRunReport = async (host, report) => {
60
+ const { provider, platform } = host;
61
+ if (provider?.kind === "local")
62
+ return;
63
+ const runs = provider?.urls?.runs;
64
+ const token = runs ? await provider?.token() : undefined;
65
+ if (runs && token)
66
+ return toRunsService(host, runs, token, report);
67
+ if (!platform)
68
+ return;
69
+ // Only a session takes calls and fetches, which a request on the app token may have made without opening one.
70
+ if (report.calls?.length || report.fetches?.length)
71
+ host.session ??= Promise.resolve(platform.session());
72
+ const session = host.session ? await host.session : undefined;
73
+ await (session ? session.runs(report) : platform.runs(report));
74
+ };
@@ -91,7 +91,7 @@ export type FetchRecord = {
91
91
  connection?: string;
92
92
  /** Sent again with a refreshed token after a 401. */
93
93
  retried?: true;
94
- /** On Zite's own AI key, which the host meters itself. */
94
+ /** On Zite's own AI key, which the platform meters itself. */
95
95
  ziteAi?: true;
96
96
  /** What a call on the org's own AI key used, for analytics. */
97
97
  ai?: AiUsageRecord;
@@ -106,7 +106,7 @@ export type PlatformSession = {
106
106
  }): Promise<void>;
107
107
  /** After a provider answered 401: the connection refreshed, as `integrations.get` now answers it. */
108
108
  refreshConnection(name: string): Promise<PlatformCallResult>;
109
- /** A call on Zite's own AI key, which the host makes with the real key. */
109
+ /** A call on Zite's own AI key, which the host makes with the real key: for a request with no token or gateway. */
110
110
  aiFetch(request: Request): Promise<Response>;
111
111
  /** The build's base and SDK names, which the app's data dispatch translates against. */
112
112
  dataContext(): Promise<{
@@ -125,6 +125,35 @@ export type PlatformSession = {
125
125
  baseId?: string;
126
126
  nameMappings?: unknown;
127
127
  } | null>;
128
+ /** A new app token for this request, when the one it holds is about to expire. */
129
+ appToken?(): Promise<string>;
130
+ };
131
+ /**
132
+ * Where the platform's services answer this app: `aiGateway` takes calls on Zite's AI key, `runs` a live page's
133
+ * analytics and each request's run detail. `email`, `pdf`, `uploads` (the upload session) and `steps` (a workflow
134
+ * run's saved steps) are each that service's own endpoint, which the platform picks per workspace; without one, the
135
+ * backend's route answers it.
136
+ */
137
+ export type PlatformUrls = {
138
+ baseRunner: string;
139
+ backend: string;
140
+ aiGateway?: string;
141
+ runs?: string;
142
+ email?: string;
143
+ pdf?: string;
144
+ uploads?: string;
145
+ steps?: string;
146
+ };
147
+ /**
148
+ * Where the platform is for one request, and what reaches it: Zite's dispatcher through props, or a developer's
149
+ * machine through env. The only zitejs code that knows which.
150
+ */
151
+ export type PlatformProvider = {
152
+ kind: "zite" | "local";
153
+ /** The request's app token, renewed when it's about to expire; undefined when the host sent none. */
154
+ token(): Promise<string | undefined>;
155
+ user(): User | null;
156
+ urls: PlatformUrls | undefined;
128
157
  };
129
158
  /** What the host hands each request: its platform, already scoped to the app, build, request and user. */
130
159
  export type PlatformBinding = {
@@ -137,6 +166,70 @@ export type PlatformBinding = {
137
166
  };
138
167
  /** A demo is the published build serving a read-only visitor: as live, but every write is refused. */
139
168
  export type HostMode = "live" | "preview" | "demo" | "validate";
169
+ /**
170
+ * The build's page settings, as the platform baked them at publish from the app's settings and name. What the settings
171
+ * set (`seo*`, `favicon`, an installable app's) replaces what a page sets; the rest fills what it leaves out.
172
+ */
173
+ export type PagePlan = {
174
+ fallbackTitle: string;
175
+ seoTitle?: string;
176
+ fallbackDescription: string;
177
+ seoDescription?: string;
178
+ /** A social image: the app's thumbnail, else its screenshot. */
179
+ image?: string;
180
+ seoImage?: string;
181
+ favicon?: string;
182
+ /** For a page with no icon of its own and none configured. */
183
+ defaultFavicon: string;
184
+ /** An installable app's; unset otherwise. */
185
+ appleTouchIcon?: string;
186
+ /** Served at `/manifest.webmanifest` when the app is installable. */
187
+ manifest: {
188
+ theme_color: string;
189
+ short_name: string;
190
+ } | null;
191
+ };
192
+ /** A marketplace demo's listing, which the platform's runtime shows the visitor. */
193
+ export type DemoListing = {
194
+ listingSlug: string;
195
+ listingUrl: string;
196
+ };
197
+ /** What the platform adds to every page's head. A host that sends none writes its tags into the HTML itself. */
198
+ export type HostPage = {
199
+ plan: PagePlan;
200
+ /** The platform's runtime script, which the editor's preview and the badge run on. */
201
+ runtimeUrl?: string;
202
+ demo?: DemoListing;
203
+ };
204
+ /** The platform's head entries for one request, as the page renders them and carries them to the browser. */
205
+ export type PlatformHead = {
206
+ title: string;
207
+ description: string;
208
+ image?: string;
209
+ icon: string;
210
+ /** Which of those the app's settings set, so they replace what a page sets. */
211
+ fromSettings: {
212
+ title: boolean;
213
+ description: boolean;
214
+ image: boolean;
215
+ icon: boolean;
216
+ };
217
+ /** An installable app's, which replaces a page's own as its manifest and app metadata do. */
218
+ appleTouchIcon?: string;
219
+ manifest?: {
220
+ themeColor: string;
221
+ shortName: string;
222
+ };
223
+ runtimeUrl?: string;
224
+ demo?: DemoListing;
225
+ /** Zite's badge, as the org's plan says. */
226
+ branding: boolean;
227
+ analytics: {
228
+ appId: string;
229
+ enabled: boolean;
230
+ endpointUrl: string;
231
+ };
232
+ };
140
233
  export type HostInvoke = {
141
234
  kind: "webhook" | "describe" | "workflow" | "register" | "warm" | "authHook" | "function";
142
235
  name: string;
@@ -158,8 +251,17 @@ export type HostProps = {
158
251
  env?: Record<string, string>;
159
252
  /** Which connection each token var in `env` holds. */
160
253
  envConnections?: Record<string, string>;
254
+ /** Each connection's service, which the calls made with its token are counted under. */
255
+ connectionServices?: Record<string, string>;
161
256
  /** A resumed run's first attempt, whose saved steps it replays. */
162
257
  runRoot?: string;
258
+ /** This request's app token, sent only to `urls`. */
259
+ appToken?: string;
260
+ urls?: PlatformUrls;
261
+ /** Sent with a page or route request by a host that leaves its head to zitejs. */
262
+ page?: HostPage;
263
+ /** The app's access mode, from the platform's records: an internal app serves no page or call to nobody. */
264
+ accessMode?: "internal" | "external";
163
265
  };
164
266
  /** What the host resolved for this request. Set by the generated server entry, never by the browser. */
165
267
  export type HostRequestState = {
@@ -174,6 +276,7 @@ export type HostRequestState = {
174
276
  /** Classic's connection env vars the host sent, set into `process.env` for the request. */
175
277
  env?: Record<string, string>;
176
278
  envConnections?: Record<string, string>;
279
+ connectionServices?: Record<string, string>;
177
280
  /** A resumed run's first attempt, whose saved steps it replays. */
178
281
  runRoot?: string;
179
282
  /** The connection each token this request was handed belongs to. */
@@ -200,6 +303,18 @@ export type HostRequestState = {
200
303
  pending?: Promise<void>[];
201
304
  platform?: PlatformBinding;
202
305
  session?: Promise<PlatformSession>;
306
+ provider?: PlatformProvider;
307
+ /** The request context's, which keeps a send going after the response. */
308
+ waitUntil?: (promise: Promise<unknown>) => void;
309
+ /** This request's direct base-runner calls in flight, capped as the host's relay capped them. */
310
+ dataSlots?: {
311
+ data: () => Promise<() => void>;
312
+ sql: () => Promise<() => void>;
313
+ };
314
+ /** This request's calls on Zite's AI key waiting on the gateway's answer, capped as the host's relay capped them. */
315
+ aiSlots?: () => Promise<() => void>;
203
316
  /** This request's router, so a page's status can follow the error it rendered. */
204
317
  router?: unknown;
318
+ /** The platform's head entries for its pages; unset when the host writes them itself. */
319
+ head?: PlatformHead;
205
320
  };
@@ -0,0 +1,2 @@
1
+ import type { HostRequestState } from "./types.js";
2
+ export declare const takeUploadSession: (request: Request, host: HostRequestState) => Promise<Response>;
@@ -0,0 +1,52 @@
1
+ // A Start page's upload session, asked of the app's own origin: the app's server asks the platform's uploads service on
2
+ // the request's token, which says the app and the mode, so neither the token nor a platform host reaches the browser.
3
+ import { platformFetch } from "../internal/platformFetch.js";
4
+ import { serviceUrl } from "../internal/serviceUrls.js";
5
+ import { textUpTo } from "./analytics.js";
6
+ import { directAccess } from "./direct.js";
7
+ const MAX_SESSION_BYTES = 16 * 1024;
8
+ const UPLOADS_TIMEOUT_MS = 15_000;
9
+ const refused = (status, message) => Response.json({ success: false, message }, { status });
10
+ // As the app's own routes are checked (instance.ts): a cookie rides only on a request from the app's own pages.
11
+ const crossSite = (request) => {
12
+ if (!request.headers.has("cookie"))
13
+ return false;
14
+ const site = request.headers.get("sec-fetch-site");
15
+ if (site !== null)
16
+ return site !== "same-origin";
17
+ return request.headers.get("origin") !== new URL(request.url).origin;
18
+ };
19
+ const sessionBody = (raw) => {
20
+ try {
21
+ const { filename, uploadLength, contentType } = JSON.parse(raw ?? "");
22
+ return JSON.stringify({ filename, uploadLength, contentType });
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ };
28
+ export const takeUploadSession = async (request, host) => {
29
+ if (request.method !== "POST")
30
+ return new Response("Method not allowed", { status: 405 });
31
+ if (crossSite(request))
32
+ return refused(403, "Forbidden");
33
+ const access = await directAccess(host);
34
+ if (!access)
35
+ return refused(503, "Uploads need the platform's app token, and this request has none");
36
+ const body = sessionBody(await textUpTo(request, MAX_SESSION_BYTES));
37
+ if (body === undefined)
38
+ return refused(400, "Invalid upload session request");
39
+ try {
40
+ const answer = await platformFetch(new Request(serviceUrl(access.urls, "uploads"), {
41
+ method: "POST",
42
+ headers: { authorization: `Bearer ${access.token}`, "content-type": "application/json" },
43
+ body,
44
+ signal: AbortSignal.timeout(UPLOADS_TIMEOUT_MS),
45
+ }));
46
+ return new Response(answer.body, { status: answer.status, headers: { "content-type": "application/json" } });
47
+ }
48
+ catch (error) {
49
+ console.error("[zite] the upload session failed", error);
50
+ return refused(502, "Upload failed");
51
+ }
52
+ };
@@ -1 +1 @@
1
- export declare const ZITEJS_VERSION = "0.10.0-start.21";
1
+ export declare const ZITEJS_VERSION = "0.10.0-start.22";
@@ -1,2 +1,2 @@
1
1
  // Written by scripts/write-version.mjs from package.json.
2
- export const ZITEJS_VERSION = "0.10.0-start.21";
2
+ export const ZITEJS_VERSION = "0.10.0-start.22";
@@ -1,4 +1,15 @@
1
- import type { PluginOption } from "vite";
1
+ import { type PluginOption } from "vite";
2
+ import type { ZiteSchema } from "../sync/lib.js";
3
+ import type { DataNameMappings } from "./data/types.js";
4
+ /** @internal A workspace's zite.schema.json as a build's `nameMappings`: the SDK names `.zite/db.ts` was generated with. */
5
+ export declare const workspaceNameMappingsOf: (raw: ZiteSchema) => DataNameMappings;
6
+ /**
7
+ * @internal The sign-in settings `zitejs dev` wrote for the app, for the module `local` mounts; null without them, or
8
+ * when the app's env sets `ZITE_DEV_USER`, whose stand-in wins.
9
+ */
10
+ export declare const devSignInOf: (appDir: string, appEnv: Record<string, string | undefined>) => Record<string, string> | null;
11
+ /** @internal The app's id in its zite.config.json, which `local` mints dev tokens for; null without one. */
12
+ export declare const devAppIdOf: (appDir: string) => string | null;
2
13
  export type ZiteOptions = {
3
14
  /** A server entry the caller owns, relative to the app root. By default zite() writes the platform's. */
4
15
  serverEntry?: string;
@@ -1,8 +1,11 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { loadEnv } from "vite";
4
+ import { parse as parseEnv } from "dotenv";
3
5
  import { tanstackStart } from "@tanstack/react-start/plugin/vite";
4
6
  import viteReact from "@vitejs/plugin-react";
5
7
  import { ziteId } from "../vite/index.js";
8
+ import { normalizeSchemaNames } from "../sync/sdkNames.js";
6
9
  import { factoryDescriptions } from "./descriptions.js";
7
10
  import { registrationHashes } from "./registrationHash.js";
8
11
  import { hasAppStart, renderStartInstance, renderStartServerEntry, renderWorkflowModules, START_INSTANCE_ENTRY, START_SERVER_ENTRY, workflowFiles, writeIfChanged, } from "./entries.js";
@@ -18,6 +21,16 @@ const WORKFLOW_REGISTRY = /[\\/]zitejs[\\/]dist[\\/]esm[\\/]start[\\/]workflowMo
18
21
  // zitejs's null auth-hooks module, which the build points at the app's `zite.auth.ts`.
19
22
  const AUTH_HOOKS_REGISTRY = /[\\/]zitejs[\\/]dist[\\/]esm[\\/]start[\\/]authHooksModule\.js$/;
20
23
  const AUTH_HOOKS_FILE = "zite.auth.ts";
24
+ // zitejs's null workspace names, which `vite dev` fills from the workspace root, where `zitejs/db` comes from too.
25
+ const WORKSPACE_SCHEMA_MODULE = /[\\/]zitejs[\\/]dist[\\/]esm[\\/]start[\\/]workspaceSchema\.js$/;
26
+ const WORKSPACE_SCHEMA_FILE = "../../zite.schema.json";
27
+ // zitejs's null app id, which `vite dev` fills from the app's zite.config.json.
28
+ const DEV_APP_MODULE = /[\\/]zitejs[\\/]dist[\\/]esm[\\/]start[\\/]devApp\.js$/;
29
+ // zitejs's null sign-in settings, which `vite dev` fills from the `.zite/dev.env` that `zitejs dev` writes.
30
+ const DEV_SIGNIN_MODULE = /[\\/]zitejs[\\/]dist[\\/]esm[\\/]start[\\/]devSignIn\.js$/;
31
+ const DEV_ENV_FILE = ".zite/dev.env";
32
+ const DEV_SIGNIN_KEYS = ["ZITE_SIGNIN", "ZITE_AUTH_SECRET"];
33
+ const APP_CONFIG_FILE = "zite.config.json";
21
34
  const SOURCE_LANGS = {
22
35
  ".ts": "ts",
23
36
  ".mts": "ts",
@@ -28,6 +41,43 @@ const SOURCE_LANGS = {
28
41
  ".cjs": "js",
29
42
  ".jsx": "jsx",
30
43
  };
44
+ /** @internal A workspace's zite.schema.json as a build's `nameMappings`: the SDK names `.zite/db.ts` was generated with. */
45
+ export const workspaceNameMappingsOf = (raw) => ({
46
+ tables: Object.fromEntries(normalizeSchemaNames(raw).schema.tables.map((table) => [
47
+ table.id,
48
+ {
49
+ mapping: { sdkName: table.sdkName },
50
+ fields: Object.fromEntries(table.fields.map((field) => [field.id, { mapping: { sdkName: field.sdkName } }])),
51
+ },
52
+ ])),
53
+ });
54
+ /**
55
+ * @internal The sign-in settings `zitejs dev` wrote for the app, for the module `local` mounts; null without them, or
56
+ * when the app's env sets `ZITE_DEV_USER`, whose stand-in wins.
57
+ */
58
+ export const devSignInOf = (appDir, appEnv) => {
59
+ if (appEnv.ZITE_DEV_USER)
60
+ return null;
61
+ let written;
62
+ try {
63
+ written = parseEnv(readFileSync(path.join(appDir, DEV_ENV_FILE), "utf-8"));
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ const kept = Object.fromEntries(DEV_SIGNIN_KEYS.flatMap((key) => (written[key] ? [[key, written[key]]] : [])));
69
+ return kept.ZITE_SIGNIN ? kept : null;
70
+ };
71
+ /** @internal The app's id in its zite.config.json, which `local` mints dev tokens for; null without one. */
72
+ export const devAppIdOf = (appDir) => {
73
+ try {
74
+ const { id } = JSON.parse(readFileSync(path.join(appDir, APP_CONFIG_FILE), "utf-8"));
75
+ return typeof id === "string" && id ? id : null;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ };
31
81
  // Platform-pinned Worker settings. The deploy uses its own fixed template, so
32
82
  // these only have to match it; apps don't carry a wrangler config.
33
83
  const WORKER_COMPATIBILITY_DATE = "2026-09-25";
@@ -63,8 +113,12 @@ export function zite(options = {}) {
63
113
  // The peer dependency gets zitejs crawled already; this keeps it true if an
64
114
  // install drops that. A Node build bundles everything, so externalized
65
115
  // libraries can't load the root's React 18 renderer.
66
- config: (config) => {
116
+ config: (config, { command, mode }) => {
67
117
  const root = path.resolve(config.root ?? ".");
118
+ // The `local` provider reads process.env. In workerd, Cloudflare's plugin sets it from the app's .env; on Node, this does.
119
+ if (command === "serve" && options.cloudflare === false) {
120
+ Object.assign(process.env, loadEnv(mode, root, ["ZITE_DEV_", "ZITE_URLS", "ZITE_SIGNIN", "ZITE_AUTH_SECRET"]));
121
+ }
68
122
  const src = `${path.join(root, "src")}/`;
69
123
  return {
70
124
  ssr: { noExternal: options.cloudflare === false ? true : ["zitejs"] },
@@ -87,8 +141,15 @@ export function zite(options = {}) {
87
141
  };
88
142
  },
89
143
  // Each new isolate loads the whole server bundle, so its size is cold-start
90
- // time; Vite leaves SSR output unminified.
91
- configEnvironment: (name, config) => name === "ssr" && options.cloudflare !== false && config.build?.minify === undefined ? { build: { minify: true } } : undefined,
144
+ // time; Vite leaves SSR output unminified. Under `vite dev`, Cloudflare's
145
+ // plugin would pre-bundle zitejs's server entry, past the modules below
146
+ // that fill zitejs's registries and workspace names.
147
+ configEnvironment: (name, config, { command }) => name !== "ssr"
148
+ ? undefined
149
+ : {
150
+ ...(options.cloudflare !== false && config.build?.minify === undefined && { build: { minify: true } }),
151
+ ...(command === "serve" && { optimizeDeps: { exclude: ["zitejs"] } }),
152
+ },
92
153
  };
93
154
  // Each server function's `description` option, by name, and each route's file, by route id: for the editor.
94
155
  const descriptions = new Map();
@@ -174,6 +235,54 @@ export function zite(options = {}) {
174
235
  : "export const authHooksModule = null;\n";
175
236
  },
176
237
  };
238
+ // Under `vite dev` only: a published build gets its names from the platform, and shouldn't carry them.
239
+ const workspaceSchema = {
240
+ name: "zite:workspace-schema",
241
+ apply: "serve",
242
+ load(id) {
243
+ if (!WORKSPACE_SCHEMA_MODULE.test(id.split("?")[0]))
244
+ return undefined;
245
+ const file = path.join(appDir, WORKSPACE_SCHEMA_FILE);
246
+ this.addWatchFile(file);
247
+ let mappings = null;
248
+ try {
249
+ if (existsSync(file))
250
+ mappings = workspaceNameMappingsOf(JSON.parse(readFileSync(file, "utf-8")));
251
+ }
252
+ catch {
253
+ // Unreadable: data calls go out under the names the app sent.
254
+ }
255
+ return `export const workspaceNameMappings = ${JSON.stringify(mappings)};\n`;
256
+ },
257
+ };
258
+ // Under `vite dev` only: a published build is never `local`'s to mint for.
259
+ const devApp = {
260
+ name: "zite:dev-app",
261
+ apply: "serve",
262
+ load(id) {
263
+ if (!DEV_APP_MODULE.test(id.split("?")[0]))
264
+ return undefined;
265
+ this.addWatchFile(path.join(appDir, APP_CONFIG_FILE));
266
+ return `export const devAppId = ${JSON.stringify(devAppIdOf(appDir))};\n`;
267
+ },
268
+ };
269
+ // Under `vite dev` only, and only to the server: the secret seals the session cookie, and never reaches a browser.
270
+ let devEnv = {};
271
+ const devSignIn = {
272
+ name: "zite:dev-signin",
273
+ apply: "serve",
274
+ configResolved(config) {
275
+ const envDir = typeof config.envDir === "string" ? config.envDir : config.root;
276
+ devEnv = { ...loadEnv(config.mode, envDir, ["ZITE_DEV_USER"]), ...process.env };
277
+ },
278
+ load(id) {
279
+ if (!DEV_SIGNIN_MODULE.test(id.split("?")[0]))
280
+ return undefined;
281
+ this.addWatchFile(path.join(appDir, DEV_ENV_FILE));
282
+ const settings = this.environment?.config.consumer === "server" ? devSignInOf(appDir, devEnv) : null;
283
+ return `export const devSignIn = ${JSON.stringify(settings)};\n`;
284
+ },
285
+ };
177
286
  return [
178
287
  // First, so ids name lines in the source, before TanStack splits a route's component out of it.
179
288
  ziteId(),
@@ -199,7 +308,7 @@ export function zite(options = {}) {
199
308
  behavior: "error",
200
309
  client: {
201
310
  // Appended to TanStack's own.
202
- specifiers: ["zitejs/start/server", "zitejs/start/worker", "zitejs/start/describe", "zitejs/runtime"],
311
+ specifiers: ["zitejs/start/fetch", "zitejs/start/server", "zitejs/start/worker", "zitejs/start/describe", "zitejs/signin", "zitejs/runtime"],
203
312
  // Replaces TanStack's list, so its `**/*.server.*` is restated. File
204
313
  // patterns also catch `zitejs/db`, `zitejs/integrations` and `zitejs/meta`,
205
314
  // which the aliases above rewrite before specifiers are matched.
@@ -213,5 +322,8 @@ export function zite(options = {}) {
213
322
  functionIds,
214
323
  workflowRegistry,
215
324
  authHooksRegistry,
325
+ workspaceSchema,
326
+ devApp,
327
+ devSignIn,
216
328
  ];
217
329
  }
@@ -0,0 +1 @@
1
+ export declare const workspaceNameMappings: unknown;
@@ -0,0 +1,3 @@
1
+ // Null as published. Under `vite dev`, `zite()` replaces this module with the workspace's SDK names from
2
+ // zite.schema.json, the source of the names Zite gives a build: what the `local` provider translates data calls with.
3
+ export const workspaceNameMappings = null;
@@ -1,6 +1,8 @@
1
1
  import { useCallback, useState } from 'react';
2
2
  import { getApiUrl, getFlowId } from '../auth/config.js';
3
- import { platformMode } from '../internal/appMode.js';
3
+ import { platformMode, platformProvider } from '../internal/appMode.js';
4
+ import { platformFetch } from '../internal/platformFetch.js';
5
+ import { serviceUrl, UPLOAD_SESSION_PATH } from '../internal/serviceUrls.js';
4
6
  import { ZITE_APP_ACTION_HOSTNAME_PREFIX, ZITE_APP_EDITOR_HOSTNAME_PREFIX, ZITE_SANDBOX_DOMAINS, } from '../auth/constants.js';
5
7
  export class FileUploadError extends Error {
6
8
  constructor(message) {
@@ -83,22 +85,76 @@ function authHeaders() {
83
85
  : null;
84
86
  return token ? { Authorization: 'Bearer ' + token } : {};
85
87
  }
86
- async function performUpload(data, filename) {
87
- const blob = toUploadBlob(data);
88
+ // On Start the session's answer says whether to complete, and where. No credential goes with it, so the app token never
89
+ // reaches an origin the platform didn't name in the app's props.
90
+ const startCompletion = session => session.completeUrl ? { url: session.completeUrl, headers: {} } : undefined;
91
+ /** On a Start server holding an app token: the platform's uploads service, which reads the app and mode from the token. */
92
+ async function tokenRoutes() {
93
+ const provider = platformProvider();
94
+ const urls = provider?.urls;
95
+ const token = urls ? await provider?.token() : undefined;
96
+ if (!urls || !token)
97
+ return undefined;
98
+ return {
99
+ session: body => platformFetch(new Request(serviceUrl(urls, 'uploads'), {
100
+ method: 'POST',
101
+ headers: {
102
+ 'Content-Type': 'application/json',
103
+ Authorization: 'Bearer ' + token,
104
+ },
105
+ body,
106
+ })),
107
+ completion: startCompletion,
108
+ };
109
+ }
110
+ /** In a Start page: the app's own server, which asks the platform on its request's token, in the mode it was served. */
111
+ function pageRoutes() {
112
+ if (typeof window === 'undefined' || !platformMode())
113
+ return undefined;
114
+ return {
115
+ session: body => fetch(UPLOAD_SESSION_PATH, {
116
+ method: 'POST',
117
+ headers: { 'Content-Type': 'application/json' },
118
+ body,
119
+ }),
120
+ completion: startCompletion,
121
+ };
122
+ }
123
+ /** A classic app's, and a Start server's on a host that sent no token. */
124
+ function publicRoutes() {
88
125
  const mode = getZiteAppMode();
89
126
  const flowId = getFlowId();
90
- const sessionRes = await fetch(getApiUrl() + '/v1/zite/public/' + flowId + '/upload-session?mode=' + mode, {
91
- method: 'POST',
92
- headers: {
93
- 'Content-Type': 'application/json',
94
- ...authHeaders(),
95
- },
96
- body: JSON.stringify({
97
- filename,
98
- uploadLength: blob.size,
99
- contentType: blob.type || 'application/octet-stream',
127
+ return {
128
+ session: body => fetch(getApiUrl() + '/v1/zite/public/' + flowId + '/upload-session?mode=' + mode, {
129
+ method: 'POST',
130
+ headers: {
131
+ 'Content-Type': 'application/json',
132
+ ...authHeaders(),
133
+ },
134
+ body,
100
135
  }),
101
- });
136
+ // Gateways that predate the storage ledger omit the token. The file is
137
+ // already at fileUrl, so those uploads still succeed.
138
+ completion: session => session.completionToken
139
+ ? {
140
+ url: getApiUrl() +
141
+ '/v1/zite/public/' +
142
+ flowId +
143
+ '/complete-upload?mode=' +
144
+ mode,
145
+ headers: authHeaders(),
146
+ }
147
+ : undefined,
148
+ };
149
+ }
150
+ async function performUpload(data, filename) {
151
+ const blob = toUploadBlob(data);
152
+ const routes = (await tokenRoutes()) ?? pageRoutes() ?? publicRoutes();
153
+ const sessionRes = await routes.session(JSON.stringify({
154
+ filename,
155
+ uploadLength: blob.size,
156
+ contentType: blob.type || 'application/octet-stream',
157
+ }));
102
158
  if (!sessionRes.ok) {
103
159
  throw new FileUploadError(await readErrorMessage(sessionRes, 'Upload failed'));
104
160
  }
@@ -116,18 +172,13 @@ async function performUpload(data, filename) {
116
172
  if (!putRes.ok) {
117
173
  throw new FileUploadError('Upload failed');
118
174
  }
119
- // Gateways that predate the storage ledger omit the token. The file is
120
- // already at fileUrl, so those uploads still succeed.
121
- if (session.completionToken) {
122
- const completeRes = await fetch(getApiUrl() +
123
- '/v1/zite/public/' +
124
- flowId +
125
- '/complete-upload?mode=' +
126
- mode, {
175
+ const completion = routes.completion(session);
176
+ if (completion) {
177
+ const completeRes = await fetch(completion.url, {
127
178
  method: 'POST',
128
179
  headers: {
129
180
  'Content-Type': 'application/json',
130
- ...authHeaders(),
181
+ ...completion.headers,
131
182
  },
132
183
  body: JSON.stringify({ completionToken: session.completionToken }),
133
184
  });