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
@@ -0,0 +1,155 @@
1
+ // The identity token's verifier (T5 design §6.1), the same rules as restly's `identityToken.ts` on the front and the
2
+ // dispatcher. Web Crypto only.
3
+ import { fromBase64Url, isRecord, jsonOf, utf8 } from "./encoding.js";
4
+ import { IDENTITY_KEY_KIND } from "./keys.js";
5
+ /** The `typ` every identity token carries in its header, and nothing else does. */
6
+ export const IDENTITY_TOKEN_TYPE = "zite-id+jwt";
7
+ export const DEFAULT_MAX_LIFETIME_S = 300;
8
+ const CLOCK_SKEW_S = 5;
9
+ const MAX_TOKEN_LENGTH = 8192;
10
+ const MAX_ROLES = 32;
11
+ const MODES = new Set(["live", "preview", "demo", "dev"]);
12
+ const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
13
+ const isText = (value, max) => typeof value === "string" && value.length <= max;
14
+ const isOptionalText = (value, max) => value === undefined || isText(value, max);
15
+ const claimsOf = (payload) => {
16
+ const { iss, sub, aud, azp, iat, exp, sid, nonce, email, name, firstName, lastName, roles, isInternal, mode, ver, preview } = payload;
17
+ if (!isText(email, 320) ||
18
+ !isText(name, 200) ||
19
+ !isOptionalText(firstName, 200) ||
20
+ !isOptionalText(lastName, 200) ||
21
+ !isOptionalText(sid, 255) ||
22
+ !isOptionalText(nonce, 255) ||
23
+ !Array.isArray(roles) ||
24
+ roles.length > MAX_ROLES ||
25
+ !roles.every((role) => isText(role, 128)) ||
26
+ typeof isInternal !== "boolean" ||
27
+ !(ver === null || (isWhole(ver) && ver >= 0))) {
28
+ return undefined;
29
+ }
30
+ return {
31
+ iss: iss,
32
+ sub: sub,
33
+ aud: aud,
34
+ ...(azp !== undefined && { azp: azp }),
35
+ iat: iat,
36
+ exp: exp,
37
+ ...(sid !== undefined && { sid }),
38
+ ...(nonce !== undefined && { nonce }),
39
+ email,
40
+ name,
41
+ ...(firstName !== undefined && { firstName }),
42
+ ...(lastName !== undefined && { lastName }),
43
+ roles: roles,
44
+ isInternal,
45
+ mode: mode,
46
+ ver,
47
+ ...(preview !== undefined && { preview: preview }),
48
+ };
49
+ };
50
+ const previewOk = (preview, mode, pinned) => {
51
+ if (mode !== "preview")
52
+ return preview === undefined;
53
+ return (isRecord(preview) &&
54
+ isWhole(preview.build) &&
55
+ preview.build >= 0 &&
56
+ isText(preview.editor, 128) &&
57
+ preview.editor.length > 0 &&
58
+ (pinned === undefined || preview.build === pinned));
59
+ };
60
+ // Imported once per process; a CryptoKey holds no request's I/O.
61
+ const imported = new Map();
62
+ const publicKey = async (raw) => {
63
+ const held = imported.get(raw);
64
+ if (held)
65
+ return held;
66
+ const bytes = fromBase64Url(raw);
67
+ if (!bytes)
68
+ return undefined;
69
+ try {
70
+ const key = await crypto.subtle.importKey("raw", bytes, { name: "Ed25519" }, false, ["verify"]);
71
+ imported.set(raw, key);
72
+ return key;
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ };
78
+ // Reported once per reason and key id, and only so many: both come from the caller.
79
+ const MAX_REPORTED = 64;
80
+ const reported = new Set();
81
+ const reportOnce = (report) => {
82
+ const key = `${report.reason} ${report.kid ?? ""}`;
83
+ if (reported.has(key) || reported.size >= MAX_REPORTED)
84
+ return;
85
+ reported.add(key);
86
+ console.warn(`[zite] refused an identity token: ${report.reason}${report.kid ? ` (kid ${report.kid})` : ""}`);
87
+ };
88
+ /**
89
+ * Verifies identity tokens against `keys`, in §6.1's order. A `kid` the keys don't know triggers one refetch. Each
90
+ * refusal is reported to `onRefusal`, by default logged once per reason and key id.
91
+ */
92
+ export const createIdentityVerifier = (keys, options = {}) => async (token, expect) => {
93
+ const refuse = (reason, kid) => {
94
+ const safeKid = kid?.slice(0, 64);
95
+ (options.onRefusal ?? reportOnce)({ reason, ...(safeKid !== undefined && { kid: safeKid }) });
96
+ return { status: "refused", reason, ...(safeKid !== undefined && { kid: safeKid }) };
97
+ };
98
+ const parts = token.length <= MAX_TOKEN_LENGTH ? token.split(".") : [];
99
+ if (parts.length !== 3)
100
+ return refuse("malformed");
101
+ const [headerPart, payloadPart, signaturePart] = parts;
102
+ const header = jsonOf(fromBase64Url(headerPart));
103
+ const payload = jsonOf(fromBase64Url(payloadPart));
104
+ const signature = fromBase64Url(signaturePart);
105
+ if (!isRecord(header) || !isRecord(payload) || !signature)
106
+ return refuse("malformed");
107
+ if (header.alg !== "EdDSA")
108
+ return refuse("alg");
109
+ if (header.typ !== IDENTITY_TOKEN_TYPE)
110
+ return refuse("typ");
111
+ const kid = typeof header.kid === "string" ? header.kid : undefined;
112
+ if (kid === undefined)
113
+ return refuse("kid");
114
+ const own = (map) => (map && Object.hasOwn(map, kid) ? map[kid] : undefined);
115
+ const entry = own(keys.current()) ?? own(await keys.refresh());
116
+ if (!entry)
117
+ return refuse("kid", kid);
118
+ if (entry.kind !== IDENTITY_KEY_KIND)
119
+ return refuse("key kind", kid);
120
+ const key = await publicKey(entry.key);
121
+ const genuine = !!key && (await crypto.subtle.verify({ name: "Ed25519" }, key, signature, utf8(`${headerPart}.${payloadPart}`)));
122
+ if (!genuine)
123
+ return refuse("signature", kid);
124
+ if (payload.iss !== expect.issuer)
125
+ return refuse("iss", kid);
126
+ if (typeof payload.aud !== "string" || payload.aud !== expect.clientId)
127
+ return refuse("aud", kid);
128
+ if (payload.azp !== undefined && payload.azp !== payload.aud)
129
+ return refuse("azp", kid);
130
+ const now = Math.floor((expect.now ?? Date.now()) / 1000);
131
+ const { iat, exp } = payload;
132
+ if (!isWhole(iat) || !isWhole(exp))
133
+ return refuse("claims", kid);
134
+ if (iat > now + CLOCK_SKEW_S)
135
+ return refuse("iat", kid);
136
+ if (exp <= iat || exp - iat > (expect.maxLifetimeS ?? DEFAULT_MAX_LIFETIME_S))
137
+ return refuse("lifetime", kid);
138
+ if (!isText(payload.sub, 255) || payload.sub.length === 0)
139
+ return refuse("sub", kid);
140
+ if (typeof payload.mode !== "string" || !MODES.has(payload.mode) || !expect.clientId.endsWith(`:${payload.mode}`)) {
141
+ return refuse("mode", kid);
142
+ }
143
+ const claims = claimsOf(payload);
144
+ if (!claims)
145
+ return refuse("claims", kid);
146
+ if (!previewOk(payload.preview, payload.mode, expect.previewBuild))
147
+ return refuse("preview", kid);
148
+ if (expect.nonce !== undefined && claims.nonce !== expect.nonce)
149
+ return refuse("nonce", kid);
150
+ if (exp <= now - CLOCK_SKEW_S)
151
+ return { status: "expired", claims };
152
+ if (expect.ver !== "any" && claims.ver !== expect.ver)
153
+ return { status: "stale", claims };
154
+ return { status: "valid", claims };
155
+ };
@@ -0,0 +1,2 @@
1
+ import type { BuiltAirtableSettings } from "./settings.js";
2
+ export declare const builtAirtableSettings: Record<string, BuiltAirtableSettings> | null;
@@ -0,0 +1,3 @@
1
+ // Null as published. `zite()` replaces this module, in a server build and under `vite dev`, with the app's Airtable
2
+ // integrations, read from its own and its workspace's zite.config.json and zite.lock.
3
+ export const builtAirtableSettings = null;
@@ -1,8 +1,6 @@
1
1
  import { type AirtableSettings } from "./dispatch.js";
2
- import type { PlatformSession, HostRequestState } from "../types.js";
2
+ import type { HostRequestState, PlatformCallResult } from "../types.js";
3
3
  /** The build's Airtable integration `integrationId`, or undefined when it isn't one. */
4
- export declare const airtableSettingsOf: (session: PlatformSession, integrationId: string) => Promise<AirtableSettings | undefined>;
4
+ export declare const airtableSettingsOf: (integrationId: string) => AirtableSettings | undefined;
5
5
  /** One generated Airtable table call, run here with the connection's token, which the outbound fetch refreshes on a 401. */
6
- export declare function runAirtableCall(host: HostRequestState, session: PlatformSession, integrationId: string, settings: AirtableSettings, methodName: string, params: unknown, access: "signedIn" | "anyone" | "webhook" | "workflow"): Promise<unknown>;
7
- /** For tests: forget what this isolate learned. */
8
- export declare const resetAirtableSettings: () => void;
6
+ export declare function runAirtableCall(host: HostRequestState, connectionOf: () => Promise<PlatformCallResult>, integrationId: string, settings: AirtableSettings, methodName: string, params: unknown): Promise<unknown>;
@@ -1,33 +1,16 @@
1
+ import { builtAirtableSettings } from "./built.js";
1
2
  import { executeAirtableCall } from "./dispatch.js";
2
- import { INTEGRATIONS_PLATFORM_ID } from "../credentials.js";
3
3
  import { ZiteError, isZiteErrorCode } from "../errors.js";
4
4
  import { rememberConnection } from "../outbound.js";
5
5
  const AIRTABLE_API = "https://api.airtable.com";
6
- // A build's integrations don't change, so per isolate: only answers, never a pending call.
7
- const settingsHeld = new Map();
8
6
  /** The build's Airtable integration `integrationId`, or undefined when it isn't one. */
9
- export const airtableSettingsOf = async (session, integrationId) => {
10
- if (settingsHeld.has(integrationId))
11
- return settingsHeld.get(integrationId) ?? undefined;
12
- const answer = await session.integrationSettings(integrationId);
13
- const settings = answer?.serviceType === "airtable" && typeof answer.baseId === "string"
14
- ? { baseId: answer.baseId, nameMappings: answer.nameMappings ?? null }
15
- : null;
16
- settingsHeld.set(integrationId, settings);
17
- return settings ?? undefined;
18
- };
7
+ export const airtableSettingsOf = (integrationId) => builtAirtableSettings && Object.hasOwn(builtAirtableSettings, integrationId) ? builtAirtableSettings[integrationId] : undefined;
19
8
  /** One generated Airtable table call, run here with the connection's token, which the outbound fetch refreshes on a 401. */
20
- export async function runAirtableCall(host, session, integrationId, settings, methodName, params, access) {
9
+ export async function runAirtableCall(host, connectionOf, integrationId, settings, methodName, params) {
21
10
  // As classic: a demo reaches no connected account.
22
11
  if (host.mode === "demo")
23
12
  throw new ZiteError("FORBIDDEN", "This action is not available in demo mode");
24
- const connection = await session.call({
25
- integrationId: INTEGRATIONS_PLATFORM_ID,
26
- className: "Connections",
27
- methodName: "get",
28
- params: { name: integrationId },
29
- access,
30
- });
13
+ const connection = await connectionOf();
31
14
  if ("error" in connection) {
32
15
  const { code, message, userFacingMessage } = connection.error;
33
16
  throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
@@ -48,7 +31,3 @@ export async function runAirtableCall(host, session, integrationId, settings, me
48
31
  }),
49
32
  }, methodName, params);
50
33
  }
