@superdurable/connector-airtable 0.1.2 → 0.2.1

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/dist/index.js CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  ConfigSchema,
3
3
  Connection,
4
4
  ConnectorID,
5
+ CredentialMaterialError,
5
6
  FieldEqualityFilterSchema,
6
7
  GetRecordBranch,
7
8
  GetRecordBranchDefect,
@@ -46,10 +47,12 @@ import {
46
47
  UpsertRecordsInputSchema,
47
48
  UpsertRecordsMetadata,
48
49
  UpsertedRecordsSchema,
50
+ decodeCredentials,
51
+ isCredentialMaterialError,
49
52
  newConnection,
50
53
  newConnectionWithOperations,
51
54
  newProjectConnection
52
- } from "./chunk-T4RPDDJS.js";
55
+ } from "./chunk-XPD7RWH6.js";
53
56
 
54
57
  // src/generated/steps.ts
55
58
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -76,7 +79,7 @@ function newGetRecordStep(configuration) {
76
79
  ] });
77
80
  }
78
81
  function newUpsertRecordsStep(configuration) {
79
- const { connection, connectionName, upserted, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
82
+ const { connection, connectionName, upserted, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
80
83
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
81
84
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.upsertRecords(), connection: connection.reference, branches: [
82
85
  goToBranch("upserted", upserted),
@@ -86,7 +89,7 @@ function newUpsertRecordsStep(configuration) {
86
89
  ] });
87
90
  }
88
91
  function newUpdateRecordsStep(configuration) {
89
- const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
92
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
90
93
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
91
94
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateRecords(), connection: connection.reference, branches: [
92
95
  goToBranch("updated", updated),
@@ -104,6 +107,7 @@ import { z } from "zod";
104
107
  // src/client.ts
105
108
  import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
106
109
  import { ReauthorizationRequiredError, SecretString } from "@superdurable/connectors-sdk";
110
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
107
111
 
108
112
  // src/operations.ts
109
113
  import { newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
@@ -212,8 +216,8 @@ var UpsertRecordsOperation = class {
212
216
  if ([...createdRecordIds, ...updatedRecordIds].some((id) => !writtenIds.has(id)) || createdRecordIds.some((id) => updatedRecordIds.includes(id))) throw new Error("invalid upsert IDs");
213
217
  const partialSuccessReasons = decodePartialSuccessReasons(body.details);
214
218
  return newMutationBranch("upserted", { records, createdRecordIds, updatedRecordIds, ...partialSuccessReasons.length ? { partialSuccessReasons } : {} }, this.client.receipt(call, objectId));
215
- } catch {
216
- return mutationFailure("upsertRecords", "invalidResponse", "PROTOCOL", zeroUpserted, this.client.receipt(call, objectId));
219
+ } catch (error) {
220
+ return unusableAnswerRetry("upsertRecords", error);
217
221
  }
218
222
  }
219
223
  };
@@ -250,8 +254,8 @@ var UpdateRecordsOperation = class {
250
254
  if (records.some((record) => !requestedIds.has(record.id))) throw new Error("unexpected updated record");
251
255
  const partialSuccessReasons = decodePartialSuccessReasons(body.details);
252
256
  return newMutationBranch("updated", { records, ...partialSuccessReasons.length ? { partialSuccessReasons } : {} }, this.client.receipt(call, objectId));
253
- } catch {
254
- return mutationFailure("updateRecords", "invalidResponse", "PROTOCOL", zeroUpdated, this.client.receipt(call, objectId));
257
+ } catch (error) {
258
+ return unusableAnswerRetry("updateRecords", error);
255
259
  }
256
260
  }
257
261
  };
@@ -260,8 +264,10 @@ function queryOutcome(outcome, zero, rejectedBranch, notFoundBranch = rejectedBr
260
264
  const branch = outcome.disposition === "notFound" ? notFoundBranch : outcome.disposition === "offsetExpired" ? "offsetExpired" : outcome.disposition === "rejected" ? rejectedBranch : outcome.disposition;
261
265
  return newQueryBranch(branch, zero, outcome.receipt, outcome.failure);
262
266
  }
267
+ var definiteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
263
268
  function mutationOutcome(outcome, zero, rejectedBranch, notFoundBranch = rejectedBranch) {
264
- if (outcome.disposition === "retry") return newMutationRetry(outcome.failure, outcome.retryAfterMs);
269
+ const isUnknownStatus = outcome.status !== void 0 && (outcome.status < 200 || outcome.status >= 300) && !definiteRefusalStatuses.has(outcome.status);
270
+ if (outcome.disposition === "retry" || outcome.disposition === "invalidResponse" || isUnknownStatus) return newMutationRetry(outcome.failure, outcome.retryAfterMs);
265
271
  const branch = outcome.disposition === "notFound" ? notFoundBranch : outcome.disposition === "rejected" || outcome.disposition === "offsetExpired" ? rejectedBranch : outcome.disposition;
266
272
  return newMutationBranch(branch, zero, outcome.receipt, outcome.failure);
267
273
  }
