zitejs 0.10.0-start.20 → 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 (154) hide show
  1. package/dist/cjs/auth/actions.d.ts +28 -0
  2. package/dist/cjs/auth/actions.js +93 -0
  3. package/dist/cjs/auth/client.d.ts +357 -0
  4. package/dist/cjs/auth/client.js +66 -0
  5. package/dist/cjs/auth/index.d.ts +2 -249
  6. package/dist/cjs/auth/index.js +11 -114
  7. package/dist/cjs/auth/index.test.js +18 -0
  8. package/dist/cjs/auth/profileUpdates.d.ts +9 -0
  9. package/dist/cjs/auth/profileUpdates.js +11 -0
  10. package/dist/cjs/check/start/sourceRules.js +73 -21
  11. package/dist/cjs/cli.js +6 -0
  12. package/dist/cjs/dev/index.js +15 -0
  13. package/dist/cjs/dev/signin.d.ts +16 -0
  14. package/dist/cjs/dev/signin.js +76 -0
  15. package/dist/cjs/integrations/rules.js +5 -3
  16. package/dist/cjs/internal/appMode.d.ts +11 -0
  17. package/dist/cjs/internal/appMode.js +4 -1
  18. package/dist/cjs/internal/appToken.d.ts +17 -0
  19. package/dist/cjs/internal/appToken.js +26 -0
  20. package/dist/cjs/internal/platformFetch.d.ts +2 -0
  21. package/dist/cjs/internal/platformFetch.js +13 -0
  22. package/dist/cjs/internal/serviceUrls.d.ts +7 -0
  23. package/dist/cjs/internal/serviceUrls.js +16 -0
  24. package/dist/cjs/runtime/index.d.ts +55 -16
  25. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  26. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.js +33 -0
  27. package/dist/cjs/start/aiUsage.d.ts +23 -0
  28. package/dist/cjs/start/aiUsage.js +151 -0
  29. package/dist/cjs/start/devApp.d.ts +1 -0
  30. package/dist/cjs/start/devApp.js +6 -0
  31. package/dist/cjs/start/entries.js +4 -0
  32. package/dist/cjs/start/provider.d.ts +24 -0
  33. package/dist/cjs/start/provider.js +159 -0
  34. package/dist/cjs/start/types.d.ts +320 -0
  35. package/dist/cjs/start/types.js +2 -0
  36. package/dist/cjs/sync/lib.js +10 -5
  37. package/dist/cjs/sync/lib.test.js +10 -0
  38. package/dist/cjs/upload/index.js +73 -22
  39. package/dist/cjs/upload/index.test.js +35 -2
  40. package/dist/esm/auth/actions.d.ts +28 -0
  41. package/dist/esm/auth/actions.js +55 -0
  42. package/dist/esm/auth/client.d.ts +357 -0
  43. package/dist/esm/auth/client.js +62 -0
  44. package/dist/esm/auth/index.d.ts +2 -249
  45. package/dist/esm/auth/index.js +2 -109
  46. package/dist/esm/auth/index.test.js +18 -0
  47. package/dist/esm/auth/profileUpdates.d.ts +9 -0
  48. package/dist/esm/auth/profileUpdates.js +6 -0
  49. package/dist/esm/check/start/sourceRules.js +73 -21
  50. package/dist/esm/cli.js +6 -0
  51. package/dist/esm/dev/index.js +15 -0
  52. package/dist/esm/dev/signin.d.ts +16 -0
  53. package/dist/esm/dev/signin.js +72 -0
  54. package/dist/esm/integrations/rules.js +5 -3
  55. package/dist/esm/internal/appMode.d.ts +11 -0
  56. package/dist/esm/internal/appMode.js +2 -0
  57. package/dist/esm/internal/appToken.d.ts +17 -0
  58. package/dist/esm/internal/appToken.js +22 -0
  59. package/dist/esm/internal/platformFetch.d.ts +2 -0
  60. package/dist/esm/internal/platformFetch.js +8 -0
  61. package/dist/esm/internal/serviceUrls.d.ts +7 -0
  62. package/dist/esm/internal/serviceUrls.js +12 -0
  63. package/dist/esm/runtime/index.d.ts +55 -16
  64. package/dist/esm/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  65. package/dist/esm/runtime/sendEmailParamsTypes.test-d.js +31 -0
  66. package/dist/esm/signin/conformance.d.ts +100 -0
  67. package/dist/esm/signin/conformance.js +471 -0
  68. package/dist/esm/signin/cookies.d.ts +28 -0
  69. package/dist/esm/signin/cookies.js +59 -0
  70. package/dist/esm/signin/encoding.d.ts +9 -0
  71. package/dist/esm/signin/encoding.js +39 -0
  72. package/dist/esm/signin/endpoints.d.ts +12 -0
  73. package/dist/esm/signin/endpoints.js +29 -0
  74. package/dist/esm/signin/http.d.ts +25 -0
  75. package/dist/esm/signin/http.js +69 -0
  76. package/dist/esm/signin/index.d.ts +8 -0
  77. package/dist/esm/signin/index.js +9 -0
  78. package/dist/esm/signin/keys.d.ts +39 -0
  79. package/dist/esm/signin/keys.js +80 -0
  80. package/dist/esm/signin/paths.d.ts +2 -0
  81. package/dist/esm/signin/paths.js +2 -0
  82. package/dist/esm/signin/seal.d.ts +8 -0
  83. package/dist/esm/signin/seal.js +35 -0
  84. package/dist/esm/signin/signin.d.ts +60 -0
  85. package/dist/esm/signin/signin.js +340 -0
  86. package/dist/esm/signin/transport.d.ts +111 -0
  87. package/dist/esm/signin/transport.js +1 -0
  88. package/dist/esm/signin/verify.d.ts +77 -0
  89. package/dist/esm/signin/verify.js +155 -0
  90. package/dist/esm/start/airtable/dispatch.js +3 -3
  91. package/dist/esm/start/airtable/formulas.d.ts +1 -1
  92. package/dist/esm/start/airtable/formulas.js +12 -10
  93. package/dist/esm/start/airtable/index.d.ts +3 -3
  94. package/dist/esm/start/analytics.d.ts +5 -0
  95. package/dist/esm/start/analytics.js +77 -0
  96. package/dist/esm/start/data/index.d.ts +3 -3
  97. package/dist/esm/start/data/index.js +1 -1
  98. package/dist/esm/start/describe.d.ts +8 -1
  99. package/dist/esm/start/describe.js +5 -3
  100. package/dist/esm/start/devApp.d.ts +1 -0
  101. package/dist/esm/start/devApp.js +3 -0
  102. package/dist/esm/start/devSignIn.d.ts +1 -0
  103. package/dist/esm/start/devSignIn.js +3 -0
  104. package/dist/esm/start/direct.d.ts +40 -0
  105. package/dist/esm/start/direct.js +313 -0
  106. package/dist/esm/start/entries.js +4 -0
  107. package/dist/esm/start/factories.test-d.d.ts +2 -1
  108. package/dist/esm/start/fetch.d.ts +1 -0
  109. package/dist/esm/start/fetch.js +4 -0
  110. package/dist/esm/start/host.d.ts +2 -2
  111. package/dist/esm/start/index.d.ts +1 -1
  112. package/dist/esm/start/index.js +4 -2
  113. package/dist/esm/start/instance.js +6 -2
  114. package/dist/esm/start/localSignIn.d.ts +18 -0
  115. package/dist/esm/start/localSignIn.js +73 -0
  116. package/dist/esm/start/outbound.d.ts +12 -3
  117. package/dist/esm/start/outbound.js +135 -23
  118. package/dist/esm/start/pageHead.d.ts +36 -0
  119. package/dist/esm/start/pageHead.js +178 -0
  120. package/dist/esm/start/provider.d.ts +24 -0
  121. package/dist/esm/start/provider.js +150 -0
  122. package/dist/esm/start/router.d.ts +13 -2
  123. package/dist/esm/start/router.js +76 -2
  124. package/dist/esm/start/runLog.d.ts +2 -2
  125. package/dist/esm/start/scope.d.ts +3 -3
  126. package/dist/esm/start/server.d.ts +15 -8
  127. package/dist/esm/start/server.js +175 -43
  128. package/dist/esm/start/telemetry.d.ts +10 -0
  129. package/dist/esm/start/telemetry.js +74 -0
  130. package/dist/esm/start/types.d.ts +118 -3
  131. package/dist/esm/start/uploads.d.ts +2 -0
  132. package/dist/esm/start/uploads.js +52 -0
  133. package/dist/esm/start/version.d.ts +1 -1
  134. package/dist/esm/start/version.js +1 -1
  135. package/dist/esm/start/vite.d.ts +12 -1
  136. package/dist/esm/start/vite.js +119 -7
  137. package/dist/esm/start/workflow.d.ts +6 -2
  138. package/dist/esm/start/workflow.js +9 -2
  139. package/dist/esm/start/workflow.test-d.js +10 -1
  140. package/dist/esm/start/workflowRun.d.ts +5 -0
  141. package/dist/esm/start/workflowRun.js +11 -1
  142. package/dist/esm/start/workspaceSchema.d.ts +1 -0
  143. package/dist/esm/start/workspaceSchema.js +3 -0
  144. package/dist/esm/sync/lib.js +10 -5
  145. package/dist/esm/sync/lib.test.js +10 -0
  146. package/dist/esm/upload/index.js +74 -23
  147. package/dist/esm/upload/index.test.js +35 -2
  148. package/package.json +21 -11
  149. package/dist/cjs/auth-server/index.d.ts +0 -369
  150. package/dist/cjs/auth-server/index.js +0 -119
  151. package/dist/esm/auth-server/index.d.ts +0 -369
  152. package/dist/esm/auth-server/index.js +0 -116
  153. package/dist/esm/start/problems.d.ts +0 -19
  154. package/dist/esm/start/problems.js +0 -8