51
- /** For tests: forget what this isolate learned. */
52
- export const resetAirtableSettings = () => {
53
- settingsHeld.clear();
54
- };
@@ -0,0 +1,31 @@
1
+ import type { AirtableNameMappings } from "./dispatch.js";
2
+ type ConfigEntry = {
3
+ type?: unknown;
4
+ base?: unknown;
5
+ } & Record<string, unknown>;
6
+ type ConfigFile = {
7
+ integrations?: Record<string, ConfigEntry>;
8
+ integrationSettings?: Record<string, unknown>;
9
+ };
10
+ type LockFile = {
11
+ integrations?: Record<string, {
12
+ idMappings?: unknown;
13
+ } | undefined>;
14
+ };
15
+ /** An Airtable integration as the build declares it, in the platform's shape. */
16
+ export type BuiltAirtableSettings = {
17
+ serviceType: "airtable";
18
+ baseId: string;
19
+ nameMappings: AirtableNameMappings | null;
20
+ };
21
+ export type AirtableSources = {
22
+ appConfig?: ConfigFile;
23
+ appLock?: LockFile;
24
+ workspaceConfig?: ConfigFile;
25
+ workspaceLock?: LockFile;
26
+ /** With zite.schema.json the workspace database is the schema's, and an app's own `databases` entry is dropped. */
27
+ hasSchema: boolean;
28
+ };
29
+ /** Each Airtable integration the build can call, by name, as the platform's `startIntegrationSettings` answers. */
30
+ export declare const airtableSettingsFrom: ({ appConfig, appLock, workspaceConfig, workspaceLock, hasSchema }: AirtableSources) => Record<string, BuiltAirtableSettings>;
31
+ export {};
@@ -0,0 +1,110 @@
1
+ // A build's Airtable integrations, from the repo files the platform derives them from (restly's
2
+ // `getEffectiveAppIntegrations`, through `startIntegrationSettings`): the app's own entries, then the workspace's it
3
+ // has settings for, each read against the app's zite.lock. Keep the two in step.
4
+ import { isCredentialServiceType, NON_CREDENTIAL_SERVICE_TYPES, normalizeIntegrationServiceType } from "../../integrations/rules.js";
5
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
+ const hasOwn = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
7
+ // Airtable base ids look like `appXYZ…`; anything else is a display name, which only the lock resolves.
8
+ const isAirtableBaseId = (value) => /^app[A-Za-z0-9]{14}$/.test(String(value));
9
+ /** An Airtable entry with its base and the lock's mappings; throws on a legacy lock with no base, as the platform does. */
10
+ const convert = (name, base, lock) => {
11
+ const lockData = lock?.integrations?.[name]?.idMappings;
12
+ let baseId = base ?? "";
13
+ const lockIsForBase = (lockBase) => !isAirtableBaseId(baseId) || lockBase === baseId;
14
+ const tables = {};
15
+ const enriched = isRecord(lockData) && Array.isArray(lockData.tables);
16
+ if (enriched && lockIsForBase(lockData.base)) {
17
+ baseId = lockData.base;
18
+ for (const table of lockData.tables) {
19
+ tables[table.id] = {
20
+ mapping: { sdkName: table.sdkName },
21
+ primaryFieldId: table.primaryFieldId,
22
+ fields: Object.fromEntries(table.fields.map((field) => [
23
+ field.id,
24
+ {
25
+ mapping: { sdkName: field.sdkName },
26
+ fieldType: field.type,
27
+ fieldName: field.name,
28
+ ...(field.config ? { fieldOptions: field.config } : {}),
29
+ },
30
+ ])),
31
+ };
32
+ }
33
+ }
34
+ else if (lockData && !enriched) {
35
+ const legacy = lockData;
36
+ if (!legacy.base)
37
+ throw new Error(`Airtable lock missing base ID for integration "${name}"`);
38
+ if (lockIsForBase(legacy.base)) {
39
+ baseId = legacy.base;
40
+ for (const [sdkName, tableId] of Object.entries(legacy.tables ?? {})) {
41
+ tables[tableId] = {
42
+ mapping: { sdkName },
43
+ fields: Object.fromEntries(Object.entries(legacy.fields?.[sdkName] ?? {}).map(([fieldSdkName, fieldId]) => [fieldId, { mapping: { sdkName: fieldSdkName } }])),
44
+ };
45
+ }
46
+ }
47
+ }
48
+ return { baseId, nameMappings: { bases: { [String(baseId)]: { mapping: { sdkName: base }, tables } } } };
49
+ };
50
+ const isAirtable = (entry) => entry?.type === "airtable";
51
+ const isServiceType = (type) => {
52
+ const normalized = typeof type === "string" ? normalizeIntegrationServiceType(type) : undefined;
53
+ return normalized !== undefined && (isCredentialServiceType(normalized) || NON_CREDENTIAL_SERVICE_TYPES.includes(normalized));
54
+ };
55
+ const isOptionalString = (value) => value === undefined || value === null || typeof value === "string";
56
+ /**
57
+ * Whether the platform's conversion of an entry gets past what any type checks (`convertConfigToIntegrationTemplate`
58
+ * throws on an unknown or missing type, a connectionId that isn't a string, and an email sender that isn't one).
59
+ * The platform skips an entry it can't read, whatever its type.
60
+ */
61
+ const platformReads = (entry) => isRecord(entry) &&
62
+ isServiceType(entry.type) &&
63
+ (!entry.connectionId || typeof entry.connectionId === "string") &&
64
+ (normalizeIntegrationServiceType(String(entry.type)) !== "email" || (isOptionalString(entry.fromName) && isOptionalString(entry.fromEmail)));
65
+ /** Each Airtable integration the build can call, by name, as the platform's `startIntegrationSettings` answers. */
66
+ export const airtableSettingsFrom = ({ appConfig, appLock, workspaceConfig, workspaceLock, hasSchema }) => {
67
+ // The app's own entries, each shadowing the workspace's of its name: only those the platform could read.
68
+ const own = {};
69
+ const effective = [];
70
+ for (const [name, entry] of Object.entries(appConfig?.integrations ?? {})) {
71
+ if ((hasSchema && entry?.type === "databases") || !platformReads(entry))
72
+ continue;
73
+ if (isAirtable(entry)) {
74
+ try {
75
+ effective.push([name, convert(name, entry.base, appLock)]);
76
+ }
77
+ catch {
78
+ continue;
79
+ }
80
+ }
81
+ own[name] = entry;
82
+ }
83
+ const settings = isRecord(appConfig?.integrationSettings) ? appConfig.integrationSettings : undefined;
84
+ for (const [name, entry] of Object.entries(workspaceConfig?.integrations ?? {})) {
85
+ // A workspace Airtable is the app's only once the app names it in its settings.
86
+ if (!isAirtable(entry) || !platformReads(entry) || hasOwn(own, name) || !settings || !hasOwn(settings, name))
87
+ continue;
88
+ let workspace;
89
+ try {
90
+ workspace = convert(name, entry.base, workspaceLock);
91
+ }
92
+ catch {
93
+ continue;
94
+ }
95
+ let applied = workspace;
96
+ const appSettings = settings[name];
97
+ if (appSettings) {
98
+ const base = isRecord(appSettings) && hasOwn(appSettings, "base") ? appSettings.base : workspace.baseId;
99
+ try {
100
+ applied = convert(name, base, appLock);
101
+ }
102
+ catch {
103
+ applied = workspace;
104
+ }
105
+ }
106
+ if (applied.baseId)
107
+ effective.push([name, applied]);
108
+ }
109
+ return Object.fromEntries(effective.flatMap(([name, { baseId, nameMappings }]) => typeof baseId === "string" ? [[name, { serviceType: "airtable", baseId, nameMappings }]] : []));
110
+ };
@@ -0,0 +1,5 @@
1
+ import type { HostRequestState } from "./types.js";
2
+ /** A request's body as text, or undefined once it runs past `max` bytes. */
3
+ export declare const textUpTo: (request: Request, max: number) => Promise<string | undefined>;
4
+ /** A beacon from the runtime: a batch of events, or one. Only a live page's reach the platform. */
5
+ export declare const takeAnalytics: (request: Request, host: HostRequestState) => Promise<Response>;
@@ -0,0 +1,77 @@
1
+ // The runtime's page analytics, taken on the app's own origin and handed to the platform's runs service on the
2
+ // request's token. The service checks the events and stamps the org and app from the token, never from the page.
3
+ import { platformFetch } from "../internal/platformFetch.js";
4
+ import { directAccess } from "./direct.js";
5
+ const MAX_ANALYTICS_BYTES = 256 * 1024;
6
+ const RUNS_TIMEOUT_MS = 5_000;
7
+ const accepted = () => Response.json({ accepted: true }, { status: 202 });
8
+ /** A request's body as text, or undefined once it runs past `max` bytes. */
9
+ export const textUpTo = async (request, max) => {
10
+ if (!request.body)
11
+ return "";
12
+ const reader = request.body.getReader();
13
+ const chunks = [];
14
+ let size = 0;
15
+ for (;;) {
16
+ const { done, value } = await reader.read();
17
+ if (done)
18
+ break;
19
+ size += value.byteLength;
20
+ if (size > max) {
21
+ await reader.cancel();
22
+ return undefined;
23
+ }
24
+ chunks.push(value);
25
+ }
26
+ const bytes = new Uint8Array(size);
27
+ let at = 0;
28
+ for (const chunk of chunks) {
29
+ bytes.set(chunk, at);
30
+ at += chunk.byteLength;
31
+ }
32
+ return new TextDecoder().decode(bytes);
33
+ };
34
+ const parsed = (raw) => {
35
+ if (raw === undefined)
36
+ return undefined;
37
+ try {
38
+ return JSON.parse(raw);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ };
44
+ // Workers sets the visitor's country on the request; Node has none.
45
+ const countryOf = (request) => {
46
+ const country = request.headers.get("cf-ipcountry") ?? request.cf?.country;
47
+ return typeof country === "string" ? country : undefined;
48
+ };
49
+ /** A beacon from the runtime: a batch of events, or one. Only a live page's reach the platform. */
50
+ export const takeAnalytics = async (request, host) => {
51
+ if (request.method !== "POST")
52
+ return new Response("Method not allowed", { status: 405 });
53
+ if (host.mode !== "live")
54
+ return accepted();
55
+ const access = await directAccess(host);
56
+ if (!access?.urls.runs)
57
+ return accepted();
58
+ const body = parsed(await textUpTo(request, MAX_ANALYTICS_BYTES));
59
+ if (body === undefined)
60
+ return Response.json({ error: "Invalid analytics payload" }, { status: 400 });
61
+ const events = body && typeof body === "object" && "events" in body ? body.events : [body];
62
+ try {
63
+ const answer = await platformFetch(new Request(`${access.urls.runs}/ingest`, {
64
+ method: "POST",
65
+ headers: { authorization: `Bearer ${access.token}`, "content-type": "application/json" },
66
+ body: JSON.stringify({ kind: "analytics", events, userAgent: request.headers.get("user-agent") ?? "", country: countryOf(request) }),
67
+ signal: AbortSignal.timeout(RUNS_TIMEOUT_MS),
68
+ }));
69
+ if (!answer.ok && answer.status !== 400)
70
+ console.error(`[zite] page analytics not kept: the runs service answered ${answer.status}`);
71
+ return new Response(answer.body, { status: answer.status, headers: { "content-type": "application/json" } });
72
+ }
73
+ catch (error) {
74
+ console.error("[zite] page analytics not kept", error);
75
+ return accepted();
76
+ }
77
+ };
@@ -1,15 +1,27 @@
1
- import type { DataNameMappings } from "./types.js";
2
- import type { HostMode, PlatformSession } from "../types.js";
1
+ import type { BaseTable, DataNameMappings } from "./types.js";
2
+ import { type SchemaNames } from "../../sync/sdkNames.js";
3
+ import type { HostMode } from "../types.js";
3
4
  /** What generated `zite.*` calls go out under. */
4
5
  export declare const DATA_INTEGRATION_ID = "databases";
5
- type Found = {
6
+ /** Sends one base-runner request on the app's token. */
7
+ export type DataTransport = {
8
+ dataFetch(request: {
9
+ method: string;
10
+ path: string;
11
+ body?: string;
12
+ }): Promise<Response>;
13
+ };
14
+ /** The build's base, and the SDK names it was built with. */
15
+ export type DataTarget = {
6
16
  baseId: string | null;
7
- nameMappings: DataNameMappings | null;
17
+ names: SchemaNames | null;
8
18
  };
9
- /** The build's base and SDK names, asked of the platform once per isolate. */
10
- export declare const dataContextOf: (session: PlatformSession) => Promise<Found>;
11
- /** One `zite.*` call, translated here and sent to base-runner through the platform. */
12
- export declare function runDataCall(session: PlatformSession, found: Found, mode: HostMode, methodName: string, sent: unknown): Promise<unknown>;
19
+ /**
20
+ * The build's names for the base's tables as they are now: the ones it was built with, locked, and for anything added
21
+ * since, the name `zitejs generate` would give it. Worked out once per read of the tables.
22
+ */
23
+ export declare const nameMappingsFor: (live: readonly BaseTable[], names: SchemaNames | null) => DataNameMappings;
24
+ /** One `zite.*` call, translated here and sent to base-runner on the app token. */
25
+ export declare function runDataCall(session: DataTransport, target: DataTarget, mode: HostMode, methodName: string, sent: unknown): Promise<unknown>;
13
26
  /** For tests: forget what this isolate learned. */
14
27
  export declare const resetDataDispatch: () => void;
15
- export {};
@@ -1,12 +1,13 @@
1
1
  import { createBaseRunner } from "./baseRunner.js";
2
2
  import { asZiteClientError, executeDatabasesCall } from "./dispatch.js";
3
+ import { nameMappingsOf } from "./names.js";
4
+ import { allocateLiveNames } from "../../sync/sdkNames.js";
3
5
  /** What generated `zite.*` calls go out under. */
4
6
  export const DATA_INTEGRATION_ID = "databases";
5
7
  // Schema changes aren't redeployed, so a new table or field reaches calls within this, as on the host.
6
8
  const TABLES_REUSE_MS = 60_000;
7
- // One build per script, so per isolate: what the platform says the build's base is, and that base's tables.
8
- // Only answers are kept, never a pending call: one request's RPC session mustn't hold up another's.
9
- let context;
9
+ // One build per script, so per isolate: its base's tables. Only answers are kept, never a pending call: one request's
10
+ // I/O mustn't hold up another's.
10
11
  let tables;
11
12
  const tablesOf = async (baseRunner, baseId) => {
12
13
  if (tables?.baseId === baseId && Date.now() - tables.at < TABLES_REUSE_MS)
@@ -15,44 +16,49 @@ const tablesOf = async (baseRunner, baseId) => {
15
16
  tables = { baseId, tables: base.tables, at: Date.now() };
16
17
  return base.tables;
17
18
  };
18
- /** The build's base and SDK names, asked of the platform once per isolate. */
19
- export const dataContextOf = async (session) => {
20
- if (context)
21
- return context;
22
- const answer = await session.dataContext();
23
- context = { baseId: answer.baseId, nameMappings: answer.nameMappings ?? null };
24
- return context;
19
+ const completed = new WeakMap();
20
+ /**
21
+ * The build's names for the base's tables as they are now: the ones it was built with, locked, and for anything added
22
+ * since, the name `zitejs generate` would give it. Worked out once per read of the tables.
23
+ */
24
+ export const nameMappingsFor = (live, names) => {
25
+ const held = completed.get(live);
26
+ if (held?.names === names)
27
+ return held.mappings;
28
+ const mappings = nameMappingsOf(allocateLiveNames(live, names ?? undefined).names);
29
+ completed.set(live, { names, mappings });
30
+ return mappings;
25
31
  };
26
32
  /**
27
33
  * The table id classic's generated client sends: its SDK name mapped through the
28
34
  * build's name mappings, which on classic the client does from the run's config.
29
35
  */
30
36
  const tableIdOf = (nameMappings, sent) => {
31
- for (const [id, table] of Object.entries(nameMappings?.tables ?? {})) {
37
+ for (const [id, table] of Object.entries(nameMappings.tables)) {
32
38
  if (table.mapping?.sdkName === sent)
33
39
  return id;
34
40
  }
35
41
  return sent;
36
42
  };
37
- /** One `zite.*` call, translated here and sent to base-runner through the platform. */
38
- export async function runDataCall(session, found, mode, methodName, sent) {
39
- const params = sent && typeof sent === "object" && typeof sent.tableId === "string"
40
- ? { ...sent, tableId: tableIdOf(found.nameMappings, sent.tableId) }
41
- : sent;
42
- if (!found.baseId)
43
+ /** One `zite.*` call, translated here and sent to base-runner on the app token. */
44
+ export async function runDataCall(session, target, mode, methodName, sent) {
45
+ if (!target.baseId)
43
46
  throw asZiteClientError(Object.assign(new Error("This app has no database"), { statusCode: 404 }));
44
47
  const baseRunner = createBaseRunner((request) => session.dataFetch(request));
45
48
  let baseTables;
46
49
  try {
47
- baseTables = await tablesOf(baseRunner, found.baseId);
50
+ baseTables = await tablesOf(baseRunner, target.baseId);
48
51
  }
49
52
  catch (error) {
50
53
  throw asZiteClientError(error);
51
54
  }
52
- return executeDatabasesCall({ baseRunner, baseId: found.baseId, nameMappings: found.nameMappings, tables: baseTables, readOnly: mode === "demo" }, methodName, params);
55
+ const nameMappings = nameMappingsFor(baseTables, target.names);
56
+ const params = sent && typeof sent === "object" && typeof sent.tableId === "string"
57
+ ? { ...sent, tableId: tableIdOf(nameMappings, sent.tableId) }
58
+ : sent;
59
+ return executeDatabasesCall({ baseRunner, baseId: target.baseId, nameMappings, tables: baseTables, readOnly: mode === "demo" }, methodName, params);
53
60
  }
54
61
  /** For tests: forget what this isolate learned. */
55
62
  export const resetDataDispatch = () => {
56
- context = undefined;
57
63
  tables = undefined;
58
64
  };
@@ -0,0 +1,7 @@
1
+ import { type SchemaNames } from "../../sync/sdkNames.js";
2
+ import type { DataNameMappings } from "./types.js";
3
+ /**
4
+ * Names as the platform's `nameMappings` keep them: each table under the class name its generated client sends
5
+ * (`createTableClient('Orders')`), each field under its own.
6
+ */
7
+ export declare const nameMappingsOf: (names: SchemaNames) => DataNameMappings;
@@ -0,0 +1,15 @@
1
+ import { toPascalCase } from "../../sync/sdkNames.js";
2
+ /**
3
+ * Names as the platform's `nameMappings` keep them: each table under the class name its generated client sends
4
+ * (`createTableClient('Orders')`), each field under its own.
5
+ */
6
+ export const nameMappingsOf = (names) => ({
7
+ mapping: { sdkName: "Database" },
8
+ tables: Object.fromEntries(names.tables.map((table) => [
9
+ table.id,
10
+ {
11
+ mapping: { sdkName: toPascalCase(table.sdkName) },
12
+ fields: Object.fromEntries(table.fields.map((field) => [field.id, { mapping: { sdkName: field.sdkName } }])),
13
+ },
14
+ ])),
15
+ });
@@ -56,8 +56,11 @@ export interface DatabaseRecord {
56
56
  id: string;
57
57
  [key: string]: unknown;
58
58
  }
59
- /** The build's tables' and fields' SDK names, by id (`projectConfig.nameMappings`). */
59
+ /** The build's tables' and fields' SDK names, by id, as `projectConfig.nameMappings` keeps them. */
60
60
  export type DataNameMappings = {
61
+ mapping?: {
62
+ sdkName: string;
63
+ };
61
64
  tables: Record<string, {
62
65
  mapping: {
63
66
  sdkName: string;
@@ -0,0 +1 @@
1
+ export declare const devAppId: string | null;
@@ -0,0 +1,3 @@
1
+ // Null as published. Under `vite dev`, `zite()` replaces this module with the app's id from its zite.config.json: the
2
+ // app the `local` provider mints dev tokens for.
3
+ export const devAppId = null;
@@ -0,0 +1 @@
1
+ export declare const devSignIn: Readonly<Record<string, string>> | null;
@@ -0,0 +1,3 @@
1
+ // Null as published. Under `vite dev`, `zite()` replaces this module in the server environment with what `zitejs dev`
2
+ // wrote to the app's `.zite/dev.env`: Cloudflare's plugin only reads the app's own `.env` into workerd.
3
+ export const devSignIn = null;