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
@@ -3,9 +3,12 @@
3
3
  * it: logged, every secret it knows redacted, with the connection whose token
4
4
  * it carries and what an org's own AI key used; a 401 on a connection's token
5
5
  * refreshed and sent once more; and a call on Zite's own AI key sent to the
6
- * host over the app's platform binding.
6
+ * AI gateway on the request's app token.
7
7
  */
8
+ import { isPlatformRequest } from "../internal/platformFetch.js";
8
9
  import { AI_USAGE_HOSTS, meterAiResponse, withStreamUsage } from "./aiUsage.js";
10
+ import { DEMO_UNAVAILABLE_MESSAGE } from "./data/dispatch.js";
11
+ import { directAccess, limiter, refreshConnection } from "./direct.js";
9
12
  import { REDACTED, redactKnown, secretForms } from "./redactSecrets.js";
10
13
  import { getHost } from "./scope.js";
11
14
  const MAX_FETCHES = 500;
@@ -13,10 +16,12 @@ const MAX_FETCHES = 500;
13
16
  const MIN_TOKEN_LENGTH = 8;
14
17
  // As classic: Workers send no User-Agent, and some APIs (GitHub) refuse a request without one.
15
18
  const DEFAULT_USER_AGENT = "zite";
16
- // The backend's stand-in for Zite's own AI key, which only the host answers.
19
+ // The backend's stand-in for Zite's own AI key, naming the connection a call bills to. Nowhere is it a key.
17
20
  const AI_MARKER = /^zite_ai_gateway:[a-z]+:(.+)$/;
18
- // Where a provider SDK given the connection's `baseUrl` sends it; it never resolves.
21
+ // The gateway's name in a connection's `baseUrl`, which zitejs resolves to the provider's `urls.aiGateway`.
19
22
  const AI_HOST = "zite-ai.invalid";
23
+ /** At the gateway, the connection a call on Zite's AI key bills to: the marker's, which the token takes the place of. */
24
+ export const AI_CONNECTION_HEADER = "x-zite-ai-connection";
20
25
  // A provider's own base URL at the host: `/v1` is OpenAI's, Anthropic's SDK sends it in the path.
21
26
  const AI_PROVIDER_HOSTS = {
22
27
  "api.openai.com": { provider: "openai", strip: "/v1" },
@@ -30,6 +35,8 @@ const MAX_ERROR_CHARS = 1_000;
30
35
  const SECRET_HEADER = /auth|key|token|secret|signature|password|cookie|session/i;
31
36
  // Usage still being read when the request's log is flushed isn't waited on for longer.
32
37
  const USAGE_WAIT_MS = 10_000;
38
+ // A request's calls on Zite's AI key at once, until each is answered, as the host once had them.
39
+ const AI_CONCURRENCY = 4;
33
40
  // Tokens refreshed in this isolate, which a later request's props may not name yet.
34
41
  const MAX_REFRESHED = 50;
35
42
  const refreshedTokens = new Map();
@@ -65,6 +72,18 @@ export const rememberConnection = (host, name, connection) => {
65
72
  }
66
73
  }
67
74
  };
75
+ /** An `integrations.get` answer with each token this isolate has since refreshed swapped for its replacement. */
76
+ export const withRefreshedTokens = (answer) => {
77
+ if (replacements.size === 0 || !answer || typeof answer !== "object")
78
+ return answer;
79
+ let swapped;
80
+ for (const [field, value] of Object.entries(answer)) {
81
+ const fresh = typeof value === "string" ? replacements.get(value) : undefined;
82
+ if (fresh)
83
+ (swapped ??= { ...answer })[field] = fresh;
84
+ }
85
+ return swapped ?? answer;
86
+ };
68
87
  const bare = (value) => value.replace(/^(?:Bearer|Token)\s+/i, "");
69
88
  const isUrl = (value) => /^https?:\/\//i.test(value);
70
89
  /** Every value this request knows is secret, longest first. */