@@ -274,6 +280,9 @@ function mutationDefect(operation, zero, error) {
274
280
  function queryFailure(operation, branch, kind, zero, receipt, error) {
275
281
  return newQueryBranch(branch, zero, receipt, { kind, provider: "airtable", operation, message: error instanceof Error ? error.message : "Airtable response is invalid" });
276
282
  }
283
+ function unusableAnswerRetry(operation, error) {
284
+ return newMutationRetry({ kind: "PROTOCOL", provider: "airtable", operation, message: error instanceof Error ? error.message : "Airtable response is invalid" });
285
+ }
277
286
  function mutationFailure(operation, branch, kind, zero, receipt, error) {
278
287
  return newMutationBranch(branch, zero, receipt, { kind, provider: "airtable", operation, message: error instanceof Error ? error.message : "Airtable response is invalid" });
279
288
  }
@@ -415,7 +424,15 @@ var defaultEndpoint = "https://api.airtable.com";
415
424
  var defaultMaxResponseBytes = 4194304;
416
425
  var requestTimeoutMs = 25e3;
417
426
  var rateLimitCooldownMs = 3e4;
427
+ var defaultPollIntervalMs = 3e4;
428
+ var defaultPollPageSize = 100;
418
429
  var AirtableClient = class {
430
+ /** Delay between recordChanged polls of one binding, in milliseconds; at least 1000, 30000 by default. */
431
+ pollIntervalMs;
432
+ /** Records one recordChanged poll request reads, 1 to 100, 100 by default. */
433
+ pollPageSize;
434
+ /** The recordChanged Trigger logger from AirtableClientOptions, or undefined for the SDK default. */
435
+ triggerLogger;
419
436
  endpoint;
420
437
  maxResponseBytes;
421
438
  credentials;
@@ -428,6 +445,11 @@ var AirtableClient = class {
428
445
  this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
429
446
  this.maxResponseBytes = config.maxResponseBytes || defaultMaxResponseBytes;
430
447
  if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("Airtable maxResponseBytes must be positive");
448
+ this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
449
+ if (!Number.isFinite(this.pollIntervalMs) || this.pollIntervalMs < 1e3) throw new TypeError("Airtable pollInterval must be at least one second");
450
+ this.pollPageSize = config.pollPageSize || defaultPollPageSize;
451
+ if (!Number.isSafeInteger(this.pollPageSize) || this.pollPageSize < 1 || this.pollPageSize > 100) throw new TypeError("Airtable pollPageSize must be from 1 to 100");
452
+ this.triggerLogger = options.logger;
431
453
  this.credentials = credentials;
432
454
  this.send = options.send ?? sendProviderRequest;
433
455
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
@@ -469,16 +491,16 @@ var AirtableClient = class {
469
491
  return { outcome: this.failure("retry", operation, "AVAILABILITY", "the Step ended while waiting for an Airtable request slot") };
470
492
  }
471
493
  }
472
- let token;
494
+ let credentials;
473
495
  try {
474
- const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
475
- if (!(credentials.personalAccessToken instanceof SecretString)) throw new TypeError("invalid Airtable token");
476
- token = credentials.personalAccessToken.reveal();
477
- if (!isHeaderSafeCredential(token)) throw new TypeError("invalid Airtable token");
496
+ credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
478
497
  } catch (error) {
479
498
  if (error instanceof ReauthorizationRequiredError) return { outcome: this.failure("rejected", operation, "AUTHENTICATION", "the Airtable connection must be authorized again") };
480
- return { outcome: this.failure("defect", operation, "AUTHENTICATION", "Airtable connection credentials are unavailable") };
499
+ if (isTerminalCredentialError(error)) return { outcome: this.failure("defect", operation, "AUTHENTICATION", "Airtable connection credentials are unavailable") };
500
+ return { outcome: this.failure("retry", operation, "AVAILABILITY", "Airtable connection credentials are temporarily unavailable") };
481
501
  }
502
+ const token = credentials.personalAccessToken instanceof SecretString ? credentials.personalAccessToken.reveal() : "";
503
+ if (!token || !isHeaderSafeCredential(token)) return { outcome: this.failure("defect", operation, "AUTHENTICATION", "Airtable connection credentials are unavailable") };
482
504
  let encoded;
483
505
  try {
484
506
  if (body !== void 0) encoded = Buffer.from(JSON.stringify(body), "utf8");
@@ -499,11 +521,11 @@ var AirtableClient = class {
499
521
  signal: call.context.cancellationSignal
500
522
  });
501
523
  } catch (error) {
502
- if (error instanceof BodyTooLargeError) return { outcome: this.failure("invalidResponse", operation, "RESPONSE_TOO_LARGE", "Airtable response exceeds the configured size limit", receipt) };
524
+ if (error instanceof BodyTooLargeError) return { outcome: { ...this.failure("invalidResponse", operation, "RESPONSE_TOO_LARGE", "Airtable response exceeds the configured size limit", receipt), ...error.status !== void 0 ? { status: error.status } : {} } };
503
525
  return { outcome: this.failure("retry", operation, "TRANSPORT", "Airtable did not return a complete response", receipt) };
504
526
  }
505
527
  if (response.status >= 200 && response.status < 300) return { response };
506
- return { outcome: this.classifyResponse(operation, baseId, response, receipt) };
528
+ return { outcome: { ...this.classifyResponse(operation, baseId, response, receipt), status: response.status } };
507
529
  }
508
530
  reserveRequestSlot(baseId) {
509
531
  const now = this.now().getTime();
@@ -533,6 +555,9 @@ var AirtableClient = class {
533
555
  return { disposition, failure: { kind, provider: "airtable", operation, message }, receipt, retryAfterMs };
534
556
  }
535
557
  };
