@lark-base-open/base-database-toolchain 1.5.0 → 1.6.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.6.0] - 2026-12-02
4
+
5
+ ### Added
6
+
7
+ - Accept Durable Trigger declarations with `type: "webhook"` in the Node API and JSON subprocess. Declare an `id` and optionally `enabled`. The Webhook POST body supplies the Function input, so the declaration does not accept static `input` or `map` fields.
8
+ - For projects that declare Webhooks, check a local limit of 10 Webhook declarations and 20 total Trigger declarations. Effective quotas are still checked at deployment. Local validation for projects with only Timer and Record triggers is unchanged.
9
+
10
+ ## [1.5.1] - 2026-12-01
11
+
12
+ ### Fixed
13
+
14
+ - Report all Functions with contract errors in one run. For unsupported input schema keywords, show their locations and suggest supported alternatives where available.
15
+ - Convert Zod input literals to single-value enums for Edge Functions while preserving existing output, Durable, and runtime-only contracts.
16
+ - Generate contracts for `z.null()` outputs. For Functions previously generated in runtime-only mode because of this issue, run `contracts generate` again if `check` reports `CONTRACT_STALE`.
17
+ - Explain how to place a root-level input union inside a `z.object()` property when generating Function contracts.
18
+
3
19
  ## [1.5.0] - 2026-11-30
4
20
 
5
21
  ### Removed
