zitejs 0.9.147 → 0.9.149

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 (37) hide show
  1. package/dist/cjs/backend/index.d.ts +7 -1
  2. package/dist/cjs/bundle/index.d.ts +8 -0
  3. package/dist/cjs/bundle/index.js +9 -8
  4. package/dist/cjs/check/index.js +41 -25
  5. package/dist/cjs/client/index.d.ts +24 -0
  6. package/dist/cjs/integrations/rules.js +5 -3
  7. package/dist/cjs/runtime/index.d.ts +49 -19
  8. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  9. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.js +32 -0
  10. package/dist/cjs/steps/index.d.ts +78 -0
  11. package/dist/cjs/steps/index.js +507 -0
  12. package/dist/cjs/steps/index.test.d.ts +1 -0
  13. package/dist/cjs/steps/index.test.js +635 -0
  14. package/dist/cjs/sync/lib.js +10 -6
  15. package/dist/cjs/sync/lib.test.js +100 -36
  16. package/dist/cjs/types/fields.d.ts +8 -1
  17. package/dist/cjs/types/fields.js +7 -1
  18. package/dist/cjs/types/tables.d.ts +16 -0
  19. package/dist/esm/backend/index.d.ts +7 -1
  20. package/dist/esm/bundle/index.d.ts +8 -0
  21. package/dist/esm/bundle/index.js +8 -8
  22. package/dist/esm/check/index.js +10 -27
  23. package/dist/esm/client/index.d.ts +24 -0
  24. package/dist/esm/integrations/rules.js +5 -3
  25. package/dist/esm/runtime/index.d.ts +49 -19
  26. package/dist/esm/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  27. package/dist/esm/runtime/sendEmailParamsTypes.test-d.js +30 -0
  28. package/dist/esm/steps/index.d.ts +78 -0
  29. package/dist/esm/steps/index.js +502 -0
  30. package/dist/esm/steps/index.test.d.ts +1 -0
  31. package/dist/esm/steps/index.test.js +633 -0
  32. package/dist/esm/sync/lib.js +10 -6
  33. package/dist/esm/sync/lib.test.js +100 -36
  34. package/dist/esm/types/fields.d.ts +8 -1
  35. package/dist/esm/types/fields.js +6 -0
  36. package/dist/esm/types/tables.d.ts +16 -0
  37. package/package.json +9 -1
@@ -83,6 +83,7 @@ const FIELD_TYPE_MAP = {
83
83
  formula: "any",
84
84
  created_at: "string",
85
85
  updated_at: "string",
86
+ created_by: "string",
86
87
  updated_by: "string",
87
88
  };
88
89
  /**
@@ -108,7 +109,7 @@ const FIELD_INPUT_TYPE_MAP = {
108
109
  * rather than typed and then refused at runtime.
109
110
  *
110
111
  * Mirrors `COMPUTED_FIELD_TYPES` in the product's own `shared/bases/fields`.
111
- * The first six are rejected by `createRecordDataSchema` — each has a
112
+ * The first seven are rejected by `createRecordDataSchema` — each has a
112
113
  * `refine(val => val == null)`, so a non-null write errors (null is a no-op
113
114
  * clear). `created_at` / `updated_at` are refused differently: they have no
114
115
  * column at all, so a write is silently dropped, which is the worse outcome to
@@ -120,6 +121,7 @@ const READ_ONLY_FIELD_TYPES = new Set([
120
121
  "source",
121
122
  "formula",
122
123
  "autonumber",
124
+ "created_by",
123
125
  "updated_by",
124
126
  "created_at",
125
127
  "updated_at",
@@ -522,7 +524,7 @@ function generateDbTs(inputSchema) {
522
524
  lines.push("// filters: { fieldName: value } for equality, or { fieldName: { <op>: value } }");
523
525
  lines.push("// operators: contains, not, in, notIn, lt, lte, gt, gte");
524
526
  lines.push('// `not: null` means "is set". An empty `in: []` matches nothing; an', "// empty `notIn: []` applies no filter.");
525
- lines.push("// sort is currently IGNORED here — it is stripped before the request.", "// (it does work on zite.auth.findAllUsers). Order in SQL instead.");
527
+ lines.push('// sort: [{ field: "fieldName", direction: "asc" | "desc" }]');
526
528
  lines.push("// limit defaults to 500, max 2000; offset is a row count (a number)");
527
529
  lines.push("// a filter value of `undefined` is REJECTED (it would query unfiltered", "// and match an arbitrary record). Check the value first.");
528
530
  lines.push("// .findOne({ id?, filters?, fields? }) → T | undefined");
@@ -1331,7 +1333,7 @@ function generateBackendWrapperTs(envVarNames = []) {
1331
1333
  " execute: (",
1332
1334
  " params: {",
1333
1335
  " input: ZiteEndpointInput<TInput, TTrigger>;",
1334
- " /** Durable steps: step.run(name, fn) runs fn once per logical run — its result is saved before anything after it executes, and a resumed run replays completed steps from their saved results. In a run fired by a schedule, webhook or trigger, step.sleep(name, \"2d\") pauses the run and a failed step is tried again. Provided by the platform; never define a local stand-in. */",
1336
+ ' /** Durable steps: step.run(name, fn) runs fn once per logical run — its result is saved before anything after it executes, and a resumed run replays completed steps from their saved results. In a run fired by a schedule, webhook or trigger, step.sleep(name, "2d") pauses the run and a failed step is tried again. Provided by the platform; never define a local stand-in. */',
1335
1337
  " step: ZiteStep;",
