@superdurable/connector-freshdesk 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
@@ -55,10 +55,11 @@ import {
55
55
  UpdateTicketInputSchema,
56
56
  UpdateTicketMetadata,
57
57
  UpdateTicketOutputSchema,
58
+ decodeCredentials,
58
59
  newConnection,
59
60
  newConnectionWithOperations,
60
61
  newProjectConnection
61
- } from "./chunk-CLK5W7ZY.js";
62
+ } from "./chunk-SSAMOXWJ.js";
62
63
 
63
64
  // src/generated/steps.ts
64
65
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -120,7 +121,7 @@ function newAddNoteStep(configuration) {
120
121
  import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
121
122
 
122
123
  // src/client.ts
123
- import { SecretString, ReauthorizationRequiredError } from "@superdurable/connectors-sdk";
124
+ import { SecretString, ReauthorizationRequiredError, defaultTriggerLogger } from "@superdurable/connectors-sdk";
124
125
  import { AddressRefusal, BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
125
126
  import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
126
127
 
@@ -196,6 +197,9 @@ function truncated(value) {
196
197
  while (end > 0 && (bytes[end] & 192) === 128) end--;
197
198
  return { text: bytes.subarray(0, end).toString("utf8"), isTruncated: true };
198
199
  }
200
+ function decodeTicketWire(value, expectedID = 0) {
201
+ return ticket(value, expectedID);
202
+ }
199
203
  function ticket(value, expectedID = 0) {
200
204
  const wire = object(value);
201
205
  const id = number(wire.id);
@@ -622,6 +626,7 @@ var AddNoteOperation = class {
622
626
  var domainPattern = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
623
627
  var requestIDPattern = /^[A-Za-z0-9._:-]{1,128}$/;
624
628
  var errorFieldPattern = /^[a-z][a-z0-9_]{0,63}$/;
629
+ var minimumPollIntervalMs = 1e4;
625
630
  var FreshdeskClient = class {
626
631
  /** Bind immutable configuration and a live credential source. */
627
632
  constructor(config, credentials, options = {}) {
@@ -630,6 +635,9 @@ var FreshdeskClient = class {
630
635
  if (!credentials) throw new TypeError("Freshdesk credential provider is required");
631
636
  this.maxResponseBytes = config.maxResponseBytes ?? 4194304;
632
637
  if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Freshdesk response limit must be positive");
638
+ this.pollIntervalMs = config.pollIntervalMs ?? 6e4;
639
+ if (!Number.isSafeInteger(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("Freshdesk pollInterval must be at least 10s");
640
+ this.triggerLogger = options.logger ?? defaultTriggerLogger;
633
641
  this.apiBaseURL = validateBaseURL(options.apiBaseURL ?? `https://${config.domain}.freshdesk.com/api/v2`);
634
642
  this.send = options.send ?? sendProviderRequest;
635
643
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
@@ -639,6 +647,10 @@ var FreshdeskClient = class {
639
647
  maxResponseBytes;
640
648
  send;
641
649
  now;
650
+ /** Delay between ticketChanged polls in milliseconds, at least 10 seconds; one minute by default. */
651
+ pollIntervalMs;
652
+ /** Receives the ticketChanged runner's and durable inboxes' records. */
653
+ triggerLogger;
642
654
  /** Bind the search query. */
643
655
  searchTickets() {
644
656
  return new SearchTicketsOperation(this);
@@ -659,6 +671,10 @@ var FreshdeskClient = class {
659
671
  addNote() {
660
672
  return new AddNoteOperation(this);
661
673
  }
674
+ /** Return the current time of the injected clock. */
675
+ currentTime() {
676
+ return this.now();
677
+ }
662
678
  /** Resolve the current API key, classifying terminal credential states. */
663
679
  async resolveCredential(call, operation) {
664
680
  let credential2;
@@ -770,11 +786,18 @@ function safeErrorSummary(body, secret) {
770
786
  }
771
787
 
772
788
  // src/project.ts
773
- function newProjectConnection2(project, connectionName) {
789
+ function newProjectConnection2(project, connectionName, options = {}) {
774
790
  return newProjectConnection(project, connectionName, (loaded, name) => {
775
791
  const selected = loaded.configuration.connections.find((entry) => entry.connectorId === "freshdesk" && entry.connectionName === name);
776
792
  if (!selected) throw new TypeError("Freshdesk project connection is not configured");
777
- const config = ConfigSchema.parse(selected.configuration);
793
+ const raw = selected.configuration;
794
+ const pollIntervalMs = raw.pollInterval === void 0 || raw.pollInterval === null ? void 0 : durationMilliseconds(raw.pollInterval);
795
+ const parsed = ConfigSchema.parse({ ...raw, ...pollIntervalMs !== void 0 ? { pollIntervalMs } : {} });
796
+ const config = {
797
+ domain: parsed.domain,
798
+ ...parsed.maxResponseBytes !== void 0 ? { maxResponseBytes: parsed.maxResponseBytes } : {},
799
+ ...parsed.pollIntervalMs !== void 0 ? { pollIntervalMs: parsed.pollIntervalMs } : {}
800
+ };
778
801
  const credentials = {
779
802
  async resolve(call, signal) {
780
803
  void call;
@@ -784,9 +807,385 @@ function newProjectConnection2(project, connectionName) {
784
807
  return { apiKey: new SecretString2(apiKey) };
785
808
  }
786
809
  };
787
- return new FreshdeskClient({ domain: config.domain, ...config.maxResponseBytes !== void 0 ? { maxResponseBytes: config.maxResponseBytes } : {} }, credentials);
810
+ return new FreshdeskClient(config, credentials, options);
788
811
  });
789
812
  }
813
+ function durationMilliseconds(value) {
814
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("Freshdesk configuration pollInterval has an invalid type");
815
+ return value === 0 ? void 0 : Math.ceil(value / 1e6);
816
+ }
817
+
818
+ // src/trigger_definition.ts
819
+ import { mustTriggerBindingDefinition } from "@superdurable/connectors-sdk";
820
+ import { z } from "zod";
821
+ var TicketChangeCreated = "created";
822
+ var TicketChangeUpdated = "updated";
823
+ var TicketChangedTriggerConfigurationSchema = z.strictObject({
824
+ /**
825
+ * Limits deliveries to these kinds, such as ["created"]. Empty or omitted delivers both. Skipped changes still
826
+ * move the cursor, so adding a kind later never delivers changes the binding already passed.
827
+ */
828
+ changeKinds: z.array(z.string()).nullable().optional()
829
+ }).superRefine((configuration, context) => {
830
+ const seen = /* @__PURE__ */ new Set();
831
+ for (const kind of configuration.changeKinds ?? []) {
832
+ if (kind !== TicketChangeCreated && kind !== TicketChangeUpdated) context.addIssue({ code: "custom", message: `ticketChanged changeKinds entry ${JSON.stringify(kind)} must be created or updated` });
833
+ else if (seen.has(kind)) context.addIssue({ code: "custom", message: `ticketChanged changeKinds lists ${JSON.stringify(kind)} twice` });
834
+ seen.add(kind);
835
+ }
836
+ });
837
+ var TicketChangedEventSchema = z.object({
838
+ /** created or updated; see TicketChangeKind. */
839
+ changeKind: z.enum([TicketChangeCreated, TicketChangeUpdated]),
840
+ /** The ticket as the list returned it, without its description; read it with getTicket for its text. */
841
+ ticket: TicketSchema
842
+ });
843
+ var TicketChangedTriggerDefinition = {
844
+ trigger: { connectorId: ConnectorID, triggerName: "ticketChanged" },
845
+ description: "Receive each Freshdesk ticket created or updated after the binding first started, read by polling the ticket list in updated_at order; the first run records a baseline and delivers no existing tickets."
846
+ };
847
+ function defineTicketChangedTriggerBinding(config) {
848
+ return mustTriggerBindingDefinition({ definition: TicketChangedTriggerDefinition, ...config });
849
+ }
850
+
851
+ // src/ticket_change_fetcher.ts
852
+ import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
853
+ var TicketChangePageSize = 100;
854
+ var MaxTicketListPage = 300;
855
+ var TicketChangeOverlapMs = 6e4;
856
+ var maximumDeliveredTicketKeys = 1500;
857
+ var maximumSeedPages = 15;
858
+ var maximumClockSkewMs = 2e3;
859
+ var requestTimeoutMs = 12e3;
860
+ var zeroTime = Number.NEGATIVE_INFINITY;
861
+ var ticketListTimePattern = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/;
862
+ var goIntegerPattern = /^[+-]?\d+$/;
863
+ var operationName = "ticketChanged";
864
+ var TicketChangeCursorInvalidError = class extends Error {
865
+ /** Describe the rejected token without echoing it. */
866
+ constructor() {
867
+ super("Freshdesk ticketChanged cursor is not decodable");
868
+ this.name = "TicketChangeCursorInvalidError";
869
+ }
870
+ };
871
+ var unixSeconds = (milliseconds) => Math.floor(milliseconds / 1e3);
872
+ var truncateToSecond = (milliseconds) => unixSeconds(milliseconds) * 1e3;
873
+ var formatTicketListTime = (milliseconds) => `${new Date(truncateToSecond(milliseconds)).toISOString().slice(0, 19)}Z`;
874
+ function parseTicketListTime(text2) {
875
+ if (typeof text2 !== "string" || !ticketListTimePattern.test(text2)) throw new TicketChangeCursorInvalidError();
876
+ const parsed = Date.parse(text2);
877
+ if (!Number.isFinite(parsed) || formatTicketListTime(parsed) !== text2) throw new TicketChangeCursorInvalidError();
878
+ return parsed;
879
+ }
880
+ function deliveredTicketKey(ticket2) {
881
+ return `${ticket2.id}@${unixSeconds(Date.parse(ticket2.updatedAt))}`;
882
+ }
883
+ function ticketChangeEventId(ticket2) {
884
+ return `freshdesk-ticket-${ticket2.id}-${unixSeconds(Date.parse(ticket2.updatedAt))}`;
885
+ }
886
+ function deliversTicketChangeKind(configuration, kind) {
887
+ const kinds = configuration.changeKinds ?? [];
888
+ return kinds.length === 0 || kinds.includes(kind);
889
+ }
890
+ function steadyTicketWindowStart(highWaterMs, floorMs) {
891
+ const windowStart = highWaterMs - TicketChangeOverlapMs;
892
+ return floorMs > windowStart ? floorMs : windowStart;
893
+ }
894
+ function formatTicketCursorFloor(floorMs, highWaterMs) {
895
+ return floorMs > highWaterMs - TicketChangeOverlapMs ? formatTicketListTime(floorMs) : "";
896
+ }
897
+ function pruneDeliveredTicketKeys(keys, windowStartMs) {
898
+ const windowSecond = BigInt(unixSeconds(windowStartMs));
899
+ const kept = [];
900
+ const seen = /* @__PURE__ */ new Set();
901
+ for (const key of keys) {
902
+ const separator = key.indexOf("@");
903
+ if (separator < 0 || seen.has(key)) continue;
904
+ const text2 = key.slice(separator + 1);
905
+ if (!goIntegerPattern.test(text2)) continue;
906
+ const updatedAt = BigInt(text2);
907
+ if (updatedAt < -(1n << 63n) || updatedAt >= 1n << 63n || updatedAt < windowSecond) continue;
908
+ seen.add(key);
909
+ kept.push({ key, updatedAt });
910
+ }
911
+ kept.sort((left, right) => left.updatedAt < right.updatedAt ? -1 : left.updatedAt > right.updatedAt ? 1 : 0);
912
+ let floorMs = zeroTime;
913
+ let retained = kept;
914
+ const dropped = kept.length - maximumDeliveredTicketKeys;
915
+ if (dropped > 0) {
916
+ let floorSecond = kept[dropped].updatedAt;
917
+ if (kept[dropped - 1].updatedAt === floorSecond) floorSecond += 1n;
918
+ floorMs = Number(floorSecond) * 1e3;
919
+ retained = kept.slice(dropped).filter((entry) => entry.updatedAt >= floorSecond);
920
+ }
921
+ return { pruned: retained.map((entry) => entry.key), floorMs };
922
+ }
923
+ function encodeGoJSONString(text2) {
924
+ return JSON.stringify(text2.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD")).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
925
+ }
926
+ function encodeTicketChangeCursor(position) {
927
+ const members = [`"updatedSince":${encodeGoJSONString(position.updatedSince)}`];
928
+ if (position.windowStart) members.push(`"windowStart":${encodeGoJSONString(position.windowStart)}`);
929
+ if (position.page) members.push(`"page":${position.page}`);
930
+ if (position.floor) members.push(`"floor":${encodeGoJSONString(position.floor)}`);
931
+ if (position.delivered.length) members.push(`"delivered":[${position.delivered.map(encodeGoJSONString).join(",")}]`);
932
+ return { token: `{${members.join(",")}}` };
933
+ }
934
+ function decodeCursorPosition(token) {
935
+ let document;
936
+ try {
937
+ document = JSON.parse(token);
938
+ } catch {
939
+ throw new TicketChangeCursorInvalidError();
940
+ }
941
+ const position = { updatedSince: "", windowStart: "", page: 0, floor: "", delivered: [] };
942
+ if (document === null) return position;
943
+ if (typeof document !== "object" || Array.isArray(document)) throw new TicketChangeCursorInvalidError();
944
+ for (const [name, value] of Object.entries(document)) {
945
+ if (value === null) continue;
946
+ const folded = name.toLowerCase();
947
+ if (folded === "updatedsince" || folded === "windowstart" || folded === "floor") {
948
+ if (typeof value !== "string") throw new TicketChangeCursorInvalidError();
949
+ if (folded === "updatedsince") position.updatedSince = value;
950
+ else if (folded === "windowstart") position.windowStart = value;
951
+ else position.floor = value;
952
+ } else if (folded === "page") {
953
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TicketChangeCursorInvalidError();
954
+ position.page = value;
955
+ } else if (folded === "delivered") {
956
+ if (!Array.isArray(value) || value.some((item) => item !== null && typeof item !== "string")) throw new TicketChangeCursorInvalidError();
957
+ position.delivered = value.map((item) => typeof item === "string" ? item : "");
958
+ }
959
+ }
960
+ return position;
961
+ }
962
+ function decodeTicketChangeCursor(cursor) {
963
+ const position = decodeCursorPosition(cursor.token);
964
+ const sinceMs = parseTicketListTime(position.updatedSince);
965
+ const floorMs = position.floor ? parseTicketListTime(position.floor) : zeroTime;
966
+ const steady = steadyTicketWindowStart(sinceMs, floorMs);
967
+ if (position.page === 0 && position.windowStart === "") return { position, sinceMs, floorMs, windowStartMs: steady, pageNumber: 1 };
968
+ const backlogStartMs = parseTicketListTime(position.windowStart);
969
+ if (backlogStartMs > sinceMs || position.page === 1 || position.page < 0 || position.page > MaxTicketListPage) throw new TicketChangeCursorInvalidError();
970
+ if (position.page === 0) return { position, sinceMs, floorMs, windowStartMs: Math.max(floorMs, backlogStartMs), pageNumber: 1 };
971
+ return { position, sinceMs, floorMs, windowStartMs: backlogStartMs, pageNumber: position.page };
972
+ }
973
+ function headerValues(headers, name) {
974
+ const value = headers[name];
975
+ return value === void 0 ? [] : Array.isArray(value) ? value : [value];
976
+ }
977
+ function parseHTTPDate(value) {
978
+ if (!value) return void 0;
979
+ const parsed = Date.parse(value);
980
+ return Number.isFinite(parsed) ? truncateToSecond(parsed) : void 0;
981
+ }
982
+ function decodeTicketList(body) {
983
+ let rows;
984
+ try {
985
+ rows = JSON.parse(Buffer.from(body).toString("utf8"));
986
+ } catch {
987
+ throw new TypeError("the response is not a ticket array");
988
+ }
989
+ if (rows === null) return [];
990
+ if (!Array.isArray(rows)) throw new TypeError("the response is not a ticket array");
991
+ if (rows.length > TicketChangePageSize) throw new TypeError(`the page has ${rows.length} tickets, more than ${TicketChangePageSize}`);
992
+ return rows.map((row) => decodeTicketWire(row));
993
+ }
994
+ var TicketChangeFetcher = class {
995
+ /** Bind the fetcher to one connection's client and one binding's validated configuration. */
996
+ constructor(client, connection, configuration) {
997
+ this.client = client;
998
+ this.connection = connection;
999
+ this.configuration = configuration;
1000
+ if (!client || !connection || !configuration) throw new TypeError("Freshdesk ticketChanged client, connection, and configuration are required");
1001
+ }
1002
+ client;
1003
+ connection;
1004
+ configuration;
1005
+ /**
1006
+ * Record the baseline without reporting existing tickets: the high-water mark is Freshdesk's current time
1007
+ * from the response Date header, or the local clock without one, and tickets changed within the overlap
1008
+ * before it are remembered as delivered.
1009
+ */
1010
+ async seedCursor(context) {
1011
+ const baselineMs = truncateToSecond(this.client.currentTime().getTime());
1012
+ let seeded = await this.listSeedWindow(context, baselineMs);
1013
+ if (seeded.serverTimeMs !== void 0 && Math.abs(seeded.serverTimeMs - baselineMs) > maximumClockSkewMs) seeded = await this.listSeedWindow(context, seeded.serverTimeMs);
1014
+ return encodeTicketChangeCursor(seeded.position);
1015
+ }
1016
+ async listSeedWindow(context, baselineMs) {
1017
+ const delivered = [];
1018
+ let serverTimeMs;
1019
+ let sinceMs = baselineMs;
1020
+ for (let pageNumber = 1; pageNumber <= maximumSeedPages; pageNumber++) {
1021
+ const listed = await this.listTicketPage(context, baselineMs - TicketChangeOverlapMs, pageNumber);
1022
+ if (pageNumber === 1) serverTimeMs = listed.serverTimeMs;
1023
+ for (const ticket2 of listed.tickets) {
1024
+ delivered.push(deliveredTicketKey(ticket2));
1025
+ sinceMs = Math.max(sinceMs, Date.parse(ticket2.updatedAt));
1026
+ }
1027
+ if (!listed.hasNextPage) break;
1028
+ }
1029
+ const { pruned, floorMs } = pruneDeliveredTicketKeys(delivered, sinceMs - TicketChangeOverlapMs);
1030
+ return { position: { updatedSince: formatTicketListTime(sinceMs), windowStart: "", page: 0, floor: formatTicketCursorFloor(floorMs, sinceMs), delivered: pruned }, serverTimeMs };
1031
+ }
1032
+ /**
1033
+ * Read one page of tickets updated since the cursor's window start, oldest first. An undecodable cursor and a
1034
+ * Freshdesk 400 for the cursor's query reject with markCursorInvalid, so the kit records a new baseline; a
1035
+ * 429 rejects with markRateLimited and Retry-After.
1036
+ */
1037
+ async fetchChanges(context, cursor) {
1038
+ let decoded;
1039
+ try {
1040
+ decoded = decodeTicketChangeCursor(cursor);
1041
+ } catch (error) {
1042
+ throw markCursorInvalid(error);
1043
+ }
1044
+ const listed = await this.listTicketPage(context, decoded.windowStartMs, decoded.pageNumber);
1045
+ const delivered = new Set(decoded.position.delivered);
1046
+ const deliveredTicketIDs = new Set(decoded.position.delivered.map((key) => key.split("@", 1)[0]));
1047
+ const createdFloorMs = Math.min(decoded.sinceMs - TicketChangeOverlapMs, decoded.windowStartMs);
1048
+ const next = { updatedSince: "", windowStart: "", page: 0, floor: "", delivered: [...decoded.position.delivered] };
1049
+ let highWaterMs = decoded.sinceMs;
1050
+ const changes = [];
1051
+ for (const ticket2 of listed.tickets) {
1052
+ const key = deliveredTicketKey(ticket2);
1053
+ const updatedAtMs = Date.parse(ticket2.updatedAt);
1054
+ if (delivered.has(key) || updatedAtMs < decoded.windowStartMs) continue;
1055
+ const kind = Date.parse(ticket2.createdAt) >= createdFloorMs && !deliveredTicketIDs.has(String(ticket2.id)) ? "created" : "updated";
1056
+ delivered.add(key);
1057
+ next.delivered.push(key);
1058
+ highWaterMs = Math.max(highWaterMs, updatedAtMs);
1059
+ if (deliversTicketChangeKind(this.configuration, kind)) changes.push({ id: ticketChangeEventId(ticket2), occurredAt: new Date(updatedAtMs), payload: { changeKind: kind, ticket: ticket2 } });
1060
+ }
1061
+ next.updatedSince = formatTicketListTime(highWaterMs);
1062
+ let floorMs = decoded.floorMs;
1063
+ let nextWindowStartMs = steadyTicketWindowStart(highWaterMs, floorMs);
1064
+ let hasMorePages = false;
1065
+ const lastTicket = listed.tickets.at(-1);
1066
+ if (decoded.pageNumber >= MaxTicketListPage && listed.tickets.length === TicketChangePageSize) {
1067
+ hasMorePages = true;
1068
+ floorMs = decoded.windowStartMs + 1e3;
1069
+ nextWindowStartMs = steadyTicketWindowStart(highWaterMs, floorMs);
1070
+ } else if (!listed.hasNextPage || !lastTicket) {
1071
+ } else if (Date.parse(lastTicket.updatedAt) > decoded.windowStartMs) {
1072
+ hasMorePages = true;
1073
+ nextWindowStartMs = Date.parse(lastTicket.updatedAt);
1074
+ next.windowStart = formatTicketListTime(nextWindowStartMs);
1075
+ } else {
1076
+ hasMorePages = true;
1077
+ nextWindowStartMs = decoded.windowStartMs;
1078
+ next.windowStart = formatTicketListTime(decoded.windowStartMs);
1079
+ next.page = decoded.pageNumber + 1;
1080
+ }
1081
+ if (!hasMorePages && listed.serverTimeMs !== void 0) {
1082
+ floorMs = Math.max(floorMs, listed.serverTimeMs - TicketChangeOverlapMs - requestTimeoutMs);
1083
+ nextWindowStartMs = steadyTicketWindowStart(highWaterMs, floorMs);
1084
+ }
1085
+ const { pruned, floorMs: overflowFloorMs } = pruneDeliveredTicketKeys(next.delivered, Math.min(steadyTicketWindowStart(highWaterMs, floorMs), nextWindowStartMs));
1086
+ next.delivered = pruned;
1087
+ floorMs = Math.max(floorMs, overflowFloorMs);
1088
+ next.floor = formatTicketCursorFloor(floorMs, highWaterMs);
1089
+ return { changes, next: encodeTicketChangeCursor(next), hasMorePages };
1090
+ }
1091
+ async listTicketPage(context, windowStartMs, pageNumber) {
1092
+ await waitForPollRequest(context);
1093
+ const call = newTriggerCredentialCall(this.connection, TicketChangedTriggerDefinition.trigger, context.signal);
1094
+ const credential2 = await this.client.resolveCredential(call, operationName);
1095
+ if (!("key" in credential2)) throw new Error("Freshdesk ticketChanged credentials are unavailable");
1096
+ const query = new URLSearchParams([
1097
+ ["order_by", "updated_at"],
1098
+ ["order_type", "asc"],
1099
+ ["page", String(pageNumber)],
1100
+ ["per_page", String(TicketChangePageSize)],
1101
+ ["updated_since", formatTicketListTime(windowStartMs)]
1102
+ ]);
1103
+ const result = await this.client.exchange(call, operationName, credential2.key, "GET", "/tickets", query, void 0, context.signal);
1104
+ if (result.outcome !== "succeeded") {
1105
+ const failure = new Error(`Freshdesk ticket list request: ${result.failure.message}`);
1106
+ if (result.outcome === "rateLimited") throw markRateLimited(failure, result.retryAfterMs);
1107
+ if (result.outcome === "rejected" && result.response?.status === 400) throw markCursorInvalid(failure);
1108
+ throw failure;
1109
+ }
1110
+ let tickets;
1111
+ try {
1112
+ tickets = decodeTicketList(result.response.body);
1113
+ } catch (error) {
1114
+ throw new Error(`Freshdesk ticket list page is invalid: ${error instanceof Error ? error.message : String(error)}`);
1115
+ }
1116
+ const headers = result.response.headers;
1117
+ return { tickets, hasNextPage: headerValues(headers, "link").some((link) => link.includes('rel="next"')), serverTimeMs: parseHTTPDate(headerValues(headers, "date")[0]) };
1118
+ }
1119
+ };
1120
+
1121
+ // src/trigger.ts
1122
+ import { newTrigger } from "@superdurable/connectors-sdk";
1123
+ import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
1124
+ import { ObjectNotFoundError as ObjectNotFoundError2, decodeTriggerConfiguration, newDurableTriggerTarget } from "@superdurable/connectors-sdk/projectconfig";
1125
+ var triggerName = TicketChangedTriggerDefinition.trigger.triggerName;
1126
+ function freshdeskClientOf(connection) {
1127
+ if (!connection) throw new TypeError("Freshdesk ticketChanged connection is required");
1128
+ if (!(connection.operations instanceof FreshdeskClient)) throw new TypeError("Freshdesk ticketChanged Triggers require a FreshdeskClient connection, not a mock");
1129
+ return connection.operations;
1130
+ }
1131
+ var pollSchedule = (client) => ({ intervalMs: client.pollIntervalMs });
1132
+ function newTicketTriggerRunner(config) {
1133
+ const client = freshdeskClientOf(config.connection);
1134
+ if (!config.ticketChangedRoutes?.length) throw new TypeError("Freshdesk ticketChanged routes are required");
1135
+ const reference = config.connection.reference;
1136
+ const pollers = config.ticketChangedRoutes.map((route) => {
1137
+ if (!route?.bindingName?.trim() || !route.target) throw new TypeError("Freshdesk ticketChanged binding name and target are required");
1138
+ const configuration = parseTicketChangedTriggerConfiguration(route.configuration ?? {});
1139
+ return newBindingPoller({
1140
+ definition: TicketChangedTriggerDefinition,
1141
+ binding: { connection: reference, trigger: TicketChangedTriggerDefinition.trigger, name: route.bindingName },
1142
+ cursor: route.cursor ?? newMemoryCursorStore(),
1143
+ fetcher: new TicketChangeFetcher(client, reference, configuration),
1144
+ target: route.target
1145
+ });
1146
+ });
1147
+ return newRunner({ connection: reference, schedule: pollSchedule(client), pollers, logger: client.triggerLogger });
1148
+ }
1149
+ function parseTicketChangedTriggerConfiguration(configuration) {
1150
+ const parsed = TicketChangedTriggerConfigurationSchema.safeParse(configuration);
1151
+ if (!parsed.success) throw new TypeError(`freshdesk ticketChanged configuration: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`);
1152
+ return parsed.data;
1153
+ }
1154
+ function decodeTicketChangedEventPayload(payloadJSON) {
1155
+ return TicketChangedEventSchema.parse(JSON.parse(payloadJSON));
1156
+ }
1157
+ function newProjectTicketTriggerRunner(project, connection, config) {
1158
+ if (!project) throw new TypeError("Freshdesk ticketChanged Triggers require a loaded project");
1159
+ const client = freshdeskClientOf(connection);
1160
+ const ticketChangedRoutes = (config.ticketChangedRoutes ?? []).map((route) => {
1161
+ if (!route?.target) throw new TypeError("Freshdesk ticketChanged binding target is required");
1162
+ const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName, bindingName: route.bindingName };
1163
+ let configuration;
1164
+ try {
1165
+ configuration = decodeTriggerConfiguration(project.configuration, key, TicketChangedTriggerConfigurationSchema);
1166
+ } catch (error) {
1167
+ if (!(error instanceof ObjectNotFoundError2)) throw new TypeError(`freshdesk ticketChanged binding ${JSON.stringify(route.bindingName)} configuration is invalid`, { cause: error });
1168
+ configuration = {};
1169
+ }
1170
+ const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { logger: client.triggerLogger, decodePayload: decodeTicketChangedEventPayload });
1171
+ return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
1172
+ });
1173
+ return newTicketTriggerRunner({ connection, ticketChangedRoutes });
1174
+ }
1175
+ function newTicketChangedTrigger(config) {
1176
+ const client = freshdeskClientOf(config.connection);
1177
+ const reference = config.connection.reference;
1178
+ if (config.connectionName !== reference.name) throw new TypeError(`freshdesk connector trigger connectionName ${JSON.stringify(config.connectionName)} must equal its connection's name ${JSON.stringify(reference.name)}`);
1179
+ const configuration = parseTicketChangedTriggerConfiguration(config.configuration ?? {});
1180
+ const binding = { connection: reference, trigger: TicketChangedTriggerDefinition.trigger, name: config.bindingName };
1181
+ const source = newBindingTriggerSource({
1182
+ definition: TicketChangedTriggerDefinition,
1183
+ binding,
1184
+ cursor: newMemoryCursorStore(),
1185
+ fetcher: new TicketChangeFetcher(client, reference, configuration)
1186
+ }, pollSchedule(client), client.triggerLogger);
1187
+ return newTrigger({ definition: TicketChangedTriggerDefinition, binding, source, target: config.target, logger: client.triggerLogger });
1188
+ }
790
1189
  export {
791
1190
  AddNoteBranch,
792
1191
  AddNoteBranchAdded,
@@ -823,6 +1222,7 @@ export {
823
1222
  GetTicketInputSchema,
824
1223
  GetTicketMetadata,
825
1224
  GetTicketOperation,
1225
+ MaxTicketListPage,
826
1226
  ProviderID,
827
1227
  SearchTicketsBranch,
828
1228
  SearchTicketsBranchDefect,
@@ -834,6 +1234,15 @@ export {
834
1234
  SearchTicketsMetadata,
835
1235
  SearchTicketsOperation,
836
1236
  SearchTicketsOutputSchema,
1237
+ TicketChangeCreated,
1238
+ TicketChangeCursorInvalidError,
1239
+ TicketChangeFetcher,
1240
+ TicketChangeOverlapMs,
1241
+ TicketChangePageSize,
1242
+ TicketChangeUpdated,
1243
+ TicketChangedEventSchema,
1244
+ TicketChangedTriggerConfigurationSchema,
1245
+ TicketChangedTriggerDefinition,
837
1246
  TicketConversationSchema,
838
1247
  TicketDetailsSchema,
839
1248
  TicketRequesterInputSchema,
@@ -850,12 +1259,21 @@ export {
850
1259
  UpdateTicketMetadata,
851
1260
  UpdateTicketOperation,
852
1261
  UpdateTicketOutputSchema,
1262
+ decodeCredentials,
1263
+ decodeTicketChangedEventPayload,
1264
+ defineTicketChangedTriggerBinding,
1265
+ deliversTicketChangeKind,
853
1266
  newAddNoteStep,
854
1267
  newConnection,
855
1268
  newConnectionWithOperations,
856
1269
  newCreateTicketStep,
857
1270
  newGetTicketStep,
858
1271
  newProjectConnection2 as newProjectConnection,
1272
+ newProjectTicketTriggerRunner,
859
1273
  newSearchTicketsStep,
860
- newUpdateTicketStep
1274
+ newTicketChangedTrigger,
1275
+ newTicketTriggerRunner,
1276
+ newUpdateTicketStep,
1277
+ parseTicketChangedTriggerConfiguration,
1278
+ ticketChangeEventId
861
1279
  };
package/dist/mock.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
2
2
  import { Failure } from '@superdurable/connectors-sdk';
3
- import { O as Operations, C as Connection, S as SearchTicketsInput, d as SearchTicketsOutput, G as GetTicketInput, T as TicketDetails, b as CreateTicketInput, c as CreateTicketOutput, U as UpdateTicketInput, e as UpdateTicketOutput, A as AddNoteInput, a as AddNoteOutput, q as Ticket, r as TicketConversation, u as TicketRequester, v as TicketRequesterInput } from './connection-BRfKrSCD.js';
3
+ import { O as Operations, C as Connection, S as SearchTicketsInput, d as SearchTicketsOutput, G as GetTicketInput, T as TicketDetails, b as CreateTicketInput, c as CreateTicketOutput, U as UpdateTicketInput, e as UpdateTicketOutput, A as AddNoteInput, a as AddNoteOutput, h as Ticket, r as TicketConversation, u as TicketRequester, v as TicketRequesterInput } from './connection-Lx6ZBW6r.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Go zero value for SearchTicketsInput in scripted cases. */
package/dist/mock.js CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  UpdateTicketInputSchema,
22
22
  UpdateTicketOutputSchema,
23
23
  newConnectionWithOperations
24
- } from "./chunk-CLK5W7ZY.js";
24
+ } from "./chunk-SSAMOXWJ.js";
25
25
 
26
26
  // src/generated/mock.ts
27
27
  import { branchCase, retryCase, uncertainCase, newMutation, newQuery } from "@superdurable/connectors-sdk/connectormock";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superdurable/connector-freshdesk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "license": "MIT",
5
5
  "description": "Freshdesk ticket operations for Dex Flows",
6
6
  "repository": {
@@ -26,7 +26,8 @@
26
26
  "./mock": {
27
27
  "types": "./dist/mock.d.ts",
28
28
  "import": "./dist/mock.js"
29
- }
29
+ },
30
+ "./dex-connector.json": "./dex-connector.json"
30
31
  },
31
32
  "files": [
32
33
  "dist",
@@ -41,11 +42,12 @@
41
42
  "test:integration": "npm run build && vitest run test/integration/*.integration.test.ts",
42
43
  "check": "npm test && npm run typecheck && npm run lint",
43
44
  "example:search": "npm run build && tsx examples/search-tickets/main.ts",
44
- "example:search:start": "npm run build && tsx examples/search-tickets/start.ts"
45
+ "example:search:start": "npm run build && tsx examples/search-tickets/start.ts",
46
+ "example:ticket-changed": "npm run build && tsx examples/ticket-changed/main.ts"
45
47
  },
46
48
  "dependencies": {
47
- "@superdurable/connectors-sdk": "0.1.0",
48
- "@superdurable/dex": ">=1.28.0",
49
+ "@superdurable/connectors-sdk": "0.12.0",
50
+ "@superdurable/dex": ">=1.45.4",
49
51
  "zod": "^4.1.0"
50
52
  },
51
53
  "devDependencies": {