@@ -10,6 +10,7 @@ const ALLOWED = new Set([
10
10
  'lazy',
11
11
  'literal',
12
12
  'never',
13
+ 'null',
13
14
  'nullable',
14
15
  'number',
15
16
  'object',
@@ -4,6 +4,7 @@ interface SQLParamMeta {
4
4
  description?: string;
5
5
  enum?: unknown[];
6
6
  }
7
+ export declare function inputConstToEnum(node: unknown): void;
7
8
  export declare function normalizeFunctionInputSchema(value: unknown, source: string): string;
8
9
  export declare function sqlParamSchema(param: SQLParamMeta, index: number): {
9
10
  enum: unknown[];
@@ -249,8 +249,70 @@ function validateSchemaNode(value, path, depth, state) {
249
249
  }
250
250
  }
251
251
  }
252
+ const SCHEMA_MAPS = new Set(['properties', 'patternProperties', '$defs']);
253
+ const SCHEMA_LISTS = new Set(['oneOf', 'anyOf', 'allOf', 'prefixItems']);
254
+ const SCHEMA_SINGLES = new Set([
255
+ 'items',
256
+ 'additionalProperties',
257
+ 'propertyNames',
258
+ 'contains',
259
+ 'not',
260
+ ]);
261
+ // Zod writes literals as `const`, which the Edge inputSchema subset does not
262
+ // accept; a single-value `enum` validates the same values. Output and Durable
263
+ // schemas accept `const` and keep it, so their generated contracts stay stable.
264
+ export function inputConstToEnum(node) {
265
+ if (!node || typeof node !== 'object' || Array.isArray(node))
266
+ return;
267
+ const schema = node;
268
+ if (Object.hasOwn(schema, 'const') && !Object.hasOwn(schema, 'enum')) {
269
+ schema.enum = [schema.const];
270
+ delete schema.const;
271
+ }
272
+ for (const [key, child] of Object.entries(schema)) {
273
+ if (SCHEMA_MAPS.has(key) && child && typeof child === 'object')
274
+ Object.values(child).forEach(inputConstToEnum);
275
+ else if (SCHEMA_LISTS.has(key) && Array.isArray(child))
276
+ child.forEach(inputConstToEnum);
277
+ else if (SCHEMA_SINGLES.has(key))
278
+ inputConstToEnum(child);
279
+ }
280
+ }
281
+ const KEYWORD_REPLACEMENTS = {
282
+ const: 'use enum with one value',
283
+ format: 'describe the format and validate it in the handler',
284
+ $ref: 'inline the type; recursive or reused schemas such as z.lazy() and z.json() are not supported in inputs',
285
+ $defs: 'inline the type; recursive or reused schemas such as z.lazy() and z.json() are not supported in inputs',
286
+ propertyNames: 'declare known properties with z.object(); records are not supported in inputs',
287
+ };
288
+ // Lists every unsupported keyword at once, walking the positions the validator
289
+ // descends into, so one generate run names all of them instead of the first.
290
+ function collectUnsupportedKeywords(value, path, out) {
291
+ if (!isRecord(value))
292
+ return;
293
+ for (const keyword of Object.keys(value)) {
294
+ if (ALLOWED_KEYWORDS.has(keyword))
295
+ continue;
296
+ const replacement = KEYWORD_REPLACEMENTS[keyword];
297
+ out.push(`${path}: ${JSON.stringify(keyword)}${replacement ? ` (${replacement})` : ''}`);
298
+ }
299
+ if (isRecord(value.properties))
300
+ for (const [name, child] of Object.entries(value.properties))
301
+ collectUnsupportedKeywords(child, `${path}.properties[${JSON.stringify(name)}]`, out);
302
+ collectUnsupportedKeywords(value.items, `${path}.items`, out);
303
+ collectUnsupportedKeywords(value.additionalProperties, `${path}.additionalProperties`, out);
304
+ for (const key of ['prefixItems', 'oneOf', 'anyOf']) {
305
+ const children = value[key];
306
+ if (Array.isArray(children))
307
+ children.forEach((child, index) => collectUnsupportedKeywords(child, `${path}.${key}[${index}]`, out));
308
+ }
309
+ }
252
310
  export function normalizeFunctionInputSchema(value, source) {
253
311
  const schema = JSON.stringify(value);
312
+ const unsupported = [];
313
+ collectUnsupportedKeywords(JSON.parse(schema), source, unsupported);
314
+ if (unsupported.length)
315
+ throw new Error(`Invalid inputSchema: ${unsupported.length} unsupported keyword${unsupported.length > 1 ? 's' : ''}: ${unsupported.join('; ')}. Supported keywords: ${[...ALLOWED_KEYWORDS].join(', ')}`);
254
316
  validateSchemaNode(JSON.parse(schema), source, 1, { nodes: 0 });
255
317
  if (Buffer.byteLength(schema, 'utf8') > MAX_SCHEMA_BYTES) {
256
318
  schemaError(source, 'exceeds 32 KiB');
@@ -578,7 +640,10 @@ export function deriveSQLInputSchema(meta, sql) {
578
640
  export function checkFaaSInputSchemaContract(value, file) {
579
641
  const result = { problems: [], hints: [] };
580
642
  if (!isRecord(value) || value.type !== 'object') {
581
- result.problems.push('inputSchema.type must be "object"');
643
+ result.problems.push(isRecord(value) &&
644
+ (value.oneOf !== undefined || value.anyOf !== undefined)
645
+ ? 'inputSchema.type must be "object"; a Zod union at the root becomes oneOf/anyOf. Keep the root a z.object() and put the union in a property, for example z.object({ command: z.discriminatedUnion("action", [...]).describe("...") })'
646
+ : 'inputSchema.type must be "object"');
582
647
  return result;
583
648
  }
584
649
  const properties = isRecord(value.properties) ? value.properties : {};
@@ -23,7 +23,7 @@ import { projectLayout } from './project-layout.js';
23
23
  import { sourceArchiveEntryIgnored } from './source-archive-inputs.js';
24
24
  import { inspectPage } from './page-inspection.js';
25
25
  import { parse as parseJSONC } from 'jsonc-parser';
26
- import { namedSQLParamSchema, checkSQLFunctionParameters, normalizeFunctionInputSchema, checkFaaSInputSchemaContract, } from './function-schema.js';
26
+ import { namedSQLParamSchema, checkSQLFunctionParameters, normalizeFunctionInputSchema, checkFaaSInputSchemaContract, inputConstToEnum, } from './function-schema.js';
27
27
  import { checkDeclaredParameters, mutationEnumType, } from './function-params.js';
28
28
  import { validateFunctionDescription, functionDescriptionHint, } from './function-description.js';
29
29
  import { readMutationMetaItem } from './mutation.js';
@@ -53,6 +53,7 @@ export async function runCompiler(request) {
53
53
  const localSQLSources = Object.create(null);
54
54
  const triggerLocations = [];
55
55
  let triggerCount = 0;
56
+ let webhookCount = 0;
56
57
  const permissionFlag = process.allowedNodeEnvironmentFlags.has('--permission')
57
58
  ? '--permission'
58
59
  : '--experimental-permission';
@@ -241,82 +242,105 @@ export async function runCompiler(request) {
241
242
  schema.description = param.description;
242
243
  return schema;
243
244
  }
244
- function collectDatabaseContracts(functions, inputs, bindBatch) {
245
+ function collectDatabaseContracts(functions, inputs, bindBatch, failures) {
245
246
  for (const [directory, type] of [
246
247
  ['database-functions', 1],
247
248
  ['mutations', 5],
248
249
  ]) {
249
250
  for (const id of entries(path.join(root, directory))) {
250
- const metadata = readJSON(path.join(root, directory, id, 'meta.json'));
251
- assertMetadataKeys(type === 1 ? 'sql' : 'mutation', id, metadata);
252
- validateFunctionDescription(metadata.description, metadata.name, path.join(directory, id, 'meta.json'));
253
- const descriptionHint = functionDescriptionHint(metadata.description, path.join(directory, id, 'meta.json'));
254
- if (descriptionHint)
255
- functionHints.push({ ...descriptionHint, functionId: id });
256
- const file = path.join(directory, id, type === 1 ? 'meta.json' : 'spec.json');
257
- let params, declared;
258
- if (type === 1) {
259
- let meta = metadata.meta;
260
- if (meta === undefined)
261
- meta = { params: [] };
262
- else if (!meta || typeof meta !== 'object' || Array.isArray(meta))
263
- throw Error(file + ': meta must be an object containing a params array.');
264
- else if (!Object.hasOwn(meta, 'params'))
265
- meta = { ...meta, params: [] };
266
- const sqlPath = safe(path.join(root, directory, id, 'main.sql'));
267
- // Metadata-only codegen can run before SQL is authored. The Go
268
- // project check requires complete declarations before any upload.
269
- let sql;
270
- if (fs.existsSync(sqlPath) || bindBatch) {
271
- sql = fs.readFileSync(sqlPath, 'utf8');
272
- if (bindBatch)
273
- localSQLSources[id] =
274
- 'sha256:' + digest(JSON.stringify({ sql, meta }));
251
+ try {
252
+ const metadata = readJSON(path.join(root, directory, id, 'meta.json'));
253
+ assertMetadataKeys(type === 1 ? 'sql' : 'mutation', id, metadata);
254
+ validateFunctionDescription(metadata.description, metadata.name, path.join(directory, id, 'meta.json'));
255
+ const descriptionHint = functionDescriptionHint(metadata.description, path.join(directory, id, 'meta.json'));
256
+ if (descriptionHint)
257
+ functionHints.push({ ...descriptionHint, functionId: id });
258
+ const file = path.join(directory, id, type === 1 ? 'meta.json' : 'spec.json');
259
+ let params, declared;
260
+ if (type === 1) {
261
+ let meta = metadata.meta;
262
+ if (meta === undefined)
263
+ meta = { params: [] };
264
+ else if (!meta || typeof meta !== 'object' || Array.isArray(meta))
265
+ throw Error(file + ': meta must be an object containing a params array.');
266
+ else if (!Object.hasOwn(meta, 'params'))
267
+ meta = { ...meta, params: [] };
268
+ const sqlPath = safe(path.join(root, directory, id, 'main.sql'));
269
+ // Metadata-only codegen can run before SQL is authored. The Go
270
+ // project check requires complete declarations before any upload.
271
+ let sql;
272
+ if (fs.existsSync(sqlPath) || bindBatch) {
273
+ sql = fs.readFileSync(sqlPath, 'utf8');
274
+ if (bindBatch)
275
+ localSQLSources[id] =
276
+ 'sha256:' + digest(JSON.stringify({ sql, meta }));
277
+ }
278
+ params = meta.params ?? [];
279
+ declared = checkSQLFunctionParameters(params, sql, file);
275
280
  }
276
- params = meta.params ?? [];
277
- declared = checkSQLFunctionParameters(params, sql, file);
278
- }
279
- else {
280
- readMutationMetaItem(safe(path.join(root, directory, id, 'meta.json')), root);
281
- params =
282
- readJSON(path.join(root, directory, id, 'spec.json')).params ?? [];
283
- declared = checkDeclaredParameters(params, {
284
- label: 'spec.params',
285
- pointer: '/params',
286
- file,
287
- enumType: mutationEnumType,
281
+ else {
282
+ readMutationMetaItem(safe(path.join(root, directory, id, 'meta.json')), root);
283
+ params =
284
+ readJSON(path.join(root, directory, id, 'spec.json')).params ??
285
+ [];
286
+ declared = checkDeclaredParameters(params, {
287
+ label: 'spec.params',
288
+ pointer: '/params',
289
+ file,
290
+ enumType: mutationEnumType,
291
+ });
292
+ }
293
+ if (declared.problems.length) {
294
+ if (type !== 1)
295
+ throw Error(declared.problems.join('; '));
296
+ const advice = declared.hints
297
+ .filter((h) => h.kind === 'parameter_declaration')
298
+ .map((h) => h.message);
299
+ throw Error(`${file}: ${[...declared.problems, ...advice].join(' ')}`);
300
+ }
301
+ functionHints.push(...declared.hints.map((hint) => ({ ...hint, functionId: id })));
302
+ const input = {
303
+ type: 'object',
304
+ properties: Object.fromEntries(params.map((p, index) => {
305
+ return [p.name, parameterSchema(p, type, index)];
306
+ })),
307
+ required: params
308
+ .filter((p) => type === 1 || p.required !== false)
309
+ .map((p) => p.name),
310
+ additionalProperties: false,
311
+ };
312
+ functions.push({ functionId: id, functionType: type, input });
313
+ inputs.push({
314
+ functionId: id,
315
+ functionType: type,
316
+ inputSchema: input,
317
+ parameters: params,
318
+ parameterOptions: Object.fromEntries(params.filter((p) => p.enum).map((p) => [p.name, p.enum])),
288
319
  });
289
320
  }
290
- if (declared.problems.length) {
291
- if (type !== 1)
292
- throw Error(declared.problems.join('; '));
293
- const advice = declared.hints
294
- .filter((h) => h.kind === 'parameter_declaration')
295
- .map((h) => h.message);
296
- throw Error(`${file}: ${[...declared.problems, ...advice].join(' ')}`);
321
+ catch (error) {
322
+ contractFailure(failures, path.join(directory, id), error);
297
323
  }
298
- functionHints.push(...declared.hints.map((hint) => ({ ...hint, functionId: id })));
299
- const input = {
300
- type: 'object',
301
- properties: Object.fromEntries(params.map((p, index) => {
302
- return [p.name, parameterSchema(p, type, index)];
303
- })),
304
- required: params
305
- .filter((p) => type === 1 || p.required !== false)
306
- .map((p) => p.name),
307
- additionalProperties: false,
308
- };
309
- functions.push({ functionId: id, functionType: type, input });
310
- inputs.push({
311
- functionId: id,
312
- functionType: type,
313
- inputSchema: input,
314
- parameters: params,
315
- parameterOptions: Object.fromEntries(params.filter((p) => p.enum).map((p) => [p.name, p.enum])),
316
- });
317
324
  }
318
325
  }
319
326
  }
327
+ // Each Function is checked independently, so one generate run reports every
328
+ // failing Function; a stale manifest stays a single project-wide answer.
329
+ function contractFailure(failures, label, error) {
330
+ const message = error instanceof Error ? error.message : String(error);
331
+ if (message.startsWith('CONTRACT_STALE'))
332
+ throw error;
333
+ failures.push(`${label}: ${message}`);
334
+ }
335
+ function throwContractFailures(failures) {
336
+ if (failures.length === 1)
337
+ throw Error(failures[0]);
338
+ if (failures.length)
339
+ throw Error(`${failures.length} Functions have contract problems; fix all of them, then regenerate contracts:\n` +
340
+ failures
341
+ .map((failure, index) => `${index + 1}. ${failure}`)
342
+ .join('\n'));
343
+ }
320
344
  async function isolatedCodegen(input) {
321
345
  return runSDKCodegen(root, input, server);
322
346
  }
@@ -377,7 +401,7 @@ export async function runCompiler(request) {
377
401
  normalizeFunctionInputSchema(schema, file);
378
402
  const declared = checkFaaSInputSchemaContract(schema, file);
379
403
  if (declared.problems.length)
380
- throw Error(`${file}: ${declared.problems.join('; ')}. Fix descriptions in this source and regenerate contracts.`);
404
+ throw Error(`${file}: ${declared.problems.join('; ')}. Fix this source and regenerate contracts.`);
381
405
  functionHints.push(...declared.hints.map((hint) => ({ ...hint, functionId: id })));
382
406
  const ajv = new Ajv2020({ strict: false, validateFormats: false });
383
407
  if (!ajv.validateSchema(schema))
@@ -387,6 +411,7 @@ export async function runCompiler(request) {
387
411
  validateTriggerDeclarations(value, input, directory + '/meta.json', triggerIDs);
388
412
  if (value?.length) {
389
413
  triggerCount += value.length;
414
+ webhookCount += value.filter(({ type }) => type === 'webhook').length;
390
415
  triggerLocations.push(path.relative(root, directory) + '/meta.json');
391
416
  }
392
417
  }
@@ -482,121 +507,138 @@ export async function runCompiler(request) {
482
507
  triggerIDs.clear();
483
508
  triggerLocations.length = 0;
484
509
  triggerCount = 0;
510
+ webhookCount = 0;
485
511
  const changes = [];
512
+ const failures = [];
486
513
  for (const kind of ['functions', 'durable'])
487
514
  for (const id of entries(path.join(serverRoot, kind))) {
488
- const directory = path.join(serverRoot, kind, id), entry = path.join(directory, 'index.ts');
489
- if (!fs.existsSync(entry))
490
- throw Error('Missing Function entry ' + id);
491
- const metaFile = path.join(directory, 'meta.json');
492
- const declaredMeta = readJSON(safe(metaFile));
493
- validateFunctionDescription(declaredMeta.description, declaredMeta.name, metaFile);
494
- const descriptionHint = functionDescriptionHint(declaredMeta.description, metaFile);
495
- if (descriptionHint)
496
- functionHints.push({ ...descriptionHint, functionId: id });
497
- const decl = definition(entry);
498
- if (!decl) {
499
- const meta = readJSON(path.join(directory, 'meta.json'));
515
+ try {
516
+ const directory = path.join(serverRoot, kind, id), entry = path.join(directory, 'index.ts');
517
+ if (!fs.existsSync(entry))
518
+ throw Error('Missing Function entry ' + id);
519
+ const metaFile = path.join(directory, 'meta.json');
520
+ const declaredMeta = readJSON(safe(metaFile));
521
+ validateFunctionDescription(declaredMeta.description, declaredMeta.name, metaFile);
522
+ const descriptionHint = functionDescriptionHint(declaredMeta.description, metaFile);
523
+ if (descriptionHint)
524
+ functionHints.push({ ...descriptionHint, functionId: id });
525
+ const decl = definition(entry);
526
+ if (!decl) {
527
+ const meta = readJSON(path.join(directory, 'meta.json'));
528
+ if (kind === 'durable')
529
+ throw Error('Durable entry must use defineDurableFunction: ' + id);
530
+ if (meta.inputSchema) {
531
+ validateFunctionInput(meta.inputSchema, id);
532
+ functions.push({
533
+ functionId: id,
534
+ functionType: 2,
535
+ input: meta.inputSchema,
536
+ });
537
+ inputs.push({
538
+ functionId: id,
539
+ functionType: 2,
540
+ inputSchema: meta.inputSchema,
541
+ parameterOptions: {},
542
+ });
543
+ }
544
+ continue;
545
+ }
546
+ if (kind === 'functions')
547
+ generatedContractIds.add(id);
548
+ const converted = await schemas(directory, decl);
549
+ const metaPath = path.join(directory, 'meta.json'), meta = readJSON(metaPath);
550
+ if (kind === 'durable')
551
+ converted.events ??= {};
552
+ if (kind === 'durable' && (!converted.input || !converted.output))
553
+ throw Error('Durable contracts must be representable: ' +
554
+ converted.warnings.join('; '));
555
+ const runtimeOnly = kind !== 'durable' &&
556
+ ((write
557
+ ? request.runtimeOnly
558
+ : meta.contract?.mode === 'runtime-only') ||
559
+ !converted.input ||
560
+ !converted.output);
561
+ // Only a discovery contract carries an inputSchema the platform
562
+ // checks; runtime-only contracts keep their hash and stay current.
563
+ if (kind === 'functions' && !runtimeOnly)
564
+ inputConstToEnum(converted.input);
565
+ const contract = {
566
+ version: 1,
567
+ generatorVersion: 'lark-cli',
568
+ sdkVersion: null,
569
+ schemaVendor: 'zod',
570
+ schemaPackageVersion: null,
571
+ schemaHash: 'sha256:' + digest(JSON.stringify(converted)),
572
+ fidelity: runtimeOnly ? 'runtime-only' : 'complete',
573
+ mode: runtimeOnly ? 'runtime-only' : 'discovery',
574
+ warnings: converted.warnings,
575
+ };
576
+ const next = { ...meta, contract };
577
+ if (!runtimeOnly) {
578
+ next.inputSchema = converted.input;
579
+ next.outputSchema = converted.output;
580
+ }
581
+ else {
582
+ delete next.inputSchema;
583
+ delete next.outputSchema;
584
+ }
585
+ if (!write &&
586
+ (!equal(meta.inputSchema, next.inputSchema) ||
587
+ !equal(meta.outputSchema, next.outputSchema) ||
588
+ !equal(meta.contract, contract)))
589
+ stale();
590
+ if (kind === 'durable') {
591
+ next.events = converted.events;
592
+ if (!write && !equal(meta.events, next.events))
593
+ stale();
594
+ }
595
+ if (converted.warnings.length)
596
+ process.stderr.write(converted.warnings.join('\n') + '\n');
500
597
  if (kind === 'durable')
501
- throw Error('Durable entry must use defineDurableFunction: ' + id);
502
- if (meta.inputSchema) {
503
- validateFunctionInput(meta.inputSchema, id);
598
+ validateTriggers(meta.triggers, converted.input, directory);
599
+ else if (!runtimeOnly)
600
+ validateFunctionInput(converted.input, id, path.join(directory, 'contract.ts'));
601
+ if (write)
602
+ changes.push([metaPath, next]);
603
+ if (kind === 'durable') {
604
+ durable.push({
605
+ functionId: id,
606
+ inputSchema: converted.input,
607
+ outputSchema: converted.output,
608
+ events: converted.events,
609
+ });
610
+ const source = `typeof import(${JSON.stringify(`../../durable/${id}/contract.js`)})`;
611
+ const registryEntry = (source) => `${JSON.stringify(id)}: { input: z.input<${source}[${JSON.stringify(decl.fields.input)}]>; output: z.output<${source}[${JSON.stringify(decl.fields.output)}]>; events: ${decl.fields.events ? `{ [E in keyof ${source}[${JSON.stringify(decl.fields.events)}]]: z.input<${source}[${JSON.stringify(decl.fields.events)}][E]> }` : '{}'} };`;
612
+ durableTypes.push(registryEntry(source));
613
+ durableCommonJSTypes.push(registryEntry(`typeof import(${JSON.stringify(`../../durable/${id}/contract.js`)}, { with: { "resolution-mode": "import" } })`));
614
+ }
615
+ else {
504
616
  functions.push({
505
617
  functionId: id,
506
618
  functionType: 2,
507
- input: meta.inputSchema,
619
+ input: converted.input ?? {},
620
+ output: converted.output ?? {},
621
+ contract,
508
622
  });
509
623
  inputs.push({
510
624
  functionId: id,
511
625
  functionType: 2,
512
- inputSchema: meta.inputSchema,
626
+ inputSchema: converted.input ?? {},
513
627
  parameterOptions: {},
514
628
  });
515
629
  }
516
- continue;
517
- }
518
- if (kind === 'functions')
519
- generatedContractIds.add(id);
520
- const converted = await schemas(directory, decl);
521
- const metaPath = path.join(directory, 'meta.json'), meta = readJSON(metaPath);
522
- if (kind === 'durable')
523
- converted.events ??= {};
524
- if (kind === 'durable' && (!converted.input || !converted.output))
525
- throw Error('Durable contracts must be representable: ' +
526
- converted.warnings.join('; '));
527
- const runtimeOnly = kind !== 'durable' &&
528
- ((write
529
- ? request.runtimeOnly
530
- : meta.contract?.mode === 'runtime-only') ||
531
- !converted.input ||
532
- !converted.output);
533
- const contract = {
534
- version: 1,
535
- generatorVersion: 'lark-cli',
536
- sdkVersion: null,
537
- schemaVendor: 'zod',
538
- schemaPackageVersion: null,
539
- schemaHash: 'sha256:' + digest(JSON.stringify(converted)),
540
- fidelity: runtimeOnly ? 'runtime-only' : 'complete',
541
- mode: runtimeOnly ? 'runtime-only' : 'discovery',
542
- warnings: converted.warnings,
543
- };
544
- const next = { ...meta, contract };
545
- if (!runtimeOnly) {
546
- next.inputSchema = converted.input;
547
- next.outputSchema = converted.output;
548
- }
549
- else {
550
- delete next.inputSchema;
551
- delete next.outputSchema;
552
- }
553
- if (!write &&
554
- (!equal(meta.inputSchema, next.inputSchema) ||
555
- !equal(meta.outputSchema, next.outputSchema) ||
556
- !equal(meta.contract, contract)))
557
- stale();
558
- if (kind === 'durable') {
559
- next.events = converted.events;
560
- if (!write && !equal(meta.events, next.events))
561
- stale();
562
630
  }
563
- if (converted.warnings.length)
564
- process.stderr.write(converted.warnings.join('\n') + '\n');
565
- if (kind === 'durable')
566
- validateTriggers(meta.triggers, converted.input, directory);
567
- else if (!runtimeOnly)
568
- validateFunctionInput(converted.input, id, path.join(directory, 'contract.ts'));
569
- if (write)
570
- changes.push([metaPath, next]);
571
- if (kind === 'durable') {
572
- durable.push({
573
- functionId: id,
574
- inputSchema: converted.input,
575
- outputSchema: converted.output,
576
- events: converted.events,
577
- });
578
- const source = `typeof import(${JSON.stringify(`../../durable/${id}/contract.js`)})`;
579
- const registryEntry = (source) => `${JSON.stringify(id)}: { input: z.input<${source}[${JSON.stringify(decl.fields.input)}]>; output: z.output<${source}[${JSON.stringify(decl.fields.output)}]>; events: ${decl.fields.events ? `{ [E in keyof ${source}[${JSON.stringify(decl.fields.events)}]]: z.input<${source}[${JSON.stringify(decl.fields.events)}][E]> }` : '{}'} };`;
580
- durableTypes.push(registryEntry(source));
581
- durableCommonJSTypes.push(registryEntry(`typeof import(${JSON.stringify(`../../durable/${id}/contract.js`)}, { with: { "resolution-mode": "import" } })`));
582
- }
583
- else {
584
- functions.push({
585
- functionId: id,
586
- functionType: 2,
587
- input: converted.input ?? {},
588
- output: converted.output ?? {},
589
- contract,
590
- });
591
- inputs.push({
592
- functionId: id,
593
- functionType: 2,
594
- inputSchema: converted.input ?? {},
595
- parameterOptions: {},
596
- });
631
+ catch (error) {
632
+ contractFailure(failures, path.join('server', kind, id), error);
597
633
  }
598
634
  }
599
- collectDatabaseContracts(functions, inputs, !!(request.batchSnapshot || previous));
635
+ // Keep the existing deployment-only quota check for Timer/Record projects.
636
+ if (webhookCount > 0 && triggerCount > 20)
637
+ throw Error(`TRIGGER_LIMIT_EXCEEDED: Trigger declarations exceed the environment limit of 20 (declared ${triggerCount})`);
638
+ if (webhookCount > 10)
639
+ throw Error(`TRIGGER_LIMIT_EXCEEDED: Webhook trigger declarations exceed the site limit of 10 (declared ${webhookCount})`);
640
+ collectDatabaseContracts(functions, inputs, !!(request.batchSnapshot || previous), failures);
641
+ throwContractFailures(failures);
600
642
  let batchSnapshot;
601
643
  if (request.batchSnapshot || previous) {
602
644
  const errors = [];
@@ -620,7 +662,9 @@ export async function runCompiler(request) {
620
662
  status: 'not_run',
621
663
  declarations: triggerCount,
622
664
  locations: triggerLocations,
623
- reason: 'Local shape, IDs, static input and map target contracts checked. Source bindings and Owner permissions, source field Schema, condition operators/values, actual map source types, calendar/timezone semantics, platform minimum interval and Trigger quota are checked during deployment. The server validates the final merged Record input at startup; Function server validation does not cover these rules.',
665
+ reason: webhookCount > 0
666
+ ? 'Local shape, IDs, declaration limits, static input and map target contracts checked. Source bindings and Owner permissions, source field Schema, condition operators/values, actual map source types, calendar/timezone semantics, platform minimum interval and effective Trigger quota are checked during deployment. The server validates merged Record input and Webhook POST input at startup; Function server validation does not cover these rules.'
667
+ : 'Local shape, IDs, static input and map target contracts checked. Source bindings and Owner permissions, source field Schema, condition operators/values, actual map source types, calendar/timezone semantics, platform minimum interval and Trigger quota are checked during deployment. The server validates the final merged Record input at startup; Function server validation does not cover these rules.',
624
668
  });
625
669
  const clientPath = safe('page/src/generated/functions.ts');
626
670
  const pageSDK = true;
@@ -216,6 +216,22 @@ export declare const triggerDeclarationsSchema: {
216
216
  };
217
217
  };
218
218
  };
219
+ } | {
220
+ type: string;
221
+ additionalProperties: boolean;
222
+ required: string[];
223
+ properties: {
224
+ id: {
225
+ type: string;
226
+ pattern: string;
227
+ };
228
+ type: {
229
+ const: string;
230
+ };
231
+ enabled: {
232
+ type: string;
233
+ };
234
+ };
219
235
  })[];
220
236
  };
221
237
  };
@@ -163,6 +163,16 @@ export const triggerDeclarationsSchema = {
163
163
  },
164
164
  },
165
165
  },
166
+ {
167
+ type: 'object',
168
+ additionalProperties: false,
169
+ required: ['id', 'type'],
170
+ properties: {
171
+ id: identifier,
172
+ type: { const: 'webhook' },
173
+ enabled: { type: 'boolean' },
174
+ },
175
+ },
166
176
  ],
167
177
  },
168
178
  };
@@ -182,6 +192,12 @@ export function validateTriggerDeclarations(value, inputSchema, path, seen) {
182
192
  if (seen.has(trigger.id))
183
193
  throw new Error(`TRIGGER_ID_DUPLICATE: ${location}/id: ${trigger.id}`);
184
194
  seen.add(trigger.id);
195
+ if (trigger.type === 'webhook') {
196
+ // The POST supplies the entire input. Validate the contract, not a
197
+ // synthetic empty input.
198
+ ajv.compile(inputSchema);
199
+ continue;
200
+ }
185
201
  let staticSchema = inputSchema;
186
202
  if (trigger.type === 'record') {
187
203
  if (Buffer.byteLength(JSON.stringify(trigger)) > 64 * 1024)
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@lark-base-open/base-database-toolchain",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@lark-base-open/base-database-toolchain",
9
- "version": "1.5.0",
9
+ "version": "1.6.0",
10
10
  "license": "SEE LICENSE IN LICENSE",
11
11
  "dependencies": {
12
12
  "@babel/parser": "7.28.5",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-base-open/base-database-toolchain",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Shared local development toolchain for Base Database application CLIs",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",