1336
1338
  " context: TSchedule extends ZiteSchedule ? ZiteRequestContext | ZiteScheduledContext : TWebhook extends ZiteWebhook ? ZiteRequestContext | ZiteScheduledContext : TTrigger extends ZiteTrigger ? ZiteRequestContext | ZiteScheduledContext : ZiteRequestContext;",
1337
1339
  // Mirrors the base module: a trigger's run gets `trigger`.
@@ -1396,18 +1398,20 @@ function generateEmailSdk(integrationId) {
1396
1398
  "// Always use 'zitejs/email' — never a relative path like '../../.zite/integrations/email'.",
1397
1399
  "// The tsconfig aliases resolve zitejs/* imports to the correct .zite/ files.",
1398
1400
  "//",
1401
+ "// await Email.send({ to, subject, html: '<p>...</p>' })",
1399
1402
  "// await Email.send({ to, subject, body: [{ type: 'text', content: '...' }] })",
1400
- "// => { success: boolean; messageId: string }",
1403
+ "// => { success: boolean; messageId: string; warnings?: string[] }",
1401
1404
  "//",
1402
- "// RTL languages (Hebrew, Arabic): pass direction: 'rtl' — dir attributes",
1403
- "// inside body text are stripped by the sanitizer and will not work.",
1405
+ "// RTL languages (Hebrew, Arabic): pass direction: 'rtl'.",
1404
1406
  "",
1405
1407
  "import { createEmailClient } from 'zitejs/runtime';",
1406
1408
  "",
1407
1409
  "export type {",
1408
1410
  " EmailBlock,",
1411
+ " SendBlocksEmailParams,",
1409
1412
  " SendEmailParams,",
1410
1413
  " SendEmailResult,",
1414
+ " SendHtmlEmailParams,",
1411
1415
  "} from 'zitejs/runtime';",
1412
1416
  "",
1413
1417
  `export const Email = createEmailClient(${tsSingleQuoted(integrationId)});`,
@@ -427,44 +427,98 @@ const duplicateIdentifierErrorsIn = (source) => {
427
427
  (0, vitest_1.expect)((0, lib_js_1.findEmailIntegrationId)(undefined, undefined)).toBeUndefined();
428
428
  });
429
429
  });
