@superdurable/connector-notion 0.1.0 → 0.2.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/dist/index.js CHANGED
@@ -67,7 +67,7 @@ import {
67
67
  newConnection,
68
68
  newConnectionWithOperations,
69
69
  newProjectConnection
70
- } from "./chunk-LZTWSFD4.js";
70
+ } from "./chunk-5TNYF4VH.js";
71
71
 
72
72
  // src/generated/steps.ts
73
73
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -908,9 +908,9 @@ function validDate(value) {
908
908
  const year = Number(match[1]);
909
909
  const month = Number(match[2]);
910
910
  const day = Number(match[3]);
911
- const isLeapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
912
- const daysInMonth = [31, isLeapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
913
- if (month < 1 || month > 12 || day < 1 || day > daysInMonth) throw new Error("invalid date");
911
+ const isLeapYear2 = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
912
+ const daysInMonth2 = [31, isLeapYear2 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
913
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth2) throw new Error("invalid date");
914
914
  if (match[4] !== void 0 && (Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59)) throw new Error("invalid date");
915
915
  const zone = match[7];
916
916
  if (zone && zone !== "Z" && (Number(zone.slice(1, 3)) > 24 || Number(zone.slice(4, 6)) > 60)) throw new Error("invalid date");
@@ -946,6 +946,8 @@ function isPlainEmailAddress(value) {
946
946
  // src/client.ts
947
947
  var defaultEndpoint = "https://api.notion.com";
948
948
  var notionVersion = "2026-03-11";
949
+ var minimumPollIntervalMs = 5e3;
950
+ var maximumPollPageSize = 100;
949
951
  var NotionClient = class {
950
952
  /** Validate the endpoint and required credential source without contacting Notion. */
951
953
  constructor(config, credentials, options = {}) {
@@ -954,12 +956,23 @@ var NotionClient = class {
954
956
  this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
955
957
  this.maxResponseBytes = config.maxResponseBytes || 4194304;
956
958
  if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Notion maxResponseBytes must be positive");
959
+ this.pollIntervalMs = config.pollIntervalMs || 3e4;
960
+ if (!Number.isSafeInteger(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("Notion pollInterval must be at least 5s");
961
+ this.pollPageSize = config.pollPageSize || maximumPollPageSize;
962
+ if (!Number.isSafeInteger(this.pollPageSize) || this.pollPageSize < 1 || this.pollPageSize > maximumPollPageSize) throw new TypeError("Notion pollPageSize must be between 1 and 100");
963
+ this.triggerLogger = options.logger;
957
964
  this.send = options.send ?? sendProviderRequest;
958
965
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
959
966
  }
960
967
  credentials;
961
968
  endpoint;
962
969
  maxResponseBytes;
970
+ /** Wait between databaseRowChanged polls of one binding, in milliseconds; at least 5000, 30000 by default. */
971
+ pollIntervalMs;
972
+ /** Rows per databaseRowChanged query page, 1 to 100, 100 by default. */
973
+ pollPageSize;
974
+ /** The databaseRowChanged Trigger logger from the options, or undefined for the SDK default. */
975
+ triggerLogger;
963
976
  send;
964
977
  now;
965
978
  /** Bind title search. */
@@ -1062,7 +1075,10 @@ var NotionClient = class {
1062
1075
  if (providerId) return { disposition: "committed", failure: failure(operation, "AVAILABILITY", "Notion saved the page"), providerId, receipt };
1063
1076
  }
1064
1077
  if (status === 404) return { disposition: "notFound", failure: failure(operation, "NOT_FOUND", `Notion ${subject} was not found`), receipt };
1065
- if (status >= 400 && status < 500 && status !== 408) return { disposition: "providerRejected", failure: failure(operation, status === 400 ? "VALIDATION" : status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION", `Notion rejected ${subject} with HTTP ${status}`), receipt };
1078
+ if (status >= 400 && status < 500 && status !== 408) {
1079
+ const providerErrorCode = readTopLevelToken(response.body, "code");
1080
+ return { disposition: "providerRejected", failure: failure(operation, status === 400 ? "VALIDATION" : status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION", `Notion rejected ${subject} with HTTP ${status}`), receipt, ...providerErrorCode ? { providerErrorCode } : {} };
1081
+ }
1066
1082
  if (status < 200 || status >= 300) return { disposition: mode === "unkeyedWrite" ? "uncertain" : "invalidResponse", failure: failure(operation, status >= 500 ? "AVAILABILITY" : "PROTOCOL", `Notion returned HTTP ${status}`), receipt };
1067
1083
  if (response.body.length > this.maxResponseBytes) return { disposition: mode === "unkeyedWrite" ? "uncertain" : "invalidResponse", failure: failure(operation, "RESPONSE_TOO_LARGE", "Notion response exceeds the configured limit"), receipt };
1068
1084
  if (Buffer.from(response.body).includes(Buffer.from(token))) return { disposition: mode === "unkeyedWrite" ? "uncertain" : "invalidResponse", failure: failure(operation, "PROTOCOL", "Notion response contains credential material"), receipt };
@@ -1072,6 +1088,16 @@ var NotionClient = class {
1072
1088
  function failure(operation, kind, message) {
1073
1089
  return { provider: "notion", operation, kind, message };
1074
1090
  }
1091
+ function readTopLevelToken(body, key) {
1092
+ try {
1093
+ const data = JSON.parse(Buffer.from(body).toString("utf8"));
1094
+ if (typeof data !== "object" || data === null) return "";
1095
+ const token = data[key];
1096
+ return typeof token === "string" && /^[!-~]{1,128}$/.test(token) ? token : "";
1097
+ } catch {
1098
+ return "";
1099
+ }
1100
+ }
1075
1101
  function readToken(body, parent, key) {
1076
1102
  try {
1077
1103
  const data = JSON.parse(Buffer.from(body).toString("utf8"));
@@ -1088,11 +1114,17 @@ function readToken(body, parent, key) {
1088
1114
  }
1089
1115
 
1090
1116
  // src/project.ts
1091
- function newProjectConnection2(project, connectionName) {
1117
+ function newProjectConnection2(project, connectionName, options = {}) {
1092
1118
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
1093
1119
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "notion" && entry.connectionName === name);
1094
1120
  if (!selected) throw new TypeError("Notion project connection is not configured");
1095
- const config = z.object({ endpoint: z.string().optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
1121
+ const settings = z.object({ endpoint: z.string().optional(), maxResponseBytes: z.number().int().optional(), pollInterval: z.number().int().nonnegative().optional(), pollPageSize: z.number().int().optional() }).parse(selected.configuration);
1122
+ const config = {
1123
+ ...settings.endpoint !== void 0 ? { endpoint: settings.endpoint } : {},
1124
+ ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
1125
+ ...settings.pollInterval ? { pollIntervalMs: Math.max(1, Math.floor(settings.pollInterval / 1e6)) } : {},
1126
+ ...settings.pollPageSize !== void 0 ? { pollPageSize: settings.pollPageSize } : {}
1127
+ };
1096
1128
  const credentials = {
1097
1129
  async resolve(call, signal) {
1098
1130
  void call;
@@ -1101,9 +1133,579 @@ function newProjectConnection2(project, connectionName) {
1101
1133
  return { apiToken: new SecretString2(decoded.api_token) };
1102
1134
  }
1103
1135
  };
1104
- return new NotionClient(config, credentials);
1136
+ return new NotionClient(config, credentials, options);
1105
1137
  });
1106
1138
  }
1139
+
1140
+ // src/database_row_trigger.ts
1141
+ import {
1142
+ mustTriggerBindingDefinition,
1143
+ newTrigger
1144
+ } from "@superdurable/connectors-sdk";
1145
+ import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
1146
+ import {
1147
+ ObjectNotFoundError,
1148
+ decodeTriggerConfiguration,
1149
+ newDurableTriggerTarget,
1150
+ parseTriggerPayloadJSON
1151
+ } from "@superdurable/connectors-sdk/projectconfig";
1152
+
1153
+ // src/database_row_cursor.ts
1154
+ import { createHash } from "crypto";
1155
+ import { encodeGoJSONValue } from "@superdurable/connectors-sdk/projectconfig";
1156
+
1157
+ // src/go_time.ts
1158
+ var rfc3339 = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{1,2}):([0-9]{2}):([0-9]{2})(?:[.,]([0-9]+))?(Z|[+-][0-9]{2}:[0-9]{2})$/;
1159
+ var nanosecondsPerSecond = 1000000000n;
1160
+ var secondsPerDay = 86400;
1161
+ var GoTime = class _GoTime {
1162
+ /** Wrap an instant; offsetSeconds only changes how it is rendered. */
1163
+ constructor(unixNanoseconds, offsetSeconds = 0) {
1164
+ this.unixNanoseconds = unixNanoseconds;
1165
+ this.offsetSeconds = offsetSeconds;
1166
+ }
1167
+ unixNanoseconds;
1168
+ offsetSeconds;
1169
+ /** Return the instant moved by nanoseconds, keeping the offset as Go's Time.Add does. */
1170
+ add(nanoseconds) {
1171
+ return new _GoTime(this.unixNanoseconds + nanoseconds, this.offsetSeconds);
1172
+ }
1173
+ /** Return the same instant rendered in UTC, as Go's Time.UTC does. */
1174
+ inUTC() {
1175
+ return new _GoTime(this.unixNanoseconds);
1176
+ }
1177
+ /** Report whether this instant precedes other. */
1178
+ isBefore(other) {
1179
+ return this.unixNanoseconds < other.unixNanoseconds;
1180
+ }
1181
+ /** Report whether this instant follows other. */
1182
+ isAfter(other) {
1183
+ return this.unixNanoseconds > other.unixNanoseconds;
1184
+ }
1185
+ /**
1186
+ * Render Go's time.RFC3339Nano: trailing fractional zeros dropped, Z for a zero offset. Throws RangeError for
1187
+ * a year outside 0 to 9999, which Go's JSON encoding refuses as well.
1188
+ */
1189
+ formatRFC3339Nano() {
1190
+ const local = this.unixNanoseconds + BigInt(this.offsetSeconds) * nanosecondsPerSecond;
1191
+ const seconds = floorDivide(local, nanosecondsPerSecond);
1192
+ const fraction = local - seconds * nanosecondsPerSecond;
1193
+ const days = Number(floorDivide(seconds, BigInt(secondsPerDay)));
1194
+ const secondOfDay = Number(seconds - BigInt(days) * BigInt(secondsPerDay));
1195
+ const [year, month, day] = civilFromDays(days);
1196
+ if (year < 0 || year > 9999) throw new RangeError("Go time year is outside the range [0,9999]");
1197
+ let text2 = `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}T${pad(Math.floor(secondOfDay / 3600), 2)}:${pad(Math.floor(secondOfDay / 60) % 60, 2)}:${pad(secondOfDay % 60, 2)}`;
1198
+ if (fraction !== 0n) text2 += `.${fraction.toString().padStart(9, "0").replace(/0+$/, "")}`;
1199
+ if (this.offsetSeconds === 0) return `${text2}Z`;
1200
+ const offsetMinutes = Math.floor(Math.abs(this.offsetSeconds) / 60);
1201
+ return `${text2}${this.offsetSeconds < 0 ? "-" : "+"}${pad(Math.floor(offsetMinutes / 60), 2)}:${pad(offsetMinutes % 60, 2)}`;
1202
+ }
1203
+ /** Return the instant as a Date, truncated to milliseconds. */
1204
+ toDate() {
1205
+ return new Date(Number(floorDivide(this.unixNanoseconds, 1000000n)));
1206
+ }
1207
+ };
1208
+ var unixEpoch = new GoTime(0n);
1209
+ function parseGoTime(value) {
1210
+ const match = rfc3339.exec(value);
1211
+ if (!match) throw new RangeError("time is not RFC 3339");
1212
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
1213
+ const fraction = match[7] ?? "";
1214
+ const offset = match[8];
1215
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) throw new RangeError("time has an invalid date");
1216
+ if (hour > 23 || minute > 59 || second > 59) throw new RangeError("time has an invalid clock time");
1217
+ let offsetSeconds = 0;
1218
+ if (offset !== "Z") {
1219
+ const offsetHours = Number(offset.slice(1, 3));
1220
+ const offsetMinutes = Number(offset.slice(4, 6));
1221
+ if (offsetHours > 24 || offsetMinutes > 60) throw new RangeError("time has an invalid zone offset");
1222
+ offsetSeconds = (offsetHours * 3600 + offsetMinutes * 60) * (offset.startsWith("-") ? -1 : 1);
1223
+ }
1224
+ const nanoseconds = BigInt(`${fraction}000000000`.slice(0, 9));
1225
+ const localSeconds = BigInt(daysFromCivil(year, month, day)) * BigInt(secondsPerDay) + BigInt(hour * 3600 + minute * 60 + second);
1226
+ return new GoTime((localSeconds - BigInt(offsetSeconds)) * nanosecondsPerSecond + nanoseconds, offsetSeconds);
1227
+ }
1228
+ function floorDivide(dividend, divisor) {
1229
+ const quotient = dividend / divisor;
1230
+ return dividend % divisor !== 0n && dividend < 0n !== divisor < 0n ? quotient - 1n : quotient;
1231
+ }
1232
+ function pad(value, width) {
1233
+ return String(value).padStart(width, "0");
1234
+ }
1235
+ function isLeapYear(year) {
1236
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1237
+ }
1238
+ function daysInMonth(year, month) {
1239
+ if (month === 2) return isLeapYear(year) ? 29 : 28;
1240
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
1241
+ }
1242
+ function daysFromCivil(year, month, day) {
1243
+ const shiftedYear = month <= 2 ? year - 1 : year;
1244
+ const era = Math.floor(shiftedYear / 400);
1245
+ const yearOfEra = shiftedYear - era * 400;
1246
+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
1247
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
1248
+ return era * 146097 + dayOfEra - 719468;
1249
+ }
1250
+ function civilFromDays(days) {
1251
+ const shifted = days + 719468;
1252
+ const era = Math.floor(shifted / 146097);
1253
+ const dayOfEra = shifted - era * 146097;
1254
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
1255
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
1256
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
1257
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
1258
+ const month = monthIndex + (monthIndex < 10 ? 3 : -9);
1259
+ return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day];
1260
+ }
1261
+
1262
+ // src/database_row_cursor.ts
1263
+ var databaseRowCursorVersion = 1;
1264
+ var databaseRowLookbackNanoseconds = 120000000000n;
1265
+ var maximumSeenDatabaseRows = 2e3;
1266
+ var maximumSeenRowBytes = 48 << 10;
1267
+ var int64Minimum = -(1n << 63n);
1268
+ var int64Maximum = (1n << 63n) - 1n;
1269
+ var goZeroTime = parseGoTime("0001-01-01T00:00:00Z");
1270
+ var DatabaseRowCursorDecodeError = class extends Error {
1271
+ constructor(message) {
1272
+ super(message);
1273
+ this.name = "DatabaseRowCursorDecodeError";
1274
+ }
1275
+ };
1276
+ var SourceNumber = class {
1277
+ constructor(source) {
1278
+ this.source = source;
1279
+ }
1280
+ source;
1281
+ };
1282
+ function decodeDatabaseRowCursor(token) {
1283
+ let document;
1284
+ const keepNumberSource = (_key, value, context) => typeof value === "number" ? new SourceNumber(context?.source ?? String(value)) : value;
1285
+ try {
1286
+ document = JSON.parse(token, keepNumberSource);
1287
+ } catch {
1288
+ throw new DatabaseRowCursorDecodeError("cursor is not JSON");
1289
+ }
1290
+ const cursor = { version: 0, dataSourceId: "", highWater: goZeroTime, queryFrom: null, startCursor: "", seen: [] };
1291
+ if (document === null) return cursor;
1292
+ if (!isPlainObject(document)) throw new DatabaseRowCursorDecodeError("cursor is not an object");
1293
+ for (const [name, value] of foldMembers(document, ["v", "dataSourceId", "highWater", "queryFrom", "startCursor", "seen"])) {
1294
+ if (value === null) {
1295
+ if (name === "queryFrom") cursor.queryFrom = null;
1296
+ else if (name === "seen") cursor.seen = [];
1297
+ continue;
1298
+ }
1299
+ switch (name) {
1300
+ case "v":
1301
+ cursor.version = decodeInt64(value);
1302
+ break;
1303
+ case "dataSourceId":
1304
+ cursor.dataSourceId = decodeString(value);
1305
+ break;
1306
+ case "highWater":
1307
+ cursor.highWater = decodeTime(value);
1308
+ break;
1309
+ case "queryFrom":
1310
+ cursor.queryFrom = decodeTime(value);
1311
+ break;
1312
+ case "startCursor":
1313
+ cursor.startCursor = decodeString(value);
1314
+ break;
1315
+ default:
1316
+ cursor.seen = decodeSeen(value);
1317
+ }
1318
+ }
1319
+ return cursor;
1320
+ }
1321
+ function encodeDatabaseRowCursor(cursor) {
1322
+ let encoded = `{"v":${cursor.version},"dataSourceId":${encodeGoJSONValue(cursor.dataSourceId)},"highWater":"${cursor.highWater.formatRFC3339Nano()}"`;
1323
+ if (cursor.queryFrom) encoded += `,"queryFrom":"${cursor.queryFrom.formatRFC3339Nano()}"`;
1324
+ if (cursor.startCursor) encoded += `,"startCursor":${encodeGoJSONValue(cursor.startCursor)}`;
1325
+ if (cursor.seen.length) {
1326
+ const groups = cursor.seen.map((group) => `{"at":"${group.lastEditedTime.formatRFC3339Nano()}","rows":${group.rowKeys === null ? "null" : `[${group.rowKeys.map((key) => encodeGoJSONValue(key)).join(",")}]`}}`);
1327
+ encoded += `,"seen":[${groups.join(",")}]`;
1328
+ }
1329
+ return `${encoded}}`;
1330
+ }
1331
+ var SeenRows = class {
1332
+ keysByInstant = /* @__PURE__ */ new Map();
1333
+ /** Index the committed groups. */
1334
+ constructor(groups) {
1335
+ for (const group of groups) for (const key of group.rowKeys ?? []) this.addKey(group.lastEditedTime, key);
1336
+ }
1337
+ /** Report whether this row version was already delivered or baselined. */
1338
+ contains(lastEditedTime2, rowId) {
1339
+ return this.keysByInstant.get(lastEditedTime2.unixNanoseconds)?.has(seenRowKey(rowId)) ?? false;
1340
+ }
1341
+ /** Remember one row version. */
1342
+ add(lastEditedTime2, rowId) {
1343
+ this.addKey(lastEditedTime2, seenRowKey(rowId));
1344
+ }
1345
+ /** Keep the newest row versions edited inside the lookback, bounded in count and encoded bytes. */
1346
+ groupsWithin(highWater) {
1347
+ const lowerBound = highWater.unixNanoseconds - databaseRowLookbackNanoseconds;
1348
+ const instants = [...this.keysByInstant.keys()].filter((instant) => instant >= lowerBound).sort((left, right) => left < right ? 1 : left > right ? -1 : 0);
1349
+ const groups = [];
1350
+ let remaining = maximumSeenDatabaseRows;
1351
+ let remainingBytes = maximumSeenRowBytes;
1352
+ const keyBytes = '"",'.length + seenRowKey("").length;
1353
+ for (const instant of instants) {
1354
+ const lastEditedTime2 = new GoTime(instant);
1355
+ const groupBytes = '{"at":"","rows":[]},'.length + lastEditedTime2.formatRFC3339Nano().length;
1356
+ const fitting = Math.min(remaining, Math.trunc((remainingBytes - groupBytes) / keyBytes));
1357
+ if (fitting <= 0) break;
1358
+ const keys = [...this.keysByInstant.get(instant)].sort(compareUTF8).slice(0, fitting);
1359
+ remaining -= keys.length;
1360
+ remainingBytes -= groupBytes + keys.length * keyBytes;
1361
+ groups.push({ lastEditedTime: lastEditedTime2, rowKeys: keys });
1362
+ }
1363
+ return groups.reverse();
1364
+ }
1365
+ addKey(lastEditedTime2, key) {
1366
+ const keys = this.keysByInstant.get(lastEditedTime2.unixNanoseconds) ?? /* @__PURE__ */ new Set();
1367
+ keys.add(key);
1368
+ this.keysByInstant.set(lastEditedTime2.unixNanoseconds, keys);
1369
+ }
1370
+ };
1371
+ function seenRowKey(rowId) {
1372
+ return createHash("sha256").update(rowId).digest().subarray(0, 12).toString("base64url");
1373
+ }
1374
+ function compareUTF8(left, right) {
1375
+ return Buffer.compare(Buffer.from(left), Buffer.from(right));
1376
+ }
1377
+ function isPlainObject(value) {
1378
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof SourceNumber);
1379
+ }
1380
+ function foldMembers(document, names) {
1381
+ const members = [];
1382
+ for (const [key, value] of Object.entries(document)) {
1383
+ const name = names.includes(key) ? key : names.find((candidate) => candidate.toLowerCase() === key.toLowerCase());
1384
+ if (name !== void 0) members.push([name, value]);
1385
+ }
1386
+ return members;
1387
+ }
1388
+ function decodeInt64(value) {
1389
+ if (!(value instanceof SourceNumber) || !/^-?(0|[1-9][0-9]*)$/.test(value.source)) throw new DatabaseRowCursorDecodeError("cursor version is not an integer");
1390
+ const parsed = BigInt(value.source);
1391
+ if (parsed < int64Minimum || parsed > int64Maximum) throw new DatabaseRowCursorDecodeError("cursor version is out of range");
1392
+ return parsed === BigInt(databaseRowCursorVersion) ? databaseRowCursorVersion : -1;
1393
+ }
1394
+ function decodeString(value) {
1395
+ if (typeof value !== "string") throw new DatabaseRowCursorDecodeError("cursor string field has another type");
1396
+ return value;
1397
+ }
1398
+ function decodeTime(value) {
1399
+ try {
1400
+ return parseGoTime(decodeString(value));
1401
+ } catch {
1402
+ throw new DatabaseRowCursorDecodeError("cursor time is not RFC 3339");
1403
+ }
1404
+ }
1405
+ function decodeSeen(value) {
1406
+ if (!Array.isArray(value)) throw new DatabaseRowCursorDecodeError("cursor seen is not an array");
1407
+ return value.map((item) => {
1408
+ const group = { lastEditedTime: goZeroTime, rowKeys: null };
1409
+ if (item === null) return group;
1410
+ if (!isPlainObject(item)) throw new DatabaseRowCursorDecodeError("cursor seen group is not an object");
1411
+ for (const [name, member] of foldMembers(item, ["at", "rows"])) {
1412
+ if (member === null) {
1413
+ if (name === "rows") group.rowKeys = null;
1414
+ continue;
1415
+ }
1416
+ if (name === "at") {
1417
+ group.lastEditedTime = decodeTime(member);
1418
+ continue;
1419
+ }
1420
+ if (!Array.isArray(member)) throw new DatabaseRowCursorDecodeError("cursor seen rows is not an array");
1421
+ group.rowKeys = member.map((key) => key === null ? "" : decodeString(key));
1422
+ }
1423
+ return group;
1424
+ });
1425
+ }
1426
+
1427
+ // src/database_row_fetcher.ts
1428
+ import { createHash as createHash2 } from "crypto";
1429
+ import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
1430
+ var operationId = "databaseRowChanged";
1431
+ var lastEditedTime = "last_edited_time";
1432
+ var maximumSeedPages = 20;
1433
+ var emptyDataSourceHighWater = unixEpoch.add(databaseRowLookbackNanoseconds);
1434
+ var DatabaseRowPollError = class extends Error {
1435
+ constructor(message, options) {
1436
+ super(message, options);
1437
+ this.name = "DatabaseRowPollError";
1438
+ }
1439
+ };
1440
+ var StaleStartCursorError = class extends DatabaseRowPollError {
1441
+ };
1442
+ var DatabaseRowFetcher = class {
1443
+ /** Bind the client and the dashed watched data source ID; it sends nothing. */
1444
+ constructor(client, connection, trigger, dataSourceId) {
1445
+ this.client = client;
1446
+ this.connection = connection;
1447
+ this.trigger = trigger;
1448
+ this.dataSourceId = dataSourceId;
1449
+ }
1450
+ client;
1451
+ connection;
1452
+ trigger;
1453
+ dataSourceId;
1454
+ /** Read the newest last edited time, then remember every row edited inside the lookback before it. */
1455
+ async seedCursor(context) {
1456
+ const newest = await this.query(context, null, "", 1, true);
1457
+ const position = { version: databaseRowCursorVersion, dataSourceId: this.dataSourceId, highWater: emptyDataSourceHighWater, queryFrom: null, startCursor: "", seen: [] };
1458
+ if (newest.rows[0]) position.highWater = newest.rows[0].lastEditedTime;
1459
+ const seen = new SeenRows([]);
1460
+ const queryFrom = position.highWater.add(-databaseRowLookbackNanoseconds);
1461
+ let startCursor = "";
1462
+ for (let page = 0; page < maximumSeedPages; page++) {
1463
+ const queried = await this.query(context, queryFrom, startCursor, this.client.pollPageSize);
1464
+ for (const row of queried.rows) {
1465
+ seen.add(row.lastEditedTime, row.page.id);
1466
+ position.highWater = laterTime(position.highWater, row.lastEditedTime);
1467
+ }
1468
+ if (!queried.nextCursor) break;
1469
+ startCursor = queried.nextCursor;
1470
+ }
1471
+ position.seen = seen.groupsWithin(position.highWater);
1472
+ return encode(position);
1473
+ }
1474
+ /**
1475
+ * Query rows edited at or after the lookback before the high water, oldest first, and return each row version
1476
+ * not yet seen. An undecodable cursor, or one for another data source, is marked invalid so the kit records a
1477
+ * new baseline; a start cursor Notion rejects restarts the query instead.
1478
+ */
1479
+ async fetchChanges(context, cursor) {
1480
+ let position;
1481
+ try {
1482
+ position = decodeDatabaseRowCursor(cursor.token);
1483
+ } catch (error) {
1484
+ if (!(error instanceof DatabaseRowCursorDecodeError)) throw error;
1485
+ }
1486
+ if (!position || position.version !== databaseRowCursorVersion || position.highWater.unixNanoseconds === goZeroTime.unixNanoseconds) {
1487
+ throw markCursorInvalid(new DatabaseRowPollError("Notion databaseRowChanged cursor is not decodable"));
1488
+ }
1489
+ if (position.dataSourceId !== this.dataSourceId) throw markCursorInvalid(new DatabaseRowPollError("Notion databaseRowChanged cursor belongs to another data source"));
1490
+ let queryFrom = position.highWater.add(-databaseRowLookbackNanoseconds);
1491
+ if (position.startCursor && position.queryFrom) queryFrom = position.queryFrom;
1492
+ let queried;
1493
+ try {
1494
+ queried = await this.query(context, queryFrom, position.startCursor, this.client.pollPageSize);
1495
+ } catch (error) {
1496
+ if (!(error instanceof StaleStartCursorError)) throw error;
1497
+ position.startCursor = "";
1498
+ position.queryFrom = null;
1499
+ return { changes: [], next: encode(position), hasMorePages: true };
1500
+ }
1501
+ const seen = new SeenRows(position.seen);
1502
+ const changes = [];
1503
+ for (const row of queried.rows) {
1504
+ if (row.lastEditedTime.isBefore(queryFrom) || seen.contains(row.lastEditedTime, row.page.id)) continue;
1505
+ seen.add(row.lastEditedTime, row.page.id);
1506
+ position.highWater = laterTime(position.highWater, row.lastEditedTime);
1507
+ changes.push(newDatabaseRowChangedTriggerEvent(this.dataSourceId, row.page, row.lastEditedTime));
1508
+ }
1509
+ position.startCursor = "";
1510
+ position.queryFrom = null;
1511
+ const hasMorePages = queried.nextCursor !== "";
1512
+ if (hasMorePages) {
1513
+ position.startCursor = queried.nextCursor;
1514
+ position.queryFrom = queryFrom;
1515
+ }
1516
+ position.seen = seen.groupsWithin(position.highWater);
1517
+ return { changes, next: encode(position), hasMorePages };
1518
+ }
1519
+ async query(context, editedOnOrAfter, startCursor, pageSize, isNewestFirst = false) {
1520
+ await waitForPollRequest(context);
1521
+ const call = newTriggerCredentialCall(this.connection, this.trigger, context.signal);
1522
+ const resolved = await this.client.resolveToken(call, operationId, context.signal);
1523
+ if ("outcome" in resolved) throw new DatabaseRowPollError("Notion databaseRowChanged credentials are unavailable; save the connection's API token again");
1524
+ const body = {
1525
+ ...editedOnOrAfter ? { filter: { [lastEditedTime]: { on_or_after: editedOnOrAfter.inUTC().formatRFC3339Nano() }, timestamp: lastEditedTime } } : {},
1526
+ sorts: [{ direction: isNewestFirst ? "descending" : "ascending", timestamp: lastEditedTime }],
1527
+ ...startCursor ? { start_cursor: startCursor } : {},
1528
+ page_size: pageSize,
1529
+ result_type: "page"
1530
+ };
1531
+ const result = await this.client.exchange(call, operationId, "databaseRowChanged data source query", "POST", `/data_sources/${encodeURIComponent(this.dataSourceId)}/query`, body, "read", context.signal, resolved.token, this.dataSourceId);
1532
+ if ("response" in result) return decodeRowsPage(result.response.body, pageSize);
1533
+ if (startCursor && result.disposition === "providerRejected" && result.failure.kind === "VALIDATION" && result.providerErrorCode === "validation_error") {
1534
+ throw new StaleStartCursorError("Notion rejected the stored query start cursor");
1535
+ }
1536
+ if (result.disposition === "retry" && result.failure.kind === "RATE_LIMIT") throw markRateLimited(new DatabaseRowPollError(result.failure.message), result.retryAfterMs ?? 0);
1537
+ if (result.disposition === "notFound") throw new DatabaseRowPollError("Notion could not find the watched data source; share its database with the connection or pick another data source");
1538
+ throw new DatabaseRowPollError(result.failure.message);
1539
+ }
1540
+ };
1541
+ function newDatabaseRowChangedTriggerEvent(dataSourceId, row, rowLastEditedTime) {
1542
+ return { id: databaseRowChangeId(dataSourceId, row.id, rowLastEditedTime), occurredAt: rowLastEditedTime.toDate(), payload: { dataSourceId, changeKind: databaseRowChangeKind(row), row } };
1543
+ }
1544
+ function databaseRowChangeId(dataSourceId, rowId, rowLastEditedTime) {
1545
+ const identity = [dataSourceId, rowId, rowLastEditedTime.inUTC().formatRFC3339Nano()].join("\0");
1546
+ return `notion-row-${createHash2("sha256").update(identity).digest().subarray(0, 16).toString("hex")}`;
1547
+ }
1548
+ function databaseRowChangeKind(row) {
1549
+ try {
1550
+ return parseGoTime(row.createdTime ?? "").unixNanoseconds === parseGoTime(row.lastEditedTime ?? "").unixNanoseconds ? "created" : "updated";
1551
+ } catch {
1552
+ return "updated";
1553
+ }
1554
+ }
1555
+ function decodeRowsPage(body, pageSize) {
1556
+ const invalidPage = (cause) => new DatabaseRowPollError("Notion returned an invalid databaseRowChanged query page", { cause });
1557
+ let page;
1558
+ try {
1559
+ page = JSON.parse(Buffer.from(body).toString("utf8"));
1560
+ } catch (error) {
1561
+ throw invalidPage(error);
1562
+ }
1563
+ if (page === null) return { rows: [], nextCursor: "" };
1564
+ if (typeof page !== "object" || Array.isArray(page)) throw invalidPage();
1565
+ const { results, next_cursor: nextCursor, has_more: hasMore, request_status: requestStatus } = page;
1566
+ if (results != null && !Array.isArray(results) || nextCursor != null && typeof nextCursor !== "string" || hasMore != null && typeof hasMore !== "boolean" || requestStatus != null && (typeof requestStatus !== "object" || Array.isArray(requestStatus)) || (results?.length ?? 0) > pageSize) throw invalidPage();
1567
+ let validatedCursor;
1568
+ try {
1569
+ validatedCursor = validateCursor(nextCursor ?? "");
1570
+ } catch (error) {
1571
+ throw new DatabaseRowPollError("Notion returned an invalid databaseRowChanged query cursor", { cause: error });
1572
+ }
1573
+ const rows = (results ?? []).map((resource, index) => {
1574
+ let row;
1575
+ try {
1576
+ row = decodePage(resource);
1577
+ } catch (error) {
1578
+ throw new DatabaseRowPollError(`Notion returned an invalid row ${index} in the databaseRowChanged query page`, { cause: error });
1579
+ }
1580
+ try {
1581
+ return { page: row, lastEditedTime: parseGoTime(row.lastEditedTime ?? "").inUTC() };
1582
+ } catch (error) {
1583
+ throw new DatabaseRowPollError(`Notion returned row ${index} without a valid last_edited_time`, { cause: error });
1584
+ }
1585
+ });
1586
+ return { rows, nextCursor: hasMore === true ? validatedCursor : "" };
1587
+ }
1588
+ function laterTime(current, candidate) {
1589
+ return candidate.isAfter(current) ? candidate : current;
1590
+ }
1591
+ function encode(position) {
1592
+ try {
1593
+ return { token: encodeDatabaseRowCursor(position) };
1594
+ } catch (error) {
1595
+ throw new DatabaseRowPollError("encode Notion databaseRowChanged cursor", { cause: error });
1596
+ }
1597
+ }
1598
+
1599
+ // src/database_row_models.ts
1600
+ import { z as z2 } from "zod";
1601
+ var DatabaseRowChangeKind = {
1602
+ /**
1603
+ * A row whose last edited time equals its created time: Notion reports no change type, and a row edited within
1604
+ * the same minute it was created still reads as created.
1605
+ */
1606
+ Created: "created",
1607
+ /** Any other edit to a row's properties or content. */
1608
+ Updated: "updated"
1609
+ };
1610
+ var DatabaseRowChangedEventSchema = z2.object({
1611
+ dataSourceId: z2.string(),
1612
+ changeKind: z2.string(),
1613
+ row: PageSchema
1614
+ });
1615
+ var DatabaseRowChangedTriggerConfigurationSchema = z2.strictObject({
1616
+ dataSourceId: z2.string().optional(),
1617
+ dataSourceName: z2.string().optional()
1618
+ });
1619
+
1620
+ // src/database_row_trigger.ts
1621
+ var DatabaseRowLookbackMs = Number(databaseRowLookbackNanoseconds / 1000000n);
1622
+ var MaximumSeenDatabaseRows = maximumSeenDatabaseRows;
1623
+ var UIUnitDataSourcePicker = "dataSourcePicker";
1624
+ var UIDataSourcePickerPortDataSourceID = "dataSourceId";
1625
+ var UIDataSourcePickerPortDataSourceName = "dataSourceName";
1626
+ var DatabaseRowChangedTriggerDefinition = {
1627
+ trigger: { connectorId: ConnectorID, triggerName: "databaseRowChanged" },
1628
+ description: "Receive each row created or edited in one Notion data source, read by polling the data source query sorted by last edited time; the first run records a baseline and delivers no existing rows, and trashed rows are not delivered."
1629
+ };
1630
+ function defineDatabaseRowChangedTriggerBinding(config) {
1631
+ return mustTriggerBindingDefinition({ definition: DatabaseRowChangedTriggerDefinition, ...config });
1632
+ }
1633
+ function validateDatabaseRowChangedTriggerConfiguration(configuration) {
1634
+ if (!configuration?.dataSourceId?.trim()) throw new TypeError("dataSourceId is required; pick the watched Notion data source in Dex Web");
1635
+ try {
1636
+ parseID(configuration.dataSourceId);
1637
+ } catch (error) {
1638
+ throw new TypeError(`dataSourceId: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1639
+ }
1640
+ }
1641
+ function decodeDatabaseRowChangedEventPayload(_payloadJSON, payloadBytes) {
1642
+ return DatabaseRowChangedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes));
1643
+ }
1644
+ function newDatabaseRowTriggerRunner(config) {
1645
+ const client = notionClientOf(config.connection);
1646
+ if (!config.databaseRowChangedRoutes?.length) throw new TypeError("Notion databaseRowChanged routes are required");
1647
+ const pollers = config.databaseRowChangedRoutes.map((route) => {
1648
+ if (!route.bindingName?.trim() || !route.target) throw new TypeError("Notion databaseRowChanged binding name and target are required");
1649
+ validateRouteConfiguration(route.configuration);
1650
+ return newBindingPoller({
1651
+ definition: DatabaseRowChangedTriggerDefinition,
1652
+ binding: { connection: config.connection.reference, trigger: DatabaseRowChangedTriggerDefinition.trigger, name: route.bindingName },
1653
+ cursor: route.cursor ?? newMemoryCursorStore(),
1654
+ fetcher: newFetcher(client, config.connection, route.configuration),
1655
+ target: route.target
1656
+ });
1657
+ });
1658
+ return newRunner({ connection: config.connection.reference, schedule: pollSchedule(client), pollers, ...client.triggerLogger ? { logger: client.triggerLogger } : {} });
1659
+ }
1660
+ function newProjectDatabaseRowTriggerRunner(project, connectionName, config, options = {}) {
1661
+ const connection = newProjectConnection2(project, connectionName, options);
1662
+ const triggerName = DatabaseRowChangedTriggerDefinition.trigger.triggerName;
1663
+ const routes = config.databaseRowChangedRoutes.map((route) => {
1664
+ if (!route.target) throw new TypeError(`Notion databaseRowChanged binding ${JSON.stringify(route.bindingName)} target is required`);
1665
+ const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName: route.bindingName };
1666
+ let configuration;
1667
+ try {
1668
+ configuration = decodeTriggerConfiguration(project.configuration, key, DatabaseRowChangedTriggerConfigurationSchema);
1669
+ } catch (error) {
1670
+ if (error instanceof ObjectNotFoundError) throw new TypeError(`notion databaseRowChanged binding ${JSON.stringify(route.bindingName)} has no saved data source; pick one in Dex Web and restart`, { cause: error });
1671
+ throw new TypeError(`notion databaseRowChanged binding ${JSON.stringify(route.bindingName)} configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1672
+ }
1673
+ const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { ...options.logger ? { logger: options.logger } : {}, decodePayload: decodeDatabaseRowChangedEventPayload });
1674
+ return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
1675
+ });
1676
+ return newDatabaseRowTriggerRunner({ connection, databaseRowChangedRoutes: routes });
1677
+ }
1678
+ function newDatabaseRowChangedTrigger(config) {
1679
+ if (config.connectionName !== config.connection.reference.name) throw new TypeError(`notion connector trigger connectionName "${config.connectionName}" must equal its connection's name "${config.connection.reference.name}"`);
1680
+ const client = notionClientOf(config.connection);
1681
+ if (!config.bindingName?.trim() || !config.target) throw new TypeError("Notion databaseRowChanged binding name and target are required");
1682
+ validateRouteConfiguration(config.configuration);
1683
+ const binding = { connection: config.connection.reference, trigger: DatabaseRowChangedTriggerDefinition.trigger, name: config.bindingName };
1684
+ const source = newBindingTriggerSource({
1685
+ definition: DatabaseRowChangedTriggerDefinition,
1686
+ binding,
1687
+ cursor: newMemoryCursorStore(),
1688
+ fetcher: newFetcher(client, config.connection, config.configuration)
1689
+ }, pollSchedule(client), client.triggerLogger);
1690
+ return newTrigger({ definition: DatabaseRowChangedTriggerDefinition, binding, source, target: config.target, ...client.triggerLogger ? { logger: client.triggerLogger } : {} });
1691
+ }
1692
+ function newFetcher(client, connection, configuration) {
1693
+ return new DatabaseRowFetcher(client, connection.reference, DatabaseRowChangedTriggerDefinition.trigger, parseID(configuration.dataSourceId ?? ""));
1694
+ }
1695
+ function validateRouteConfiguration(configuration) {
1696
+ try {
1697
+ validateDatabaseRowChangedTriggerConfiguration(configuration ?? {});
1698
+ } catch (error) {
1699
+ throw new TypeError(`notion databaseRowChanged configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1700
+ }
1701
+ }
1702
+ function pollSchedule(client) {
1703
+ return { intervalMs: client.pollIntervalMs };
1704
+ }
1705
+ function notionClientOf(connection) {
1706
+ if (!(connection?.operations instanceof NotionClient)) throw new TypeError("Notion Triggers require a connection from newProjectConnection or newConnection with a NotionClient");
1707
+ return connection.operations;
1708
+ }
1107
1709
  export {
1108
1710
  ConfigSchema,
1109
1711
  Connection,
@@ -1120,6 +1722,11 @@ export {
1120
1722
  CreatePageMetadata,
1121
1723
  CreatePageOperation,
1122
1724
  CreatePageOutputSchema,
1725
+ DatabaseRowChangeKind,
1726
+ DatabaseRowChangedEventSchema,
1727
+ DatabaseRowChangedTriggerConfigurationSchema,
1728
+ DatabaseRowChangedTriggerDefinition,
1729
+ DatabaseRowLookbackMs,
1123
1730
  DateRangeSchema,
1124
1731
  GetPageBranch,
1125
1732
  GetPageBranchDefect,
@@ -1132,6 +1739,7 @@ export {
1132
1739
  GetPageMetadata,
1133
1740
  GetPageOperation,
1134
1741
  GetPageOutputSchema,
1742
+ MaximumSeenDatabaseRows,
1135
1743
  NotionClient,
1136
1744
  PageContentSchema,
1137
1745
  PagePropertySchema,
@@ -1164,6 +1772,9 @@ export {
1164
1772
  SearchMetadata,
1165
1773
  SearchOperation,
1166
1774
  SearchOutputSchema,
1775
+ UIDataSourcePickerPortDataSourceID,
1776
+ UIDataSourcePickerPortDataSourceName,
1777
+ UIUnitDataSourcePicker,
1167
1778
  UpdatePagePropertiesBranch,
1168
1779
  UpdatePagePropertiesBranchDefect,
1169
1780
  UpdatePagePropertiesBranchInvalidResponse,
@@ -1176,12 +1787,18 @@ export {
1176
1787
  UpdatePagePropertiesOperation,
1177
1788
  UpdatePagePropertiesOutputSchema,
1178
1789
  decodeCredentials,
1790
+ decodeDatabaseRowChangedEventPayload,
1791
+ defineDatabaseRowChangedTriggerBinding,
1179
1792
  newConnection,
1180
1793
  newConnectionWithOperations,
1181
1794
  newCreatePageStep,
1795
+ newDatabaseRowChangedTrigger,
1796
+ newDatabaseRowTriggerRunner,
1182
1797
  newGetPageStep,
1183
1798
  newProjectConnection2 as newProjectConnection,
1799
+ newProjectDatabaseRowTriggerRunner,
1184
1800
  newQueryDatabaseStep,
1185
1801
  newSearchStep,
1186
- newUpdatePagePropertiesStep
1802
+ newUpdatePagePropertiesStep,
1803
+ validateDatabaseRowChangedTriggerConfiguration
1187
1804
  };