zitejs 0.10.0-start.2 → 0.10.0-start.20

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 (171) hide show
  1. package/dist/cjs/auth/index.d.ts +2 -2
  2. package/dist/cjs/auth/index.js +6 -0
  3. package/dist/cjs/auth/index.test.js +30 -0
  4. package/dist/cjs/auth/previewClaim.d.ts +7 -0
  5. package/dist/cjs/auth/previewClaim.js +16 -0
  6. package/dist/cjs/backend/index.d.ts +121 -3
  7. package/dist/cjs/backend/index.test.js +58 -0
  8. package/dist/cjs/bundle/index.d.ts +8 -0
  9. package/dist/cjs/bundle/index.js +9 -8
  10. package/dist/cjs/check/index.d.ts +45 -1
  11. package/dist/cjs/check/index.js +198 -109
  12. package/dist/cjs/check/start/problem.d.ts +11 -0
  13. package/dist/cjs/check/start/problem.js +5 -0
  14. package/dist/cjs/check/start/routeTree.d.ts +9 -0
  15. package/dist/cjs/check/start/routeTree.js +111 -0
  16. package/dist/cjs/check/start/sourceRules.d.ts +8 -0
  17. package/dist/cjs/check/start/sourceRules.js +1110 -0
  18. package/dist/cjs/check/start/tsgo.d.ts +2 -0
  19. package/dist/cjs/check/start/tsgo.js +35 -0
  20. package/dist/cjs/cli.js +1 -1
  21. package/dist/cjs/client/index.d.ts +24 -0
  22. package/dist/cjs/dev/index.js +14 -4
  23. package/dist/cjs/integrations/rules.d.ts +13 -0
  24. package/dist/cjs/integrations/rules.js +29 -0
  25. package/dist/cjs/integrations/rules.test.js +1 -0
  26. package/dist/cjs/internal/appMode.d.ts +3 -0
  27. package/dist/cjs/internal/appMode.js +15 -0
  28. package/dist/cjs/runtime/index.d.ts +13 -13
  29. package/dist/cjs/start/entries.d.ts +10 -4
  30. package/dist/cjs/start/entries.js +23 -6
  31. package/dist/cjs/steps/index.d.ts +78 -0
  32. package/dist/cjs/steps/index.js +507 -0
  33. package/dist/cjs/steps/index.test.d.ts +1 -0
  34. package/dist/cjs/steps/index.test.js +635 -0
  35. package/dist/cjs/sync/index.js +2 -1
  36. package/dist/cjs/sync/lib.d.ts +10 -3
  37. package/dist/cjs/sync/lib.js +35 -21
  38. package/dist/cjs/sync/lib.test.js +106 -36
  39. package/dist/cjs/types/fields.d.ts +8 -1
  40. package/dist/cjs/types/fields.js +7 -1
  41. package/dist/cjs/types/tables.d.ts +16 -0
  42. package/dist/cjs/upload/index.js +12 -2
  43. package/dist/cjs/upload/index.test.js +39 -0
  44. package/dist/cjs/vite/index.js +8 -3
  45. package/dist/cjs/vite/index.test.js +10 -2
  46. package/dist/esm/auth/index.d.ts +2 -2
  47. package/dist/esm/auth/index.js +6 -0
  48. package/dist/esm/auth/index.test.js +30 -0
  49. package/dist/esm/auth/previewClaim.d.ts +7 -0
  50. package/dist/esm/auth/previewClaim.js +12 -0
  51. package/dist/esm/backend/index.d.ts +121 -3
  52. package/dist/esm/backend/index.test.js +58 -0
  53. package/dist/esm/bundle/index.d.ts +8 -0
  54. package/dist/esm/bundle/index.js +8 -8
  55. package/dist/esm/check/index.d.ts +45 -1
  56. package/dist/esm/check/index.js +198 -113
  57. package/dist/esm/check/start/problem.d.ts +11 -0
  58. package/dist/esm/check/start/problem.js +1 -0
  59. package/dist/esm/check/start/routeTree.d.ts +9 -0
  60. package/dist/esm/check/start/routeTree.js +70 -0
  61. package/dist/esm/check/start/sourceRules.d.ts +8 -0
  62. package/dist/esm/check/start/sourceRules.js +1107 -0
  63. package/dist/esm/check/start/tsgo.d.ts +2 -0
  64. package/dist/esm/check/start/tsgo.js +29 -0
  65. package/dist/esm/cli.js +1 -1
  66. package/dist/esm/client/index.d.ts +24 -0
  67. package/dist/esm/dev/index.js +16 -6
  68. package/dist/esm/integrations/rules.d.ts +13 -0
  69. package/dist/esm/integrations/rules.js +29 -0
  70. package/dist/esm/integrations/rules.test.js +1 -0
  71. package/dist/esm/internal/appMode.d.ts +3 -0
  72. package/dist/esm/internal/appMode.js +10 -0
  73. package/dist/esm/runtime/index.d.ts +13 -13
  74. package/dist/esm/start/aiUsage.d.ts +23 -0
  75. package/dist/esm/start/aiUsage.js +146 -0
  76. package/dist/esm/start/airtable/arrayFields.d.ts +10 -0
  77. package/dist/esm/start/airtable/arrayFields.js +30 -0
  78. package/dist/esm/start/airtable/dispatch.d.ts +54 -0
  79. package/dist/esm/start/airtable/dispatch.js +483 -0
  80. package/dist/esm/start/airtable/formulas.d.ts +70 -0
  81. package/dist/esm/start/airtable/formulas.js +258 -0
  82. package/dist/esm/start/airtable/index.d.ts +8 -0
  83. package/dist/esm/start/airtable/index.js +54 -0
  84. package/dist/esm/start/authHooks.d.ts +7 -0
  85. package/dist/esm/start/authHooks.js +10 -0
  86. package/dist/esm/start/authHooksModule.d.ts +1 -0
  87. package/dist/esm/start/authHooksModule.js +3 -0
  88. package/dist/esm/start/clientErrorMessage.test.d.ts +1 -0
  89. package/dist/esm/start/clientErrorMessage.test.js +105 -0
  90. package/dist/esm/start/credentials.d.ts +2 -0
  91. package/dist/esm/start/credentials.js +2 -0
  92. package/dist/esm/start/data/baseRunner.d.ts +92 -0
  93. package/dist/esm/start/data/baseRunner.js +83 -0
  94. package/dist/esm/start/data/dispatch.d.ts +16 -0
  95. package/dist/esm/start/data/dispatch.js +198 -0
  96. package/dist/esm/start/data/index.d.ts +15 -0
  97. package/dist/esm/start/data/index.js +58 -0
  98. package/dist/esm/start/data/sqlNameMappings.d.ts +58 -0
  99. package/dist/esm/start/data/sqlNameMappings.js +92 -0
  100. package/dist/esm/start/data/transformations.d.ts +97 -0
  101. package/dist/esm/start/data/transformations.js +262 -0
  102. package/dist/esm/start/data/types.d.ts +91 -0
  103. package/dist/esm/start/data/types.js +14 -0
  104. package/dist/esm/start/describe.d.ts +35 -5
  105. package/dist/esm/start/describe.js +74 -22
  106. package/dist/esm/start/entries.d.ts +10 -4
  107. package/dist/esm/start/entries.js +21 -5
  108. package/dist/esm/start/errors.d.ts +63 -0
  109. package/dist/esm/start/errors.js +146 -0
  110. package/dist/esm/start/errors.test.d.ts +1 -0
  111. package/dist/esm/start/errors.test.js +23 -0
  112. package/dist/esm/start/factories.test-d.d.ts +1 -0
  113. package/dist/esm/start/factories.test-d.js +20 -0
  114. package/dist/esm/start/index.d.ts +32 -27
  115. package/dist/esm/start/index.js +77 -47
  116. package/dist/esm/start/instance.d.ts +4 -4
  117. package/dist/esm/start/instance.js +54 -11
  118. package/dist/esm/start/outbound.d.ts +11 -0
  119. package/dist/esm/start/outbound.js +398 -0
  120. package/dist/esm/start/previewClaim.d.ts +7 -0
  121. package/dist/esm/start/previewClaim.js +23 -0
  122. package/dist/esm/start/problems.js +1 -1
  123. package/dist/esm/start/quiet.d.ts +2 -0
  124. package/dist/esm/start/quiet.js +27 -0
  125. package/dist/esm/start/redactSecrets.d.ts +15 -0
  126. package/dist/esm/start/redactSecrets.js +154 -0
  127. package/dist/esm/start/redactSecrets.test.d.ts +1 -0
  128. package/dist/esm/start/redactSecrets.test.js +151 -0
  129. package/dist/esm/start/registration.d.ts +13 -0
  130. package/dist/esm/start/registration.js +21 -0
  131. package/dist/esm/start/registrationHash.d.ts +22 -0
  132. package/dist/esm/start/registrationHash.js +470 -0
  133. package/dist/esm/start/router.d.ts +18 -4
  134. package/dist/esm/start/router.js +134 -11
  135. package/dist/esm/start/runLog.d.ts +7 -4
  136. package/dist/esm/start/runLog.js +64 -6
  137. package/dist/esm/start/scope.d.ts +2 -2
  138. package/dist/esm/start/server.d.ts +40 -36
  139. package/dist/esm/start/server.js +320 -48
  140. package/dist/esm/start/steps.d.ts +28 -0
  141. package/dist/esm/start/steps.js +97 -0
  142. package/dist/esm/start/types.d.ts +178 -5
  143. package/dist/esm/start/version.d.ts +1 -0
  144. package/dist/esm/start/version.js +2 -0
  145. package/dist/esm/start/vite.js +88 -11
  146. package/dist/esm/start/worker.d.ts +6 -0
  147. package/dist/esm/start/worker.js +12 -0
  148. package/dist/esm/start/workflow.d.ts +42 -12
  149. package/dist/esm/start/workflow.js +3 -3
  150. package/dist/esm/start/workflow.test-d.js +41 -8
  151. package/dist/esm/start/workflowModules.js +1 -1
  152. package/dist/esm/start/workflowRun.d.ts +21 -8
  153. package/dist/esm/start/workflowRun.js +29 -8
  154. package/dist/esm/steps/index.d.ts +78 -0
  155. package/dist/esm/steps/index.js +502 -0
  156. package/dist/esm/steps/index.test.d.ts +1 -0
  157. package/dist/esm/steps/index.test.js +633 -0
  158. package/dist/esm/sync/index.js +2 -1
  159. package/dist/esm/sync/lib.d.ts +10 -3
  160. package/dist/esm/sync/lib.js +35 -21
  161. package/dist/esm/sync/lib.test.js +106 -36
  162. package/dist/esm/types/fields.d.ts +8 -1
  163. package/dist/esm/types/fields.js +6 -0
  164. package/dist/esm/types/tables.d.ts +16 -0
  165. package/dist/esm/upload/index.js +12 -2
  166. package/dist/esm/upload/index.test.js +39 -0
  167. package/dist/esm/vite/index.js +8 -3
  168. package/dist/esm/vite/index.test.js +10 -2
  169. package/package.json +37 -16
  170. package/dist/cjs/start/problems.d.ts +0 -19
  171. package/dist/cjs/start/problems.js +0 -11