@@ -0,0 +1,16 @@
1
+ export declare const DEV_ENV_FILE: string;
2
+ type Env = Record<string, string | undefined>;
3
+ export type DevSignInResult = {
4
+ written: true;
5
+ issuer: string;
6
+ clientId: string;
7
+ } | {
8
+ written: false;
9
+ reason: string;
10
+ };
11
+ /**
12
+ * Writes the app's `.zite/dev.env` from its dev token's `appUrl`: issuer `<appUrl>/auth`, client `<app>:dev`. Keeps
13
+ * the secret a previous run wrote, so sessions outlive a restart.
14
+ */
15
+ export declare function writeDevSignIn(appDir: string, shell?: Env): Promise<DevSignInResult>;
16
+ export {};
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEV_ENV_FILE = void 0;
4
+ exports.writeDevSignIn = writeDevSignIn;
5
+ // `zitejs dev`'s share of sign-in under `vite dev` (T5 design §5.9): the app's issuer and dev client, and a secret
6
+ // that seals its session cookie, in `.zite/dev.env`, which `zite()` hands the module.
7
+ const node_crypto_1 = require("node:crypto");
8
+ const node_fs_1 = require("node:fs");
9
+ const node_path_1 = require("node:path");
10
+ const dotenv_1 = require("dotenv");
11
+ const appToken_js_1 = require("../internal/appToken.js");
12
+ const provider_js_1 = require("../start/provider.js");
13
+ exports.DEV_ENV_FILE = (0, node_path_1.join)(".zite", "dev.env");
14
+ const readEnvFile = (path) => {
15
+ try {
16
+ return (0, dotenv_1.parse)((0, node_fs_1.readFileSync)(path, "utf-8"));
17
+ }
18
+ catch {
19
+ return {};
20
+ }
21
+ };
22
+ /** The app's env as `vite dev` reads it: its `.env`, then `.env.local`, over the shell's. */
23
+ const appEnvOf = (appDir, shell) => ({
24
+ ...readEnvFile((0, node_path_1.join)(appDir, ".env")),
25
+ ...readEnvFile((0, node_path_1.join)(appDir, ".env.local")),
26
+ ...shell,
27
+ });
28
+ const appIdOf = (appDir) => {
29
+ try {
30
+ const { id } = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(appDir, "zite.config.json"), "utf-8"));
31
+ return typeof id === "string" && id ? id : undefined;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ };
37
+ // `.zite/` is otherwise committed, generated code; the secret must never be.
38
+ const ignoreDevEnv = (appDir) => {
39
+ const path = (0, node_path_1.join)(appDir, ".zite", ".gitignore");
40
+ const current = (0, node_fs_1.existsSync)(path) ? (0, node_fs_1.readFileSync)(path, "utf-8") : "";
41
+ if (current.split(/\r?\n/).includes("dev.env"))
42
+ return;
43
+ (0, node_fs_1.writeFileSync)(path, `${current}${current && !current.endsWith("\n") ? "\n" : ""}dev.env\n`);
44
+ };
45
+ /**
46
+ * Writes the app's `.zite/dev.env` from its dev token's `appUrl`: issuer `<appUrl>/auth`, client `<app>:dev`. Keeps
47
+ * the secret a previous run wrote, so sessions outlive a restart.
48
+ */
49
+ async function writeDevSignIn(appDir, shell = process.env) {
50
+ const env = appEnvOf(appDir, shell);
51
+ const appId = appIdOf(appDir);
52
+ if (!appId)
53
+ return { written: false, reason: "zite.config.json names no app id" };
54
+ const apiKey = env[provider_js_1.LOCAL_ENV.apiKey];
55
+ const given = env[provider_js_1.LOCAL_ENV.token];
56
+ if (!given && !apiKey)
57
+ return { written: false, reason: `neither ${provider_js_1.LOCAL_ENV.token} nor ${provider_js_1.LOCAL_ENV.apiKey} is set` };
58
+ const token = given ?? (await (0, provider_js_1.mintDevToken)((0, provider_js_1.localUrls)(env[provider_js_1.LOCAL_ENV.urls]).backend, appId, apiKey));
59
+ const appUrl = (0, appToken_js_1.appTokenClaims)(token)?.appUrl;
60
+ if (!appUrl)
61
+ return { written: false, reason: "the app has no live URL yet; publish it once to sign in under vite dev" };
62
+ const issuer = `${new URL(appUrl).origin}/auth`;
63
+ const clientId = `${appId}:dev`;
64
+ const path = (0, node_path_1.join)(appDir, exports.DEV_ENV_FILE);
65
+ const previous = readEnvFile(path).ZITE_AUTH_SECRET;
66
+ const secret = previous && previous.length >= 32 ? previous : (0, node_crypto_1.randomBytes)(32).toString("base64url");
67
+ (0, node_fs_1.mkdirSync)((0, node_path_1.join)(appDir, ".zite"), { recursive: true });
68
+ ignoreDevEnv(appDir);
69
+ (0, node_fs_1.writeFileSync)(path, [
70
+ "# Written by `zitejs dev` for sign-in under `vite dev`. The secret seals your session cookie: never commit it.",
71
+ `ZITE_SIGNIN='${JSON.stringify({ issuer, clientId })}'`,
72
+ `ZITE_AUTH_SECRET=${secret}`,
73
+ "",
74
+ ].join("\n"), { mode: 0o600 });
75
+ return { written: true, issuer, clientId };
76
+ }
@@ -75,8 +75,8 @@ const FIELDS_BY_TYPE = {
75
75
  // one host to call.
76
76
  pipedrive: extras("apiBaseUrl"),
77
77
  // Shopify has no global API host: every call goes to the store's own domain
78
- // under a pinned API version. The storefront pair is the shopper-facing API,
79
- // which installs predating those scopes do not have.
78
+ // under a pinned API version. The storefront pair is the shopper-facing API;
79
+ // its URL comes from the store domain, so only the token can be missing.
80
80
  shopify: extras("shopDomain", "apiBaseUrl", "storefrontApiUrl", "storefrontAccessToken"),
81
81
  sharepoint: extras(),
82
82
  excel: extras(),
@@ -96,7 +96,9 @@ exports.OPTIONAL_CREDENTIAL_FIELDS = {
96
96
  // Only S3-compatible providers set an endpoint, and a prefix is opt-in.
97
97
  amazonS3: ["endpoint", "pathPrefix"],
98
98
  snowflake: ["warehouse"],
99
- shopify: ["storefrontApiUrl", "storefrontAccessToken"],
99
+ // A store that didn't grant the storefront scopes gets no token, and
100
+ // Shopify then serves the Storefront API tokenless.
101
+ shopify: ["storefrontAccessToken"],
100
102
  };
101
103
  /**
102
104
  * Types the runtime never serves: those with a generated client (Airtable, email,
@@ -1,3 +1,14 @@
1
+ /** As Start's `PlatformProvider`: the request's app token, and where the backend and uploads are. */
2
+ type Provider = {
3
+ token(): Promise<string | undefined>;
4
+ urls?: {
5
+ backend: string;
6
+ uploads?: string;
7
+ };
8
+ };
1
9
  export declare const keepRenderedMode: (mode: string | undefined) => void;
2
10
  /** The mode the platform served this request or page in; undefined outside a Start app. */
3
11
  export declare const platformMode: () => string | undefined;
12
+ /** The request's way to the platform on its app token; undefined in the browser and outside a Start request. */
13
+ export declare const platformProvider: () => Provider | undefined;
14
+ export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.platformMode = exports.keepRenderedMode = void 0;
3
+ exports.platformProvider = exports.platformMode = exports.keepRenderedMode = void 0;
4
4
  // Classic's upload client reads this too, so it imports nothing of Start: the
5
5
  // request's host comes through the key src/start/host.ts reads it under.
6
6
  const HOST_STORE_KEY = Symbol.for("zitejs:host-context");
@@ -13,3 +13,6 @@ exports.keepRenderedMode = keepRenderedMode;
13
13
  /** The mode the platform served this request or page in; undefined outside a Start app. */
14
14
  const platformMode = () => globalThis[HOST_STORE_KEY]?.getStore()?.mode ?? globalThis[RENDERED_MODE];
15
15
  exports.platformMode = platformMode;
16
+ /** The request's way to the platform on its app token; undefined in the browser and outside a Start request. */
17
+ const platformProvider = () => globalThis[HOST_STORE_KEY]?.getStore()?.provider;
18
+ exports.platformProvider = platformProvider;
@@ -0,0 +1,17 @@
1
+ /** The claims zitejs reads from its own app token. It never verifies one: the platform does, and zitejs only reads what it was handed. */
2
+ export type AppTokenClaims = {
3
+ /** Seconds since the epoch. */
4
+ exp: number;
5
+ app?: string;
6
+ /** The build it was minted for; a dev token's is the app's newest. */
7
+ build?: number;
8
+ base?: string | null;
9
+ mode?: string;
10
+ /** The org's settings version the token was minted under. */
11
+ ver?: number | null;
12
+ /** Whether the org's plan shows Zite's badge. */
13
+ branding?: boolean;
14
+ appUrl?: string | null;
15
+ };
16
+ /** The token's payload, or undefined for anything that isn't one. */
17
+ export declare const appTokenClaims: (token: string) => AppTokenClaims | undefined;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ // Isomorphic: the upload client reads the app id from it too.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.appTokenClaims = void 0;
5
+ const PREFIX = "zite_app_v1.";
6
+ const decodeSegment = (segment) => {
7
+ const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
8
+ const bytes = Uint8Array.from(atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4)), (c) => c.charCodeAt(0));
9
+ return JSON.parse(new TextDecoder().decode(bytes));
10
+ };
11
+ /** The token's payload, or undefined for anything that isn't one. */
12
+ const appTokenClaims = (token) => {
13
+ if (!token.startsWith(PREFIX))
14
+ return undefined;
15
+ const payload = token.slice(PREFIX.length).split(".")[1];
16
+ if (!payload)
17
+ return undefined;
18
+ try {
19
+ const claims = decodeSegment(payload);
20
+ return claims && typeof claims.exp === "number" ? claims : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ };
26
+ exports.appTokenClaims = appTokenClaims;
@@ -0,0 +1,2 @@
1
+ export declare const isPlatformRequest: (input: unknown) => boolean;
2
+ export declare const platformFetch: (request: Request) => Promise<Response>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.platformFetch = exports.isPlatformRequest = void 0;
4
+ // The platform's own requests on the app token. The outbound fetch passes them through unlogged, so the token never
5
+ // reaches the run log. On globalThis, as that wrapper is, for two copies of zitejs in one bundle.
6
+ const PLATFORM_REQUESTS = Symbol.for("zitejs:platform-requests");
7
+ const isPlatformRequest = (input) => input instanceof Request && (globalThis[PLATFORM_REQUESTS]?.has(input) ?? false);
8
+ exports.isPlatformRequest = isPlatformRequest;
9
+ const platformFetch = (request) => {
10
+ (globalThis[PLATFORM_REQUESTS] ??= new WeakSet()).add(request);
11
+ return fetch(request);
12
+ };
13
+ exports.platformFetch = platformFetch;
@@ -0,0 +1,7 @@
1
+ export type ServiceName = "email" | "pdf" | "uploads" | "steps";
2
+ /** Where a service answers this app on its token: the URL the platform named for it, else the backend's route. */
3
+ export declare const serviceUrl: (urls: {
4
+ backend: string;
5
+ } & Partial<Record<ServiceName, string>>, name: ServiceName) => string;
6
+ /** A Start page's upload session, which the app's own server asks the platform for on its token. */
7
+ export declare const UPLOAD_SESSION_PATH = "/__zite/uploads/session";
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ // Isomorphic, and nothing of Start: classic's upload client reads it too.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.UPLOAD_SESSION_PATH = exports.serviceUrl = void 0;
5
+ // What answered each before the platform named their URLs, which a host from then still relies on.
6
+ const BACKEND_ROUTES = {
7
+ email: "/v1/start/app/email",
8
+ pdf: "/v1/start/app/pdf",
9
+ uploads: "/v1/start/app/uploads/session",
10
+ steps: "/v1/start/app/runs/steps",
11
+ };
12
+ /** Where a service answers this app on its token: the URL the platform named for it, else the backend's route. */
13
+ const serviceUrl = (urls, name) => urls[name] ?? `${urls.backend}${BACKEND_ROUTES[name]}`;
14
+ exports.serviceUrl = serviceUrl;
15
+ /** A Start page's upload session, which the app's own server asks the platform for on its token. */
16
+ exports.UPLOAD_SESSION_PATH = "/__zite/uploads/session";
@@ -48,9 +48,9 @@ export type FilterOperators<V> = FilterCondition<V> | V;
48
48
  * object, the whole `{ equals: … }` is taken as the value, and the filter
49
49
  * fails.
50
50
  *
51
- * One operator per field on this path — `formulas.ts` reads
52
- * `Object.keys(condition)[0]` and drops the rest, unlike the Zite DB filter
53
- * builder which iterates them all.
51
+ * One operator per field on this path — `formulas.ts` reads the first key that
52
+ * is an operator and drops the rest, unlike the Zite DB filter builder which
53
+ * iterates them all.
54
54
  */
55
55
  export type AirtableFilterCondition<V> = FilterCondition<V> & {
56
56
  ilike?: V | V[];
@@ -183,7 +183,7 @@ export declare function createSqlClient(): (params: {
183
183
  query: string;
184
184
  params?: unknown[];
185
185
  }) => Promise<SqlResult>;
186
- /** Must agree with `User` in `zitejs/auth` and `ZiteAuthUser` in `zitejs/auth-server` — the three used to disagree on whether the name fields were nullable or optional. */
186
+ /** Must agree with `User` in `zitejs/auth`; the two used to disagree on whether the name fields were nullable or optional. */
187
187
  export interface AuthUser {
188
188
  id: string;
189
189
  name: string;
@@ -257,7 +257,7 @@ export interface AirtableTableClient<T, TInput = T> {
257
257
  }): Promise<DeleteResult>;
258
258
  }
259
259
  export declare function createAirtableClient<T, TInput = T>(integrationId: string, className: string, implicitParams: Record<string, unknown>): AirtableTableClient<T, TInput>;
260
- /** A block of content in an email body. */
260
+ /** A block of the older `body` format. New emails are written with `html`. */
261
261
  export type EmailBlock = {
262
262
  type: "text";
263
263
  content: string;
@@ -266,11 +266,11 @@ export type EmailBlock = {
266
266
  label: string;
267
267
  href: string;
268
268
  alignment?: "left" | "center" | "right";
269
- /** A hex or `rgb()` color; defaults to the platform's button color. */
269
+ /** Hex colour, e.g. "#7c2d3a". Defaults to the platform blue. */
270
270
  backgroundColor?: string;
271
- /** A hex or `rgb()` color; defaults to white. */
271
+ /** Hex colour. Defaults to white. */
272
272
  textColor?: string;
273
- /** Corner radius in pixels; defaults to 6. */
273
+ /** Corner radius in pixels. Defaults to 6. */
274
274
  borderRadius?: number;
275
275
  } | {
276
276
  type: "image";
@@ -286,25 +286,23 @@ export type EmailBlock = {
286
286
  type: "divider";
287
287
  borderColor?: string;
288
288
  };
289
- export interface SendEmailParams {
289
+ interface SendEmailBaseParams {
290
290
  /** Recipient address(es). Must be valid emails — never placeholders like "me". */
291
291
  to: string | string[];
292
292
  subject: string;
293
- /** Email body as an array of content blocks. */
294
- body: EmailBlock[];
295
293
  cc?: string[];
296
294
  bcc?: string[];
297
295
  replyTo?: string;
298
- /** 'formatted' (default) for styled HTML, 'plain' for text-only. */
299
- layout?: "formatted" | "plain";
300
296
  /**
301
297
  * Text direction of the email. Use 'rtl' for right-to-left languages
302
298
  * (Hebrew, Arabic) — sets dir="rtl" on the email wrapper and right-aligns
303
- * text blocks. HTML like `<div dir="rtl">` inside text blocks is stripped
304
- * by the sanitizer and will NOT work. Defaults to 'ltr'.
299
+ * text. Defaults to 'ltr'.
305
300
  */
306
301
  direction?: "ltr" | "rtl";
307
- /** Custom logo shown above the email content (header area), for branding. */
302
+ /**
303
+ * Logo shown above the email content (header area), for branding. On an
304
+ * html email it replaces the brand kit's logo.
305
+ */
308
306
  logo?: {
309
307
  url: string;
310
308
  width?: number;
@@ -317,9 +315,50 @@ export interface SendEmailParams {
317
315
  contentType?: string;
318
316
  }[];
319
317
  }
318
+ /** An email written as HTML. */
319
+ export interface SendHtmlEmailParams extends SendEmailBaseParams {
320
+ /**
321
+ * Email-safe HTML: tables for layout, inline styles, `<a class="button">`
322
+ * for buttons. Sanitized and its `<style>` rules inlined at send time.
323
+ */
324
+ html: string;
325
+ /** Plain-text part. Generated from `html` when omitted. */
326
+ text?: string;
327
+ /**
328
+ * 'formatted' (default) puts the html in a card under the logo, in the
329
+ * app's brand kit; 'plain' drops the card and logo.
330
+ */
331
+ layout?: "formatted" | "plain";
332
+ /**
333
+ * Hex colour around the card, or behind a plain email's text as a sheet
334
+ * the width of its column. Defaults to the brand kit's.
335
+ */
336
+ background?: string;
337
+ /** Hex colour of the card in a formatted email. Defaults to the brand kit's. */
338
+ cardBackground?: string;
339
+ body?: never;
340
+ }
341
+ /**
342
+ * An email in the older block format. Existing emails keep working; new ones
343
+ * are written with `html`.
344
+ */
345
+ export interface SendBlocksEmailParams extends SendEmailBaseParams {
346
+ /** Email body as an array of content blocks. */
347
+ body: EmailBlock[];
348
+ /**
349
+ * 'formatted' (default) for styled HTML, 'plain' for text-only. HTML like
350
+ * `<div dir="rtl">` inside text blocks is stripped by the sanitizer.
351
+ */
352
+ layout?: "formatted" | "plain";
353
+ html?: never;
354
+ text?: never;
355
+ }
356
+ export type SendEmailParams = SendHtmlEmailParams | SendBlocksEmailParams;
320
357
  export interface SendEmailResult {
321
358
  success: boolean;
322
359
  messageId: string;
360
+ /** Problems that did not stop the send, e.g. an email large enough for Gmail to clip. */
361
+ warnings?: string[];
323
362
  }
324
363
  export interface EmailClient {
325
364
  send(params: SendEmailParams): Promise<SendEmailResult>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ (0, vitest_1.test)("an email is written as html or as blocks, not both", () => {
5
+ (0, vitest_1.expectTypeOf)({
6
+ to: "a@example.com",
7
+ subject: "Hi",
8
+ html: "<p>Hi</p>",
9
+ layout: "plain",
10
+ background: "#e8efe6",
11
+ }).toExtend();
12
+ (0, vitest_1.expectTypeOf)({
13
+ to: "a@example.com",
14
+ subject: "Hi",
15
+ body: [{ type: "text", content: "Hi" }],
16
+ }).toExtend();
17
+ (0, vitest_1.expectTypeOf)({
18
+ to: "a@example.com",
19
+ subject: "Hi",
20
+ html: "<p>Hi</p>",
21
+ body: [],
22
+ }).not.toExtend();
23
+ (0, vitest_1.expectTypeOf)({
24
+ to: "a@example.com",
25
+ subject: "Hi",
26
+ html: "<p>Hi</p>",
27
+ layout: "none",
28
+ }).not.toExtend();
29
+ (0, vitest_1.expectTypeOf)({
30
+ to: "a@example.com",
31
+ subject: "Hi",
32
+ }).not.toExtend();
33
+ });
@@ -0,0 +1,23 @@
1
+ /**
2
+ * What a call on an org's own AI key used, read from the provider's answer as
3
+ * classic's runtime reads it. For analytics only: the org pays the provider.
4
+ * OpenAI and Anthropic; the host meters Zite's own key itself.
5
+ */
6
+ export type AiProvider = "openai" | "anthropic";
7
+ export type AiUsageRecord = {
8
+ provider: AiProvider;
9
+ model?: string;
10
+ inputTokens?: number;
11
+ outputTokens?: number;
12
+ cachedReadInputTokens?: number;
13
+ cacheCreationInputTokens?: number;
14
+ isStreaming?: true;
15
+ };
16
+ export declare const AI_USAGE_HOSTS: Record<string, AiProvider>;
17
+ /** As classic: an OpenAI chat stream reports its usage only when asked to. The body to send instead, if any. */
18
+ export declare const withStreamUsage: (url: URL, method: string, body: unknown) => string | undefined;
19
+ /** The response to hand the app, and its usage once read; a stream is split so the app reads one copy as it arrives. */
20
+ export declare const meterAiResponse: (provider: AiProvider, response: Response) => {
21
+ response: Response;
22
+ usage: Promise<AiUsageRecord | undefined>;
23
+ };
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * What a call on an org's own AI key used, read from the provider's answer as
4
+ * classic's runtime reads it. For analytics only: the org pays the provider.
5
+ * OpenAI and Anthropic; the host meters Zite's own key itself.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.meterAiResponse = exports.withStreamUsage = exports.AI_USAGE_HOSTS = void 0;
9
+ exports.AI_USAGE_HOSTS = {
10
+ "api.openai.com": "openai",
11
+ "api.anthropic.com": "anthropic",
12
+ };
13
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
15
+ /** As classic: an OpenAI chat stream reports its usage only when asked to. The body to send instead, if any. */
16
+ const withStreamUsage = (url, method, body) => {
17
+ if (method !== "POST" || typeof body !== "string" || !url.pathname.endsWith("/chat/completions"))
18
+ return undefined;
19
+ try {
20
+ const json = JSON.parse(body);
21
+ if (!isRecord(json) || json.stream !== true)
22
+ return undefined;
23
+ const options = isRecord(json.stream_options) ? json.stream_options : {};
24
+ if (options.include_usage === true)
25
+ return undefined;
26
+ return JSON.stringify({ ...json, stream_options: { ...options, include_usage: true } });
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ };
32
+ exports.withStreamUsage = withStreamUsage;
33
+ // OpenAI counts cached tokens inside its input; classic takes them apart.
34
+ const tokensFromJson = (provider, body) => {
35
+ const tokens = {};
36
+ if (!isRecord(body))
37
+ return tokens;
38
+ if (provider === "openai") {
39
+ const source = isRecord(body.response) ? body.response : body;
40
+ if (typeof source.model === "string")
41
+ tokens.model = source.model;
42
+ const usage = isRecord(source.usage) ? source.usage : undefined;
43
+ if (!usage)
44
+ return tokens;
45
+ const details = (name) => (isRecord(usage[name]) ? usage[name] : {});
46
+ const cached = details("prompt_tokens_details").cached_tokens ?? details("input_tokens_details").cached_tokens;
47
+ const input = usage.prompt_tokens ?? usage.input_tokens;
48
+ const output = usage.completion_tokens ?? usage.output_tokens;
49
+ if (isNumber(input))
50
+ tokens.inputTokens = input - (isNumber(cached) ? cached : 0);
51
+ if (isNumber(output))
52
+ tokens.outputTokens = output;
53
+ if (isNumber(cached))
54
+ tokens.cachedReadInputTokens = cached;
55
+ return tokens;
56
+ }
57
+ // A stream splits these: message_start has the input, message_delta the running output.
58
+ const message = isRecord(body.message) ? body.message : body;
59
+ if (typeof message.model === "string")
60
+ tokens.model = message.model;
61
+ const usage = isRecord(message.usage) ? message.usage : isRecord(body.usage) ? body.usage : undefined;
62
+ if (!usage)
63
+ return tokens;
64
+ if (isNumber(usage.input_tokens))
65
+ tokens.inputTokens = usage.input_tokens;
66
+ if (isNumber(usage.output_tokens))
67
+ tokens.outputTokens = usage.output_tokens;
68
+ if (isNumber(usage.cache_read_input_tokens))
69
+ tokens.cachedReadInputTokens = usage.cache_read_input_tokens;
70
+ if (isNumber(usage.cache_creation_input_tokens))
71
+ tokens.cacheCreationInputTokens = usage.cache_creation_input_tokens;
72
+ return tokens;
73
+ };
74
+ // Later readings win: Anthropic's output is cumulative, OpenAI's usage comes last.
75
+ const merge = (into, next) => ({
76
+ model: next.model ?? into.model,
77
+ inputTokens: next.inputTokens ?? into.inputTokens,
78
+ outputTokens: next.outputTokens ?? into.outputTokens,
79
+ cachedReadInputTokens: next.cachedReadInputTokens ?? into.cachedReadInputTokens,
80
+ cacheCreationInputTokens: next.cacheCreationInputTokens ?? into.cacheCreationInputTokens,
81
+ });
82
+ const MAX_PENDING_LINE = 1024 * 1024;
83
+ const tokensFromStream = async (provider, stream) => {
84
+ const reader = stream.getReader();
85
+ const decoder = new TextDecoder();
86
+ let pending = "";
87
+ let tokens = {};
88
+ const readLine = (line) => {
89
+ if (!line.startsWith("data:"))
90
+ return;
91
+ const payload = line.slice(5).trim();
92
+ if (!payload || payload === "[DONE]")
93
+ return;
94
+ try {
95
+ tokens = merge(tokens, tokensFromJson(provider, JSON.parse(payload)));
96
+ }
97
+ catch {
98
+ // Not JSON; nothing to count.
99
+ }
100
+ };
101
+ try {
102
+ for (;;) {
103
+ const { done, value } = await reader.read();
104
+ if (done)
105
+ break;
106
+ pending += decoder.decode(value, { stream: true });
107
+ const lines = pending.split("\n");
108
+ pending = lines.pop() ?? "";
109
+ if (pending.length > MAX_PENDING_LINE)
110
+ pending = "";
111
+ lines.forEach(readLine);
112
+ }
113
+ readLine(pending);
114
+ }
115
+ catch {
116
+ // What was read before the stream broke still counts.
117
+ }
118
+ return tokens;
119
+ };
120
+ const counted = (tokens) => tokens.inputTokens !== undefined || tokens.outputTokens !== undefined;
121
+ const usageOf = (provider, tokens, streaming) => counted(tokens)
122
+ ? {
123
+ provider,
124
+ ...Object.fromEntries(Object.entries(tokens).filter(([, value]) => value !== undefined)),
125
+ ...(streaming && { isStreaming: true }),
126
+ }
127
+ : undefined;
128
+ /** The response to hand the app, and its usage once read; a stream is split so the app reads one copy as it arrives. */
129
+ const meterAiResponse = (provider, response) => {
130
+ const type = response.headers.get("content-type") ?? "";
131
+ if (!response.ok || !response.body)
132
+ return { response, usage: Promise.resolve(undefined) };
133
+ if (type.includes("text/event-stream")) {
134
+ const [forApp, forUs] = response.body.tee();
135
+ return {
136
+ response: new Response(forApp, response),
137
+ usage: tokensFromStream(provider, forUs).then((tokens) => usageOf(provider, tokens, true)),
138
+ };
139
+ }
140
+ if (!type.includes("json"))
141
+ return { response, usage: Promise.resolve(undefined) };
142
+ return {
143
+ response,
144
+ usage: response
145
+ .clone()
146
+ .json()
147
+ .then((json) => usageOf(provider, tokensFromJson(provider, json), false))
148
+ .catch(() => undefined),
149
+ };
150
+ };
151
+ exports.meterAiResponse = meterAiResponse;
@@ -0,0 +1 @@
1
+ export declare const devAppId: string | null;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.devAppId = void 0;
4
+ // Null as published. Under `vite dev`, `zite()` replaces this module with the app's id from its zite.config.json: the
5
+ // app the `local` provider mints dev tokens for.
6
+ exports.devAppId = null;
@@ -16,6 +16,8 @@ const APP_START_FILES = ["src/start.ts", "src/start.tsx"];
16
16
  */
17
17
  const renderStartServerEntry = (target = "cloudflare") => target === "cloudflare"
18
18
  ? `// Generated by zitejs for TanStack Start apps. The platform owns this file.
19
+ // First, so an SDK client an app module builds as it loads gets zitejs's fetch.
20
+ import 'zitejs/start/fetch';
19
21
  import handler from '@tanstack/react-start/server-entry';
20
22
  import { createZiteWorker } from 'zitejs/start/worker';
21
23
  import { getRouter } from '../src/router';
@@ -24,6 +26,8 @@ import { startInstance } from './start';
24
26
  export default createZiteWorker({ handler, getRouter, startInstance });
25
27
  `
26
28
  : `// Generated by zitejs for TanStack Start apps. The platform owns this file.
29
+ // First, so an SDK client an app module builds as it loads gets zitejs's fetch.
30
+ import 'zitejs/start/fetch';
27
31
  import handler, { createServerEntry } from '@tanstack/react-start/server-entry';
28
32
  import { createZiteFetch } from 'zitejs/start/server';
29
33
  import { getRouter } from '../src/router';
@@ -0,0 +1,24 @@
1
+ import { type AppTokenClaims } from "../internal/appToken.js";
2
+ import type { HostMode, HostProps, PlatformProvider, PlatformSession, PlatformUrls } from "./types.js";
3
+ export declare const ziteProvider: (props: HostProps, session: () => Promise<PlatformSession | undefined>) => 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 {};