558
+ function isTerminalCredentialError(error) {
559
+ return error instanceof ReauthorizationRequiredError || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || isCredentialMaterialError(error);
560
+ }
536
561
  function header(response, name) {
537
562
  const value = response.headers[name];
538
563
  return Array.isArray(value) ? value[0] ?? "" : value ?? "";
@@ -560,11 +585,22 @@ function waitForSlot(delayMs, signal) {
560
585
  }
561
586
 
562
587
  // src/project.ts
563
- function newProjectConnection2(project, connectionName) {
588
+ function newProjectConnection2(project, connectionName, options = {}) {
564
589
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
565
590
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "airtable" && entry.connectionName === name);
566
591
  if (!selected) throw new TypeError("Airtable project connection is not configured");
567
- const config = z.object({ endpoint: z.string().optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
592
+ const settings = z.object({
593
+ endpoint: z.string().optional(),
594
+ maxResponseBytes: z.number().int().optional(),
595
+ pollInterval: z.number().int().nonnegative().optional(),
596
+ pollPageSize: z.number().int().optional()
597
+ }).parse(selected.configuration);
598
+ const config = {
599
+ ...settings.endpoint !== void 0 ? { endpoint: settings.endpoint } : {},
600
+ ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
601
+ ...settings.pollInterval ? { pollIntervalMs: Math.ceil(settings.pollInterval / 1e6) } : {},
602
+ ...settings.pollPageSize !== void 0 ? { pollPageSize: settings.pollPageSize } : {}
603
+ };
568
604
  const credentials = {
569
605
  async resolve(call, signal) {
570
606
  void call;
@@ -573,14 +609,713 @@ function newProjectConnection2(project, connectionName) {
573
609
  return { personalAccessToken: new SecretString2(decoded.personal_access_token) };
574
610
  }
575
611
  };
576
- return new AirtableClient(config, credentials);
612
+ return new AirtableClient(config, credentials, options);
577
613
  });
578
614
  }
615
+
616
+ // src/trigger.ts
617
+ import {
618
+ mustTriggerBindingDefinition,
619
+ newTrigger
620
+ } from "@superdurable/connectors-sdk";
621
+ import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
622
+ import {
623
+ ObjectNotFoundError as ObjectNotFoundError2,
624
+ decodeTriggerConfiguration,
625
+ newDurableTriggerTarget,
626
+ parseTriggerPayloadJSON
627
+ } from "@superdurable/connectors-sdk/projectconfig";
628
+
629
+ // src/record_changed_fetcher.ts
630
+ import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
631
+
632
+ // src/record_changed_cursor.ts
633
+ import { encodeGoJSONValue } from "@superdurable/connectors-sdk/projectconfig";
634
+
635
+ // src/record_changed_time.ts
636
+ var NanosecondsPerMillisecond = 1000000n;
637
+ var NanosecondsPerSecond = 1000000000n;
638
+ var nanosecondsPerDay = 86400n * NanosecondsPerSecond;
639
+ var rfc3339Pattern = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:[.,]([0-9]+))?(Z|[+-][0-9]{2}:[0-9]{2})$/;
640
+ function parseRFC3339Nanoseconds(text) {
641
+ const match = rfc3339Pattern.exec(text);
642
+ if (!match) return void 0;
643
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
644
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return void 0;
645
+ if (hour > 23 || minute > 59 || second > 59) return void 0;
646
+ const fraction = (match[7] ?? "").slice(0, 9).padEnd(9, "0");
647
+ const zone = match[8];
648
+ let offsetSeconds = 0;
649
+ if (zone !== "Z") {
650
+ const zoneHours = Number(zone.slice(1, 3)), zoneMinutes = Number(zone.slice(4, 6));
651
+ if (zoneHours > 23 || zoneMinutes > 59) return void 0;
652
+ offsetSeconds = (zoneHours * 3600 + zoneMinutes * 60) * (zone[0] === "-" ? -1 : 1);
653
+ }
654
+ const seconds = BigInt(daysFromCivil(year, month, day)) * 86400n + BigInt(hour * 3600 + minute * 60 + second - offsetSeconds);
655
+ return seconds * NanosecondsPerSecond + BigInt(fraction);
656
+ }
657
+ function formatRFC3339Nanoseconds(at) {
658
+ const { date, nanoseconds } = split(at);
659
+ const fraction = nanoseconds.toString().padStart(9, "0").replace(/0+$/, "");
660
+ return `${date}${fraction ? `.${fraction}` : ""}Z`;
661
+ }
662
+ function formatMilliseconds(at) {
663
+ const { date, nanoseconds } = split(at);
664
+ return `${date}.${(nanoseconds / NanosecondsPerMillisecond).toString().padStart(3, "0")}Z`;
665
+ }
666
+ function formatEventIDTime(at) {
667
+ const { date, nanoseconds } = split(at);
668
+ return `${date.replace(/[-:]/g, "")}${nanoseconds.toString().padStart(9, "0")}Z`;
669
+ }
670
+ function truncateToMillisecond(at) {
671
+ return at - floorModulo(at, NanosecondsPerMillisecond);
672
+ }
673
+ function nanosecondsToDate(at) {
674
+ return new Date(Number(floorDivide(at, NanosecondsPerMillisecond)));
675
+ }
676
+ function split(at) {
677
+ const days = floorDivide(at, nanosecondsPerDay);
678
+ const withinDay = at - days * nanosecondsPerDay;
679
+ const [year, month, day] = civilFromDays(Number(days));
680
+ const seconds = Number(withinDay / NanosecondsPerSecond);
681
+ const nanoseconds = withinDay % NanosecondsPerSecond;
682
+ const two = (value) => value.toString().padStart(2, "0");
683
+ const date = `${year.toString().padStart(4, "0")}-${two(month)}-${two(day)}T${two(Math.floor(seconds / 3600))}:${two(Math.floor(seconds / 60) % 60)}:${two(seconds % 60)}`;
684
+ return { date, nanoseconds };
685
+ }
686
+ function floorDivide(value, divisor) {
687
+ const quotient = value / divisor;
688
+ return value % divisor < 0n ? quotient - 1n : quotient;
689
+ }
690
+ function floorModulo(value, divisor) {
691
+ return value - floorDivide(value, divisor) * divisor;
692
+ }
693
+ function daysInMonth(year, month) {
694
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
695
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
696
+ }
697
+ function daysFromCivil(year, month, day) {
698
+ const shiftedYear = month <= 2 ? year - 1 : year;
699
+ const era = Math.floor(shiftedYear / 400);
700
+ const yearOfEra = shiftedYear - era * 400;
701
+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
702
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
703
+ return era * 146097 + dayOfEra - 719468;
704
+ }
705
+ function civilFromDays(daysSinceEpoch) {
706
+ const days = daysSinceEpoch + 719468;
707
+ const era = Math.floor(days / 146097);
708
+ const dayOfEra = days - era * 146097;
709
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
710
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
711
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
712
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
713
+ const month = monthIndex + (monthIndex < 10 ? 3 : -9);
714
+ return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day];
715
+ }
716
+
717
+ // src/record_changed_cursor.ts
718
+ var recordChangedCursorVersion = 2;
719
+ var recordChangedOverlap = 5n * NanosecondsPerSecond;
720
+ var maximumRecordChangedSeen = 2e3;
721
+ var recordIdPattern2 = /^rec[0-9A-Za-z]{14}$/;
722
+ var int64DecimalPattern = /^[+-]?[0-9]+$/;
723
+ var maximumInt64 = (1n << 63n) - 1n;
724
+ var RecordChangedCursorError = class extends Error {
725
+ constructor(message) {
726
+ super(message);
727
+ this.name = "RecordChangedCursorError";
728
+ }
729
+ };
730
+ function later(left, right) {
731
+ return right !== void 0 && (left === void 0 || right > left) ? right : left;
732
+ }
733
+ var RecordChangedPosition = class {
734
+ constructor(fieldId) {
735
+ this.fieldId = fieldId;
736
+ }
737
+ fieldId;
738
+ after;
739
+ floor;
740
+ burst;
741
+ seen = [];
742
+ scan;
743
+ /** Return the earliest modification time a poll still delivers; undefined means every record. */
744
+ lowerBound() {
745
+ return this.after === void 0 ? void 0 : later(this.after - recordChangedOverlap, this.floor);
746
+ }
747
+ /** Report a record older than the lower bound or already delivered at this time. */
748
+ isDelivered(recordId, modifiedAt) {
749
+ const lowerBound = this.lowerBound();
750
+ if (lowerBound !== void 0 && modifiedAt < lowerBound) return true;
751
+ const at = truncateToMillisecond(modifiedAt);
752
+ return this.seen.some((seen) => seen.recordId === recordId && seen.at === at);
753
+ }
754
+ /** Remember one delivered record; records arrive oldest first within a scan. */
755
+ deliver(recordId, modifiedAt) {
756
+ if (this.burst !== void 0 && modifiedAt > this.burst) this.closeBurst();
757
+ this.after = later(this.after, modifiedAt);
758
+ this.seen.push({ recordId, at: truncateToMillisecond(modifiedAt) });
759
+ this.bound();
760
+ }
761
+ /** Move the floor past a burst time once every record at that time was listed. */
762
+ closeBurst() {
763
+ if (this.burst !== void 0) {
764
+ this.floor = later(this.floor, this.burst + NanosecondsPerMillisecond);
765
+ this.burst = void 0;
766
+ }
767
+ this.bound();
768
+ }
769
+ /** Return the listRecords filter bound: the lower bound minus one second of formula rounding. */
770
+ filterSince() {
771
+ const lowerBound = this.lowerBound();
772
+ return lowerBound === void 0 ? 0n : truncateToMillisecond(lowerBound - NanosecondsPerSecond);
773
+ }
774
+ bound() {
775
+ const lowerBound = this.lowerBound();
776
+ if (lowerBound !== void 0) this.seen = this.seen.filter((seen) => !(seen.at < lowerBound));
777
+ if (this.seen.length <= maximumRecordChangedSeen) return;
778
+ this.seen.sort((left, right) => left.at < right.at ? -1 : left.at > right.at ? 1 : 0);
779
+ const dropped = this.seen[this.seen.length - maximumRecordChangedSeen - 1].at;
780
+ this.seen = this.seen.filter((seen) => seen.at > dropped);
781
+ if (this.after !== void 0 && dropped < truncateToMillisecond(this.after)) {
782
+ this.floor = later(this.floor, dropped + NanosecondsPerMillisecond);
783
+ return;
784
+ }
785
+ this.burst = later(this.burst, dropped);
786
+ }
787
+ };
788
+ function encodeRecordChangedCursor(position) {
789
+ const parts = [`"v":${recordChangedCursorVersion}`, `"fieldId":${encodeGoJSONValue(position.fieldId)}`, `"after":${encodeGoJSONValue(formatCursorTime(position.after))}`];
790
+ if (position.floor !== void 0) parts.push(`"floor":${encodeGoJSONValue(formatCursorTime(position.floor))}`);
791
+ if (position.burst !== void 0) parts.push(`"burst":${encodeGoJSONValue(formatCursorTime(position.burst))}`);
792
+ if (position.seen.length > 0) {
793
+ const after = truncateToMillisecond(position.after ?? 0n);
794
+ parts.push(`"seen":[${position.seen.map((seen) => encodeGoJSONValue(`${seen.recordId}:${(after - seen.at) / NanosecondsPerMillisecond}`)).join(",")}]`);
795
+ }
796
+ if (position.scan) parts.push(`"scan":{"since":${encodeGoJSONValue(position.scan.since)},"offset":${encodeGoJSONValue(position.scan.offset)}}`);
797
+ return { token: `{${parts.join(",")}}` };
798
+ }
799
+ function decodeRecordChangedCursor(encoded) {
800
+ let token;
801
+ try {
802
+ token = decodeToken(encoded);
803
+ } catch {
804
+ throw new RecordChangedCursorError("Airtable recordChanged cursor is not a version 2 cursor");
805
+ }
806
+ if (token.version !== BigInt(recordChangedCursorVersion)) throw new RecordChangedCursorError("Airtable recordChanged cursor is not a version 2 cursor");
807
+ if (token.seen.length > maximumRecordChangedSeen) throw new RecordChangedCursorError("Airtable recordChanged cursor holds too many record IDs");
808
+ const position = new RecordChangedPosition(token.fieldId);
809
+ position.scan = token.scan;
810
+ position.after = parseCursorTime(token.after);
811
+ position.floor = parseCursorTime(token.floor);
812
+ position.burst = parseCursorTime(token.burst);
813
+ if (position.after === void 0 && (token.seen.length > 0 || position.floor !== void 0 || position.burst !== void 0)) {
814
+ throw new RecordChangedCursorError("Airtable recordChanged cursor remembers records without a time");
815
+ }
816
+ if (token.scan && (!token.scan.since || !token.scan.offset || parseRFC3339Nanoseconds(token.scan.since) === void 0)) {
817
+ throw new RecordChangedCursorError("Airtable recordChanged cursor scan is invalid");
818
+ }
819
+ const after = truncateToMillisecond(position.after ?? 0n);
820
+ for (const entry of token.seen) {
821
+ const separator = entry.indexOf(":");
822
+ const recordId = separator < 0 ? entry : entry.slice(0, separator), delta = separator < 0 ? "" : entry.slice(separator + 1);
823
+ const milliseconds = int64DecimalPattern.test(delta) ? BigInt(delta) : -1n;
824
+ if (separator < 0 || milliseconds < 0n || milliseconds > maximumInt64 || !recordIdPattern2.test(recordId)) {
825
+ throw new RecordChangedCursorError("Airtable recordChanged cursor holds an invalid record entry");
826
+ }
827
+ position.seen.push({ recordId, at: after - milliseconds * NanosecondsPerMillisecond });
828
+ }
829
+ return position;
830
+ }
831
+ function parseCursorTime(text) {
832
+ if (text === "") return void 0;
833
+ const at = parseRFC3339Nanoseconds(text);
834
+ if (at === void 0) throw new RecordChangedCursorError("Airtable recordChanged cursor time is invalid");
835
+ return at;
836
+ }
837
+ function formatCursorTime(at) {
838
+ return at === void 0 ? "" : formatRFC3339Nanoseconds(at);
839
+ }
840
+ var tokenFields = ["v", "fieldId", "after", "floor", "burst", "seen", "scan"];
841
+ function decodeToken(encoded) {
842
+ const document = new StrictJSONParser(encoded).parseDocument();
843
+ const token = { version: 0n, fieldId: "", after: "", floor: "", burst: "", seen: [], scan: void 0 };
844
+ if (document === null) return token;
845
+ for (const [name, value] of objectPairs(document, tokenFields)) {
846
+ if (name === "v") {
847
+ if (value === null) continue;
848
+ if (typeof value !== "object" || !("number" in value) || !/^-?(0|[1-9][0-9]*)$/.test(value.number)) throw new TypeError("v is not an int");
849
+ token.version = BigInt(value.number);
850
+ if (token.version > maximumInt64 || token.version < -maximumInt64 - 1n) throw new TypeError("v overflows int");
851
+ } else if (name === "seen") {
852
+ if (value === null) {
853
+ token.seen = [];
854
+ continue;
855
+ }
856
+ if (!Array.isArray(value)) throw new TypeError("seen is not an array");
857
+ token.seen = value.map((item) => goString(item, ""));
858
+ } else if (name === "scan") {
859
+ if (value === null) {
860
+ token.scan = void 0;
861
+ continue;
862
+ }
863
+ const scan = { since: "", offset: "" };
864
+ for (const [scanName, scanValue] of objectPairs(value, ["since", "offset"])) scan[scanName] = goString(scanValue, scan[scanName]);
865
+ token.scan = scan;
866
+ } else {
867
+ token[name] = goString(value, token[name]);
868
+ }
869
+ }
870
+ return token;
871
+ }
872
+ function objectPairs(value, names) {
873
+ if (value === null || typeof value !== "object" || !("pairs" in value)) throw new TypeError("JSON value is not an object");
874
+ const matched = [];
875
+ for (const [key, item] of value.pairs) {
876
+ const name = names.find((candidate) => candidate === key) ?? names.find((candidate) => candidate.toLowerCase() === key.toLowerCase());
877
+ if (name !== void 0) matched.push([name, item]);
878
+ }
879
+ return matched;
880
+ }
881
+ function goString(value, current) {
882
+ if (value === null) return current;
883
+ if (typeof value !== "string") throw new TypeError("JSON value is not a string");
884
+ return value;
885
+ }
886
+ var jsonNumberPattern = /-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y;
887
+ var jsonStringPattern = /"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/y;
888
+ var StrictJSONParser = class {
889
+ constructor(text) {
890
+ this.text = text;
891
+ }
892
+ text;
893
+ index = 0;
894
+ parseDocument() {
895
+ const value = this.parseValue(0);
896
+ this.skipWhitespace();
897
+ if (this.index !== this.text.length) throw new SyntaxError("trailing data after JSON value");
898
+ return value;
899
+ }
900
+ parseValue(depth) {
901
+ if (depth > 1e4) throw new SyntaxError("JSON nests too deeply");
902
+ this.skipWhitespace();
903
+ const character = this.text[this.index];
904
+ if (character === "{") return this.parseObject(depth);
905
+ if (character === "[") return this.parseArray(depth);
906
+ if (character === '"') return this.parseString();
907
+ for (const [literal, value] of [["true", true], ["false", false], ["null", null]]) {
908
+ if (this.text.startsWith(literal, this.index)) {
909
+ this.index += literal.length;
910
+ return value;
911
+ }
912
+ }
913
+ const number = this.matchAt(jsonNumberPattern);
914
+ if (!number) throw new SyntaxError("invalid JSON value");
915
+ this.index += number[0].length;
916
+ return { number: number[0] };
917
+ }
918
+ parseObject(depth) {
919
+ const pairs = [];
920
+ this.index++;
921
+ this.skipWhitespace();
922
+ if (this.text[this.index] === "}") {
923
+ this.index++;
924
+ return { pairs };
925
+ }
926
+ for (; ; ) {
927
+ this.skipWhitespace();
928
+ if (this.text[this.index] !== '"') throw new SyntaxError("object key must be a string");
929
+ const key = this.parseString();
930
+ this.skipWhitespace();
931
+ if (this.text[this.index++] !== ":") throw new SyntaxError("expected colon");
932
+ pairs.push([key, this.parseValue(depth + 1)]);
933
+ this.skipWhitespace();
934
+ const separator = this.text[this.index++];
935
+ if (separator === "}") return { pairs };
936
+ if (separator !== ",") throw new SyntaxError("expected comma or closing brace");
937
+ }
938
+ }
939
+ parseArray(depth) {
940
+ const items = [];
941
+ this.index++;
942
+ this.skipWhitespace();
943
+ if (this.text[this.index] === "]") {
944
+ this.index++;
945
+ return items;
946
+ }
947
+ for (; ; ) {
948
+ items.push(this.parseValue(depth + 1));
949
+ this.skipWhitespace();
950
+ const separator = this.text[this.index++];
951
+ if (separator === "]") return items;
952
+ if (separator !== ",") throw new SyntaxError("expected comma or closing bracket");
953
+ }
954
+ }
955
+ parseString() {
956
+ const match = this.matchAt(jsonStringPattern);
957
+ if (!match || [...match[0]].some((character) => character < " ")) throw new SyntaxError("invalid JSON string");
958
+ this.index += match[0].length;
959
+ return JSON.parse(match[0]);
960
+ }
961
+ matchAt(pattern) {
962
+ pattern.lastIndex = this.index;
963
+ return pattern.exec(this.text);
964
+ }
965
+ skipWhitespace() {
966
+ while (this.index < this.text.length && " \n\r".includes(this.text[this.index])) this.index++;
967
+ }
968
+ };
969
+
970
+ // src/record_changed_fetcher.ts
971
+ var maximumRecordChangedScanPages = 20;
972
+ var lastModifiedTimeFieldType = "lastModifiedTime";
973
+ var maximumOffsetBytes = 1024;
974
+ var RecordChangedPollError = class extends Error {
975
+ constructor(message) {
976
+ super(message);
977
+ this.name = "RecordChangedPollError";
978
+ }
979
+ };
980
+ var ListOffsetExpiredError = class extends RecordChangedPollError {
981
+ };
982
+ function recordChangedEventId(recordId, lastModifiedTime) {
983
+ return `${recordId}-${formatEventIDTime(lastModifiedTime)}`;
984
+ }
985
+ var RecordChangedFetcher = class {
986
+ /** Bind the client and the binding's table; it sends nothing. */
987
+ constructor(client, binding, configuration) {
988
+ this.client = client;
989
+ this.binding = binding;
990
+ this.configuration = configuration;
991
+ }
992
+ client;
993
+ binding;
994
+ configuration;
995
+ /** The watched field's current name, resolved from the base schema; blank until resolved. */
996
+ fieldName = "";
997
+ /** Position the cursor at the table's most recent change, so existing records are not delivered. */
998
+ async seedCursor(context) {
999
+ await this.resolveFieldName(context);
1000
+ const { records, nextOffset } = await this.listRecords(context, void 0, "desc", "");
1001
+ const position = new RecordChangedPosition(this.configuration.fieldId);
1002
+ if (nextOffset && records.length > 0) {
1003
+ const oldest = records.reduce((minimum, changed) => changed.modifiedAt < minimum ? changed.modifiedAt : minimum, records[0].modifiedAt);
1004
+ position.floor = truncateToMillisecond(oldest) + NanosecondsPerMillisecond;
1005
+ }
1006
+ for (const changed of records) position.deliver(changed.record.id, changed.modifiedAt);
1007
+ return encodeRecordChangedCursor(position);
1008
+ }
1009
+ /**
1010
+ * List records modified since the cursor's lower bound, oldest first, and return those not yet delivered.
1011
+ * An open scan resumes from its stored Airtable offset.
1012
+ */
1013
+ async fetchChanges(context, cursor) {
1014
+ let position;
1015
+ try {
1016
+ position = decodeRecordChangedCursor(cursor.token);
1017
+ } catch (error) {
1018
+ if (error instanceof RecordChangedCursorError) throw markCursorInvalid(error);
1019
+ throw error;
1020
+ }
1021
+ if (position.fieldId !== this.configuration.fieldId) throw markCursorInvalid(new RecordChangedPollError("the binding now watches a different Last modified time field"));
1022
+ await this.resolveFieldName(context);
1023
+ let since = position.filterSince(), offset = "";
1024
+ if (position.scan) {
1025
+ since = parseRFC3339Nanoseconds(position.scan.since) ?? 0n;
1026
+ offset = position.scan.offset;
1027
+ }
1028
+ let hasRestartedScan = false;
1029
+ const changes = [];
1030
+ for (let scannedPages = 0; scannedPages < maximumRecordChangedScanPages; scannedPages++) {
1031
+ let page;
1032
+ try {
1033
+ page = await this.listRecords(context, since, "asc", offset);
1034
+ } catch (error) {
1035
+ if (!(error instanceof ListOffsetExpiredError) || !offset || hasRestartedScan) throw error;
1036
+ hasRestartedScan = true;
1037
+ position.scan = void 0;
1038
+ since = position.filterSince();
1039
+ offset = "";
1040
+ continue;
1041
+ }
1042
+ for (const changed of page.records) {
1043
+ if (position.isDelivered(changed.record.id, changed.modifiedAt)) continue;
1044
+ changes.push(this.newEvent(changed));
1045
+ position.deliver(changed.record.id, changed.modifiedAt);
1046
+ }
1047
+ position.scan = void 0;
1048
+ if (!page.nextOffset) position.closeBurst();
1049
+ else position.scan = { since: formatRFC3339Nanoseconds(since), offset: page.nextOffset };
1050
+ if (changes.length > 0 || !page.nextOffset) return { changes, next: encodeRecordChangedCursor(position), hasMorePages: page.nextOffset !== "" };
1051
+ offset = page.nextOffset;
1052
+ }
1053
+ return { changes, next: encodeRecordChangedCursor(position), hasMorePages: true };
1054
+ }
1055
+ newEvent(changed) {
1056
+ const createdAt = parseRFC3339Nanoseconds(changed.record.createdTime) ?? 0n;
1057
+ const distance = changed.modifiedAt - createdAt;
1058
+ return {
1059
+ id: recordChangedEventId(changed.record.id, changed.modifiedAt),
1060
+ occurredAt: nanosecondsToDate(changed.modifiedAt),
1061
+ payload: {
1062
+ baseId: this.configuration.baseId,
1063
+ tableId: this.configuration.tableId,
1064
+ lastModifiedTime: formatRFC3339Nanoseconds(changed.modifiedAt),
1065
+ isCreatedRecord: (distance < 0n ? -distance : distance) <= NanosecondsPerSecond,
1066
+ record: changed.record
1067
+ }
1068
+ };
1069
+ }
1070
+ /** Read one page sorted by the watched field, of records whose field value is after since. */
1071
+ async listRecords(context, since, direction, offset) {
1072
+ const fieldId = this.configuration.fieldId;
1073
+ const body = {
1074
+ pageSize: this.client.pollPageSize,
1075
+ ...offset ? { offset } : {},
1076
+ filterByFormula: `IS_AFTER({${fieldId}}, DATETIME_PARSE("${formatMilliseconds(since ?? 0n)}"))`,
1077
+ sort: [{ field: fieldId, direction }]
1078
+ };
1079
+ const path = `/v0/${encodeURIComponent(this.configuration.baseId)}/${encodeURIComponent(this.configuration.tableId)}/listRecords`;
1080
+ const response = await this.exchange(context, "POST", path, body);
1081
+ let records, nextOffset;
1082
+ try {
1083
+ const document = decodeJSONObject(response);
1084
+ if (document.records === void 0 || document.records === null) throw new RecordChangedPollError("Airtable returned a list response without records");
1085
+ if (!Array.isArray(document.records)) throw new RecordChangedPollError("Airtable returned a malformed response");
1086
+ if (document.records.length > this.client.pollPageSize) throw new RecordChangedPollError("Airtable returned more records than the requested page size");
1087
+ nextOffset = optionalMember(document, "offset", "string") ?? "";
1088
+ if (Buffer.byteLength(nextOffset, "utf8") > maximumOffsetBytes) throw new RecordChangedPollError("Airtable returned an oversized offset");
1089
+ records = document.records.map(decodeRecord);
1090
+ } catch (error) {
1091
+ if (error instanceof RecordChangedPollError) throw error;
1092
+ throw new RecordChangedPollError("Airtable returned a malformed response");
1093
+ }
1094
+ return { records: records.map((record) => ({ record, modifiedAt: this.readLastModifiedTime(record) })), nextOffset };
1095
+ }
1096
+ /** Parse the watched field of a record the filter matched, so the field has a value. */
1097
+ readLastModifiedTime(record) {
1098
+ const fields = record.fields ?? {};
1099
+ if (!Object.hasOwn(fields, this.fieldName)) {
1100
+ this.fieldName = "";
1101
+ throw new RecordChangedPollError("Airtable returned a changed record without the Last modified time field; the field name is read again");
1102
+ }
1103
+ const value = fields[this.fieldName];
1104
+ const modifiedAt = typeof value === "string" ? parseRFC3339Nanoseconds(value) : void 0;
1105
+ if (modifiedAt === void 0) throw new RecordChangedPollError("Airtable returned a Last modified time value without a time of day");
1106
+ return modifiedAt;
1107
+ }
1108
+ /** Read the base schema once, and again after a rename, to find the watched field's current name, since listed records key their fields by name. */
1109
+ async resolveFieldName(context) {
1110
+ if (this.fieldName) return;
1111
+ const response = await this.exchange(context, "GET", `/v0/meta/bases/${encodeURIComponent(this.configuration.baseId)}/tables`, void 0);
1112
+ let tables;
1113
+ try {
1114
+ tables = readSchemaTables(decodeJSONObject(response));
1115
+ } catch {
1116
+ throw new RecordChangedPollError("Airtable returned a malformed response");
1117
+ }
1118
+ const table = tables.find((candidate) => candidate.id === this.configuration.tableId);
1119
+ if (!table) throw new RecordChangedPollError("the Airtable base schema has no table with the recordChanged table ID");
1120
+ const field = table.fields.find((candidate) => candidate.id === this.configuration.fieldId);
1121
+ if (!field) throw new RecordChangedPollError("the Airtable table has no field with the recordChanged field ID");
1122
+ if (field.type !== lastModifiedTimeFieldType || field.name === "") throw new RecordChangedPollError("the Airtable recordChanged field is not a Last modified time field");
1123
+ if (field.resultType !== void 0 && field.resultType !== "dateTime") throw new RecordChangedPollError("the Airtable recordChanged Last modified time field must include a time of day");
1124
+ this.fieldName = field.name;
1125
+ }
1126
+ /** Wait on the runner's request limiter, then send one paced request through the client. */
1127
+ async exchange(context, method, path, body) {
1128
+ await waitForPollRequest(context);
1129
+ const call = newTriggerCredentialCall(this.binding.connection, this.binding.trigger, context.signal);
1130
+ const baseId = this.configuration.baseId;
1131
+ const result = await this.client.exchange(call, this.binding.trigger.triggerName, baseId, baseId, method, path, body);
1132
+ if ("response" in result) return result.response.body;
1133
+ const outcome = result.outcome;
1134
+ if (outcome.disposition === "offsetExpired") throw new ListOffsetExpiredError("Airtable no longer recognizes the list offset");
1135
+ const error = new RecordChangedPollError(outcome.failure.message);
1136
+ if (outcome.disposition === "retry" && outcome.failure.kind === "RATE_LIMIT") throw markRateLimited(error, outcome.retryAfterMs);
1137
+ throw error;
1138
+ }
1139
+ };
1140
+ function readSchemaTables(document) {
1141
+ return (optionalMember(document, "tables", "array") ?? []).map((table) => ({
1142
+ id: optionalMember(table, "id", "string") ?? "",
1143
+ fields: (optionalMember(table, "fields", "array") ?? []).map((field) => {
1144
+ const result = optionalMember(optionalMember(field, "options", "object"), "result", "object");
1145
+ return {
1146
+ id: optionalMember(field, "id", "string") ?? "",
1147
+ name: optionalMember(field, "name", "string") ?? "",
1148
+ type: optionalMember(field, "type", "string") ?? "",
1149
+ resultType: result === void 0 ? void 0 : optionalMember(result, "type", "string") ?? ""
1150
+ };
1151
+ })
1152
+ }));
1153
+ }
1154
+ function optionalMember(document, name, kind) {
1155
+ if (document === void 0 || document === null) return void 0;
1156
+ if (!isJSONObject(document)) throw new TypeError("Airtable returned a malformed response");
1157
+ const value = document[name];
1158
+ if (value === void 0 || value === null) return void 0;
1159
+ const matches = kind === "string" ? typeof value === "string" : kind === "array" ? Array.isArray(value) : isJSONObject(value);
1160
+ if (!matches) throw new TypeError("Airtable returned a malformed response");
1161
+ return value;
1162
+ }
1163
+ function isJSONObject(value) {
1164
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1165
+ }
1166
+ function decodeJSONObject(body) {
1167
+ const document = JSON.parse(Buffer.from(body).toString("utf8"));
1168
+ if (!isJSONObject(document)) throw new TypeError("Airtable returned a malformed response");
1169
+ return document;
1170
+ }
1171
+
1172
+ // src/record_changed_models.ts
1173
+ import { z as z2 } from "zod";
1174
+ var goString2 = z2.string().nullish().transform((value) => value ?? "");
1175
+ var optionalGoString = z2.string().nullish().transform((value) => value || void 0);
1176
+ var RecordChangedTriggerConfigurationSchema = z2.strictObject({
1177
+ baseId: goString2,
1178
+ baseName: optionalGoString,
1179
+ tableId: goString2,
1180
+ tableName: optionalGoString,
1181
+ fieldId: goString2,
1182
+ fieldName: optionalGoString
1183
+ }).transform((configuration) => ({
1184
+ baseId: configuration.baseId,
1185
+ ...configuration.baseName ? { baseName: configuration.baseName } : {},
1186
+ tableId: configuration.tableId,
1187
+ ...configuration.tableName ? { tableName: configuration.tableName } : {},
1188
+ fieldId: configuration.fieldId,
1189
+ ...configuration.fieldName ? { fieldName: configuration.fieldName } : {}
1190
+ }));
1191
+ var RecordChangedEventSchema = z2.object({
1192
+ baseId: goString2,
1193
+ tableId: goString2,
1194
+ lastModifiedTime: z2.string(),
1195
+ isCreatedRecord: z2.boolean().nullish().transform((value) => value ?? false),
1196
+ record: z2.object({
1197
+ id: goString2,
1198
+ createdTime: z2.string(),
1199
+ fields: z2.record(z2.string(), z2.unknown()).nullish().transform((value) => value ?? null)
1200
+ })
1201
+ }).transform((event) => ({
1202
+ baseId: event.baseId,
1203
+ tableId: event.tableId,
1204
+ lastModifiedTime: event.lastModifiedTime,
1205
+ isCreatedRecord: event.isCreatedRecord,
1206
+ record: { id: event.record.id, createdTime: event.record.createdTime, fields: event.record.fields }
1207
+ }));
1208
+
1209
+ // src/trigger.ts
1210
+ var UIUnitBasePicker = "basePicker";
1211
+ var UIBasePickerPortBaseID = "baseId";
1212
+ var UIBasePickerPortBaseName = "baseName";
1213
+ var UIUnitTablePicker = "tablePicker";
1214
+ var UITablePickerPortBaseID = "baseId";
1215
+ var UITablePickerPortTableID = "tableId";
1216
+ var UITablePickerPortTableName = "tableName";
1217
+ var UIUnitLastModifiedTimeFieldPicker = "lastModifiedTimeFieldPicker";
1218
+ var UILastModifiedTimeFieldPickerPortBaseID = "baseId";
1219
+ var UILastModifiedTimeFieldPickerPortTableID = "tableId";
1220
+ var UILastModifiedTimeFieldPickerPortFieldID = "fieldId";
1221
+ var UILastModifiedTimeFieldPickerPortFieldName = "fieldName";
1222
+ var recordChangedMaximumBackoffMs = 5 * 6e4;
1223
+ var baseIdPattern2 = /^app[0-9A-Za-z]{14}$/;
1224
+ var tableIdPattern = /^tbl[0-9A-Za-z]{14}$/;
1225
+ var fieldIdPattern = /^fld[0-9A-Za-z]{14}$/;
1226
+ var RecordChangedTriggerDefinition = {
1227
+ trigger: { connectorId: ConnectorID, triggerName: "recordChanged" },
1228
+ description: "Receive each record of one picked table that is created or changed after the last processed change, as reported by a picked Last modified time field."
1229
+ };
1230
+ function defineRecordChangedTriggerBinding(config) {
1231
+ return mustTriggerBindingDefinition({ definition: RecordChangedTriggerDefinition, ...config });
1232
+ }
1233
+ function validateRecordChangedTriggerConfiguration(configuration) {
1234
+ if (!baseIdPattern2.test(configuration?.baseId ?? "")) throw new TypeError("Airtable recordChanged baseId must be app followed by 14 letters and digits");
1235
+ if (!tableIdPattern.test(configuration.tableId ?? "")) throw new TypeError("Airtable recordChanged tableId must be tbl followed by 14 letters and digits");
1236
+ if (!fieldIdPattern.test(configuration.fieldId ?? "")) throw new TypeError("Airtable recordChanged fieldId must be fld followed by 14 letters and digits");
1237
+ }
1238
+ function decodeRecordChangedEventPayload(_payloadJSON, payloadBytes) {
1239
+ return RecordChangedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes));
1240
+ }
1241
+ function newRecordChangedTriggerRunner(config) {
1242
+ const client = airtableClientOf(config.connection);
1243
+ if (!config.routes?.length) throw new TypeError("Airtable recordChanged Trigger routes are required");
1244
+ const pollers = config.routes.map((route) => {
1245
+ if (!route.bindingName?.trim() || !route.target || !route.cursor) throw new TypeError("Airtable recordChanged binding name, cursor, and target are required");
1246
+ validateRouteConfiguration(route.bindingName, route.configuration);
1247
+ const binding = bindingRef(config.connection, route.bindingName);
1248
+ return newBindingPoller({
1249
+ definition: RecordChangedTriggerDefinition,
1250
+ binding,
1251
+ cursor: route.cursor,
1252
+ fetcher: new RecordChangedFetcher(client, binding, route.configuration),
1253
+ target: route.target
1254
+ });
1255
+ });
1256
+ return newRunner({
1257
+ connection: config.connection.reference,
1258
+ schedule: pollSchedule(client),
1259
+ pollers,
1260
+ ...config.requestLimiter ? { requestLimiter: config.requestLimiter } : {},
1261
+ ...client.triggerLogger ? { logger: client.triggerLogger } : {}
1262
+ });
1263
+ }
1264
+ function newProjectRecordChangedTriggerRunner(project, connectionName, routes, options = {}) {
1265
+ const connection = newProjectConnection2(project, connectionName, options);
1266
+ const triggerName = RecordChangedTriggerDefinition.trigger.triggerName;
1267
+ const durableRoutes = routes.map((route) => {
1268
+ const name = JSON.stringify(route.bindingName);
1269
+ if (!route.target) throw new TypeError(`Airtable recordChanged binding ${name} target is required`);
1270
+ const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName: route.bindingName };
1271
+ let configuration;
1272
+ try {
1273
+ configuration = decodeTriggerConfiguration(project.configuration, key, RecordChangedTriggerConfigurationSchema);
1274
+ } catch (error) {
1275
+ if (error instanceof ObjectNotFoundError2) throw new TypeError(`Airtable recordChanged binding ${name} has no saved configuration; pick the base, table, and field in Dex Web and restart`, { cause: error });
1276
+ throw new TypeError(`Airtable recordChanged binding ${name} configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1277
+ }
1278
+ const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { ...options.logger ? { logger: options.logger } : {}, decodePayload: decodeRecordChangedEventPayload });
1279
+ return { bindingName: route.bindingName, configuration, cursor: project.pollCursorStore(key), target };
1280
+ });
1281
+ return newRecordChangedTriggerRunner({ connection, routes: durableRoutes });
1282
+ }
1283
+ function newRecordChangedTrigger(config) {
1284
+ const client = airtableClientOf(config.connection);
1285
+ if (!config.bindingName?.trim() || !config.target) throw new TypeError("Airtable recordChanged binding name, cursor, and target are required");
1286
+ validateRouteConfiguration(config.bindingName, config.configuration);
1287
+ const binding = bindingRef(config.connection, config.bindingName);
1288
+ const source = newBindingTriggerSource({
1289
+ definition: RecordChangedTriggerDefinition,
1290
+ binding,
1291
+ cursor: newMemoryCursorStore(),
1292
+ fetcher: new RecordChangedFetcher(client, binding, config.configuration)
1293
+ }, pollSchedule(client), client.triggerLogger);
1294
+ return newTrigger({ definition: RecordChangedTriggerDefinition, binding, source, target: config.target, ...client.triggerLogger ? { logger: client.triggerLogger } : {} });
1295
+ }
1296
+ function bindingRef(connection, bindingName) {
1297
+ return { connection: connection.reference, trigger: RecordChangedTriggerDefinition.trigger, name: bindingName };
1298
+ }
1299
+ function validateRouteConfiguration(bindingName, configuration) {
1300
+ try {
1301
+ validateRecordChangedTriggerConfiguration(configuration);
1302
+ } catch (error) {
1303
+ throw new TypeError(`Airtable recordChanged binding ${JSON.stringify(bindingName)}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1304
+ }
1305
+ }
1306
+ function pollSchedule(client) {
1307
+ return { intervalMs: client.pollIntervalMs, maxBackoffMs: Math.max(recordChangedMaximumBackoffMs, client.pollIntervalMs) };
1308
+ }
1309
+ function airtableClientOf(connection) {
1310
+ if (!(connection?.operations instanceof AirtableClient)) throw new TypeError("Airtable recordChanged requires a connection from newProjectConnection or newConnection with an AirtableClient");
1311
+ return connection.operations;
1312
+ }
579
1313
  export {
580
1314
  AirtableClient,
581
1315
  ConfigSchema,
582
1316
  Connection,
583
1317
  ConnectorID,
1318
+ CredentialMaterialError,
584
1319
  FieldEqualityFilterSchema,
585
1320
  GetRecordBranch,
586
1321
  GetRecordBranchDefect,
@@ -603,11 +1338,26 @@ export {
603
1338
  ListRecordsMetadata,
604
1339
  ListRecordsOperation,
605
1340
  ProviderID,
1341
+ RecordChangedEventSchema,
1342
+ RecordChangedTriggerConfigurationSchema,
1343
+ RecordChangedTriggerDefinition,
606
1344
  RecordPageSchema,
607
1345
  RecordSchema,
608
1346
  RecordSortSchema,
609
1347
  RecordUpdateSchema,
610
1348
  RecordUpsertSchema,
1349
+ UIBasePickerPortBaseID,
1350
+ UIBasePickerPortBaseName,
1351
+ UILastModifiedTimeFieldPickerPortBaseID,
1352
+ UILastModifiedTimeFieldPickerPortFieldID,
1353
+ UILastModifiedTimeFieldPickerPortFieldName,
1354
+ UILastModifiedTimeFieldPickerPortTableID,
1355
+ UITablePickerPortBaseID,
1356
+ UITablePickerPortTableID,
1357
+ UITablePickerPortTableName,
1358
+ UIUnitBasePicker,
1359
+ UIUnitLastModifiedTimeFieldPicker,
1360
+ UIUnitTablePicker,
611
1361
  UpdateRecordsBranch,
612
1362
  UpdateRecordsBranchDefect,
613
1363
  UpdateRecordsBranchInvalidResponse,
@@ -629,11 +1379,19 @@ export {
629
1379
  UpsertRecordsMetadata,
630
1380
  UpsertRecordsOperation,
631
1381
  UpsertedRecordsSchema,
1382
+ decodeCredentials,
1383
+ decodeRecordChangedEventPayload,
1384
+ defineRecordChangedTriggerBinding,
1385
+ isCredentialMaterialError,
632
1386
  newConnection,
633
1387
  newConnectionWithOperations,
634
1388
  newGetRecordStep,
635
1389
  newListRecordsStep,
636
1390
  newProjectConnection2 as newProjectConnection,
1391
+ newProjectRecordChangedTriggerRunner,
1392
+ newRecordChangedTrigger,
1393
+ newRecordChangedTriggerRunner,
637
1394
  newUpdateRecordsStep,
638
- newUpsertRecordsStep
1395
+ newUpsertRecordsStep,
1396
+ validateRecordChangedTriggerConfiguration
639
1397
  };