@@ -209,22 +228,62 @@ const swapHeaders = (headers, from, to) => {
209
228
  headers.set(name, value.split(from).join(to));
210
229
  }
211
230
  };
212
- /** Where a call on Zite's AI key goes at the host, whether the app named the provider or the `baseUrl` it was given. */
213
- const aiTarget = (url, headers) => {
214
- const marker = [...headers].map(([, value]) => AI_MARKER.exec(bare(value))).find(Boolean);
215
- if (url.hostname === AI_HOST)
216
- return { target: url, connection: marker?.[1] };
231
+ /** The provider's AI gateway, from `urls.aiGateway`. */
232
+ const gatewayOf = (host) => {
233
+ const configured = host.provider?.urls?.aiGateway;
234
+ if (!configured)
235
+ return undefined;
236
+ try {
237
+ return new URL(configured);
238
+ }
239
+ catch {
240
+ return undefined;
241
+ }
242
+ };
243
+ /** `url`'s provider and path when it's under `base`'s path, which names the provider next. */
244
+ const underBase = (url, basePath) => {
245
+ const prefix = basePath.replace(/\/+$/, "");
246
+ if (!url.pathname.startsWith(`${prefix}/`))
247
+ return undefined;
248
+ const [provider = "", ...rest] = url.pathname.slice(prefix.length + 1).split("/");
249
+ return { provider, path: `/${rest.join("/")}${url.search}` };
250
+ };
251
+ /** A call on Zite's AI key, whether the app named the provider, the `baseUrl` it was given, or the gateway itself. */
252
+ const aiCallOf = (url, headers, gateway) => {
253
+ const found = [...headers].map(([, value]) => AI_MARKER.exec(bare(value))).find(Boolean);
254
+ const marker = found ? { marker: found[0], connection: found[1] } : { marker: undefined, connection: undefined };
255
+ if (url.hostname === AI_HOST) {
256
+ const route = underBase(url, "");
257
+ return route && { ...route, ...marker };
258
+ }
259
+ if (!found)
260
+ return undefined;
261
+ if (gateway && url.origin === gateway.origin) {
262
+ const route = underBase(url, gateway.pathname);
263
+ return route && { ...route, ...marker };
264
+ }
217
265
  const route = AI_PROVIDER_HOSTS[url.hostname];
218
- if (!route || !marker)
266
+ if (!route)
219
267
  return undefined;
220
268
  const path = url.pathname.startsWith(route.strip) ? url.pathname.slice(route.strip.length) : url.pathname;
221
- return { target: new URL(`https://${AI_HOST}/${route.provider}${path}${url.search}`), connection: marker[1] };
269
+ return { provider: route.provider, path: `${path}${url.search}`, ...marker };
222
270
  };
223
- const sessionOf = async (host) => {
224
- if (!host.platform)
225
- return undefined;
226
- host.session ??= Promise.resolve(host.platform.session());
227
- return host.session;
271
+ /** A connection on Zite's AI key as `integrations.get` answers it, its `baseUrl` at the provider's gateway. */
272
+ export const withAiGatewayUrl = (host, answer) => {
273
+ const gateway = gatewayOf(host);
274
+ const baseUrl = answer?.baseUrl;
275
+ if (!gateway || typeof baseUrl !== "string" || !answer || typeof answer !== "object")
276
+ return answer;
277
+ let url;
278
+ try {
279
+ url = new URL(baseUrl);
280
+ }
281
+ catch {
282
+ return answer;
283
+ }
284
+ if (url.hostname !== AI_HOST)
285
+ return answer;
286
+ return { ...answer, baseUrl: `${gateway.origin}${gateway.pathname.replace(/\/+$/, "")}${url.pathname}` };
228
287
  };
229
288
  /** The token to send instead of `token`, refreshed once per connection per request. */
230
289
  const freshToken = async (host, token, connection) => {
@@ -235,9 +294,8 @@ const freshToken = async (host, token, connection) => {
235
294
  let pending = refreshing.get(connection);
236
295
  if (!pending) {
237
296
  pending = (async () => {
238
- const session = await sessionOf(host);
239
- const result = session ? await session.refreshConnection(connection) : undefined;
240
- if (!result || !("value" in result))
297
+ const result = await refreshConnection(host, connection);
298
+ if (!("value" in result))
241
299
  return undefined;
242
300
  const fresh = result.value;
243
301
  const previous = (host.connectionAnswers?.get(connection) ?? {});
@@ -262,11 +320,33 @@ const freshToken = async (host, token, connection) => {
262
320
  }
263
321
  return value;
264
322
  };
265
- const aiUnavailable = () => Response.json({ error: { type: "unavailable", message: "Zite's AI key works only in an app Zite hosts" } }, { status: 503 });
323
+ const aiRefusal = (status, type, message) => Response.json({ error: { type, code: type, message } }, { status });
324
+ const aiUnavailable = (host) => aiRefusal(503, "unavailable", host.provider?.kind === "local"
325
+ ? "Zite's AI key needs the AI gateway: name aiGateway in ZITE_URLS"
326
+ : "Zite's AI key needs the platform's AI gateway, which this request wasn't given");
327
+ /**
328
+ * A call on Zite's AI key at the gateway, the marker swapped for the request's app token. The token goes to the
329
+ * gateway's origin alone: the target is built from it, and a redirect is handed back rather than followed.
330
+ */
331
+ const toAiGateway = async (nativeFetch, base, headers, call, gateway, token) => {
332
+ const target = new URL(`${gateway.origin}${gateway.pathname.replace(/\/+$/, "")}/${call.provider}${call.path}`);
333
+ const sent = new Headers(headers);
334
+ sent.delete(AI_CONNECTION_HEADER);
335
+ sent.delete("content-length");
336
+ // As for a connection's call: a Node SDK that asks for gzip inflates a body Workers already inflated.
337
+ sent.delete("accept-encoding");
338
+ if (call.marker && call.connection) {
339
+ swapHeaders(sent, call.marker, token);
340
+ sent.set(AI_CONNECTION_HEADER, call.connection);
341
+ }
342
+ // Whole, so it goes with its length and the gateway holds only what it is.
343
+ const body = base.body ? await base.arrayBuffer() : undefined;
344
+ return nativeFetch(new Request(target, { method: base.method, headers: sent, body, redirect: "manual", signal: base.signal }));
345
+ };
266
346
  const cfOf = (request) => request.cf;
267
347
  export const createOutboundFetch = (nativeFetch) => async (input, init) => {
268
348
  const host = getHost();
269
- if (!host)
349
+ if (!host || isPlatformRequest(input))
270
350
  return nativeFetch(input, init);
271
351
  let url;
272
352
  try {
@@ -279,7 +359,8 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
279
359
  if (!headers.has("user-agent"))
280
360
  headers.set("user-agent", DEFAULT_USER_AGENT);
281
361
  const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
282
- const ai = aiTarget(url, headers);
362
+ const gateway = gatewayOf(host);
363
+ const ai = aiCallOf(url, headers, gateway);
283
364
  const found = ai ? undefined : carried(headers, url, tokensOf(host));
284
365
  const startedAt = Date.now();
285
366
  const sentBody = bodyText(init?.body);
@@ -331,19 +412,27 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
331
412
  const base = new Request(input, usageBody === undefined ? init : { ...init, body: usageBody });
332
413
  if (ai) {
333
414
  try {
334
- const session = await sessionOf(host);
335
- if (!session) {
336
- const refused = aiUnavailable();
415
+ // As the gateway and the host refuse it: a demo has no AI on Zite's key.
416
+ if (host.mode === "demo") {
417
+ const refused = aiRefusal(403, "permission_denied", DEMO_UNAVAILABLE_MESSAGE);
337
418
  record({ status: refused.status });
338
419
  return refused;
339
420
  }
340
- // Whole, so it crosses RPC as bytes whatever stream the app built it from, and sized, so the host
341
- // reserves only what it is rather than the most it allows.
342
- const body = base.body ? await base.arrayBuffer() : undefined;
343
- headers.set("content-length", String(body?.byteLength ?? 0));
344
- const response = await session.aiFetch(new Request(ai.target, { method: base.method, headers, body, redirect: "manual" }));
345
- record({ status: response.status });
346
- return response;
421
+ const access = gateway ? await directAccess(host) : undefined;
422
+ if (gateway && access) {
423
+ const release = await (host.aiSlots ??= limiter(AI_CONCURRENCY))();
424
+ try {
425
+ const response = await toAiGateway(nativeFetch, base, headers, ai, gateway, access.token);
426
+ record({ status: response.status });
427
+ return response;
428
+ }
429
+ finally {
430
+ release();
431
+ }
432
+ }
433
+ const refused = aiUnavailable(host);
434
+ record({ status: refused.status });
435
+ return refused;
347
436
  }
348
437
  catch (error) {
349
438
  record({ error });
@@ -398,3 +487,13 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
398
487
  throw error;
399
488
  }
400
489
  };
490
+ // Keyed on globalThis so two copies of zitejs in one bundle wrap fetch once.
491
+ const WATCHED_KEY = Symbol.for("zitejs:outbound-fetch");
492
+ /** Wraps the global fetch once. Next patches fetch for the same reason: the run log must hear of each. */
493
+ export const watchOutboundFetches = () => {
494
+ const marks = globalThis;
495
+ if (marks[WATCHED_KEY])
496
+ return;
497
+ marks[WATCHED_KEY] = true;
498
+ globalThis.fetch = createOutboundFetch(globalThis.fetch.bind(globalThis));
499
+ };
@@ -0,0 +1,36 @@
1
+ import type { HostMode, HostPage, PlatformHead } from "./types.js";
2
+ /** Where the runtime posts a page's analytics: its `endpointUrl` and then its own path. */
3
+ export declare const ANALYTICS_PATH = "/__zite/public/zite/analytics";
4
+ type Tag = Record<string, unknown>;
5
+ type Meta = Tag & {
6
+ title?: unknown;
7
+ name?: unknown;
8
+ property?: unknown;
9
+ content?: unknown;
10
+ };
11
+ /** What a route's `head()` answers. */
12
+ export type RouteHead = {
13
+ meta?: Array<Meta | undefined>;
14
+ links?: Array<Tag | undefined>;
15
+ scripts?: Array<Tag | undefined>;
16
+ styles?: unknown;
17
+ };
18
+ /** For one request: the plan its host sent, the badge its token carries, and analytics on a live page. */
19
+ export declare const platformHeadOf: (page: HostPage, request: {
20
+ url: string;
21
+ mode: HostMode;
22
+ token: string | undefined;
23
+ }) => PlatformHead;
24
+ /**
25
+ * The root route's head: the platform's entries first, so TanStack lets the app's own win wherever both set a title,
26
+ * the same meta, or an icon or manifest link, except where the platform replaced the app's own.
27
+ */
28
+ export declare const rootHead: (given: RouteHead | undefined, head: PlatformHead) => RouteHead;
29
+ /**
30
+ * A deeper route's head. The root rendered social metadata from the app's name; a route that sets its own title or
31
+ * description has the social metadata follow it, unless the app's settings or the app itself set it on the way down.
32
+ */
33
+ export declare const routeHead: (given: RouteHead | undefined, head: PlatformHead, above: Array<{
34
+ meta?: unknown;
35
+ }>) => RouteHead | undefined;
36
+ export {};
@@ -0,0 +1,178 @@
1
+ // The platform's part of every page's head: its runtime, the badge and analytics config, an installable app's manifest,
2
+ // the metadata the app's settings set, and what the app's own head() leaves out. Isomorphic: head() runs on the server and again in the browser.
3
+ import { appTokenClaims } from "../internal/appToken.js";
4
+ /** Where the runtime posts a page's analytics: its `endpointUrl` and then its own path. */
5
+ export const ANALYTICS_PATH = "/__zite/public/zite/analytics";
6
+ const ANALYTICS_ENDPOINT = "/__zite";
7
+ /** Served by the platform when the app is installable. */
8
+ const MANIFEST_PATH = "/manifest.webmanifest";
9
+ /** For one request: the plan its host sent, the badge its token carries, and analytics on a live page. */
10
+ export const platformHeadOf = (page, request) => {
11
+ const { plan } = page;
12
+ const claims = request.token ? appTokenClaims(request.token) : undefined;
13
+ const image = plan.seoImage ?? plan.image;
14
+ return {
15
+ title: plan.seoTitle ?? plan.fallbackTitle,
16
+ description: plan.seoDescription ?? plan.fallbackDescription,
17
+ ...(image && { image }),
18
+ icon: plan.favicon ?? plan.defaultFavicon,
19
+ fromSettings: {
20
+ title: plan.seoTitle !== undefined,
21
+ description: plan.seoDescription !== undefined,
22
+ image: plan.seoImage !== undefined,
23
+ icon: plan.favicon !== undefined,
24
+ },
25
+ ...(plan.appleTouchIcon && { appleTouchIcon: plan.appleTouchIcon }),
26
+ ...(plan.manifest && { manifest: { themeColor: plan.manifest.theme_color, shortName: plan.manifest.short_name } }),
27
+ ...(page.runtimeUrl && { runtimeUrl: page.runtimeUrl }),
28
+ ...(page.demo && { demo: { listingSlug: page.demo.listingSlug, listingUrl: page.demo.listingUrl } }),
29
+ // As the host decided before it read the org's plan, when there's no token to say.
30
+ branding: claims?.branding ?? true,
31
+ analytics: {
32
+ appId: claims?.app ?? "",
33
+ // Previews are the builder's own visits; demos aren't the app's.
34
+ enabled: request.mode === "live",
35
+ endpointUrl: `${new URL(request.url).origin}${ANALYTICS_ENDPOINT}`,
36
+ },
37
+ };
38
+ };
39
+ // Safe inside a <script>: nothing in it can close the tag.
40
+ const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
41
+ // The entries zitejs added, so a deeper route can tell the app's own from them.
42
+ const made = new WeakSet();
43
+ const platform = (tags) => {
44
+ for (const tag of tags)
45
+ made.add(tag);
46
+ return tags;
47
+ };
48
+ const metaKey = (meta) => {
49
+ const key = meta?.name ?? meta?.property;
50
+ return typeof key === "string" ? key : undefined;
51
+ };
52
+ // The last one wins, as TanStack renders a route's own head.
53
+ const lastText = (metas, pick) => {
54
+ for (let i = metas.length - 1; i >= 0; i--) {
55
+ const value = metas[i] && pick(metas[i]);
56
+ if (typeof value === "string")
57
+ return value.trim();
58
+ }
59
+ return undefined;
60
+ };
61
+ const titleOf = (metas) => lastText(metas, (meta) => meta.title);
62
+ const descriptionOf = (metas) => lastText(metas, (meta) => (metaKey(meta) === "description" ? meta.content : undefined));
63
+ // Social metadata follows the page's own title and description, as classic's does.
64
+ const followTitle = (title) => [
65
+ { property: "og:title", content: title },
66
+ { property: "og:site_name", content: title || "Zite" },
67
+ { name: "twitter:title", content: title },
68
+ ];
69
+ const followDescription = (description) => [
70
+ { property: "og:description", content: description },
71
+ { name: "twitter:description", content: description },
72
+ ];
73
+ const rels = (link) => String(link?.rel ?? "").toLowerCase().split(/\s+/);
74
+ const PWA_METAS = ["theme-color", "mobile-web-app-capable", "apple-mobile-web-app-capable", "apple-mobile-web-app-title"];
75
+ // Only the platform writes these; a page's own copy would stand in for its badge, analytics or demo listing.
76
+ const PLATFORM_SCRIPTS = ["data-zite-branding", "data-zite-analytics", "data-zite-demo"];
77
+ /** A route's own head, less what the platform sets over it, as classic's index.html had it replaced. */
78
+ const withoutReplaced = (own, head) => {
79
+ if (!own)
80
+ return own;
81
+ // The editor's settings are the user's deliberate choice, so they win over what a page sets.
82
+ const { fromSettings } = head;
83
+ const replaced = new Set([
84
+ ...(fromSettings.title ? ["og:title", "og:site_name", "twitter:title"] : []),
85
+ ...(fromSettings.description ? ["description", "og:description", "twitter:description"] : []),
86
+ ...(fromSettings.image ? ["og:image", "twitter:image"] : []),
87
+ ...(head.manifest ? PWA_METAS : []),
88
+ ]);
89
+ const replacedLink = (link) => {
90
+ const rel = rels(link);
91
+ if (rel.includes("manifest"))
92
+ return !!head.manifest;
93
+ if (rel.includes("apple-touch-icon"))
94
+ return !!head.appleTouchIcon;
95
+ return rel.includes("icon") && fromSettings.icon;
96
+ };
97
+ return {
98
+ ...own,
99
+ ...(own.meta && {
100
+ meta: own.meta.filter((meta) => !(meta && ((fromSettings.title && meta.title !== undefined) || replaced.has(metaKey(meta) ?? "")))),
101
+ }),
102
+ ...(own.links && { links: own.links.filter((link) => !replacedLink(link)) }),
103
+ ...(own.scripts && { scripts: own.scripts.filter((script) => !PLATFORM_SCRIPTS.some((marker) => script && marker in script)) }),
104
+ };
105
+ };
106
+ /**
107
+ * The root route's head: the platform's entries first, so TanStack lets the app's own win wherever both set a title,
108
+ * the same meta, or an icon or manifest link, except where the platform replaced the app's own.
109
+ */
110
+ export const rootHead = (given, head) => {
111
+ const own = withoutReplaced(given, head);
112
+ const ownMeta = own?.meta ?? [];
113
+ const ownLinks = own?.links ?? [];
114
+ const title = titleOf(ownMeta) || head.title;
115
+ const description = descriptionOf(ownMeta) || head.description;
116
+ const meta = [
117
+ { title: head.title },
118
+ { name: "viewport", content: "width=device-width, initial-scale=1" },
119
+ { name: "description", content: head.description },
120
+ ...followTitle(title),
121
+ ...followDescription(description),
122
+ { property: "og:type", content: "website" },
123
+ { name: "twitter:card", content: "summary_large_image" },
124
+ ...(head.image
125
+ ? [
126
+ { property: "og:image", content: head.image },
127
+ { name: "twitter:image", content: head.image },
128
+ ]
129
+ : []),
130
+ ...(head.manifest
131
+ ? [
132
+ { name: "theme-color", content: head.manifest.themeColor },
133
+ { name: "mobile-web-app-capable", content: "yes" },
134
+ { name: "apple-mobile-web-app-capable", content: "yes" },
135
+ { name: "apple-mobile-web-app-title", content: head.manifest.shortName },
136
+ ]
137
+ : []),
138
+ ];
139
+ const ownIcon = ownLinks.some((link) => rels(link).includes("icon"));
140
+ const ownAppleIcon = ownLinks.some((link) => rels(link).includes("apple-touch-icon"));
141
+ const ownManifest = ownLinks.some((link) => rels(link).includes("manifest"));
142
+ const links = [
143
+ ...(ownIcon ? [] : [{ rel: "icon", type: "image/x-icon", href: head.icon }]),
144
+ // Zite's icon would stand in for one the page set, unless the app is installable and has its own.
145
+ ...(ownAppleIcon || (ownIcon && !head.appleTouchIcon) ? [] : [{ rel: "apple-touch-icon", href: head.appleTouchIcon ?? head.icon }]),
146
+ ...(head.manifest && !ownManifest ? [{ rel: "manifest", href: MANIFEST_PATH, crossOrigin: "use-credentials" }] : []),
147
+ ];
148
+ // The demo's listing before the runtime, whose demo bridge reads it as it starts.
149
+ const scripts = [
150
+ ...(head.demo ? [{ "data-zite-demo": "true", children: `window.__ziteDemo = ${scriptJson(head.demo)};` }] : []),
151
+ ...(head.runtimeUrl ? [{ src: head.runtimeUrl }] : []),
152
+ { "data-zite-branding": "true", children: `window.__ziteBranding = ${head.branding};` },
153
+ { "data-zite-analytics": "true", children: `window.__ziteAnalytics = ${scriptJson(head.analytics)};` },
154
+ ];
155
+ return {
156
+ ...own,
157
+ meta: [...platform(meta), ...ownMeta],
158
+ links: [...platform(links), ...ownLinks],
159
+ scripts: [...platform(scripts), ...(own?.scripts ?? [])],
160
+ };
161
+ };
162
+ /**
163
+ * A deeper route's head. The root rendered social metadata from the app's name; a route that sets its own title or
164
+ * description has the social metadata follow it, unless the app's settings or the app itself set it on the way down.
165
+ */
166
+ export const routeHead = (given, head, above) => {
167
+ const own = withoutReplaced(given, head);
168
+ const ownMeta = own?.meta ?? [];
169
+ const title = titleOf(ownMeta);
170
+ const description = descriptionOf(ownMeta);
171
+ if (!title && !description)
172
+ return own;
173
+ const appSet = new Set([...above.flatMap((match) => (Array.isArray(match.meta) ? match.meta : [])), ...ownMeta]
174
+ .filter((meta) => meta && !made.has(meta))
175
+ .map(metaKey));
176
+ const follow = [...(title ? followTitle(title) : []), ...(description ? followDescription(description) : [])].filter((meta) => !appSet.has(metaKey(meta)));
177
+ return follow.length ? { ...own, meta: [...platform(follow), ...ownMeta] } : own;
178
+ };
@@ -0,0 +1,24 @@
1
+ import { type AppTokenClaims } from "../internal/appToken.js";
2
+ import type { HostMode, HostProps, PlatformProvider, PlatformUrls } from "./types.js";
3
+ export declare const ziteProvider: (props: HostProps) => PlatformProvider;
4
+ /** What `local` reads, documented in `zitejs`'s help. */
5
+ export declare const LOCAL_ENV: {
6
+ readonly token: "ZITE_DEV_TOKEN";
7
+ readonly apiKey: "ZITE_DEV_API_KEY";
8
+ readonly urls: "ZITE_URLS";
9
+ readonly user: "ZITE_DEV_USER";
10
+ };
11
+ type Env = Record<string, string | undefined>;
12
+ /** `ZITE_URLS`, or a throw saying what it must name. */
13
+ export declare const localUrls: (raw: string | undefined) => PlatformUrls;
14
+ /** The mode a dev token names; preview for one it doesn't. */
15
+ export declare const localModeOf: (claims: AppTokenClaims | undefined) => HostMode;
16
+ /** For tests: forget the minted dev token. */
17
+ export declare const resetDevToken: () => void;
18
+ export declare const mintDevToken: (backend: string, appId: string, apiKey: string) => Promise<string>;
19
+ /**
20
+ * `local` when the developer set a dev token, or a key to mint them with, else undefined. Throws on env it can't read,
21
+ * so a typo fails loudly rather than signing nobody in.
22
+ */
23
+ export declare const localPlatform: (env?: Env, appId?: string | null) => PlatformProvider | undefined;
24
+ export {};
@@ -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) => {
18
+ let current = props.appToken;
19
+ let renewing;
20
+ const renew = async () => {
21
+ try {
22
+ const fresh = await props.platform.appToken();
23
+ return typeof fresh === "string" && fresh ? fresh : undefined;
24
+ }
25
+ catch (error) {
26
+ // The token held still serves 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;