@@ -0,0 +1,258 @@
1
+ import { z } from 'zod';
2
+ import { airtableEqualsFormula } from './arrayFields.js';
3
+ // =============================================================================
4
+ // Condition Operators
5
+ // =============================================================================
6
+ /**
7
+ * Supported filter operators for Airtable queries
8
+ */
9
+ export const WhereConditionOperators = z.enum([
10
+ 'contains',
11
+ 'not',
12
+ 'in',
13
+ 'notIn',
14
+ 'lt',
15
+ 'lte',
16
+ 'gt',
17
+ 'gte',
18
+ 'ilike',
19
+ ]);
20
+ const WHERE_CONDITION_OPERATORS = WhereConditionOperators.options;
21
+ /**
22
+ * Check if a key is a condition operator
23
+ */
24
+ export const isConditionOperator = (key) => WHERE_CONDITION_OPERATORS.includes(key);
25
+ /**
26
+ * Check if a value is a nested condition object (e.g., { contains: 'value' })
27
+ */
28
+ export const isNestedCondition = (value) => {
29
+ if (value === null || typeof value !== 'object')
30
+ return false;
31
+ if (Array.isArray(value))
32
+ return false;
33
+ // Check if any keys are condition operators
34
+ return Object.keys(value).some(key => isConditionOperator(key));
35
+ };
36
+ // =============================================================================
37
+ // Formula Helpers
38
+ // =============================================================================
39
+ /** Regex to validate Airtable record IDs */
40
+ const AIRTABLE_RECORD_ID_REGEX = /^rec[a-zA-Z0-9]{14}$/;
41
+ /** SDK field name for record ID */
42
+ const SDK_ID_FIELD = 'id';
43
+ /**
44
+ * Check if a string is a valid Airtable record ID
45
+ */
46
+ export const isValidRecordId = (value) => {
47
+ return !!value.match(AIRTABLE_RECORD_ID_REGEX);
48
+ };
49
+ /**
50
+ * Escape a string value for an Airtable formula. Backslashes go first: a
51
+ * caller's trailing backslash would otherwise escape the closing quote and let
52
+ * the rest of the value into the formula.
53
+ */
54
+ const escapeFormulaString = (value) => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
55
+ // Record ids go into the formula unquoted, so only well-formed ones may: any
56
+ // other value matches no record anyway.
57
+ export const isRecordId = (value) => typeof value === 'string' && isValidRecordId(value);
58
+ const anyRecordIdOf = (recordIds) => recordIds.length
59
+ ? `OR(${recordIds.map(id => `RECORD_ID() = '${id}'`).join(', ')})`
60
+ : 'FALSE()';
61
+ /**
62
+ * Format a value for use in Airtable formulas
63
+ */
64
+ // A lookup's value, or a linked record's id or primary value, comes as a one-item list.
65
+ const singleValue = (value) => Array.isArray(value) && value.length === 1 ? value[0] : value;
66
+ const getAirtableFilterValue = (given) => {
67
+ const value = singleValue(given);
68
+ if (value instanceof Date) {
69
+ if (!Number.isFinite(value.getTime())) {
70
+ throw new Error('Invalid Date passed to Airtable filter formula. Use a valid Date or ISO date string.');
71
+ }
72
+ return `"${value.toISOString()}"`;
73
+ }
74
+ if (typeof value === 'string') {
75
+ return `"${escapeFormulaString(value)}"`;
76
+ }
77
+ if (typeof value === 'boolean') {
78
+ return value ? 'TRUE()' : 'FALSE()';
79
+ }
80
+ if (value === undefined || value === null) {
81
+ return 'BLANK()';
82
+ }
83
+ if ((typeof value === 'number' && Number.isFinite(value)) || typeof value === 'bigint') {
84
+ return String(value);
85
+ }
86
+ // Anything else would be pasted into the formula as is.
87
+ const what = Array.isArray(value)
88
+ ? 'a list'
89
+ : typeof value === 'number'
90
+ ? "a number that isn't finite"
91
+ : typeof value;
92
+ throw new Error(`Can't filter an Airtable field by ${what} here: pass a string, number, boolean, date or null.`);
93
+ };
94
+ /**
95
+ * Convert filters to Airtable filterByFormula string.
96
+ *
97
+ * Supports operators: contains, not, in, notIn, lt, lte, gt, gte, ilike
98
+ *
99
+ * @example
100
+ * // Equality
101
+ * { name: 'John' } -> {Name}="John"
102
+ *
103
+ * @example
104
+ * // Contains
105
+ * { name: { contains: 'john' } } -> SEARCH("john", {Name}) != ""
106
+ *
107
+ * @example
108
+ * // Multiple conditions
109
+ * { status: 'active', age: { gte: 18 } } -> AND({Status}="active", {Age}>=18)
110
+ */
111
+ export const filtersToFormula = async ({ filters, tableSchema, getPrimaryFieldForRecord, }) => {
112
+ if (!filters || Object.keys(filters).length === 0)
113
+ return undefined;
114
+ const conditions = [];
115
+ for (const [field, condition] of Object.entries(filters)) {
116
+ let value = condition;
117
+ let operator = 'equals';
118
+ if (isNestedCondition(condition)) {
119
+ operator = Object.keys(condition).find(isConditionOperator);
120
+ value = condition[operator];
121
+ }
122
+ // Special case for id field - use RECORD_ID()
123
+ if (field === SDK_ID_FIELD || field === 'id') {
124
+ const recordIds = (Array.isArray(value) ? value : [value]).map(singleValue);
125
+ if (operator === 'equals') {
126
+ const [recordId] = recordIds;
127
+ conditions.push(isRecordId(recordId) ? `RECORD_ID() = '${recordId}'` : 'FALSE()');
128
+ }
129
+ else {
130
+ const recordIdClause = anyRecordIdOf(recordIds.filter(isRecordId));
131
+ if (operator === 'notIn' || operator === 'not') {
132
+ conditions.push(`NOT(${recordIdClause})`);
133
+ continue;
134
+ }
135
+ conditions.push(recordIdClause);
136
+ }
137
+ continue;
138
+ }
139
+ // Find the actual field in the schema
140
+ const fieldInfo = tableSchema?.fields.find(f => f.id === field || f.name === field);
141
+ // Skip undefined conditions
142
+ if (condition === undefined)
143
+ continue;
144
+ // Use field name from schema if available, otherwise use the key as-is,
145
+ // which then can't close the braces it's pasted between.
146
+ if (!fieldInfo && /[{}]/.test(field)) {
147
+ throw new Error(`Can't filter by "${field}": an Airtable field name can't contain { or }.`);
148
+ }
149
+ const fieldName = `{${fieldInfo?.name || field}}`;
150
+ // Pre-process linked record values
151
+ if (fieldInfo?.type === 'multipleRecordLinks' && getPrimaryFieldForRecord) {
152
+ const linkedRecordOptions = fieldInfo.options;
153
+ let linkedRecords = [];
154
+ if (value !== undefined) {
155
+ if (!Array.isArray(value)) {
156
+ if (value !== '') {
157
+ linkedRecords = [String(value)];
158
+ }
159
+ }
160
+ else {
161
+ linkedRecords = value;
162
+ }
163
+ }
164
+ // Resolve record IDs to primary field values
165
+ if (linkedRecordOptions?.linkedTableId) {
166
+ value = (await Promise.all(linkedRecords.map(async (recordValue) => {
167
+ if (isValidRecordId(recordValue)) {
168
+ const primaryColumn = await getPrimaryFieldForRecord(linkedRecordOptions.linkedTableId, recordValue);
169
+ if (primaryColumn) {
170
+ return primaryColumn;
171
+ }
172
+ }
173
+ return recordValue;
174
+ }))).flat();
175
+ }
176
+ }
177
+ // Handle checkbox fields with string values
178
+ if (fieldInfo?.type === 'checkbox' &&
179
+ (operator === 'equals' || operator === 'not') &&
180
+ typeof value === 'string') {
181
+ const TRUE_VALUES = ['true', 'yes', 'y', 'TRUE'];
182
+ value = TRUE_VALUES.includes(value.toLowerCase()) ? true : false;
183
+ }
184
+ // Skip undefined values
185
+ if (value === undefined)
186
+ continue;
187
+ const textFieldRef = `ARRAYJOIN(${fieldName})`;
188
+ const equalsClause = (v) => fieldInfo
189
+ ? airtableEqualsFormula({
190
+ field: fieldInfo,
191
+ fieldName,
192
+ value: getAirtableFilterValue(v),
193
+ })
194
+ : `${fieldName}=${getAirtableFilterValue(v)}`;
195
+ // Build condition based on operator
196
+ switch (operator) {
197
+ case 'equals':
198
+ if (Array.isArray(value)) {
199
+ const andClauses = value.map(equalsClause);
200
+ conditions.push(`AND(${andClauses.join(',')})`);
201
+ }
202
+ else {
203
+ conditions.push(equalsClause(value));
204
+ }
205
+ break;
206
+ case 'contains':
207
+ if (Array.isArray(value)) {
208
+ const andClauses = value.map(v => `SEARCH(${getAirtableFilterValue(v)}, ${textFieldRef}) != ""`);
209
+ conditions.push(`AND(${andClauses.join(',')})`);
210
+ }
211
+ else {
212
+ conditions.push(`SEARCH(${getAirtableFilterValue(value)}, ${textFieldRef}) != ""`);
213
+ }
214
+ break;
215
+ case 'not':
216
+ if (Array.isArray(value) && value.length === 0) {
217
+ break;
218
+ }
219
+ conditions.push(`NOT(${Array.isArray(value)
220
+ ? `OR(${value.map(equalsClause).join(',')})`
221
+ : equalsClause(value)})`);
222
+ break;
223
+ // One value stands for a list of it, as on the id path: skipping it would match every record.
224
+ case 'in': {
225
+ const orClauses = (Array.isArray(value) ? value : [value]).map(equalsClause);
226
+ conditions.push(`OR(${orClauses.join(',')})`);
227
+ break;
228
+ }
229
+ case 'notIn': {
230
+ const orClauses = (Array.isArray(value) ? value : [value]).map(equalsClause);
231
+ if (orClauses.length > 0) {
232
+ conditions.push(`NOT(OR(${orClauses.join(',')}))`);
233
+ }
234
+ break;
235
+ }
236
+ case 'lt':
237
+ conditions.push(`${fieldName}<${getAirtableFilterValue(value)}`);
238
+ break;
239
+ case 'lte':
240
+ conditions.push(`${fieldName}<=${getAirtableFilterValue(value)}`);
241
+ break;
242
+ case 'gt':
243
+ conditions.push(`${fieldName}>${getAirtableFilterValue(value)}`);
244
+ break;
245
+ case 'gte':
246
+ conditions.push(`${fieldName}>=${getAirtableFilterValue(value)}`);
247
+ break;
248
+ case 'ilike':
249
+ conditions.push(`LOWER(${textFieldRef}) = LOWER(${getAirtableFilterValue(value)})`);
250
+ break;
251
+ }
252
+ }
253
+ if (conditions.length === 0)
254
+ return undefined;
255
+ if (conditions.length === 1)
256
+ return conditions[0];
257
+ return `AND(${conditions.join(',')})`;
258
+ };
@@ -0,0 +1,8 @@
1
+ import { type AirtableSettings } from "./dispatch.js";
2
+ import type { PlatformSession, ZiteRequestContext } from "../types.js";
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>;
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: ZiteRequestContext, 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;
@@ -0,0 +1,54 @@
1
+ import { executeAirtableCall } from "./dispatch.js";
2
+ import { INTEGRATIONS_PLATFORM_ID } from "../credentials.js";
3
+ import { ZiteError, isZiteErrorCode } from "../errors.js";
4
+ import { rememberConnection } from "../outbound.js";
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
+ /** 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
+ };
19
+ /** 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) {
21
+ // As classic: a demo reaches no connected account.
22
+ if (host.mode === "demo")
23
+ 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
+ });
31
+ if ("error" in connection) {
32
+ const { code, message, userFacingMessage } = connection.error;
33
+ throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
34
+ }
35
+ const token = connection.value?.accessToken;
36
+ if (typeof token !== "string") {
37
+ throw new ZiteError("INTERNAL_ERROR", `The ${integrationId} connection has no token`);
38
+ }
39
+ rememberConnection(host, integrationId, connection.value);
40
+ host.airtableReads ??= new Map();
41
+ return executeAirtableCall({
42
+ settings,
43
+ reads: host.airtableReads,
44
+ fetch: (path, init) => fetch(`${AIRTABLE_API}${path}`, {
45
+ method: init.method,
46
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
47
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
48
+ }),
49
+ }, methodName, params);
50
+ }
51
+ /** For tests: forget what this isolate learned. */
52
+ export const resetAirtableSettings = () => {
53
+ settingsHeld.clear();
54
+ };
@@ -0,0 +1,7 @@
1
+ export declare const AUTH_HOOK_NAMES: readonly ["beforeSignUp", "beforeSignIn", "afterSignUp", "afterSignIn", "verifySession"];
2
+ export type AuthHookName = (typeof AUTH_HOOK_NAMES)[number];
3
+ type AuthHook = (input: unknown) => unknown;
4
+ export declare const isAuthHookName: (name: string) => name is AuthHookName;
5
+ /** The hooks the app's `zite.auth.ts` defines, by name. */
6
+ export declare function loadAuthHooks(): Promise<Partial<Record<AuthHookName, AuthHook>>>;
7
+ export {};
@@ -0,0 +1,10 @@
1
+ import { authHooksModule } from "./authHooksModule.js";
2
+ export const AUTH_HOOK_NAMES = ["beforeSignUp", "beforeSignIn", "afterSignUp", "afterSignIn", "verifySession"];
3
+ export const isAuthHookName = (name) => AUTH_HOOK_NAMES.includes(name);
4
+ /** The hooks the app's `zite.auth.ts` defines, by name. */
5
+ export async function loadAuthHooks() {
6
+ if (!authHooksModule)
7
+ return {};
8
+ const hooks = (await authHooksModule()).default?.hooks ?? {};
9
+ return Object.fromEntries(AUTH_HOOK_NAMES.flatMap((name) => (typeof hooks[name] === "function" ? [[name, hooks[name]]] : [])));
10
+ }
@@ -0,0 +1 @@
1
+ export declare const authHooksModule: (() => Promise<Record<string, unknown>>) | null;
@@ -0,0 +1,3 @@
1
+ // Replaced at build by zite() with a lazy import of the app's `zite.auth.ts`,
2
+ // when it has one. Null wherever the plugin didn't build the app.
3
+ export const authHooksModule = null;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,105 @@
1
+ // Classic's cases (restly packages/endpoint-setup/src/endpointErrors.test.ts), for the port in errors.ts.
2
+ import { describe, it, expect } from 'vitest';
3
+ import { toClientErrorMessage } from './errors.js';
4
+ describe('toClientErrorMessage', () => {
5
+ describe('live mode', () => {
6
+ it('preserves a signal the app throws for its own frontend to parse', () => {
7
+ // The regression case: apps throw structured messages as control flow
8
+ // and parse them client-side. Blanking this breaks the app silently.
9
+ expect(toClientErrorMessage('CLOTHES_CHANGE_PENDING:recAbc,recDef', 'live')).toBe('CLOTHES_CHANGE_PENDING:recAbc,recDef');
10
+ });
11
+ it('preserves user-facing copy the app author wrote', () => {
12
+ const message = 'Registration is missing child information. Please contact team@example.org';
13
+ expect(toClientErrorMessage(message, 'live')).toBe(message);
14
+ });
15
+ it('preserves incidental errors, which are no worse than a generic string', () => {
16
+ expect(toClientErrorMessage('window is not defined', 'live')).toBe('window is not defined');
17
+ });
18
+ it('replaces private-range IP addresses', () => {
19
+ expect(toClientErrorMessage('connect ECONNREFUSED 10.205.134.213:2507', 'live')).toBe('A service this app depends on is temporarily unavailable. Please try again.');
20
+ });
21
+ it('replaces internal service hostnames', () => {
22
+ expect(toClientErrorMessage('ConnectTimeoutError (attempted address: zite-shard-restly-server:2500, timeout: 10000ms)', 'live')).toBe('A service this app depends on is temporarily unavailable. Please try again.');
23
+ });
24
+ it('replaces internal service hostnames with no port, as DNS failures report them', () => {
25
+ expect(toClientErrorMessage('getaddrinfo ENOTFOUND workflow-runner', 'live')).toBe('A service this app depends on is temporarily unavailable. Please try again.');
26
+ });
27
+ it('replaces a portless hostname carrying a pod suffix', () => {
28
+ expect(toClientErrorMessage('getaddrinfo EAI_AGAIN workflow-runner-3l4c', 'live')).toBe('A service this app depends on is temporarily unavailable. Please try again.');
29
+ });
30
+ it('does not match a service name embedded in a longer token', () => {
31
+ // "app-runner" sits inside this, but it is the app's own resource name.
32
+ const message = 'Deployment my-app-runner-config failed';
33
+ expect(toClientErrorMessage(message, 'live')).toBe(message);
34
+ });
35
+ it("replaces Zite's AI billing notice, which is addressed to the app owner", () => {
36
+ expect(toClientErrorMessage('402 AI is paused: your organization is over its AI credit limit. To resume, increase your credits (upgrade your plan) or connect your own AI provider key (BYOK).', 'live')).toBe('AI features are temporarily unavailable. Please contact the app owner.');
37
+ });
38
+ it("replaces an upstream provider's billing state", () => {
39
+ expect(toClientErrorMessage('429 You have no credits remaining. Add credits to continue using the API at https://platform.openai.com/settings/organization/billing/.', 'live')).toBe('AI features are temporarily unavailable. Please contact the app owner.');
40
+ });
41
+ it("does not swallow an app's own copy about credits or quotas", () => {
42
+ // Narrowness check: the billing patterns key on our prefix and on the
43
+ // provider's URLs, so an app writing about its users' credit stays intact.
44
+ const message = 'You have exceeded your credit limit for this month.';
45
+ expect(toClientErrorMessage(message, 'live')).toBe(message);
46
+ });
47
+ it('does not treat a public IP as internal', () => {
48
+ const message = 'Request to 203.0.113.10:443 failed';
49
+ expect(toClientErrorMessage(message, 'live')).toBe(message);
50
+ });
51
+ it('replaces link-local addresses, which reach cloud metadata services', () => {
52
+ expect(toClientErrorMessage('connect ETIMEDOUT 169.254.169.254:80', 'live')).toBe('A service this app depends on is temporarily unavailable. Please try again.');
53
+ });
54
+ it('replaces IPv6 loopback, unique-local and link-local addresses', () => {
55
+ const unavailable = 'A service this app depends on is temporarily unavailable. Please try again.';
56
+ expect(toClientErrorMessage('connect ECONNREFUSED ::1', 'live')).toBe(unavailable);
57
+ expect(toClientErrorMessage('no route to fd12:3456:789a::1', 'live')).toBe(unavailable);
58
+ // fe80::/10 — the IPv6 counterpart to 169.254, and it turns up in the
59
+ // same container-networking failures.
60
+ expect(toClientErrorMessage('connect ETIMEDOUT fe80::1', 'live')).toBe(unavailable);
61
+ expect(toClientErrorMessage('no route to feba:1234::abcd', 'live')).toBe(unavailable);
62
+ });
63
+ it('replaces a bare localhost reference', () => {
64
+ expect(toClientErrorMessage('connect ECONNREFUSED localhost:2506', 'live')).toBe('A service this app depends on is temporarily unavailable. Please try again.');
65
+ });
66
+ });
67
+ describe('live mode — credentials', () => {
68
+ it('redacts a secret but keeps the rest of the message', () => {
69
+ // The whole point of redacting in place: the sentence around the
70
+ // credential is the app author's and still has to reach the user.
71
+ expect(toClientErrorMessage('Could not reach the roster database: postgres://svc:hunter2@db.example.com/prod', 'live')).toBe('Could not reach the roster database: postgres://svc:REDACTED@db.example.com/prod');
72
+ });
73
+ it('redacts a provider key inside otherwise user-facing copy', () => {
74
+ expect(toClientErrorMessage('Payment provider rejected the request (sk_live_abcdefghijklmnop1234)', 'live')).toBe('Payment provider rejected the request (REDACTED)');
75
+ });
76
+ it('still replaces the message when infrastructure detail survives redaction', () => {
77
+ // Both concerns in one message: the secret goes, and the internal
78
+ // hostname then triggers wholesale replacement.
79
+ expect(toClientErrorMessage('connect ECONNREFUSED base-runner:2500 using api_key=abc123def456', 'live')).toBe('A service this app depends on is temporarily unavailable. Please try again.');
80
+ });
81
+ });
82
+ describe('userFacingMessage', () => {
83
+ it('prefers the author-written message over the technical one', () => {
84
+ expect(toClientErrorMessage('Airtable findAll failed for tblIx0DJvbXjjfA42 after 3 retries', 'live', 'We could not load this week’s roster. Please try again shortly.')).toBe('We could not load this week’s roster. Please try again shortly.');
85
+ });
86
+ it('keeps the technical message in preview so the developer can debug', () => {
87
+ expect(toClientErrorMessage('Airtable findAll failed for tblIx0DJvbXjjfA42 after 3 retries', 'preview', 'We could not load this week’s roster.')).toBe('Airtable findAll failed for tblIx0DJvbXjjfA42 after 3 retries');
88
+ });
89
+ it('falls back to the thrown message when the author set none', () => {
90
+ expect(toClientErrorMessage('CLOTHES_CHANGE_PENDING:recAbc', 'live', undefined)).toBe('CLOTHES_CHANGE_PENDING:recAbc');
91
+ });
92
+ it('ignores an empty userFacingMessage rather than blanking the response', () => {
93
+ expect(toClientErrorMessage('Week #11 is now full', 'live', '')).toBe('Week #11 is now full');
94
+ });
95
+ });
96
+ describe('preview mode', () => {
97
+ it('passes infrastructure detail through so the developer can debug', () => {
98
+ const message = 'connect ECONNREFUSED 10.205.134.213:2507';
99
+ expect(toClientErrorMessage(message, 'preview')).toBe(message);
100
+ });
101
+ });
102
+ it('treats an unspecified mode as live', () => {
103
+ expect(toClientErrorMessage('connect ECONNREFUSED 10.205.134.213:2507', undefined)).toBe('A service this app depends on is temporarily unavailable. Please try again.');
104
+ });
105
+ });
@@ -0,0 +1,2 @@
1
+ /** The platform id `integrations.get` is answered under. */
2
+ export declare const INTEGRATIONS_PLATFORM_ID = "__connections__";
@@ -0,0 +1,2 @@
1
+ /** The platform id `integrations.get` is answered under. */
2
+ export const INTEGRATIONS_PLATFORM_ID = "__connections__";
@@ -0,0 +1,92 @@
1
+ import { type BulkCreateResponseType, type FindAllResponseType, type FindOneResponseType, type GetBaseResponseType, type LegacyRecordsFilterClauseType, type NameMappings } from "./types.js";
2
+ /** One base-runner request, `path` from `/api/v1`; the platform sends it and answers with base-runner's response. */
3
+ export type DataTransport = (request: {
4
+ method: string;
5
+ path: string;
6
+ body?: string;
7
+ }) => Promise<Response>;
8
+ type Sort = string | Array<{
9
+ field: string;
10
+ direction: "asc" | "desc";
11
+ }>;
12
+ /** An id as one path segment: an unencoded `/` or a `..` would move the request to another base's URL. */
13
+ export declare const segment: (id: string | number) => string;
14
+ export declare const createBaseRunner: (transport: DataTransport) => {
15
+ bases: {
16
+ get: ({ baseId }: {
17
+ baseId: string;
18
+ }) => Promise<GetBaseResponseType>;
19
+ };
20
+ records: {
21
+ get: ({ baseId, tableId, recordId, fields }: {
22
+ baseId: string;
23
+ tableId: string;
24
+ recordId: string;
25
+ fields?: string[];
26
+ }) => Promise<FindOneResponseType>;
27
+ findAll: ({ baseId, tableId, filters, offset, sort, limit, fields, }: {
28
+ baseId: string;
29
+ tableId: string;
30
+ filters?: LegacyRecordsFilterClauseType;
31
+ offset?: number;
32
+ sort?: Sort;
33
+ limit?: number;
34
+ fields?: string[];
35
+ }) => Promise<FindAllResponseType>;
36
+ create: ({ baseId, tableId, record }: {
37
+ baseId: string;
38
+ tableId: string;
39
+ record: Record<string, unknown>;
40
+ }) => Promise<FindOneResponseType>;
41
+ update: ({ baseId, tableId, recordId, record, }: {
42
+ baseId: string;
43
+ tableId: string;
44
+ recordId: string;
45
+ record: Record<string, unknown>;
46
+ }) => Promise<FindOneResponseType>;
47
+ delete: ({ baseId, tableId, recordId }: {
48
+ baseId: string;
49
+ tableId: string;
50
+ recordId: string;
51
+ }) => Promise<{
52
+ id: string;
53
+ }>;
54
+ bulkCreate: ({ baseId, tableId, records, matchOn, }: {
55
+ baseId: string;
56
+ tableId: string;
57
+ records: Record<string, unknown>[];
58
+ matchOn?: string[];
59
+ }) => Promise<BulkCreateResponseType>;
60
+ };
61
+ sql: {
62
+ execute: ({ baseId, sql, params, statementTimeoutMs, nameMappings, }: {
63
+ baseId: string;
64
+ sql: string;
65
+ params?: unknown[];
66
+ statementTimeoutMs?: number;
67
+ nameMappings?: NameMappings;
68
+ }) => Promise<unknown>;
69
+ };
70
+ auth: {
71
+ findAll: ({ baseId, appIds, filters, filter, offset, sort, limit, }: {
72
+ baseId: string;
73
+ appIds?: string[];
74
+ filters?: LegacyRecordsFilterClauseType;
75
+ filter?: unknown;
76
+ offset?: number;
77
+ sort?: Sort;
78
+ limit?: number;
79
+ }) => Promise<unknown>;
80
+ update: ({ baseId, userId, profile, }: {
81
+ baseId: string;
82
+ userId: string;
83
+ profile: {
84
+ firstName?: string | null;
85
+ lastName?: string | null;
86
+ image?: string | null;
87
+ };
88
+ }) => Promise<unknown>;
89
+ };
90
+ };
91
+ export type BaseRunner = ReturnType<typeof createBaseRunner>;
92
+ export {};
@@ -0,0 +1,83 @@
1
+ // Ported from restly's packages/workflow-edge/src/databases (client, records, sql, authUsers, bases):
2
+ // the requests are the same bytes classic's DatabasesSdk sends; the host adds the key and the acting user.
3
+ import { DatabasesApiError, } from "./types.js";
4
+ /** An id as one path segment: an unencoded `/` or a `..` would move the request to another base's URL. */
5
+ export const segment = (id) => {
6
+ const value = String(id);
7
+ const invalid = new DatabasesApiError(`Invalid id: "${value}"`, 400, "Bad Request");
8
+ if (value === "" || value === "." || value === "..")
9
+ throw invalid;
10
+ try {
11
+ return encodeURIComponent(value);
12
+ }
13
+ catch {
14
+ // A lone surrogate, which a visitor can send as JSON.
15
+ throw invalid;
16
+ }
17
+ };
18
+ /** Every path, however it was built: none may climb out of where it starts. */
19
+ const apiPath = (path) => {
20
+ const full = `/api/v1${path}`;
21
+ const pathname = full.split("?")[0];
22
+ if (!new URL(full, "https://base-runner.invalid").pathname.endsWith(pathname)) {
23
+ throw new DatabasesApiError(`Invalid path: ${pathname}`, 400, "Bad Request");
24
+ }
25
+ return full;
26
+ };
27
+ export const createBaseRunner = (transport) => {
28
+ const send = async (method, path, body) => {
29
+ const response = await transport({ method, path: apiPath(path), body: body ? JSON.stringify(body) : undefined });
30
+ if (!response.ok) {
31
+ let errorMessage = response.statusText;
32
+ try {
33
+ const errorBody = (await response.json());
34
+ errorMessage = errorBody?.error?.message || errorBody?.message || errorMessage;
35
+ }
36
+ catch {
37
+ // If we can't parse the error body, fall back to statusText
38
+ }
39
+ throw new DatabasesApiError(errorMessage, response.status, response.statusText);
40
+ }
41
+ return response;
42
+ };
43
+ const json = async (method, path, body) => (await send(method, path, body)).json();
44
+ return {
45
+ bases: {
46
+ get: ({ baseId }) => json("GET", `/bases/${segment(baseId)}`),
47
+ },
48
+ records: {
49
+ get: ({ baseId, tableId, recordId, fields }) => json("GET", `/bases/${segment(baseId)}/tables/${segment(tableId)}/records/${segment(recordId)}${fields?.length ? `?fields=${encodeURIComponent(fields.join(","))}` : ""}`),
50
+ findAll: ({ baseId, tableId, filters, offset, sort, limit = 500, fields, }) => json("POST", `/bases/${segment(baseId)}/tables/${segment(tableId)}/records/list`, {
51
+ filters,
52
+ offset,
53
+ sort,
54
+ limit,
55
+ fields,
56
+ }),
57
+ create: ({ baseId, tableId, record }) => json("POST", `/bases/${segment(baseId)}/tables/${segment(tableId)}/records`, { record }),
58
+ update: ({ baseId, tableId, recordId, record, }) => json("PATCH", `/bases/${segment(baseId)}/tables/${segment(tableId)}/records/${segment(recordId)}`, { record }),
59
+ delete: async ({ baseId, tableId, recordId }) => {
60
+ await send("DELETE", `/bases/${segment(baseId)}/tables/${segment(tableId)}/records/${segment(recordId)}`);
61
+ return { id: recordId };
62
+ },
63
+ bulkCreate: ({ baseId, tableId, records, matchOn, }) => json("POST", `/bases/${segment(baseId)}/tables/${segment(tableId)}/records/bulk`, {
64
+ records,
65
+ matchOn,
66
+ }),
67
+ },
68
+ sql: {
69
+ execute: ({ baseId, sql, params, statementTimeoutMs, nameMappings, }) => json("POST", `/bases/${segment(baseId)}/sql`, { sql, params, statementTimeoutMs, nameMappings }),
70
+ },
71
+ auth: {
72
+ findAll: ({ baseId, appIds, filters, filter, offset, sort, limit = 500, }) => json("POST", `/bases/${segment(baseId)}/auth/users/list`, {
73
+ appIds,
74
+ filters,
75
+ filter,
76
+ offset,
77
+ sort,
78
+ limit,
79
+ }),
80
+ update: ({ baseId, userId, profile, }) => json("PATCH", `/bases/${segment(baseId)}/auth/users/${segment(userId)}`, profile),
81
+ },
82
+ };
83
+ };
@@ -0,0 +1,16 @@
1
+ import type { BaseRunner } from "./baseRunner.js";
2
+ import { type BaseTable, type DataNameMappings } from "./types.js";
3
+ export type DataContext = {
4
+ baseRunner: BaseRunner;
5
+ /** The build's base, from the platform; a base id the app sends is ignored. */
6
+ baseId: string;
7
+ nameMappings: DataNameMappings | null;
8
+ /** The base's tables, for field names and SQL names. */
9
+ tables: BaseTable[] | undefined;
10
+ /** A demo: only reads reach the database. */
11
+ readOnly: boolean;
12
+ };
13
+ export declare const DEMO_UNAVAILABLE_MESSAGE = "This action is not available in demo mode";
14
+ export declare function asZiteClientError(error: unknown): unknown;
15
+ /** One `zite.*` data call, as classic's dispatch runs it. */
16
+ export declare function executeDatabasesCall(context: DataContext, methodName: string, params: any): Promise<any>;