430
- (0, vitest_1.describe)('generateIntegrationsIndex', () => {
431
- // Not import.meta: this file also compiles to CommonJS. Vitest runs from the repo root.
432
- const runtimePath = (0, path_1.resolve)('src/runtime/index.ts');
433
- /** Type errors in `usage` compiled beside the generated file, `zitejs/runtime` mapped to this source. */
434
- const typeErrorsIn = (generated, usage, airtable) => {
435
- const files = {
436
- '/app/.zite/integrations/index.ts': generated,
437
- ...(airtable ? { '/app/.zite/integrations/airtable.ts': airtable } : {}),
438
- '/app/src/usage.ts': usage,
439
- };
440
- const options = {
441
- strict: true,
442
- noEmit: true,
443
- target: typescript_1.default.ScriptTarget.ES2022,
444
- module: typescript_1.default.ModuleKind.ESNext,
445
- moduleResolution: typescript_1.default.ModuleResolutionKind.Bundler,
446
- skipLibCheck: true,
447
- baseUrl: '/app',
448
- paths: {
449
- 'zitejs/runtime': [runtimePath],
450
- 'zitejs/integrations': ['/app/.zite/integrations/index.ts'],
430
+ // Not import.meta: this file also compiles to CommonJS. Vitest runs from the repo root.
431
+ const runtimePath = (0, path_1.resolve)('src/runtime/index.ts');
432
+ /** Type errors in the `/app/` files, `zitejs/runtime` mapped to this source. */
433
+ const appTypeErrors = (files, paths) => {
434
+ const options = {
435
+ strict: true,
436
+ noEmit: true,
437
+ target: typescript_1.default.ScriptTarget.ES2022,
438
+ module: typescript_1.default.ModuleKind.ESNext,
439
+ moduleResolution: typescript_1.default.ModuleResolutionKind.Bundler,
440
+ skipLibCheck: true,
441
+ baseUrl: '/app',
442
+ paths: { 'zitejs/runtime': [runtimePath], ...paths },
443
+ };
444
+ const host = typescript_1.default.createCompilerHost(options);
445
+ const { getSourceFile, fileExists, readFile, directoryExists } = host;
446
+ host.fileExists = f => f in files || fileExists(f);
447
+ host.directoryExists = d => Object.keys(files).some(f => f.startsWith(`${d}/`)) ||
448
+ (directoryExists?.(d) ?? false);
449
+ host.readFile = f => files[f] ?? readFile(f);
450
+ host.getSourceFile = (f, lang, ...rest) => f in files
451
+ ? typescript_1.default.createSourceFile(f, files[f], lang)
452
+ : getSourceFile(f, lang, ...rest);
453
+ const program = typescript_1.default.createProgram(Object.keys(files), options, host);
454
+ return typescript_1.default
455
+ .getPreEmitDiagnostics(program)
456
+ .filter(d => d.file?.fileName.startsWith('/app/'))
457
+ .map(d => typescript_1.default.flattenDiagnosticMessageText(d.messageText, ' '));
458
+ };
459
+ (0, vitest_1.describe)('generateDbTs created_by and updated_by', () => {
460
+ const schema = {
461
+ tables: [
462
+ {
463
+ id: 'tbl1',
464
+ sdkName: 'tasks',
465
+ fields: [
466
+ {
467
+ id: 'fld1',
468
+ sdkName: 'title',
469
+ definition: { name: 'Title', type: 'single_line_text', template: {} },
470
+ },
471
+ {
472
+ id: 'fld2',
473
+ sdkName: 'createdBy',
474
+ definition: { name: 'Created By', type: 'created_by', template: {} },
475
+ },
476
+ {
477
+ id: 'fld3',
478
+ sdkName: 'updatedBy',
479
+ definition: { name: 'Last Modified By', type: 'updated_by', template: {} },
480
+ },
481
+ ],
451
482
  },
452
- };
453
- const host = typescript_1.default.createCompilerHost(options);
454
- const { getSourceFile, fileExists, readFile, directoryExists } = host;
455
- host.fileExists = f => f in files || fileExists(f);
456
- host.directoryExists = d => Object.keys(files).some(f => f.startsWith(`${d}/`)) ||
457
- (directoryExists?.(d) ?? false);
458
- host.readFile = f => files[f] ?? readFile(f);
459
- host.getSourceFile = (f, lang, ...rest) => f in files
460
- ? typescript_1.default.createSourceFile(f, files[f], lang)
461
- : getSourceFile(f, lang, ...rest);
462
- const program = typescript_1.default.createProgram(Object.keys(files), options, host);
463
- return typescript_1.default
464
- .getPreEmitDiagnostics(program)
465
- .filter(d => d.file?.fileName.startsWith('/app/'))
466
- .map(d => typescript_1.default.flattenDiagnosticMessageText(d.messageText, ' '));
483
+ ],
467
484
  };
485
+ const typeErrorsIn = (usage) => appTypeErrors({ '/app/.zite/db.ts': (0, lib_js_1.generateDbTs)(schema), '/app/src/usage.ts': usage }, { 'zitejs/db': ['/app/.zite/db.ts'] });
486
+ const EQUAL = 'type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;';
487
+ // TanStack Start's serializability check rejects `unknown`, so a server
488
+ // function returning a raw row failed typecheck while created_by fell through.
489
+ (0, vitest_1.it)('reads both as a user id', () => {
490
+ (0, vitest_1.expect)(typeErrorsIn([
491
+ "import type { TasksRecordType } from 'zitejs/db';",
492
+ EQUAL,
493
+ "export const createdBy: Equal<TasksRecordType['createdBy'], string | undefined> = true;",
494
+ "export const updatedBy: Equal<TasksRecordType['updatedBy'], string | undefined> = true;",
495
+ ].join('\n'))).toEqual([]);
496
+ });
497
+ (0, vitest_1.it)('leaves both out of the input type', () => {
498
+ (0, vitest_1.expect)(typeErrorsIn([
499
+ "import type { TasksRecordInput } from 'zitejs/db';",
500
+ EQUAL,
501
+ "export const writable: Equal<keyof TasksRecordInput, 'title'> = true;",
502
+ ].join('\n'))).toEqual([]);
503
+ });
504
+ (0, vitest_1.it)('filters both by a user id', () => {
505
+ (0, vitest_1.expect)(typeErrorsIn([
506
+ "import { zite } from 'zitejs/db';",
507
+ 'export const mine = (userId: string) => [',
508
+ ' zite.tasks.findAll({ filters: { createdBy: userId } }),',
509
+ ' zite.tasks.findAll({ filters: { updatedBy: { in: [userId] } } }),',
510
+ ' zite.tasks.findOne({ filters: { createdBy: { not: null } } }),',
511
+ '];',
512
+ ].join('\n'))).toEqual([]);
513
+ (0, vitest_1.expect)(typeErrorsIn("import { zite } from 'zitejs/db';\nvoid zite.tasks.findAll({ filters: { createdBy: 42 } });")).toHaveLength(1);
514
+ });
515
+ });
516
+ (0, vitest_1.describe)('generateIntegrationsIndex', () => {
517
+ const typeErrorsIn = (generated, usage, airtable) => appTypeErrors({
518
+ '/app/.zite/integrations/index.ts': generated,
519
+ ...(airtable ? { '/app/.zite/integrations/airtable.ts': airtable } : {}),
520
+ '/app/src/usage.ts': usage,
521
+ }, { 'zitejs/integrations': ['/app/.zite/integrations/index.ts'] });
468
522
  (0, vitest_1.it)('emits the client typed by name', () => {
469
523
  (0, vitest_1.expect)((0, lib_js_1.generateIntegrationsIndex)([
470
524
  { name: 'team', serviceType: 'slack', perUser: false },
@@ -512,6 +566,16 @@ const duplicateIdentifierErrorsIn = (source) => {
512
566
  const jira = await integrations.get('tickets');
513
567
  const cloudId: string = jira.cloudId;
514
568
  const siteUrl: string = jira.siteUrl;
569
+ `)).toEqual([
570
+ vitest_1.expect.stringContaining("Type 'string | undefined' is not assignable"),
571
+ ]);
572
+ });
573
+ (0, vitest_1.it)('types the Shopify storefront URL as always present and only its token as optional', () => {
574
+ const generated = (0, lib_js_1.generateIntegrationsIndex)([{ name: 'shopify', serviceType: 'shopify', perUser: false }], { reexportAirtable: false });
575
+ (0, vitest_1.expect)(typeErrorsIn(generated, `import { integrations } from 'zitejs/integrations';
576
+ const shop = await integrations.get('shopify');
577
+ const storefrontApiUrl: string = shop.storefrontApiUrl;
578
+ const storefrontAccessToken: string = shop.storefrontAccessToken;
515
579
  `)).toEqual([
516
580
  vitest_1.expect.stringContaining("Type 'string | undefined' is not assignable"),
517
581
  ]);
@@ -7,7 +7,7 @@ export declare const timeFormatEnum: readonly ["12h", "24h"];
7
7
  export type TimeFormat = (typeof timeFormatEnum)[number];
8
8
  export declare const durationFormatEnum: readonly ["h:mm", "h:mm:ss", "h:mm:ss.s", "h:mm:ss.ss", "h:mm:ss.sss"];
9
9
  export type DurationFormat = (typeof durationFormatEnum)[number];
10
- export declare const fieldTypeEnum: readonly ["currency", "single_line_text", "long_text", "rich_text", "number", "single_select", "multiple_select", "date", "datetime", "checkbox", "attachments", "email", "url", "phone_number", "rating", "duration", "percent", "linked_record", "lookup", "source", "formula", "autonumber", "created_at", "updated_at", "rollup", "updated_by", "user"];
10
+ export declare const fieldTypeEnum: readonly ["currency", "single_line_text", "long_text", "rich_text", "number", "single_select", "multiple_select", "date", "datetime", "checkbox", "attachments", "email", "url", "phone_number", "rating", "duration", "percent", "linked_record", "lookup", "source", "formula", "autonumber", "created_at", "updated_at", "rollup", "created_by", "updated_by", "user"];
11
11
  export type FieldType = (typeof fieldTypeEnum)[number];
12
12
  export declare const fieldTypeSchema: z.ZodEnum<{
13
13
  number: "number";
@@ -35,6 +35,7 @@ export declare const fieldTypeSchema: z.ZodEnum<{
35
35
  created_at: "created_at";
36
36
  updated_at: "updated_at";
37
37
  rollup: "rollup";
38
+ created_by: "created_by";
38
39
  updated_by: "updated_by";
39
40
  user: "user";
40
41
  }>;
@@ -240,6 +241,7 @@ export declare const rollupTemplateSchema: z.ZodObject<{
240
241
  text: "text";
241
242
  }>>;
242
243
  }, z.core.$strip>;
244
+ export declare const createdByTemplateSchema: z.ZodObject<{}, z.core.$strip>;
243
245
  export declare const updatedByTemplateSchema: z.ZodObject<{}, z.core.$strip>;
244
246
  export declare const userTemplateSchema: z.ZodObject<{
245
247
  allowMultiple: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodBoolean>>, z.ZodTransform<boolean, boolean | null | undefined>>;
@@ -554,6 +556,10 @@ export declare const publicFieldDefinitionSchema: z.ZodDiscriminatedUnion<[z.Zod
554
556
  text: "text";
555
557
  }>>;
556
558
  }, z.core.$strip>;
559
+ }, z.core.$strip>, z.ZodObject<{
560
+ name: z.ZodString;
561
+ type: z.ZodLiteral<"created_by">;
562
+ template: z.ZodObject<{}, z.core.$strip>;
557
563
  }, z.core.$strip>, z.ZodObject<{
558
564
  name: z.ZodString;
559
565
  type: z.ZodLiteral<"updated_by">;
@@ -661,6 +667,7 @@ export type FieldTemplateMap = {
661
667
  linked_record: z.infer<typeof linkedRecordTemplateSchema>;
662
668
  lookup: z.infer<typeof lookupTemplateSchema>;
663
669
  rollup: z.infer<typeof rollupTemplateSchema>;
670
+ created_by: z.infer<typeof createdByTemplateSchema>;
664
671
  updated_by: z.infer<typeof updatedByTemplateSchema>;
665
672
  user: z.infer<typeof userTemplateSchema>;
666
673
  source: z.infer<typeof sourceTemplateSchema>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.publicFieldDefinitionSchema = exports.updatedAtTemplateSchema = exports.createdAtTemplateSchema = exports.autonumberTemplateSchema = exports.formulaTemplateSchema = exports.sourceTemplateSchema = exports.userTemplateSchema = exports.updatedByTemplateSchema = exports.rollupTemplateSchema = exports.lookupTemplateSchema = exports.linkedRecordTemplateSchema = exports.percentTemplateSchema = exports.durationTemplateSchema = exports.ratingTemplateSchema = exports.phoneNumberTemplateSchema = exports.urlTemplateSchema = exports.emailTemplateSchema = exports.attachmentsTemplateSchema = exports.checkboxTemplateSchema = exports.datetimeTemplateSchema = exports.dateTemplateSchema = exports.multipleSelectTemplateSchema = exports.singleSelectTemplateSchema = exports.numberTemplateSchema = exports.richTextTemplateSchema = exports.longTextTemplateSchema = exports.singleLineTextTemplateSchema = exports.currencyTemplateSchema = exports.aiGenerationConfigSchema = exports.selectOptionSchema = exports.fieldTypeSchema = exports.fieldTypeEnum = exports.durationFormatEnum = exports.timeFormatEnum = exports.dateFormatEnum = exports.numberFormatEnum = void 0;
3
+ exports.publicFieldDefinitionSchema = exports.updatedAtTemplateSchema = exports.createdAtTemplateSchema = exports.autonumberTemplateSchema = exports.formulaTemplateSchema = exports.sourceTemplateSchema = exports.userTemplateSchema = exports.updatedByTemplateSchema = exports.createdByTemplateSchema = exports.rollupTemplateSchema = exports.lookupTemplateSchema = exports.linkedRecordTemplateSchema = exports.percentTemplateSchema = exports.durationTemplateSchema = exports.ratingTemplateSchema = exports.phoneNumberTemplateSchema = exports.urlTemplateSchema = exports.emailTemplateSchema = exports.attachmentsTemplateSchema = exports.checkboxTemplateSchema = exports.datetimeTemplateSchema = exports.dateTemplateSchema = exports.multipleSelectTemplateSchema = exports.singleSelectTemplateSchema = exports.numberTemplateSchema = exports.richTextTemplateSchema = exports.longTextTemplateSchema = exports.singleLineTextTemplateSchema = exports.currencyTemplateSchema = exports.aiGenerationConfigSchema = exports.selectOptionSchema = exports.fieldTypeSchema = exports.fieldTypeEnum = exports.durationFormatEnum = exports.timeFormatEnum = exports.dateFormatEnum = exports.numberFormatEnum = void 0;
4
4
  const zod_1 = require("zod");
5
5
  exports.numberFormatEnum = [
6
6
  "local",
@@ -45,6 +45,7 @@ exports.fieldTypeEnum = [
45
45
  "created_at",
46
46
  "updated_at",
47
47
  "rollup",
48
+ "created_by",
48
49
  "updated_by",
49
50
  "user",
50
51
  ];
@@ -183,6 +184,7 @@ exports.rollupTemplateSchema = zod_1.z.object({
183
184
  .enum(["text", "number", "date", "boolean", "array"])
184
185
  .optional(),
185
186
  });
187
+ exports.createdByTemplateSchema = zod_1.z.object({});
186
188
  exports.updatedByTemplateSchema = zod_1.z.object({});
187
189
  exports.userTemplateSchema = zod_1.z.object({
188
190
  allowMultiple: zod_1.z
@@ -329,6 +331,10 @@ exports.publicFieldDefinitionSchema = zod_1.z.discriminatedUnion("type", [
329
331
  type: zod_1.z.literal("rollup"),
330
332
  template: exports.rollupTemplateSchema,
331
333
  }),
334
+ basePublicFieldSchema.extend({
335
+ type: zod_1.z.literal("created_by"),
336
+ template: exports.createdByTemplateSchema,
337
+ }),
332
338
  basePublicFieldSchema.extend({
333
339
  type: zod_1.z.literal("updated_by"),
334
340
  template: exports.updatedByTemplateSchema,
@@ -253,6 +253,10 @@ export declare const fieldSchema: z.ZodIntersection<z.ZodObject<{
253
253
  text: "text";
254
254
  }>>;
255
255
  }, z.core.$strip>;
256
+ }, z.core.$strip>, z.ZodObject<{
257
+ name: z.ZodString;
258
+ type: z.ZodLiteral<"created_by">;
259
+ template: z.ZodObject<{}, z.core.$strip>;
256
260
  }, z.core.$strip>, z.ZodObject<{
257
261
  name: z.ZodString;
258
262
  type: z.ZodLiteral<"updated_by">;
@@ -605,6 +609,10 @@ export declare const tableSchema: z.ZodObject<{
605
609
  text: "text";
606
610
  }>>;
607
611
  }, z.core.$strip>;
612
+ }, z.core.$strip>, z.ZodObject<{
613
+ name: z.ZodString;
614
+ type: z.ZodLiteral<"created_by">;
615
+ template: z.ZodObject<{}, z.core.$strip>;
608
616
  }, z.core.$strip>, z.ZodObject<{
609
617
  name: z.ZodString;
610
618
  type: z.ZodLiteral<"updated_by">;
@@ -952,6 +960,10 @@ export declare const publicTableDefinitionSchema: z.ZodObject<{
952
960
  text: "text";
953
961
  }>>;
954
962
  }, z.core.$strip>;
963
+ }, z.core.$strip>, z.ZodObject<{
964
+ name: z.ZodString;
965
+ type: z.ZodLiteral<"created_by">;
966
+ template: z.ZodObject<{}, z.core.$strip>;
955
967
  }, z.core.$strip>, z.ZodObject<{
956
968
  name: z.ZodString;
957
969
  type: z.ZodLiteral<"updated_by">;
@@ -1301,6 +1313,10 @@ export declare const databaseSchema: z.ZodObject<{
1301
1313
  text: "text";
1302
1314
  }>>;
1303
1315
  }, z.core.$strip>;
1316
+ }, z.core.$strip>, z.ZodObject<{
1317
+ name: z.ZodString;
1318
+ type: z.ZodLiteral<"created_by">;
1319
+ template: z.ZodObject<{}, z.core.$strip>;
1304
1320
  }, z.core.$strip>, z.ZodObject<{
1305
1321
  name: z.ZodString;
1306
1322
  type: z.ZodLiteral<"updated_by">;
@@ -332,6 +332,11 @@ export interface ZiteStep {
332
332
  * In a run fired by a schedule, webhook or trigger, a step that throws is
333
333
  * tried again `retries` more times (default 3, at most 10), 30 seconds,
334
334
  * 2 minutes, then 10 minutes apart. Elsewhere its error fails the request.
335
+ * Once its tries are spent the code gets its error, and later calls of the
336
+ * run throw it there again, rebuilt as an `Error` with its `name`,
337
+ * `message` and plain fields such as `code` or `status`, so branch on
338
+ * those rather than on `instanceof`. A result over 256KB, or one JSON
339
+ * can't hold such as a cycle, fails the step without a retry.
335
340
  */
336
341
  run<T>(name: string, fn: () => Promise<T> | T, options?: ZiteStepOptions): Promise<T>;
337
342
  /**
@@ -342,7 +347,8 @@ export interface ZiteStep {
342
347
  *
343
348
  * The run continues in a later call, which runs `execute` again from the
344
349
  * top: finished steps return their saved results, and code outside a step
345
- * runs again, so keep side effects inside steps.
350
+ * runs again, so keep side effects inside steps. Call it between steps, not
351
+ * inside a step's code: a step can't pause halfway, so a sleep there throws.
346
352
  */
347
353
  sleep(name: string, duration: ZiteStepDuration): Promise<void>;
348
354
  /** Pause the run until `when`, at most 30 days ahead. See {@link ZiteStep.sleep}. */
@@ -20,10 +20,18 @@
20
20
  * "@babel/parser": "^7.26.0"
21
21
  */
22
22
  import * as esbuild from 'esbuild';
23
+ import { type SourceRoot } from '../sourceRoots.js';
23
24
  export declare const UNSUPPORTED_IN_WORKERD: Set<string>;
24
25
  export declare const BASE_BUILD_OPTIONS: esbuild.BuildOptions;
25
26
  export declare function createAliasPlugin(opts: {
26
27
  baseDir?: string;
27
28
  sdkPath?: string;
28
29
  }): esbuild.Plugin;
30
+ export interface EndpointBundleResult {
31
+ bundledEndpoints: Record<string, string>;
32
+ endpointErrors?: Record<string, string>;
33
+ bundledAuthHooks?: string;
34
+ authHooksError?: string;
35
+ }
36
+ export declare function bundleEndpoints(baseDir: string, root: SourceRoot, endpointNames: string[], logLevel: esbuild.LogLevel): Promise<EndpointBundleResult>;
29
37
  export declare function runBundle(): Promise<void>;
@@ -366,7 +366,7 @@ import endpoint from '${entryImport}';
366
366
  globalThis.__endpoint = endpoint;
367
367
  `;
368
368
  }
369
- async function bundleEndpointsImpl(baseDir, root, endpointNames) {
369
+ export async function bundleEndpoints(baseDir, root, endpointNames, logLevel) {
370
370
  const bundledEndpoints = {};
371
371
  const endpointErrors = {};
372
372
  const aliasPlugin = createAliasPlugin({ baseDir });
@@ -403,7 +403,7 @@ async function bundleEndpointsImpl(baseDir, root, endpointNames) {
403
403
  resolveDir: `${baseDir}/src`,
404
404
  loader: 'ts',
405
405
  },
406
- logLevel: 'warning',
406
+ logLevel,
407
407
  plugins: [aliasPlugin],
408
408
  });
409
409
  if (result.warnings && result.warnings.length > 0) {
@@ -473,7 +473,7 @@ globalThis.__endpoint = endpoint;
473
473
  resolveDir: `${baseDir}/src`,
474
474
  loader: 'ts',
475
475
  },
476
- logLevel: 'warning',
476
+ logLevel,
477
477
  plugins: [aliasPlugin],
478
478
  });
479
479
  if (result.outputFiles && result.outputFiles.length > 0) {
@@ -500,14 +500,12 @@ globalThis.__endpoint = endpoint;
500
500
  }
501
501
  }
502
502
  }
503
- const output = JSON.stringify({
503
+ return {
504
504
  bundledEndpoints,
505
505
  endpointErrors: Object.keys(endpointErrors).length > 0 ? endpointErrors : undefined,
506
506
  bundledAuthHooks,
507
507
  authHooksError,
508
- });
509
- fs.writeFileSync('/tmp/zitejs-bundle-result.json', output);
510
- console.log(output);
508
+ };
511
509
  }
512
510
  async function bundleOneOffScriptImpl(scriptPath, sdkPath) {
513
511
  const rawScript = fs.readFileSync(scriptPath, 'utf-8');
@@ -625,5 +623,7 @@ export async function runBundle() {
625
623
  endpointNames = listEndpointNames(root, baseDir);
626
624
  }
627
625
  // Even with no endpoints, zite.auth.ts may still need bundling.
628
- return bundleEndpointsImpl(baseDir, root, endpointNames);
626
+ const output = JSON.stringify(await bundleEndpoints(baseDir, root, endpointNames, 'warning'));
627
+ fs.writeFileSync('/tmp/zitejs-bundle-result.json', output);
628
+ console.log(output);
629
629
  }
@@ -1,7 +1,9 @@
1
1
  import { execFileSync } from 'child_process';
2
+ import * as esbuild from 'esbuild';
2
3
  import { existsSync } from 'fs';
3
- import { join } from 'path';
4
- import { listEndpointNames, listSourceDirs } from '../sourceRoots.js';
4
+ import { join, resolve } from 'path';
5
+ import { bundleEndpoints } from '../bundle/index.js';
6
+ import { listEndpointNames, listSourceDirs, } from '../sourceRoots.js';
5
7
  /**
6
8
  * An argument array, not a command string, so no shell is involved.
7
9
  *
@@ -25,28 +27,9 @@ function run(file, args, cwd) {
25
27
  return { ok: false, output: (e.stderr ?? '') + (e.stdout ?? '') };
26
28
  }
27
29
  }
28
- /**
29
- * `zitejs bundle` reports per-endpoint failures inside its JSON payload and
30
- * still exits 0, so a non-empty `endpointErrors` is the only signal there is.
31
- */
32
- function bundleFailures(output) {
33
- const line = output
34
- .trim()
35
- .split('\n')
36
- .reverse()
37
- .find(l => l.startsWith('{'));
38
- if (!line)
39
- return ['bundle produced no result'];
40
- let result;
41
- try {
42
- result = JSON.parse(line);
43
- }
44
- catch {
45
- return [`could not parse bundle output: ${line.slice(0, 200)}`];
46
- }
30
+ async function bundleFailures(root, appPath, endpointNames) {
31
+ const result = await bundleEndpoints(resolve(appPath), root, endpointNames, 'silent').finally(() => esbuild.stop());
47
32
  const failures = [];
48
- if (result.error)
49
- failures.push(result.error);
50
33
  for (const [name, err] of Object.entries(result.endpointErrors ?? {})) {
51
34
  failures.push(`${name}: ${err}`);
52
35
  }
@@ -62,7 +45,7 @@ export async function runCheck() {
62
45
  process.exit(1);
63
46
  }
64
47
  let allPassed = true;
65
- for (const { root, dir: app, path: appPath } of appDirs) {
48
+ for (const { root, path: appPath } of appDirs) {
66
49
  console.log(`\n── ${appPath} ──`);
67
50
  // Only tsconfig.app.json compiles anything. The app's tsconfig.json is a
68
51
  // solution-style config — `"files": []` plus a reference — so
@@ -89,10 +72,10 @@ export async function runCheck() {
89
72
  // Endpoints never reach vite — they are bundled separately for the lambda,
90
73
  // against a different resolver. tsc and vite both pass on an endpoint whose
91
74
  // `zitejs/*` alias has no generated file behind it; only the bundler knows.
92
- if (listEndpointNames(root, appPath).length > 0) {
75
+ const endpointNames = listEndpointNames(root, appPath);
76
+ if (endpointNames.length > 0) {
93
77
  process.stdout.write(' bundle endpoints ... ');
94
- const bundle = run('npx', ['zitejs', 'bundle', '--app', app], '.');
95
- const failures = bundle.ok ? bundleFailures(bundle.output) : [bundle.output];
78
+ const failures = await bundleFailures(root, appPath, endpointNames);
96
79
  if (failures.length === 0) {
97
80
  console.log('✓');
98
81
  }
@@ -275,6 +275,10 @@ export declare class Zite {
275
275
  sortEnabled?: boolean | undefined;
276
276
  resultType?: "number" | "boolean" | "date" | "array" | "text" | undefined;
277
277
  };
278
+ } | {
279
+ name: string;
280
+ type: "created_by";
281
+ template: globalThis.Record<string, never>;
278
282
  } | {
279
283
  name: string;
280
284
  type: "updated_by";
@@ -488,6 +492,10 @@ export declare class Zite {
488
492
  sortEnabled?: boolean | undefined;
489
493
  resultType?: "number" | "boolean" | "date" | "array" | "text" | undefined;
490
494
  };
495
+ } | {
496
+ name: string;
497
+ type: "created_by";
498
+ template: globalThis.Record<string, never>;
491
499
  } | {
492
500
  name: string;
493
501
  type: "updated_by";
@@ -711,6 +719,10 @@ export declare class Zite {
711
719
  sortEnabled?: boolean | undefined;
712
720
  resultType?: "number" | "boolean" | "date" | "array" | "text" | undefined;
713
721
  };
722
+ } | {
723
+ name: string;
724
+ type: "created_by";
725
+ template: globalThis.Record<string, never>;
714
726
  } | {
715
727
  name: string;
716
728
  type: "updated_by";
@@ -937,6 +949,10 @@ export declare class Zite {
937
949
  sortEnabled?: boolean | undefined;
938
950
  resultType?: "number" | "boolean" | "date" | "array" | "text" | undefined;
939
951
  };
952
+ } | {
953
+ name: string;
954
+ type: "created_by";
955
+ template: globalThis.Record<string, never>;
940
956
  } | {
941
957
  name: string;
942
958
  type: "updated_by";
@@ -1171,6 +1187,10 @@ export declare class Zite {
1171
1187
  sortEnabled?: boolean | undefined;
1172
1188
  resultType?: "number" | "boolean" | "date" | "array" | "text" | undefined;
1173
1189
  };
1190
+ } | {
1191
+ name: string;
1192
+ type: "created_by";
1193
+ template: globalThis.Record<string, never>;
1174
1194
  } | {
1175
1195
  name: string;
1176
1196
  type: "updated_by";
@@ -1406,6 +1426,10 @@ export declare class Zite {
1406
1426
  sortEnabled?: boolean | undefined;
1407
1427
  resultType?: "number" | "boolean" | "date" | "array" | "text" | undefined;
1408
1428
  };
1429
+ } | {
1430
+ name: string;
1431
+ type: "created_by";
1432
+ template: globalThis.Record<string, never>;
1409
1433
  } | {
1410
1434
  name: string;
1411
1435
  type: "updated_by";
@@ -72,8 +72,8 @@ const FIELDS_BY_TYPE = {
72
72
  // one host to call.
73
73
  pipedrive: extras("apiBaseUrl"),
74
74
  // Shopify has no global API host: every call goes to the store's own domain
75
- // under a pinned API version. The storefront pair is the shopper-facing API,
76
- // which installs predating those scopes do not have.
75
+ // under a pinned API version. The storefront pair is the shopper-facing API;
76
+ // its URL comes from the store domain, so only the token can be missing.
77
77
  shopify: extras("shopDomain", "apiBaseUrl", "storefrontApiUrl", "storefrontAccessToken"),
78
78
  sharepoint: extras(),
79
79
  excel: extras(),
@@ -93,7 +93,9 @@ export const OPTIONAL_CREDENTIAL_FIELDS = {
93
93
  // Only S3-compatible providers set an endpoint, and a prefix is opt-in.
94
94
  amazonS3: ["endpoint", "pathPrefix"],
95
95
  snowflake: ["warehouse"],
96
- shopify: ["storefrontApiUrl", "storefrontAccessToken"],
96
+ // A store that didn't grant the storefront scopes gets no token, and
97
+ // Shopify then serves the Storefront API tokenless.
98
+ shopify: ["storefrontAccessToken"],
97
99
  };
98
100
  /**
99
101
  * Types the runtime never serves: those with a generated client (Airtable, email,