@mastra/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/authenticator.d.ts +62 -0
  2. package/dist/constants.d.ts +1 -0
  3. package/dist/core.cjs.development.js +5011 -0
  4. package/dist/core.cjs.development.js.map +1 -0
  5. package/dist/core.cjs.production.min.js +2 -0
  6. package/dist/core.cjs.production.min.js.map +1 -0
  7. package/dist/core.esm.js +4947 -0
  8. package/dist/core.esm.js.map +1 -0
  9. package/dist/data-access/index.d.ts +350 -0
  10. package/dist/framework.d.ts +116 -0
  11. package/dist/generated-types/index.d.ts +4 -0
  12. package/dist/index.d.ts +16 -0
  13. package/dist/index.js +8 -0
  14. package/dist/integration.d.ts +100 -0
  15. package/dist/lib/index.d.ts +5 -0
  16. package/dist/lib/query-builder/constants.d.ts +16 -0
  17. package/dist/lib/query-builder/filters/sql.d.ts +8 -0
  18. package/dist/lib/query-builder/schema.d.ts +36 -0
  19. package/dist/lib/query-builder/sorts/sql.d.ts +7 -0
  20. package/dist/lib/query-builder/types.d.ts +30 -0
  21. package/dist/lib/query-builder/utils.d.ts +26 -0
  22. package/dist/lib/utils/object.d.ts +50 -0
  23. package/dist/next/callback.d.ts +3 -0
  24. package/dist/next/connect.d.ts +3 -0
  25. package/dist/next/index.d.ts +15 -0
  26. package/dist/next/inngest.d.ts +3 -0
  27. package/dist/next/utils.d.ts +9 -0
  28. package/dist/next/webhook.d.ts +9 -0
  29. package/dist/prisma/client.d.ts +2 -0
  30. package/dist/prisma/client.ts +31 -0
  31. package/dist/prisma/gen.js +139 -0
  32. package/dist/prisma/migrations/20240828034109_initial_migration/migration.sql +111 -0
  33. package/dist/prisma/migrations/20240829210901_initial_migration/migration.sql +1 -0
  34. package/dist/prisma/migrations/20240905143158_initial_migration/migration.sql +1 -0
  35. package/dist/prisma/migrations/20240911212856_initial_migration/migration.sql +1 -0
  36. package/dist/prisma/migrations/20240915044235_initial_migration/migration.sql +1 -0
  37. package/dist/prisma/migrations/migration_lock.toml +3 -0
  38. package/dist/prisma/schema.prisma +129 -0
  39. package/dist/schemas.d.ts +84 -0
  40. package/dist/service/service.property.d.ts +24 -0
  41. package/dist/service/service.record.d.ts +24 -0
  42. package/dist/sync-factory.d.ts +13 -0
  43. package/dist/sync-fixtures/github.d.ts +949 -0
  44. package/dist/sync-fixtures/stripe.d.ts +92 -0
  45. package/dist/types.d.ts +367 -0
  46. package/dist/utils/errors.d.ts +3 -0
  47. package/dist/utils/index.d.ts +12 -0
  48. package/dist/utils/inngest.d.ts +4 -0
  49. package/dist/workflows/conditions/constants.d.ts +16 -0
  50. package/dist/workflows/conditions/types.d.ts +2 -0
  51. package/dist/workflows/handler.d.ts +38 -0
  52. package/dist/workflows/runner.d.ts +43 -0
  53. package/dist/workflows/schemas.d.ts +1043 -0
  54. package/dist/workflows/types.d.ts +96 -0
  55. package/dist/workflows/utils.d.ts +111 -0
  56. package/package.json +2 -2
@@ -0,0 +1,4947 @@
1
+ import { PrismaClient, PropertyType, Prisma } from '@prisma-app/client';
2
+ export { PropertyType } from '@prisma-app/client';
3
+ import { UTCDate } from '@date-fns/utc';
4
+ import * as dateFns from 'date-fns';
5
+ import { startOfDay, endOfDay } from 'date-fns';
6
+ import { PrismaClientKnownRequestError, PrismaClientValidationError } from '@prisma/client/runtime/library';
7
+ import { NextResponse } from 'next/server';
8
+ import { z } from 'zod';
9
+ import { headers } from 'next/headers';
10
+ import qs from 'qs';
11
+ import { serve } from 'inngest/next';
12
+ import path from 'path';
13
+ import * as fs from 'fs';
14
+ import first from 'lodash-es/first';
15
+ import last from 'lodash-es/last';
16
+ import { Inngest } from 'inngest';
17
+ import { OAuth2Client } from '@badgateway/oauth2-client';
18
+ import _, { isEmpty, omit, omitBy } from 'lodash-es';
19
+
20
+ var WorkflowStatusEnum = {
21
+ DRAFT: 'DRAFT',
22
+ UNPUBLISHED: 'UNPUBLISHED',
23
+ PUBLISHED: 'PUBLISHED'
24
+ };
25
+ var RunStatus = {
26
+ PENDING: 'PENDING',
27
+ RUNNING: 'RUNNING',
28
+ COMPLETED: 'COMPLETED',
29
+ FAILED: 'FAILED'
30
+ };
31
+
32
+ function _arrayLikeToArray(r, a) {
33
+ (null == a || a > r.length) && (a = r.length);
34
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
35
+ return n;
36
+ }
37
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
38
+ try {
39
+ var i = n[a](c),
40
+ u = i.value;
41
+ } catch (n) {
42
+ return void e(n);
43
+ }
44
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
45
+ }
46
+ function _asyncToGenerator(n) {
47
+ return function () {
48
+ var t = this,
49
+ e = arguments;
50
+ return new Promise(function (r, o) {
51
+ var a = n.apply(t, e);
52
+ function _next(n) {
53
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
54
+ }
55
+ function _throw(n) {
56
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
57
+ }
58
+ _next(void 0);
59
+ });
60
+ };
61
+ }
62
+ function _construct(t, e, r) {
63
+ if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
64
+ var o = [null];
65
+ o.push.apply(o, e);
66
+ var p = new (t.bind.apply(t, o))();
67
+ return r && _setPrototypeOf(p, r.prototype), p;
68
+ }
69
+ function _defineProperties(e, r) {
70
+ for (var t = 0; t < r.length; t++) {
71
+ var o = r[t];
72
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
73
+ }
74
+ }
75
+ function _createClass(e, r, t) {
76
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
77
+ writable: !1
78
+ }), e;
79
+ }
80
+ function _createForOfIteratorHelperLoose(r, e) {
81
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
82
+ if (t) return (t = t.call(r)).next.bind(t);
83
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
84
+ t && (r = t);
85
+ var o = 0;
86
+ return function () {
87
+ return o >= r.length ? {
88
+ done: !0
89
+ } : {
90
+ done: !1,
91
+ value: r[o++]
92
+ };
93
+ };
94
+ }
95
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
96
+ }
97
+ function _extends() {
98
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
99
+ for (var e = 1; e < arguments.length; e++) {
100
+ var t = arguments[e];
101
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
102
+ }
103
+ return n;
104
+ }, _extends.apply(null, arguments);
105
+ }
106
+ function _getPrototypeOf(t) {
107
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
108
+ return t.__proto__ || Object.getPrototypeOf(t);
109
+ }, _getPrototypeOf(t);
110
+ }
111
+ function _inheritsLoose(t, o) {
112
+ t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
113
+ }
114
+ function _isNativeFunction(t) {
115
+ try {
116
+ return -1 !== Function.toString.call(t).indexOf("[native code]");
117
+ } catch (n) {
118
+ return "function" == typeof t;
119
+ }
120
+ }
121
+ function _isNativeReflectConstruct() {
122
+ try {
123
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
124
+ } catch (t) {}
125
+ return (_isNativeReflectConstruct = function () {
126
+ return !!t;
127
+ })();
128
+ }
129
+ function _objectWithoutPropertiesLoose(r, e) {
130
+ if (null == r) return {};
131
+ var t = {};
132
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
133
+ if (e.includes(n)) continue;
134
+ t[n] = r[n];
135
+ }
136
+ return t;
137
+ }
138
+ function _regeneratorRuntime() {
139
+ _regeneratorRuntime = function () {
140
+ return e;
141
+ };
142
+ var t,
143
+ e = {},
144
+ r = Object.prototype,
145
+ n = r.hasOwnProperty,
146
+ o = Object.defineProperty || function (t, e, r) {
147
+ t[e] = r.value;
148
+ },
149
+ i = "function" == typeof Symbol ? Symbol : {},
150
+ a = i.iterator || "@@iterator",
151
+ c = i.asyncIterator || "@@asyncIterator",
152
+ u = i.toStringTag || "@@toStringTag";
153
+ function define(t, e, r) {
154
+ return Object.defineProperty(t, e, {
155
+ value: r,
156
+ enumerable: !0,
157
+ configurable: !0,
158
+ writable: !0
159
+ }), t[e];
160
+ }
161
+ try {
162
+ define({}, "");
163
+ } catch (t) {
164
+ define = function (t, e, r) {
165
+ return t[e] = r;
166
+ };
167
+ }
168
+ function wrap(t, e, r, n) {
169
+ var i = e && e.prototype instanceof Generator ? e : Generator,
170
+ a = Object.create(i.prototype),
171
+ c = new Context(n || []);
172
+ return o(a, "_invoke", {
173
+ value: makeInvokeMethod(t, r, c)
174
+ }), a;
175
+ }
176
+ function tryCatch(t, e, r) {
177
+ try {
178
+ return {
179
+ type: "normal",
180
+ arg: t.call(e, r)
181
+ };
182
+ } catch (t) {
183
+ return {
184
+ type: "throw",
185
+ arg: t
186
+ };
187
+ }
188
+ }
189
+ e.wrap = wrap;
190
+ var h = "suspendedStart",
191
+ l = "suspendedYield",
192
+ f = "executing",
193
+ s = "completed",
194
+ y = {};
195
+ function Generator() {}
196
+ function GeneratorFunction() {}
197
+ function GeneratorFunctionPrototype() {}
198
+ var p = {};
199
+ define(p, a, function () {
200
+ return this;
201
+ });
202
+ var d = Object.getPrototypeOf,
203
+ v = d && d(d(values([])));
204
+ v && v !== r && n.call(v, a) && (p = v);
205
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
206
+ function defineIteratorMethods(t) {
207
+ ["next", "throw", "return"].forEach(function (e) {
208
+ define(t, e, function (t) {
209
+ return this._invoke(e, t);
210
+ });
211
+ });
212
+ }
213
+ function AsyncIterator(t, e) {
214
+ function invoke(r, o, i, a) {
215
+ var c = tryCatch(t[r], t, o);
216
+ if ("throw" !== c.type) {
217
+ var u = c.arg,
218
+ h = u.value;
219
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
220
+ invoke("next", t, i, a);
221
+ }, function (t) {
222
+ invoke("throw", t, i, a);
223
+ }) : e.resolve(h).then(function (t) {
224
+ u.value = t, i(u);
225
+ }, function (t) {
226
+ return invoke("throw", t, i, a);
227
+ });
228
+ }
229
+ a(c.arg);
230
+ }
231
+ var r;
232
+ o(this, "_invoke", {
233
+ value: function (t, n) {
234
+ function callInvokeWithMethodAndArg() {
235
+ return new e(function (e, r) {
236
+ invoke(t, n, e, r);
237
+ });
238
+ }
239
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
240
+ }
241
+ });
242
+ }
243
+ function makeInvokeMethod(e, r, n) {
244
+ var o = h;
245
+ return function (i, a) {
246
+ if (o === f) throw Error("Generator is already running");
247
+ if (o === s) {
248
+ if ("throw" === i) throw a;
249
+ return {
250
+ value: t,
251
+ done: !0
252
+ };
253
+ }
254
+ for (n.method = i, n.arg = a;;) {
255
+ var c = n.delegate;
256
+ if (c) {
257
+ var u = maybeInvokeDelegate(c, n);
258
+ if (u) {
259
+ if (u === y) continue;
260
+ return u;
261
+ }
262
+ }
263
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
264
+ if (o === h) throw o = s, n.arg;
265
+ n.dispatchException(n.arg);
266
+ } else "return" === n.method && n.abrupt("return", n.arg);
267
+ o = f;
268
+ var p = tryCatch(e, r, n);
269
+ if ("normal" === p.type) {
270
+ if (o = n.done ? s : l, p.arg === y) continue;
271
+ return {
272
+ value: p.arg,
273
+ done: n.done
274
+ };
275
+ }
276
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
277
+ }
278
+ };
279
+ }
280
+ function maybeInvokeDelegate(e, r) {
281
+ var n = r.method,
282
+ o = e.iterator[n];
283
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
284
+ var i = tryCatch(o, e.iterator, r.arg);
285
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
286
+ var a = i.arg;
287
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
288
+ }
289
+ function pushTryEntry(t) {
290
+ var e = {
291
+ tryLoc: t[0]
292
+ };
293
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
294
+ }
295
+ function resetTryEntry(t) {
296
+ var e = t.completion || {};
297
+ e.type = "normal", delete e.arg, t.completion = e;
298
+ }
299
+ function Context(t) {
300
+ this.tryEntries = [{
301
+ tryLoc: "root"
302
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
303
+ }
304
+ function values(e) {
305
+ if (e || "" === e) {
306
+ var r = e[a];
307
+ if (r) return r.call(e);
308
+ if ("function" == typeof e.next) return e;
309
+ if (!isNaN(e.length)) {
310
+ var o = -1,
311
+ i = function next() {
312
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
313
+ return next.value = t, next.done = !0, next;
314
+ };
315
+ return i.next = i;
316
+ }
317
+ }
318
+ throw new TypeError(typeof e + " is not iterable");
319
+ }
320
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
321
+ value: GeneratorFunctionPrototype,
322
+ configurable: !0
323
+ }), o(GeneratorFunctionPrototype, "constructor", {
324
+ value: GeneratorFunction,
325
+ configurable: !0
326
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
327
+ var e = "function" == typeof t && t.constructor;
328
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
329
+ }, e.mark = function (t) {
330
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
331
+ }, e.awrap = function (t) {
332
+ return {
333
+ __await: t
334
+ };
335
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
336
+ return this;
337
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
338
+ void 0 === i && (i = Promise);
339
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
340
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
341
+ return t.done ? t.value : a.next();
342
+ });
343
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
344
+ return this;
345
+ }), define(g, "toString", function () {
346
+ return "[object Generator]";
347
+ }), e.keys = function (t) {
348
+ var e = Object(t),
349
+ r = [];
350
+ for (var n in e) r.push(n);
351
+ return r.reverse(), function next() {
352
+ for (; r.length;) {
353
+ var t = r.pop();
354
+ if (t in e) return next.value = t, next.done = !1, next;
355
+ }
356
+ return next.done = !0, next;
357
+ };
358
+ }, e.values = values, Context.prototype = {
359
+ constructor: Context,
360
+ reset: function (e) {
361
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
362
+ },
363
+ stop: function () {
364
+ this.done = !0;
365
+ var t = this.tryEntries[0].completion;
366
+ if ("throw" === t.type) throw t.arg;
367
+ return this.rval;
368
+ },
369
+ dispatchException: function (e) {
370
+ if (this.done) throw e;
371
+ var r = this;
372
+ function handle(n, o) {
373
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
374
+ }
375
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
376
+ var i = this.tryEntries[o],
377
+ a = i.completion;
378
+ if ("root" === i.tryLoc) return handle("end");
379
+ if (i.tryLoc <= this.prev) {
380
+ var c = n.call(i, "catchLoc"),
381
+ u = n.call(i, "finallyLoc");
382
+ if (c && u) {
383
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
384
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
385
+ } else if (c) {
386
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
387
+ } else {
388
+ if (!u) throw Error("try statement without catch or finally");
389
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
390
+ }
391
+ }
392
+ }
393
+ },
394
+ abrupt: function (t, e) {
395
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
396
+ var o = this.tryEntries[r];
397
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
398
+ var i = o;
399
+ break;
400
+ }
401
+ }
402
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
403
+ var a = i ? i.completion : {};
404
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
405
+ },
406
+ complete: function (t, e) {
407
+ if ("throw" === t.type) throw t.arg;
408
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
409
+ },
410
+ finish: function (t) {
411
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
412
+ var r = this.tryEntries[e];
413
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
414
+ }
415
+ },
416
+ catch: function (t) {
417
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
418
+ var r = this.tryEntries[e];
419
+ if (r.tryLoc === t) {
420
+ var n = r.completion;
421
+ if ("throw" === n.type) {
422
+ var o = n.arg;
423
+ resetTryEntry(r);
424
+ }
425
+ return o;
426
+ }
427
+ }
428
+ throw Error("illegal catch attempt");
429
+ },
430
+ delegateYield: function (e, r, n) {
431
+ return this.delegate = {
432
+ iterator: values(e),
433
+ resultName: r,
434
+ nextLoc: n
435
+ }, "next" === this.method && (this.arg = t), y;
436
+ }
437
+ }, e;
438
+ }
439
+ function _setPrototypeOf(t, e) {
440
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
441
+ return t.__proto__ = e, t;
442
+ }, _setPrototypeOf(t, e);
443
+ }
444
+ function _toPrimitive(t, r) {
445
+ if ("object" != typeof t || !t) return t;
446
+ var e = t[Symbol.toPrimitive];
447
+ if (void 0 !== e) {
448
+ var i = e.call(t, r || "default");
449
+ if ("object" != typeof i) return i;
450
+ throw new TypeError("@@toPrimitive must return a primitive value.");
451
+ }
452
+ return ("string" === r ? String : Number)(t);
453
+ }
454
+ function _toPropertyKey(t) {
455
+ var i = _toPrimitive(t, "string");
456
+ return "symbol" == typeof i ? i : i + "";
457
+ }
458
+ function _unsupportedIterableToArray(r, a) {
459
+ if (r) {
460
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
461
+ var t = {}.toString.call(r).slice(8, -1);
462
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
463
+ }
464
+ }
465
+ function _wrapNativeSuper(t) {
466
+ var r = "function" == typeof Map ? new Map() : void 0;
467
+ return _wrapNativeSuper = function (t) {
468
+ if (null === t || !_isNativeFunction(t)) return t;
469
+ if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
470
+ if (void 0 !== r) {
471
+ if (r.has(t)) return r.get(t);
472
+ r.set(t, Wrapper);
473
+ }
474
+ function Wrapper() {
475
+ return _construct(t, arguments, _getPrototypeOf(this).constructor);
476
+ }
477
+ return Wrapper.prototype = Object.create(t.prototype, {
478
+ constructor: {
479
+ value: Wrapper,
480
+ enumerable: !1,
481
+ writable: !0,
482
+ configurable: !0
483
+ }
484
+ }), _setPrototypeOf(Wrapper, t);
485
+ }, _wrapNativeSuper(t);
486
+ }
487
+
488
+ var IntegrationError = /*#__PURE__*/function (_Error) {
489
+ function IntegrationError(message) {
490
+ var _this;
491
+ _this = _Error.call(this, message) || this;
492
+ _this.name = _this.constructor.name;
493
+ return _this;
494
+ }
495
+ _inheritsLoose(IntegrationError, _Error);
496
+ return IntegrationError;
497
+ }(/*#__PURE__*/_wrapNativeSuper(Error));
498
+
499
+ var globalForPrisma = globalThis;
500
+ var logLevels = ['error', 'warn', 'info'];
501
+ if (process.env.SHOW_SQL_QUERY === 'true') {
502
+ logLevels.push('query');
503
+ }
504
+ var prisma = function prisma(url) {
505
+ var prismaInstance;
506
+ if (globalForPrisma.standardPrisma) {
507
+ console.log('Reusing Global Prisma Client...');
508
+ prismaInstance = globalForPrisma.standardPrisma;
509
+ } else {
510
+ prismaInstance = new PrismaClient({
511
+ datasourceUrl: url,
512
+ log: logLevels
513
+ });
514
+ }
515
+ if (process.env.NODE_ENV !== 'production') {
516
+ globalForPrisma.standardPrisma = prismaInstance;
517
+ }
518
+ return prismaInstance;
519
+ };
520
+
521
+ var PropertyService = /*#__PURE__*/function () {
522
+ function PropertyService(_ref) {
523
+ var db = _ref.db;
524
+ this.db = void 0;
525
+ this.db = db;
526
+ }
527
+ var _proto = PropertyService.prototype;
528
+ _proto.getPropertiesByEntityType = /*#__PURE__*/function () {
529
+ var _getPropertiesByEntityType = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
530
+ var entityType;
531
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
532
+ while (1) switch (_context.prev = _context.next) {
533
+ case 0:
534
+ entityType = _ref2.entityType;
535
+ return _context.abrupt("return", this.db.property.findMany({
536
+ where: {
537
+ entity: {
538
+ type: entityType
539
+ }
540
+ }
541
+ }));
542
+ case 2:
543
+ case "end":
544
+ return _context.stop();
545
+ }
546
+ }, _callee, this);
547
+ }));
548
+ function getPropertiesByEntityType(_x) {
549
+ return _getPropertiesByEntityType.apply(this, arguments);
550
+ }
551
+ return getPropertiesByEntityType;
552
+ }();
553
+ return PropertyService;
554
+ }();
555
+
556
+ var FilterOperators;
557
+ (function (FilterOperators) {
558
+ FilterOperators["IS"] = "is";
559
+ FilterOperators["EQUAL"] = "eq";
560
+ FilterOperators["NOT_EQUAL"] = "not_eq";
561
+ FilterOperators["CONTAINS"] = "contains";
562
+ FilterOperators["IN"] = "in";
563
+ FilterOperators["NOT_IN"] = "not_in";
564
+ FilterOperators["GREATER_THAN"] = "gt";
565
+ FilterOperators["LESS_THAN"] = "lt";
566
+ FilterOperators["NOT_CONTAINS"] = "not_contains";
567
+ FilterOperators["GREATER_THAN_OR_EQUAL"] = "gte";
568
+ FilterOperators["LESS_THAN_OR_EQUAL"] = "lte";
569
+ FilterOperators["OP"] = "op";
570
+ FilterOperators["SET"] = "set";
571
+ FilterOperators["NOT_SET"] = "not_set";
572
+ })(FilterOperators || (FilterOperators = {}));
573
+
574
+ var _FieldTypePrimitiveMa, _FilterOperatorToSQL;
575
+ var fieldsWithCommaSeparatedValues = ['SINGLE_SELECT', 'MULTI_SELECT', 'USER', 'COMPANY', 'CONTACT'];
576
+ var FieldTypePrimitiveMap = (_FieldTypePrimitiveMa = {}, _FieldTypePrimitiveMa[PropertyType.BADGE_LIST] = 'string', _FieldTypePrimitiveMa[PropertyType.CHECKBOX] = 'boolean', _FieldTypePrimitiveMa[PropertyType.BOOLEAN] = 'boolean', _FieldTypePrimitiveMa[PropertyType.NUMBER] = 'number', _FieldTypePrimitiveMa[PropertyType.FLOAT] = 'number', _FieldTypePrimitiveMa[PropertyType.JSON_ARRAY] = 'string', _FieldTypePrimitiveMa[PropertyType.JSON_OBJECT] = 'string', _FieldTypePrimitiveMa[PropertyType.CURRENCY] = 'number', _FieldTypePrimitiveMa[PropertyType.DATE] = 'date', _FieldTypePrimitiveMa[PropertyType.LONG_TEXT] = 'string', _FieldTypePrimitiveMa[PropertyType.MULTI_SELECT] = 'string', _FieldTypePrimitiveMa[PropertyType.PHONE] = 'string', _FieldTypePrimitiveMa[PropertyType.SINGLE_LINE_TEXT] = 'string', _FieldTypePrimitiveMa[PropertyType.SINGLE_SELECT] = 'string', _FieldTypePrimitiveMa[PropertyType.URL] = 'string', _FieldTypePrimitiveMa[PropertyType.USER] = 'string', _FieldTypePrimitiveMa[PropertyType.CONTACT] = 'string', _FieldTypePrimitiveMa[PropertyType.COMPANY] = 'string', _FieldTypePrimitiveMa[PropertyType.COMPOSITE] = 'string', _FieldTypePrimitiveMa[PropertyType.PERSON] = 'string', _FieldTypePrimitiveMa[PropertyType.ENRICHMENT] = 'string', _FieldTypePrimitiveMa);
577
+ var SORT_MODE_TO_ABBR = {
578
+ ascending: 'asc',
579
+ descending: 'desc'
580
+ };
581
+ var FilterOperatorToSQL = (_FilterOperatorToSQL = {}, _FilterOperatorToSQL[FilterOperators.IS] = '=', _FilterOperatorToSQL[FilterOperators.EQUAL] = '=', _FilterOperatorToSQL[FilterOperators.NOT_EQUAL] = '!=', _FilterOperatorToSQL[FilterOperators.CONTAINS] = '~*', _FilterOperatorToSQL[FilterOperators.IN] = 'IN', _FilterOperatorToSQL[FilterOperators.NOT_IN] = 'NOT IN', _FilterOperatorToSQL[FilterOperators.GREATER_THAN] = '>', _FilterOperatorToSQL[FilterOperators.LESS_THAN] = '<', _FilterOperatorToSQL[FilterOperators.NOT_CONTAINS] = '!~*', _FilterOperatorToSQL[FilterOperators.GREATER_THAN_OR_EQUAL] = '>=', _FilterOperatorToSQL[FilterOperators.LESS_THAN_OR_EQUAL] = '<=', _FilterOperatorToSQL[FilterOperators.OP] = 'AND', _FilterOperatorToSQL[FilterOperators.SET] = 'IS NOT NULL', _FilterOperatorToSQL[FilterOperators.NOT_SET] = 'IS NULL', _FilterOperatorToSQL);
582
+
583
+ /**
584
+ * Split a string on commas and strip quotes from each part
585
+ * @param str input string
586
+ * @returns array of strings
587
+ */
588
+ var splitAndStripQuotes = function splitAndStripQuotes(str) {
589
+ // Raw regex pattern for splitting on non-quoted commas
590
+ var pattern = /,\s*(?=(?:[^"]*"[^"]*")*[^"]*$)/;
591
+ // Split the string
592
+ var parts = str.split(pattern);
593
+ // Strip quotes from each part
594
+ var cleanedParts = parts.map(function (part) {
595
+ return part.trim().replace(/^"|"$/g, '');
596
+ });
597
+ return cleanedParts;
598
+ };
599
+ var transformFilterValueArray = function transformFilterValueArray(value) {
600
+ if (typeof value === 'string') return value.split(',');
601
+ return value;
602
+ };
603
+ var transformFilterValueBoolean = function transformFilterValueBoolean(value) {
604
+ if (typeof value === 'string') return value === 'true';
605
+ return value;
606
+ };
607
+ /**
608
+ * This returns the SQL field for a JSON field with appropriate casting.
609
+ * @param column - JSON field to cast.
610
+ * @param type - Type of the JSON field.
611
+ */
612
+ var getJSONField = function getJSONField(column, type) {
613
+ var primitiveType = FieldTypePrimitiveMap[type];
614
+ switch (primitiveType) {
615
+ case 'number':
616
+ {
617
+ // cast to number if field is numeric
618
+ return "(" + column + ")::bigint";
619
+ }
620
+ case 'boolean':
621
+ {
622
+ // cast to boolean if field is boolean
623
+ return "(" + column + ")::boolean";
624
+ }
625
+ case 'date':
626
+ {
627
+ return "(" + column + ")::timestamp";
628
+ }
629
+ }
630
+ return "(" + column + ")::text";
631
+ };
632
+ /**
633
+ * @description
634
+ * Builds a query string from filter and sort query strings
635
+ * @param filterQueryString Filter query string
636
+ * @param sortQueryString Sort query string
637
+ * @returns
638
+ */
639
+ function buildQueryString(_ref) {
640
+ var filterQueryString = _ref.filterQueryString,
641
+ sortQueryString = _ref.sortQueryString;
642
+ if (!filterQueryString && !sortQueryString) return '';
643
+ if (!filterQueryString) return "" + sortQueryString;
644
+ if (!sortQueryString) return "" + filterQueryString;
645
+ return filterQueryString + "&" + sortQueryString;
646
+ }
647
+
648
+ /**
649
+ * Get the SQL filter clause for the given filters.
650
+ * @param filters - Filters to apply.
651
+ * @param fields - Optional. JSON fields with associated types to apply filters on.
652
+ * @param parentTableRef - Parent table reference to apply filters on.
653
+ */
654
+ var getFilterClauseSQL = function getFilterClauseSQL(_ref) {
655
+ var filters = _ref.filters,
656
+ fields = _ref.fields,
657
+ parentTableRef = _ref.parentTableRef;
658
+ if (!parentTableRef || !Object.keys(filters).length) return '';
659
+ var getValue = function getValue(value, primitiveType, isMultiple) {
660
+ if (isMultiple) {
661
+ var multipleValues = splitAndStripQuotes(value);
662
+ return "(" + multipleValues.map(function (v) {
663
+ return primitiveType === 'number' ? Number(v) + "::bigint" : "'" + v + "'";
664
+ }).join(',') + ")";
665
+ }
666
+ switch (primitiveType) {
667
+ case 'number':
668
+ {
669
+ // cast to number if field is numeric
670
+ return Number(value) + "::bigint";
671
+ }
672
+ case 'boolean':
673
+ {
674
+ // cast to boolean if field is boolean
675
+ return value + "::boolean";
676
+ }
677
+ case 'string':
678
+ {
679
+ return "'" + value + "'";
680
+ }
681
+ case 'date':
682
+ {
683
+ return "'" + value + "'::timestamp";
684
+ }
685
+ default:
686
+ {
687
+ return value;
688
+ }
689
+ }
690
+ };
691
+ var getFilterClause = function getFilterClause(table, field, filter) {
692
+ var _fields$find;
693
+ var fieldType = (fields == null || (_fields$find = fields.find(function (f) {
694
+ return field.startsWith(f.name);
695
+ })) == null ? void 0 : _fields$find.type) || PropertyType.SINGLE_LINE_TEXT;
696
+ var column = "\"mastra\".\"" + table + "\".\"" + field + "\"";
697
+ var operators = Object.keys(filter);
698
+ var logicOperator = filter.op || 'or';
699
+ var isJSONField = field.includes('.');
700
+ // JSON fields contains a parent field and a child field. e.g. data.amount
701
+ if (isJSONField) {
702
+ var _fields$find2;
703
+ var _field$split = field.split('.'),
704
+ parentField = _field$split[0],
705
+ childField = _field$split[1];
706
+ fieldType = (fields == null || (_fields$find2 = fields.find(function (f) {
707
+ return f.name === childField;
708
+ })) == null ? void 0 : _fields$find2.type) || PropertyType.SINGLE_LINE_TEXT;
709
+ var JSONField = "\"mastra\".\"" + table + "\".\"" + parentField + "\"->>'" + childField + "'";
710
+ column = getJSONField(JSONField, fieldType);
711
+ }
712
+ var primitiveType = FieldTypePrimitiveMap[fieldType || PropertyType.SINGLE_LINE_TEXT];
713
+ var clauses = operators.filter(function (op) {
714
+ return op !== FilterOperators.OP;
715
+ }).map(function (op) {
716
+ var isContains = op === FilterOperators.CONTAINS || op === FilterOperators.NOT_CONTAINS;
717
+ var isSetOperator = op === FilterOperators.SET || op === FilterOperators.NOT_SET;
718
+ var isINOperator = op === FilterOperators.IN || op === FilterOperators.NOT_IN;
719
+ var operatorSQL = FilterOperatorToSQL[op];
720
+ var inputValues = Array.isArray(filter[op]) ? filter[op] : [filter[op]];
721
+ var queryValues = isContains ?
722
+ // if operator is 'contains', we use POSIX regex to match any the values
723
+ ["'.*" + inputValues.join('.*|.*') + ".*'"] // e.g. ['foo', 'bar'] => /.*foo.*|.*bar.*/
724
+ :
725
+ // limitation of this is that we can't have `AND` clauses for the `contains` operator
726
+ // else, we use the value as is
727
+ // N/B: in and not_in operators are handled differently as they're not transformed to arrays
728
+ inputValues.map(function (v) {
729
+ return getValue(v, primitiveType, isINOperator && v.includes(','));
730
+ });
731
+ if (primitiveType === "date" && !isSetOperator) {
732
+ var hasTimezone = filter[op].toLowerCase().includes('z');
733
+ var inputVal = new UTCDate(hasTimezone ? filter[op] : filter[op] + "Z");
734
+ var startDayVal = getValue(startOfDay(inputVal).toISOString(), primitiveType, false);
735
+ var endDayVal = getValue(endOfDay(inputVal).toISOString(), primitiveType, false);
736
+ if (op === "eq") {
737
+ return "((" + column + " >= " + startDayVal + ") AND (" + column + " <= " + endDayVal + "))";
738
+ } else if (op === "lt") {
739
+ return "(" + column + " " + operatorSQL + " " + startDayVal + ")";
740
+ } else if (op === "gt") {
741
+ return "(" + column + " " + operatorSQL + " " + endDayVal + ")";
742
+ } else if (op === "lte") {
743
+ return "(" + column + " " + operatorSQL + " " + endDayVal + ")";
744
+ } else if (op === "gte") {
745
+ return "(" + column + " " + operatorSQL + " " + startDayVal + ")";
746
+ } else if (op === "not_eq") {
747
+ return "((" + column + " < " + startDayVal + ") OR (" + column + " > " + endDayVal + "))";
748
+ }
749
+ }
750
+ return "(" + queryValues.map(function (value) {
751
+ return isSetOperator ? "(" + column + " " + operatorSQL + ")" : "(" + column + " " + operatorSQL + " " + value + ")";
752
+ }).join(" " + logicOperator.toUpperCase() + " ") + ")";
753
+ });
754
+ var filterClause = "(" + clauses.join(" " + logicOperator.toUpperCase() + " ") + ")";
755
+ return filterClause;
756
+ };
757
+ var combinedFields = Object.keys(filters).filter(function (field) {
758
+ return field.includes(',');
759
+ });
760
+ var normalFields = Object.keys(filters).filter(function (field) {
761
+ return !field.includes(',');
762
+ });
763
+ var filterClauseMap = normalFields.reduce(function (acc, field) {
764
+ var _extends2;
765
+ return _extends({}, acc, (_extends2 = {}, _extends2[field] = getFilterClause(parentTableRef, field, filters[field]), _extends2));
766
+ }, {});
767
+ var combinedFilterClauses = combinedFields.map(function (field) {
768
+ var fields = field.split(',');
769
+ var logicGroupOperator = filters[field].op || 'and';
770
+ var clauses = fields.map(function (f) {
771
+ return filterClauseMap[f];
772
+ });
773
+ return "(" + clauses.join(" " + logicGroupOperator.toUpperCase() + " ") + ")";
774
+ });
775
+ var normalFilterClauses = Object.entries(filterClauseMap).map(function (_ref2) {
776
+ var field = _ref2[0],
777
+ clause = _ref2[1];
778
+ return combinedFields.some(function (f) {
779
+ return f.includes(field);
780
+ }) ? [] : clause;
781
+ }).flat();
782
+ return "(" + [].concat(combinedFilterClauses, normalFilterClauses).join(' AND ') + ")";
783
+ };
784
+
785
+ /**
786
+ * Get the SQL sort clause for the given sort fields.
787
+ * A sort clause is an array of strings where each string is a field to sort by.
788
+ * e.g. ["field1 ASC", "field2 DESC"] will sort by field1 in ascending order and field2 in descending order.
789
+ */
790
+ var getSortClauseSQL = function getSortClauseSQL(_ref) {
791
+ var sort = _ref.sort,
792
+ parentTableRef = _ref.parentTableRef,
793
+ fields = _ref.fields;
794
+ if (!parentTableRef) return [];
795
+ return sort
796
+ // filter out invalid sort fields
797
+ .filter(function (sortField) {
798
+ return sortField.startsWith('asc(') || sortField.startsWith('desc(');
799
+ }).map(function (sortField) {
800
+ var _sortField$slice$spli = sortField.slice(0, sortField.length - 1).split('('),
801
+ order = _sortField$slice$spli[0],
802
+ field = _sortField$slice$spli[1];
803
+ var isJSONField = typeof field.split('.')[1] !== 'undefined';
804
+ if (isJSONField) {
805
+ var _fields$find;
806
+ var _field$split = field.split('.'),
807
+ parentField = _field$split[0],
808
+ childField = _field$split[1];
809
+ var fieldType = (fields == null || (_fields$find = fields.find(function (f) {
810
+ return f.name === childField;
811
+ })) == null ? void 0 : _fields$find.type) || PropertyType.SINGLE_LINE_TEXT;
812
+ var JSONField = "\"mastra\".\"" + parentTableRef + "\".\"" + parentField + "\"->>'" + childField + "'";
813
+ var column = getJSONField(JSONField, fieldType);
814
+ return column + " " + order.toUpperCase();
815
+ }
816
+ return "\"mastra\".\"" + parentTableRef + "\".\"" + field + "\" " + order.toUpperCase();
817
+ });
818
+ };
819
+
820
+ var RecordService = /*#__PURE__*/function () {
821
+ function RecordService(_ref) {
822
+ var db = _ref.db;
823
+ this.db = void 0;
824
+ this.propertyService = void 0;
825
+ this.db = db;
826
+ this.propertyService = new PropertyService({
827
+ db: db
828
+ });
829
+ }
830
+ var _proto = RecordService.prototype;
831
+ _proto.buildRecordQuerySql = function buildRecordQuerySql(_ref2) {
832
+ var whereClause = _ref2.whereClause,
833
+ filterClause = _ref2.filterClause,
834
+ sortClauses = _ref2.sortClauses,
835
+ entityType = _ref2.entityType;
836
+ return "\n SELECT\n \"mastra\".\"records\".*,\n row_to_json(\"mastra\".\"entity\".*) AS \"entity\"\n FROM \"mastra\".\"records\"\n LEFT JOIN \"mastra\".\"entity\" ON \"mastra\".\"entity\".\"id\" = \"mastra\".\"records\".\"entityId\"\n " + whereClause + "\n " + (entityType ? "AND \"mastra\".\"entity\".\"type\" = '" + entityType + "'" : '') + "\n AND \"records\".\"deletedAt\" IS NULL\n " + (filterClause ? "AND " + filterClause : '') + "\n ORDER BY " + (sortClauses.length > 0 ? sortClauses.join(', ') : '') + "\n ";
837
+ };
838
+ _proto.getFilteredRecords = /*#__PURE__*/function () {
839
+ var _getFilteredRecords = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref3) {
840
+ var entityType, k_id, filters, sort, properties, dateFields, fullProperties, filterClause, sortClauses, sqlStatement, records;
841
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
842
+ while (1) switch (_context.prev = _context.next) {
843
+ case 0:
844
+ entityType = _ref3.entityType, k_id = _ref3.k_id, filters = _ref3.filters, sort = _ref3.sort;
845
+ _context.next = 3;
846
+ return this.propertyService.getPropertiesByEntityType({
847
+ entityType: entityType
848
+ });
849
+ case 3:
850
+ properties = _context.sent;
851
+ dateFields = [{
852
+ name: "createdAt",
853
+ type: "DATE"
854
+ }, {
855
+ name: "updatedAt",
856
+ type: "DATE"
857
+ }];
858
+ fullProperties = [].concat(properties, dateFields);
859
+ filterClause = '', sortClauses = ["\"mastra\".\"records\".\"createdAt\" DESC"];
860
+ if (filters) {
861
+ filterClause = getFilterClauseSQL({
862
+ filters: filters,
863
+ fields: fullProperties,
864
+ parentTableRef: 'records'
865
+ });
866
+ }
867
+ if (sort) {
868
+ sortClauses = getSortClauseSQL({
869
+ sort: sort,
870
+ fields: fullProperties,
871
+ parentTableRef: 'records'
872
+ });
873
+ }
874
+ sqlStatement = this.buildRecordQuerySql({
875
+ whereClause: "WHERE \"mastra\".\"entity\".\"k_id\" = '" + k_id + "'",
876
+ filterClause: filterClause,
877
+ sortClauses: sortClauses,
878
+ entityType: entityType
879
+ });
880
+ _context.prev = 10;
881
+ _context.next = 13;
882
+ return this.db.$queryRawUnsafe(sqlStatement);
883
+ case 13:
884
+ records = _context.sent;
885
+ return _context.abrupt("return", records);
886
+ case 17:
887
+ _context.prev = 17;
888
+ _context.t0 = _context["catch"](10);
889
+ if (!(_context.t0 instanceof PrismaClientValidationError)) {
890
+ _context.next = 21;
891
+ break;
892
+ }
893
+ return _context.abrupt("return", []);
894
+ case 21:
895
+ if (!(_context.t0 instanceof PrismaClientKnownRequestError)) {
896
+ _context.next = 24;
897
+ break;
898
+ }
899
+ if (!(_context.t0.code === 'P2010' && _context.t0.meta && _context.t0.meta.code === '42703')) {
900
+ _context.next = 24;
901
+ break;
902
+ }
903
+ return _context.abrupt("return", []);
904
+ case 24:
905
+ throw _context.t0;
906
+ case 25:
907
+ case "end":
908
+ return _context.stop();
909
+ }
910
+ }, _callee, this, [[10, 17]]);
911
+ }));
912
+ function getFilteredRecords(_x) {
913
+ return _getFilteredRecords.apply(this, arguments);
914
+ }
915
+ return getFilteredRecords;
916
+ }();
917
+ return RecordService;
918
+ }();
919
+
920
+ var _excluded$4 = ["k_id"];
921
+ var DataLayer = /*#__PURE__*/function () {
922
+ function DataLayer(_ref) {
923
+ var url = _ref.url;
924
+ this.db = void 0;
925
+ this.recordService = void 0;
926
+ this.db = prisma(url);
927
+ this.recordService = new RecordService({
928
+ db: this.db
929
+ });
930
+ }
931
+ var _proto = DataLayer.prototype;
932
+ _proto.createConnection = /*#__PURE__*/function () {
933
+ var _createConnection = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
934
+ var connection, credential;
935
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
936
+ while (1) switch (_context.prev = _context.next) {
937
+ case 0:
938
+ connection = _ref2.connection, credential = _ref2.credential;
939
+ return _context.abrupt("return", this.db.connection.upsert({
940
+ where: {
941
+ connectionId_name: {
942
+ connectionId: connection.connectionId,
943
+ name: connection.name
944
+ }
945
+ },
946
+ create: _extends({}, connection, {
947
+ credential: {
948
+ create: credential
949
+ }
950
+ }),
951
+ update: _extends({}, connection, {
952
+ credential: {
953
+ update: credential
954
+ }
955
+ }),
956
+ include: {
957
+ credential: true
958
+ }
959
+ }));
960
+ case 2:
961
+ case "end":
962
+ return _context.stop();
963
+ }
964
+ }, _callee, this);
965
+ }));
966
+ function createConnection(_x) {
967
+ return _createConnection.apply(this, arguments);
968
+ }
969
+ return createConnection;
970
+ }();
971
+ _proto.deleteConnection = /*#__PURE__*/function () {
972
+ var _deleteConnection = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref3) {
973
+ var connectionId;
974
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
975
+ while (1) switch (_context2.prev = _context2.next) {
976
+ case 0:
977
+ connectionId = _ref3.connectionId;
978
+ return _context2.abrupt("return", this.db.connection["delete"]({
979
+ where: {
980
+ id: connectionId
981
+ }
982
+ }));
983
+ case 2:
984
+ case "end":
985
+ return _context2.stop();
986
+ }
987
+ }, _callee2, this);
988
+ }));
989
+ function deleteConnection(_x2) {
990
+ return _deleteConnection.apply(this, arguments);
991
+ }
992
+ return deleteConnection;
993
+ }();
994
+ _proto.getConnection = /*#__PURE__*/function () {
995
+ var _getConnection = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref4) {
996
+ var connectionId, name;
997
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
998
+ while (1) switch (_context3.prev = _context3.next) {
999
+ case 0:
1000
+ connectionId = _ref4.connectionId, name = _ref4.name;
1001
+ return _context3.abrupt("return", this.db.connection.findUnique({
1002
+ where: {
1003
+ connectionId_name: {
1004
+ connectionId: connectionId,
1005
+ name: name
1006
+ }
1007
+ }
1008
+ }));
1009
+ case 2:
1010
+ case "end":
1011
+ return _context3.stop();
1012
+ }
1013
+ }, _callee3, this);
1014
+ }));
1015
+ function getConnection(_x3) {
1016
+ return _getConnection.apply(this, arguments);
1017
+ }
1018
+ return getConnection;
1019
+ }();
1020
+ _proto.getConnectionsByIntegrationName = /*#__PURE__*/function () {
1021
+ var _getConnectionsByIntegrationName = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref5) {
1022
+ var name;
1023
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1024
+ while (1) switch (_context4.prev = _context4.next) {
1025
+ case 0:
1026
+ name = _ref5.name;
1027
+ return _context4.abrupt("return", this.db.connection.findMany({
1028
+ where: {
1029
+ name: name
1030
+ },
1031
+ orderBy: {
1032
+ createdAt: 'desc'
1033
+ }
1034
+ }));
1035
+ case 2:
1036
+ case "end":
1037
+ return _context4.stop();
1038
+ }
1039
+ }, _callee4, this);
1040
+ }));
1041
+ function getConnectionsByIntegrationName(_x4) {
1042
+ return _getConnectionsByIntegrationName.apply(this, arguments);
1043
+ }
1044
+ return getConnectionsByIntegrationName;
1045
+ }();
1046
+ _proto.getAllConnections = /*#__PURE__*/function () {
1047
+ var _getAllConnections = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
1048
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1049
+ while (1) switch (_context5.prev = _context5.next) {
1050
+ case 0:
1051
+ return _context5.abrupt("return", this.db.connection.findMany({
1052
+ select: {
1053
+ name: true,
1054
+ connectionId: true
1055
+ }
1056
+ }));
1057
+ case 1:
1058
+ case "end":
1059
+ return _context5.stop();
1060
+ }
1061
+ }, _callee5, this);
1062
+ }));
1063
+ function getAllConnections() {
1064
+ return _getAllConnections.apply(this, arguments);
1065
+ }
1066
+ return getAllConnections;
1067
+ }();
1068
+ _proto.getConnectionById = /*#__PURE__*/function () {
1069
+ var _getConnectionById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref6) {
1070
+ var k_id;
1071
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1072
+ while (1) switch (_context6.prev = _context6.next) {
1073
+ case 0:
1074
+ k_id = _ref6.k_id;
1075
+ return _context6.abrupt("return", this.db.connection.findUnique({
1076
+ where: {
1077
+ id: k_id
1078
+ }
1079
+ }));
1080
+ case 2:
1081
+ case "end":
1082
+ return _context6.stop();
1083
+ }
1084
+ }, _callee6, this);
1085
+ }));
1086
+ function getConnectionById(_x5) {
1087
+ return _getConnectionById.apply(this, arguments);
1088
+ }
1089
+ return getConnectionById;
1090
+ }();
1091
+ _proto.getCredentialsByConnection = /*#__PURE__*/function () {
1092
+ var _getCredentialsByConnection = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(k_id) {
1093
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1094
+ while (1) switch (_context7.prev = _context7.next) {
1095
+ case 0:
1096
+ _context7.next = 2;
1097
+ return this.db.credential.findUniqueOrThrow({
1098
+ where: {
1099
+ k_id: k_id
1100
+ },
1101
+ include: {
1102
+ connection: true
1103
+ }
1104
+ });
1105
+ case 2:
1106
+ return _context7.abrupt("return", _context7.sent);
1107
+ case 3:
1108
+ case "end":
1109
+ return _context7.stop();
1110
+ }
1111
+ }, _callee7, this);
1112
+ }));
1113
+ function getCredentialsByConnection(_x6) {
1114
+ return _getCredentialsByConnection.apply(this, arguments);
1115
+ }
1116
+ return getCredentialsByConnection;
1117
+ }();
1118
+ _proto.updateConnectionCredential = /*#__PURE__*/function () {
1119
+ var _updateConnectionCredential = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref7) {
1120
+ var k_id, token;
1121
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1122
+ while (1) switch (_context8.prev = _context8.next) {
1123
+ case 0:
1124
+ k_id = _ref7.k_id, token = _ref7.token;
1125
+ return _context8.abrupt("return", this.db.credential.update({
1126
+ where: {
1127
+ k_id: k_id
1128
+ },
1129
+ data: {
1130
+ value: token
1131
+ }
1132
+ }));
1133
+ case 2:
1134
+ case "end":
1135
+ return _context8.stop();
1136
+ }
1137
+ }, _callee8, this);
1138
+ }));
1139
+ function updateConnectionCredential(_x7) {
1140
+ return _updateConnectionCredential.apply(this, arguments);
1141
+ }
1142
+ return updateConnectionCredential;
1143
+ }();
1144
+ _proto.createEntity = /*#__PURE__*/function () {
1145
+ var _createEntity = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref8) {
1146
+ var connectionId, type, k_id;
1147
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1148
+ while (1) switch (_context9.prev = _context9.next) {
1149
+ case 0:
1150
+ connectionId = _ref8.connectionId, type = _ref8.type, k_id = _ref8.k_id;
1151
+ return _context9.abrupt("return", this.db.entity.create({
1152
+ data: {
1153
+ k_id: k_id,
1154
+ type: type,
1155
+ createdBy: connectionId
1156
+ }
1157
+ }));
1158
+ case 2:
1159
+ case "end":
1160
+ return _context9.stop();
1161
+ }
1162
+ }, _callee9, this);
1163
+ }));
1164
+ function createEntity(_x8) {
1165
+ return _createEntity.apply(this, arguments);
1166
+ }
1167
+ return createEntity;
1168
+ }();
1169
+ _proto.getEntityById = /*#__PURE__*/function () {
1170
+ var _getEntityById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(entityId) {
1171
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1172
+ while (1) switch (_context10.prev = _context10.next) {
1173
+ case 0:
1174
+ _context10.next = 2;
1175
+ return this.db.entity.findUniqueOrThrow({
1176
+ where: {
1177
+ id: entityId
1178
+ }
1179
+ });
1180
+ case 2:
1181
+ return _context10.abrupt("return", _context10.sent);
1182
+ case 3:
1183
+ case "end":
1184
+ return _context10.stop();
1185
+ }
1186
+ }, _callee10, this);
1187
+ }));
1188
+ function getEntityById(_x9) {
1189
+ return _getEntityById.apply(this, arguments);
1190
+ }
1191
+ return getEntityById;
1192
+ }();
1193
+ _proto.addPropertiesToEntity = /*#__PURE__*/function () {
1194
+ var _addPropertiesToEntity = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref9) {
1195
+ var entityId, properties;
1196
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1197
+ while (1) switch (_context11.prev = _context11.next) {
1198
+ case 0:
1199
+ entityId = _ref9.entityId, properties = _ref9.properties;
1200
+ return _context11.abrupt("return", this.db.entity.update({
1201
+ where: {
1202
+ id: entityId
1203
+ },
1204
+ data: {
1205
+ properties: {
1206
+ create: properties
1207
+ }
1208
+ }
1209
+ }));
1210
+ case 2:
1211
+ case "end":
1212
+ return _context11.stop();
1213
+ }
1214
+ }, _callee11, this);
1215
+ }));
1216
+ function addPropertiesToEntity(_x10) {
1217
+ return _addPropertiesToEntity.apply(this, arguments);
1218
+ }
1219
+ return addPropertiesToEntity;
1220
+ }();
1221
+ _proto.getEntityRecordsByConnectionAndType = /*#__PURE__*/function () {
1222
+ var _getEntityRecordsByConnectionAndType = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(_ref10) {
1223
+ var k_id, type;
1224
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1225
+ while (1) switch (_context12.prev = _context12.next) {
1226
+ case 0:
1227
+ k_id = _ref10.k_id, type = _ref10.type;
1228
+ _context12.next = 3;
1229
+ return this.db.entity.findUnique({
1230
+ where: {
1231
+ k_id_type: {
1232
+ k_id: k_id,
1233
+ type: type
1234
+ }
1235
+ },
1236
+ include: {
1237
+ properties: true,
1238
+ records: true
1239
+ }
1240
+ });
1241
+ case 3:
1242
+ return _context12.abrupt("return", _context12.sent);
1243
+ case 4:
1244
+ case "end":
1245
+ return _context12.stop();
1246
+ }
1247
+ }, _callee12, this);
1248
+ }));
1249
+ function getEntityRecordsByConnectionAndType(_x11) {
1250
+ return _getEntityRecordsByConnectionAndType.apply(this, arguments);
1251
+ }
1252
+ return getEntityRecordsByConnectionAndType;
1253
+ }();
1254
+ _proto.getEntityByConnectionAndType = /*#__PURE__*/function () {
1255
+ var _getEntityByConnectionAndType = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(_ref11) {
1256
+ var k_id, type;
1257
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1258
+ while (1) switch (_context13.prev = _context13.next) {
1259
+ case 0:
1260
+ k_id = _ref11.k_id, type = _ref11.type;
1261
+ _context13.next = 3;
1262
+ return this.db.entity.findUnique({
1263
+ where: {
1264
+ k_id_type: {
1265
+ k_id: k_id,
1266
+ type: type
1267
+ }
1268
+ }
1269
+ });
1270
+ case 3:
1271
+ return _context13.abrupt("return", _context13.sent);
1272
+ case 4:
1273
+ case "end":
1274
+ return _context13.stop();
1275
+ }
1276
+ }, _callee13, this);
1277
+ }));
1278
+ function getEntityByConnectionAndType(_x12) {
1279
+ return _getEntityByConnectionAndType.apply(this, arguments);
1280
+ }
1281
+ return getEntityByConnectionAndType;
1282
+ }();
1283
+ _proto.updateEntityLastSyncId = /*#__PURE__*/function () {
1284
+ var _updateEntityLastSyncId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14(_ref12) {
1285
+ var entityId, syncId;
1286
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1287
+ while (1) switch (_context14.prev = _context14.next) {
1288
+ case 0:
1289
+ entityId = _ref12.entityId, syncId = _ref12.syncId;
1290
+ return _context14.abrupt("return", this.db.entity.update({
1291
+ where: {
1292
+ id: entityId
1293
+ },
1294
+ data: {
1295
+ lastSyncId: syncId
1296
+ }
1297
+ }));
1298
+ case 2:
1299
+ case "end":
1300
+ return _context14.stop();
1301
+ }
1302
+ }, _callee14, this);
1303
+ }));
1304
+ function updateEntityLastSyncId(_x13) {
1305
+ return _updateEntityLastSyncId.apply(this, arguments);
1306
+ }
1307
+ return updateEntityLastSyncId;
1308
+ }();
1309
+ _proto.deleteEntityById = /*#__PURE__*/function () {
1310
+ var _deleteEntityById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee15(entityId) {
1311
+ return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1312
+ while (1) switch (_context15.prev = _context15.next) {
1313
+ case 0:
1314
+ return _context15.abrupt("return", this.db.entity["delete"]({
1315
+ where: {
1316
+ id: entityId
1317
+ }
1318
+ }));
1319
+ case 1:
1320
+ case "end":
1321
+ return _context15.stop();
1322
+ }
1323
+ }, _callee15, this);
1324
+ }));
1325
+ function deleteEntityById(_x14) {
1326
+ return _deleteEntityById.apply(this, arguments);
1327
+ }
1328
+ return deleteEntityById;
1329
+ }()
1330
+ /**
1331
+ * Creates new records for a entity, or updates existing record 'data' if it already exists
1332
+ * @param entityId
1333
+ * @param records
1334
+ */
1335
+ ;
1336
+ _proto.mergeExternalRecordsForEntity =
1337
+ /*#__PURE__*/
1338
+ function () {
1339
+ var _mergeExternalRecordsForEntity = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee16(_ref13) {
1340
+ var entityId, records, uniqueRecordsMap, _iterator, _step, record, uniqueRecords, externalIds, existingRecords, toCreate, toUpdate, createPromise, updatePromise;
1341
+ return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1342
+ while (1) switch (_context16.prev = _context16.next) {
1343
+ case 0:
1344
+ entityId = _ref13.entityId, records = _ref13.records;
1345
+ if (records != null && records.length) {
1346
+ _context16.next = 3;
1347
+ break;
1348
+ }
1349
+ return _context16.abrupt("return");
1350
+ case 3:
1351
+ uniqueRecordsMap = new Map();
1352
+ for (_iterator = _createForOfIteratorHelperLoose(records); !(_step = _iterator()).done;) {
1353
+ record = _step.value;
1354
+ if (record.externalId && !uniqueRecordsMap.has(record.externalId)) {
1355
+ uniqueRecordsMap.set(record.externalId, record);
1356
+ }
1357
+ }
1358
+ uniqueRecords = Array.from(uniqueRecordsMap.values());
1359
+ externalIds = uniqueRecords.map(function (record) {
1360
+ return record.externalId;
1361
+ });
1362
+ _context16.next = 9;
1363
+ return this.db.record.findMany({
1364
+ select: {
1365
+ id: true,
1366
+ externalId: true,
1367
+ data: true
1368
+ },
1369
+ where: {
1370
+ entityId: entityId,
1371
+ externalId: {
1372
+ "in": externalIds
1373
+ }
1374
+ }
1375
+ });
1376
+ case 9:
1377
+ existingRecords = _context16.sent;
1378
+ toCreate = [];
1379
+ toUpdate = [];
1380
+ uniqueRecords.forEach(function (record) {
1381
+ var existing = existingRecords.find(function (existingRecord) {
1382
+ return existingRecord.externalId === record.externalId;
1383
+ });
1384
+ if (existing) {
1385
+ toUpdate.push(_extends({}, record, {
1386
+ data: _extends({}, existing.data, record.data)
1387
+ }));
1388
+ } else {
1389
+ toCreate.push(_extends({}, record, {
1390
+ entityId: entityId
1391
+ }));
1392
+ }
1393
+ });
1394
+ createPromise = toCreate.length ? this.db.record.createMany({
1395
+ data: toCreate.map(function (record) {
1396
+ return _extends({}, record, {
1397
+ data: record.data
1398
+ });
1399
+ })
1400
+ }) : undefined;
1401
+ updatePromise = toUpdate.length ? this.db.$executeRaw(Prisma.raw("\n WITH updated_records (\"externalId\", \"data\") AS (\n VALUES\n " + toUpdate.map(function (_ref14) {
1402
+ var externalId = _ref14.externalId,
1403
+ data = _ref14.data;
1404
+ return "('" + externalId + "', '" + JSON.stringify(data).replace(/'/g, "''") + "'::jsonb)";
1405
+ }).join(',') + "\n )\n UPDATE records\n SET \"data\" = updated_records.\"data\"\n FROM updated_records\n WHERE records.\"externalId\" = updated_records.\"externalId\";\n ")) : undefined;
1406
+ return _context16.abrupt("return", Promise.all([createPromise, updatePromise]));
1407
+ case 16:
1408
+ case "end":
1409
+ return _context16.stop();
1410
+ }
1411
+ }, _callee16, this);
1412
+ }));
1413
+ function mergeExternalRecordsForEntity(_x15) {
1414
+ return _mergeExternalRecordsForEntity.apply(this, arguments);
1415
+ }
1416
+ return mergeExternalRecordsForEntity;
1417
+ }();
1418
+ _proto.updateConnectionCredentials = /*#__PURE__*/function () {
1419
+ var _updateConnectionCredentials = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee17(_ref15) {
1420
+ var k_id, update;
1421
+ return _regeneratorRuntime().wrap(function _callee17$(_context17) {
1422
+ while (1) switch (_context17.prev = _context17.next) {
1423
+ case 0:
1424
+ k_id = _ref15.k_id, update = /*#__PURE__*/_objectWithoutPropertiesLoose(_ref15, _excluded$4);
1425
+ return _context17.abrupt("return", this.db.credential.update({
1426
+ where: {
1427
+ k_id: k_id
1428
+ },
1429
+ data: update
1430
+ }));
1431
+ case 2:
1432
+ case "end":
1433
+ return _context17.stop();
1434
+ }
1435
+ }, _callee17, this);
1436
+ }));
1437
+ function updateConnectionCredentials(_x16) {
1438
+ return _updateConnectionCredentials.apply(this, arguments);
1439
+ }
1440
+ return updateConnectionCredentials;
1441
+ }();
1442
+ _proto.getRecords = /*#__PURE__*/function () {
1443
+ var _getRecords = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee18(_ref16) {
1444
+ var entityType, k_id, filters, sort, recordData;
1445
+ return _regeneratorRuntime().wrap(function _callee18$(_context18) {
1446
+ while (1) switch (_context18.prev = _context18.next) {
1447
+ case 0:
1448
+ entityType = _ref16.entityType, k_id = _ref16.k_id, filters = _ref16.filters, sort = _ref16.sort;
1449
+ recordData = this.recordService.getFilteredRecords({
1450
+ entityType: entityType,
1451
+ k_id: k_id,
1452
+ filters: filters,
1453
+ sort: sort
1454
+ });
1455
+ return _context18.abrupt("return", recordData);
1456
+ case 3:
1457
+ case "end":
1458
+ return _context18.stop();
1459
+ }
1460
+ }, _callee18, this);
1461
+ }));
1462
+ function getRecords(_x17) {
1463
+ return _getRecords.apply(this, arguments);
1464
+ }
1465
+ return getRecords;
1466
+ }();
1467
+ _proto.getRecordByPropertyNameAndValues = /*#__PURE__*/function () {
1468
+ var _getRecordByPropertyNameAndValues = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee19(_ref17) {
1469
+ var propertyName, propertValues, type, connectionId, OR;
1470
+ return _regeneratorRuntime().wrap(function _callee19$(_context19) {
1471
+ while (1) switch (_context19.prev = _context19.next) {
1472
+ case 0:
1473
+ propertyName = _ref17.propertyName, propertValues = _ref17.propertValues, type = _ref17.type, connectionId = _ref17.connectionId;
1474
+ OR = propertValues.map(function (value) {
1475
+ return {
1476
+ data: {
1477
+ path: [propertyName],
1478
+ equals: value
1479
+ }
1480
+ };
1481
+ });
1482
+ return _context19.abrupt("return", this.db.record.findMany({
1483
+ where: {
1484
+ entity: {
1485
+ connection: {
1486
+ connectionId: connectionId
1487
+ },
1488
+ type: type
1489
+ },
1490
+ OR: OR
1491
+ }
1492
+ }));
1493
+ case 3:
1494
+ case "end":
1495
+ return _context19.stop();
1496
+ }
1497
+ }, _callee19, this);
1498
+ }));
1499
+ function getRecordByPropertyNameAndValues(_x18) {
1500
+ return _getRecordByPropertyNameAndValues.apply(this, arguments);
1501
+ }
1502
+ return getRecordByPropertyNameAndValues;
1503
+ }();
1504
+ _proto.getRecordByPropertyNameAndValue = /*#__PURE__*/function () {
1505
+ var _getRecordByPropertyNameAndValue = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee20(_ref18) {
1506
+ var propertyName, propertyValue, type, connectionId;
1507
+ return _regeneratorRuntime().wrap(function _callee20$(_context20) {
1508
+ while (1) switch (_context20.prev = _context20.next) {
1509
+ case 0:
1510
+ propertyName = _ref18.propertyName, propertyValue = _ref18.propertyValue, type = _ref18.type, connectionId = _ref18.connectionId;
1511
+ return _context20.abrupt("return", this.db.record.findFirst({
1512
+ where: {
1513
+ entity: {
1514
+ connection: {
1515
+ connectionId: connectionId
1516
+ },
1517
+ type: type
1518
+ },
1519
+ data: {
1520
+ path: [propertyName],
1521
+ equals: propertyValue
1522
+ }
1523
+ }
1524
+ }));
1525
+ case 2:
1526
+ case "end":
1527
+ return _context20.stop();
1528
+ }
1529
+ }, _callee20, this);
1530
+ }));
1531
+ function getRecordByPropertyNameAndValue(_x19) {
1532
+ return _getRecordByPropertyNameAndValue.apply(this, arguments);
1533
+ }
1534
+ return getRecordByPropertyNameAndValue;
1535
+ }();
1536
+ _proto.getRecordsByPropertyName = /*#__PURE__*/function () {
1537
+ var _getRecordsByPropertyName = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee21(_ref19) {
1538
+ var propertyName, connectionId;
1539
+ return _regeneratorRuntime().wrap(function _callee21$(_context21) {
1540
+ while (1) switch (_context21.prev = _context21.next) {
1541
+ case 0:
1542
+ propertyName = _ref19.propertyName, connectionId = _ref19.connectionId;
1543
+ return _context21.abrupt("return", this.db.record.findMany({
1544
+ where: {
1545
+ entity: {
1546
+ connection: {
1547
+ connectionId: connectionId
1548
+ }
1549
+ },
1550
+ data: {
1551
+ path: [propertyName],
1552
+ not: Prisma.JsonNull
1553
+ }
1554
+ }
1555
+ }));
1556
+ case 2:
1557
+ case "end":
1558
+ return _context21.stop();
1559
+ }
1560
+ }, _callee21, this);
1561
+ }));
1562
+ function getRecordsByPropertyName(_x20) {
1563
+ return _getRecordsByPropertyName.apply(this, arguments);
1564
+ }
1565
+ return getRecordsByPropertyName;
1566
+ }();
1567
+ _proto.setConnectionError = /*#__PURE__*/function () {
1568
+ var _setConnectionError = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee22(_ref20) {
1569
+ var k_id, error;
1570
+ return _regeneratorRuntime().wrap(function _callee22$(_context22) {
1571
+ while (1) switch (_context22.prev = _context22.next) {
1572
+ case 0:
1573
+ k_id = _ref20.k_id, error = _ref20.error;
1574
+ _context22.next = 3;
1575
+ return this.db.connection.update({
1576
+ where: {
1577
+ id: k_id
1578
+ },
1579
+ data: {
1580
+ issues: [error]
1581
+ }
1582
+ });
1583
+ case 3:
1584
+ return _context22.abrupt("return", _context22.sent);
1585
+ case 4:
1586
+ case "end":
1587
+ return _context22.stop();
1588
+ }
1589
+ }, _callee22, this);
1590
+ }));
1591
+ function setConnectionError(_x21) {
1592
+ return _setConnectionError.apply(this, arguments);
1593
+ }
1594
+ return setConnectionError;
1595
+ }();
1596
+ _proto.setConnectionSubscriptionId = /*#__PURE__*/function () {
1597
+ var _setConnectionSubscriptionId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee23(_ref21) {
1598
+ var k_id, subscriptionId;
1599
+ return _regeneratorRuntime().wrap(function _callee23$(_context23) {
1600
+ while (1) switch (_context23.prev = _context23.next) {
1601
+ case 0:
1602
+ k_id = _ref21.k_id, subscriptionId = _ref21.subscriptionId;
1603
+ _context23.next = 3;
1604
+ return this.db.connection.update({
1605
+ where: {
1606
+ id: k_id
1607
+ },
1608
+ data: {
1609
+ subscriptionId: subscriptionId
1610
+ }
1611
+ });
1612
+ case 3:
1613
+ return _context23.abrupt("return", _context23.sent);
1614
+ case 4:
1615
+ case "end":
1616
+ return _context23.stop();
1617
+ }
1618
+ }, _callee23, this);
1619
+ }));
1620
+ function setConnectionSubscriptionId(_x22) {
1621
+ return _setConnectionSubscriptionId.apply(this, arguments);
1622
+ }
1623
+ return setConnectionSubscriptionId;
1624
+ }();
1625
+ _proto.syncData = /*#__PURE__*/function () {
1626
+ var _syncData = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee24(_ref22) {
1627
+ var _existingEntity2;
1628
+ var connectionId, name, data, type, properties, lastSyncId, dataInt, existingEntity, _existingEntity, _existingEntity3;
1629
+ return _regeneratorRuntime().wrap(function _callee24$(_context24) {
1630
+ while (1) switch (_context24.prev = _context24.next) {
1631
+ case 0:
1632
+ connectionId = _ref22.connectionId, name = _ref22.name, data = _ref22.data, type = _ref22.type, properties = _ref22.properties, lastSyncId = _ref22.lastSyncId;
1633
+ _context24.next = 3;
1634
+ return this.getConnection({
1635
+ connectionId: connectionId,
1636
+ name: name
1637
+ });
1638
+ case 3:
1639
+ dataInt = _context24.sent;
1640
+ _context24.next = 6;
1641
+ return this.getEntityByConnectionAndType({
1642
+ k_id: dataInt == null ? void 0 : dataInt.id,
1643
+ type: type
1644
+ });
1645
+ case 6:
1646
+ existingEntity = _context24.sent;
1647
+ if (existingEntity) {
1648
+ _context24.next = 13;
1649
+ break;
1650
+ }
1651
+ _context24.next = 10;
1652
+ return this.createEntity({
1653
+ k_id: dataInt == null ? void 0 : dataInt.id,
1654
+ type: type,
1655
+ connectionId: connectionId
1656
+ });
1657
+ case 10:
1658
+ existingEntity = _context24.sent;
1659
+ _context24.next = 13;
1660
+ return this.addPropertiesToEntity({
1661
+ entityId: (_existingEntity = existingEntity) == null ? void 0 : _existingEntity.id,
1662
+ properties: properties
1663
+ });
1664
+ case 13:
1665
+ _context24.next = 15;
1666
+ return this.mergeExternalRecordsForEntity({
1667
+ entityId: (_existingEntity2 = existingEntity) == null ? void 0 : _existingEntity2.id,
1668
+ records: data
1669
+ });
1670
+ case 15:
1671
+ if (!lastSyncId) {
1672
+ _context24.next = 18;
1673
+ break;
1674
+ }
1675
+ _context24.next = 18;
1676
+ return this.updateEntityLastSyncId({
1677
+ entityId: (_existingEntity3 = existingEntity) == null ? void 0 : _existingEntity3.id,
1678
+ syncId: lastSyncId
1679
+ });
1680
+ case 18:
1681
+ case "end":
1682
+ return _context24.stop();
1683
+ }
1684
+ }, _callee24, this);
1685
+ }));
1686
+ function syncData(_x23) {
1687
+ return _syncData.apply(this, arguments);
1688
+ }
1689
+ return syncData;
1690
+ }();
1691
+ _proto.getConnectionsBySubscriptionId = /*#__PURE__*/function () {
1692
+ var _getConnectionsBySubscriptionId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee25(_ref23) {
1693
+ var subscriptionId;
1694
+ return _regeneratorRuntime().wrap(function _callee25$(_context25) {
1695
+ while (1) switch (_context25.prev = _context25.next) {
1696
+ case 0:
1697
+ subscriptionId = _ref23.subscriptionId;
1698
+ _context25.next = 3;
1699
+ return this.db.connection.findMany({
1700
+ where: {
1701
+ subscriptionId: subscriptionId
1702
+ }
1703
+ });
1704
+ case 3:
1705
+ return _context25.abrupt("return", _context25.sent);
1706
+ case 4:
1707
+ case "end":
1708
+ return _context25.stop();
1709
+ }
1710
+ }, _callee25, this);
1711
+ }));
1712
+ function getConnectionsBySubscriptionId(_x24) {
1713
+ return _getConnectionsBySubscriptionId.apply(this, arguments);
1714
+ }
1715
+ return getConnectionsBySubscriptionId;
1716
+ }();
1717
+ return DataLayer;
1718
+ }();
1719
+
1720
+ var connectParams = /*#__PURE__*/z.object({
1721
+ name: /*#__PURE__*/z.string(),
1722
+ connectionId: /*#__PURE__*/z.string(),
1723
+ clientRedirectPath: /*#__PURE__*/z.string().optional()["default"]('/')
1724
+ });
1725
+ var oauthState = /*#__PURE__*/connectParams.extend({
1726
+ previewRedirect: /*#__PURE__*/z.string().optional()
1727
+ });
1728
+ var callbackParams = /*#__PURE__*/z.object({
1729
+ state: /*#__PURE__*/z.preprocess(function (s) {
1730
+ return JSON.parse(Buffer.from(s, 'base64').toString());
1731
+ }, oauthState),
1732
+ error: /*#__PURE__*/z.string().optional()
1733
+ });
1734
+ var webhookQueryParams = /*#__PURE__*/z.object({
1735
+ event: /*#__PURE__*/z.string(),
1736
+ name: /*#__PURE__*/z.string()
1737
+ });
1738
+ var apiKeyConnectionOptions = /*#__PURE__*/z.object({
1739
+ apiKey: /*#__PURE__*/z.string()
1740
+ });
1741
+
1742
+ var parseQueryParams = function parseQueryParams(req, schema) {
1743
+ var search = req.nextUrl.search.slice(1);
1744
+ var queryParams = qs.parse(search);
1745
+ var _schema$safeParse = schema.safeParse(queryParams),
1746
+ data = _schema$safeParse.data,
1747
+ success = _schema$safeParse.success,
1748
+ error = _schema$safeParse.error;
1749
+ return {
1750
+ success: success,
1751
+ data: data,
1752
+ error: error
1753
+ };
1754
+ };
1755
+ var nextHeaders = headers;
1756
+
1757
+ var makeConnect = function makeConnect(framework) {
1758
+ return /*#__PURE__*/function () {
1759
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
1760
+ var _parseQueryParams, success, error, _parseQueryParams$dat, name, connectionId, clientRedirectPath, _int, authenticator, redirectUri;
1761
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1762
+ while (1) switch (_context.prev = _context.next) {
1763
+ case 0:
1764
+ _parseQueryParams = parseQueryParams(req, connectParams), success = _parseQueryParams.success, error = _parseQueryParams.error, _parseQueryParams$dat = _parseQueryParams.data, name = _parseQueryParams$dat.name, connectionId = _parseQueryParams$dat.connectionId, clientRedirectPath = _parseQueryParams$dat.clientRedirectPath;
1765
+ if (success) {
1766
+ _context.next = 3;
1767
+ break;
1768
+ }
1769
+ return _context.abrupt("return", NextResponse.json({
1770
+ error: error,
1771
+ status: 400
1772
+ }));
1773
+ case 3:
1774
+ _int = framework.getIntegration(name);
1775
+ authenticator = _int.getAuthenticator();
1776
+ _context.next = 7;
1777
+ return authenticator.getRedirectUri({
1778
+ connectionId: connectionId,
1779
+ clientRedirectPath: clientRedirectPath
1780
+ });
1781
+ case 7:
1782
+ redirectUri = _context.sent;
1783
+ return _context.abrupt("return", NextResponse.redirect(redirectUri));
1784
+ case 9:
1785
+ case "end":
1786
+ return _context.stop();
1787
+ }
1788
+ }, _callee);
1789
+ }));
1790
+ return function (_x) {
1791
+ return _ref.apply(this, arguments);
1792
+ };
1793
+ }();
1794
+ };
1795
+
1796
+ var makeCallback = function makeCallback(framework) {
1797
+ return /*#__PURE__*/function () {
1798
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
1799
+ var _parseQueryParams, data, error, _data$state, name, clientRedirectPath, callbackError, _int, redirectUri;
1800
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1801
+ while (1) switch (_context.prev = _context.next) {
1802
+ case 0:
1803
+ _parseQueryParams = parseQueryParams(req, callbackParams), data = _parseQueryParams.data, error = _parseQueryParams.error;
1804
+ _data$state = data.state, name = _data$state.name, clientRedirectPath = _data$state.clientRedirectPath, callbackError = data.error;
1805
+ if (!(error || callbackError)) {
1806
+ _context.next = 4;
1807
+ break;
1808
+ }
1809
+ return _context.abrupt("return", NextResponse.json({
1810
+ error: error,
1811
+ status: 400
1812
+ }));
1813
+ case 4:
1814
+ _int = framework.getIntegration(name);
1815
+ if (_int) {
1816
+ _context.next = 7;
1817
+ break;
1818
+ }
1819
+ return _context.abrupt("return", NextResponse.json({
1820
+ error: "Callback state cannot locate integration: \"" + name + "\"",
1821
+ status: 400
1822
+ }));
1823
+ case 7:
1824
+ _context.next = 9;
1825
+ return _int.getAuthenticator().processCallback(req.url);
1826
+ case 9:
1827
+ redirectUri = new URL(clientRedirectPath || '', req.nextUrl.protocol + '//' + req.nextUrl.host);
1828
+ return _context.abrupt("return", NextResponse.redirect(redirectUri));
1829
+ case 11:
1830
+ case "end":
1831
+ return _context.stop();
1832
+ }
1833
+ }, _callee);
1834
+ }));
1835
+ return function (_x) {
1836
+ return _ref.apply(this, arguments);
1837
+ };
1838
+ }();
1839
+ };
1840
+
1841
+ var APP_ID = 'mastra';
1842
+ var client = /*#__PURE__*/new Inngest({
1843
+ id: APP_ID
1844
+ });
1845
+
1846
+ function readBlueprint(_x) {
1847
+ return _readBlueprint.apply(this, arguments);
1848
+ }
1849
+ function _readBlueprint() {
1850
+ _readBlueprint = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(filePath) {
1851
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1852
+ while (1) switch (_context4.prev = _context4.next) {
1853
+ case 0:
1854
+ return _context4.abrupt("return", new Promise(function (resolve, reject) {
1855
+ fs.readFile(filePath, 'utf8', function (err, data) {
1856
+ if (err) reject(err);else {
1857
+ var jsonData = JSON.parse(data);
1858
+ var blueprintFile = last(filePath == null ? void 0 : filePath.split('/'));
1859
+ var blueprintId = first(blueprintFile == null ? void 0 : blueprintFile.split('.json'));
1860
+ resolve(_extends({}, jsonData, {
1861
+ id: blueprintId
1862
+ }));
1863
+ }
1864
+ });
1865
+ }));
1866
+ case 1:
1867
+ case "end":
1868
+ return _context4.stop();
1869
+ }
1870
+ }, _callee4);
1871
+ }));
1872
+ return _readBlueprint.apply(this, arguments);
1873
+ }
1874
+ function getBlueprints(_x2) {
1875
+ return _getBlueprints.apply(this, arguments);
1876
+ }
1877
+ function _getBlueprints() {
1878
+ _getBlueprints = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref) {
1879
+ var directoryPath;
1880
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1881
+ while (1) switch (_context6.prev = _context6.next) {
1882
+ case 0:
1883
+ directoryPath = _ref.directoryPath;
1884
+ return _context6.abrupt("return", new Promise(function (resolve, reject) {
1885
+ fs.readdir(directoryPath, /*#__PURE__*/function () {
1886
+ var _ref7 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(err, files) {
1887
+ var jsonFiles, result, _iterator, _step, file, filePath, jsonData, blueprintFile, blueprintId;
1888
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1889
+ while (1) switch (_context5.prev = _context5.next) {
1890
+ case 0:
1891
+ if (!err) {
1892
+ _context5.next = 4;
1893
+ break;
1894
+ }
1895
+ reject(err);
1896
+ _context5.next = 17;
1897
+ break;
1898
+ case 4:
1899
+ jsonFiles = files.filter(function (file) {
1900
+ return file.endsWith('.json');
1901
+ });
1902
+ result = [];
1903
+ _iterator = _createForOfIteratorHelperLoose(jsonFiles);
1904
+ case 7:
1905
+ if ((_step = _iterator()).done) {
1906
+ _context5.next = 16;
1907
+ break;
1908
+ }
1909
+ file = _step.value;
1910
+ filePath = path.join(directoryPath, file);
1911
+ _context5.next = 12;
1912
+ return readBlueprint(filePath);
1913
+ case 12:
1914
+ jsonData = _context5.sent;
1915
+ if (jsonData.title) {
1916
+ blueprintFile = last(filePath == null ? void 0 : filePath.split('/'));
1917
+ blueprintId = first(blueprintFile == null ? void 0 : blueprintFile.split('.json'));
1918
+ result.push(_extends({}, jsonData, {
1919
+ id: blueprintId
1920
+ }));
1921
+ }
1922
+ case 14:
1923
+ _context5.next = 7;
1924
+ break;
1925
+ case 16:
1926
+ resolve(result);
1927
+ case 17:
1928
+ case "end":
1929
+ return _context5.stop();
1930
+ }
1931
+ }, _callee5);
1932
+ }));
1933
+ return function (_x4, _x5) {
1934
+ return _ref7.apply(this, arguments);
1935
+ };
1936
+ }());
1937
+ }));
1938
+ case 2:
1939
+ case "end":
1940
+ return _context6.stop();
1941
+ }
1942
+ }, _callee6);
1943
+ }));
1944
+ return _getBlueprints.apply(this, arguments);
1945
+ }
1946
+ var createWorkflowHandler = function createWorkflowHandler(_ref2) {
1947
+ var blueprintDirPath = _ref2.blueprintDirPath,
1948
+ runBlueprint = _ref2.runBlueprint;
1949
+ return client.createFunction({
1950
+ id: 'workflow-executor',
1951
+ retries: 0
1952
+ }, {
1953
+ event: 'workflow/run-automations'
1954
+ }, /*#__PURE__*/function () {
1955
+ var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref3) {
1956
+ var event, step, _event$data, trigger, payload, connectionId, getBlueprintsDirPath, blueprints, triggeredAndPublishedBlueprints, runs;
1957
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1958
+ while (1) switch (_context3.prev = _context3.next) {
1959
+ case 0:
1960
+ event = _ref3.event, step = _ref3.step;
1961
+ _context3.prev = 1;
1962
+ _event$data = event.data, trigger = _event$data.trigger, payload = _event$data.payload;
1963
+ connectionId = event.user.connectionId;
1964
+ getBlueprintsDirPath = /*#__PURE__*/function () {
1965
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1966
+ var ARK_APP_DIR;
1967
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1968
+ while (1) switch (_context.prev = _context.next) {
1969
+ case 0:
1970
+ ARK_APP_DIR = process.env.ARK_APP_DIR || process.cwd();
1971
+ return _context.abrupt("return", path.join(ARK_APP_DIR, blueprintDirPath || '/blueprints'));
1972
+ case 2:
1973
+ case "end":
1974
+ return _context.stop();
1975
+ }
1976
+ }, _callee);
1977
+ }));
1978
+ return function getBlueprintsDirPath() {
1979
+ return _ref5.apply(this, arguments);
1980
+ };
1981
+ }();
1982
+ _context3.next = 7;
1983
+ return getBlueprintsDirPath().then(function (dir) {
1984
+ return getBlueprints({
1985
+ directoryPath: dir
1986
+ });
1987
+ });
1988
+ case 7:
1989
+ blueprints = _context3.sent;
1990
+ triggeredAndPublishedBlueprints = blueprints.filter(function (blueprint) {
1991
+ var _blueprint$trigger;
1992
+ return ((_blueprint$trigger = blueprint.trigger) == null ? void 0 : _blueprint$trigger.type) === trigger && blueprint.status === WorkflowStatusEnum.PUBLISHED;
1993
+ });
1994
+ runs = triggeredAndPublishedBlueprints.map(function (blueprint) {
1995
+ return step.run("run-blueprint: " + blueprint.id, /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1996
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1997
+ while (1) switch (_context2.prev = _context2.next) {
1998
+ case 0:
1999
+ return _context2.abrupt("return", runBlueprint({
2000
+ blueprint: blueprint,
2001
+ dataCtx: payload,
2002
+ ctx: {
2003
+ connectionId: connectionId
2004
+ }
2005
+ }));
2006
+ case 1:
2007
+ case "end":
2008
+ return _context2.stop();
2009
+ }
2010
+ }, _callee2);
2011
+ })));
2012
+ });
2013
+ _context3.next = 12;
2014
+ return Promise.all(runs);
2015
+ case 12:
2016
+ return _context3.abrupt("return", {
2017
+ event: event,
2018
+ body: "sync completed"
2019
+ });
2020
+ case 15:
2021
+ _context3.prev = 15;
2022
+ _context3.t0 = _context3["catch"](1);
2023
+ return _context3.abrupt("return", {
2024
+ event: event,
2025
+ body: "error occurred while running sync: " + _context3.t0
2026
+ });
2027
+ case 18:
2028
+ case "end":
2029
+ return _context3.stop();
2030
+ }
2031
+ }, _callee3, null, [[1, 15]]);
2032
+ }));
2033
+ return function (_x3) {
2034
+ return _ref4.apply(this, arguments);
2035
+ };
2036
+ }());
2037
+ };
2038
+
2039
+ var makeInngest = function makeInngest(framework) {
2040
+ var _framework$config$wor;
2041
+ // TODO: hook into framework to add framework functions to the inngest client
2042
+ var eventHandlers = framework.getGlobalEventHandlers();
2043
+ var globalEventHandlers = eventHandlers.map(function (eh) {
2044
+ return client.createFunction({
2045
+ id: eh.id
2046
+ }, {
2047
+ event: eh.event
2048
+ }, eh.executor);
2049
+ });
2050
+ var systemWorkflowHandler = createWorkflowHandler({
2051
+ blueprintDirPath: (_framework$config$wor = framework.config.workflows) == null ? void 0 : _framework$config$wor.blueprintDirPath,
2052
+ runBlueprint: framework.runBlueprint
2053
+ });
2054
+ var handler = serve({
2055
+ client: client,
2056
+ functions: [].concat(globalEventHandlers, [systemWorkflowHandler])
2057
+ });
2058
+ // @ts-ignore
2059
+ return function (req) {
2060
+ return handler(req);
2061
+ };
2062
+ };
2063
+
2064
+ var makeWebhook = function makeWebhook(framework) {
2065
+ return function (req) {
2066
+ var params = parseQueryParams(req, webhookQueryParams);
2067
+ var data = params.data,
2068
+ error = params.error;
2069
+ if (error) {
2070
+ return NextResponse.json({
2071
+ error: error,
2072
+ status: 400
2073
+ });
2074
+ }
2075
+ var decodedEvent = decodeURI(data == null ? void 0 : data.event);
2076
+ console.log("webhook event: " + decodedEvent + " from " + (data == null ? void 0 : data.name));
2077
+ var body = req.body;
2078
+ var integration = framework.getIntegration(data == null ? void 0 : data.name);
2079
+ var dataLayer = integration == null ? void 0 : integration.dataLayer;
2080
+ var connectionsBySubscriptionId = /*#__PURE__*/function () {
2081
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(subscriptionId) {
2082
+ var subscriptions;
2083
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2084
+ while (1) switch (_context.prev = _context.next) {
2085
+ case 0:
2086
+ _context.next = 2;
2087
+ return dataLayer == null ? void 0 : dataLayer.getConnectionsBySubscriptionId({
2088
+ subscriptionId: subscriptionId
2089
+ });
2090
+ case 2:
2091
+ subscriptions = _context.sent;
2092
+ return _context.abrupt("return", subscriptions != null ? subscriptions : []);
2093
+ case 4:
2094
+ case "end":
2095
+ return _context.stop();
2096
+ }
2097
+ }, _callee);
2098
+ }));
2099
+ return function connectionsBySubscriptionId(_x) {
2100
+ return _ref.apply(this, arguments);
2101
+ };
2102
+ }();
2103
+ void (integration == null ? void 0 : integration.processWebhookRequest({
2104
+ reqBody: body,
2105
+ event: decodedEvent,
2106
+ connectionsBySubscriptionId: connectionsBySubscriptionId
2107
+ }));
2108
+ return NextResponse.json({
2109
+ message: 'acknowledged'
2110
+ });
2111
+ };
2112
+ };
2113
+
2114
+ var registerRoutes = function registerRoutes(_ref) {
2115
+ var framework = _ref.framework;
2116
+ var registry = {
2117
+ connect: makeConnect(framework),
2118
+ 'connect/callback': makeCallback(framework),
2119
+ inngest: makeInngest(framework),
2120
+ webhook: makeWebhook(framework)
2121
+ };
2122
+ return function (req, _ref2) {
2123
+ var _Object$keys$at;
2124
+ var params = _ref2.params;
2125
+ var pathKey = (_Object$keys$at = Object.keys(params).at(0)) != null ? _Object$keys$at : 'routes';
2126
+ var route = params[pathKey].length ? params[pathKey].join('/') : '';
2127
+ if (route in registry) {
2128
+ return registry[route](req);
2129
+ }
2130
+ return NextResponse.json({
2131
+ status: 404
2132
+ });
2133
+ };
2134
+ };
2135
+
2136
+ var IntegrationErrors;
2137
+ (function (IntegrationErrors) {
2138
+ IntegrationErrors["BROKEN_CONNECTION"] = "BROKEN_CONNECTION";
2139
+ IntegrationErrors["MISSING_SCOPES"] = "MISSING_SCOPES";
2140
+ })(IntegrationErrors || (IntegrationErrors = {}));
2141
+ var IntegrationCredentialType;
2142
+ (function (IntegrationCredentialType) {
2143
+ IntegrationCredentialType["OAUTH"] = "OAUTH";
2144
+ IntegrationCredentialType["API_KEY"] = "API_KEY";
2145
+ })(IntegrationCredentialType || (IntegrationCredentialType = {}));
2146
+ var IntegrationFieldTypeEnum = {
2147
+ SINGLE_LINE_TEXT: 'SINGLE_LINE_TEXT',
2148
+ LONG_TEXT: 'LONG_TEXT',
2149
+ RICH_TEXT: 'RICH_TEXT',
2150
+ SINGLE_SELECT: 'SINGLE_SELECT',
2151
+ MULTI_SELECT: 'MULTI_SELECT',
2152
+ CREATABLE_SELECT: 'CREATABLE_SELECT',
2153
+ CHECKBOX: 'CHECKBOX',
2154
+ DATE: 'DATE',
2155
+ USER: 'USER',
2156
+ BADGE_LIST: 'BADGE_LIST',
2157
+ CURRENCY: 'CURRENCY',
2158
+ URL: 'URL',
2159
+ PHONE: 'PHONE',
2160
+ CONTACT: 'CONTACT',
2161
+ COMPANY: 'COMPANY',
2162
+ COMPOSITE: 'COMPOSITE',
2163
+ PERSON: 'PERSON',
2164
+ ENRICHMENT: 'ENRICHMENT'
2165
+ };
2166
+
2167
+ var filterQuerySchema = /*#__PURE__*/z.object({
2168
+ is: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2169
+ eq: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2170
+ not_eq: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2171
+ contains: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2172
+ not_contains: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2173
+ gt: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2174
+ gte: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2175
+ lt: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2176
+ lte: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2177
+ "in": /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2178
+ not_in: /*#__PURE__*/z.array(z.string()).or(z.string()).optional(),
2179
+ op: /*#__PURE__*/z["enum"](['or', 'and']).optional()["default"]('or'),
2180
+ set: /*#__PURE__*/z.string().optional().transform(transformFilterValueBoolean),
2181
+ not_set: /*#__PURE__*/z.string().optional().transform(transformFilterValueBoolean)
2182
+ });
2183
+ var sortQuerySchema = /*#__PURE__*/z.string().transform(transformFilterValueArray);
2184
+
2185
+ /**
2186
+ * Checks if object is empty
2187
+ * @param objectName
2188
+ * @returns boolean
2189
+ */
2190
+ var isObjectEmpty = function isObjectEmpty(objectName) {
2191
+ return objectName && Object.keys(objectName).length === 0 && objectName.constructor === Object;
2192
+ };
2193
+ /**
2194
+ * Get a value from an object by a given path. This function emulates the behavior of lodash's _.get method.
2195
+ *
2196
+ * @param {Record<string, any>} object - The object from which to get the value.
2197
+ * @param {string | string[]} path - The path to the value in the object. This can be a string (e.g., 'a.b.c') or an array of keys (e.g., ['a', 'b', 'c']).
2198
+ * @returns {unknown} The value at the given path in the object, or undefined if the path does not exist.
2199
+ */
2200
+ var getPath = function getPath(object, path) {
2201
+ if (typeof path === 'string') {
2202
+ path = path.split('.');
2203
+ }
2204
+ return path.reduce(function (obj, key) {
2205
+ return obj && obj[key] !== undefined ? obj[key] : undefined;
2206
+ }, object);
2207
+ };
2208
+ function recordHasData(record) {
2209
+ return Object.keys(record).length > 0;
2210
+ }
2211
+ function isLiteralObject(a) {
2212
+ return !!a && a.constructor === Object;
2213
+ }
2214
+ var constructObjFromStringPath = function constructObjFromStringPath(path, value) {
2215
+ var _newObject;
2216
+ //key, split the key with ., and then for each item, we update object data.pipeline
2217
+ // {data: {pipeline: 'kbdkjd'}}
2218
+ var pathArr = path.split('.');
2219
+ var newObject = (_newObject = {}, _newObject[pathArr[pathArr.length - 1]] = value, _newObject);
2220
+ var index = pathArr.length - 2;
2221
+ while (index >= 0) {
2222
+ var _newObject2;
2223
+ newObject = (_newObject2 = {}, _newObject2[pathArr[index]] = newObject, _newObject2);
2224
+ index = index - 1;
2225
+ }
2226
+ return newObject;
2227
+ };
2228
+ /**
2229
+ * Flatten a nested object, flatten from flat package works - https://www.npmjs.com/package/flat
2230
+ * but this allows you to define where you want it to stop by passing the keys that'll exist in the object you want it to stop at
2231
+ *
2232
+ * @param {Record<string, any>} object - The object to flatten.
2233
+ * @param {string[]} endKeys - The keys you want each value (which will be an object in this case) in the flattened object to possible have (e.g., ['a', 'b', 'c']).
2234
+ * @param {boolean} flattenArrayValue - This flag indicates that any array value should be flattened to object too.
2235
+ * @returns {Record<string, any>} Your flattened object
2236
+ */
2237
+ var flattenObject = function flattenObject(object, endKeys, flattenArrayValue) {
2238
+ if (endKeys === void 0) {
2239
+ endKeys = [];
2240
+ }
2241
+ var newObj = {};
2242
+ function recurseDip(obj, path) {
2243
+ var _loop = function _loop() {
2244
+ var _Object$entries$_i = _Object$entries[_i],
2245
+ key = _Object$entries$_i[0],
2246
+ value = _Object$entries$_i[1];
2247
+ var newPath = [].concat(path, [key]);
2248
+ if (value && value.constructor === Object) {
2249
+ var _endKeys;
2250
+ var hasOnlyEndKeys = (_endKeys = endKeys) != null && _endKeys.length ? endKeys.every(function (v) {
2251
+ return Object.keys(value).includes(v);
2252
+ }) : false;
2253
+ if (hasOnlyEndKeys) {
2254
+ var _extends2;
2255
+ newObj = _extends({}, newObj, (_extends2 = {}, _extends2[newPath.join('.')] = value, _extends2));
2256
+ } else {
2257
+ recurseDip(value, newPath);
2258
+ }
2259
+ } else if (flattenArrayValue && Array.isArray(value)) {
2260
+ var contructValue = value.reduce(function (a, b) {
2261
+ var _extends3;
2262
+ return _extends({}, a, (_extends3 = {}, _extends3[value.indexOf(b)] = b, _extends3));
2263
+ }, {});
2264
+ recurseDip(contructValue, newPath);
2265
+ } else {
2266
+ var _extends4;
2267
+ newObj = _extends({}, newObj, (_extends4 = {}, _extends4[newPath.join('.')] = value, _extends4));
2268
+ }
2269
+ };
2270
+ for (var _i = 0, _Object$entries = Object.entries(obj); _i < _Object$entries.length; _i++) {
2271
+ _loop();
2272
+ }
2273
+ }
2274
+ recurseDip(object, []);
2275
+ return newObj;
2276
+ };
2277
+ /**
2278
+ * Merges two objects, ensuring that only defined properties from the second object
2279
+ * override those in the first object.
2280
+ *
2281
+ * @template T - The type of the base object.
2282
+ * @template U - The type of the overrides object.
2283
+ * @param {T} base - The base object whose properties will be overridden.
2284
+ * @param {U} overrides - The object containing properties to override in the base object.
2285
+ * Only properties that are defined (not `undefined`) will override.
2286
+ * @returns {T & U} - A new object that combines properties from both `base` and `overrides`.
2287
+ * Properties in `base` will be overridden by defined properties in `overrides`.
2288
+ *
2289
+ * @example
2290
+ * const worksheetData = { a: 1, b: 2, c: 3 };
2291
+ * const payload = { b: undefined, c: 4 };
2292
+ * const extendedData = mergeWithDefinedOnly(worksheetData, payload);
2293
+ * // extendedData = { a: 1, b: 2, c: 4 }
2294
+ */
2295
+ function mergeWithDefinedOnly(base, overrides) {
2296
+ var result = _extends({}, base);
2297
+ for (var key in overrides) {
2298
+ if (overrides[key] !== undefined) {
2299
+ result[key] = overrides[key];
2300
+ }
2301
+ }
2302
+ return result;
2303
+ }
2304
+
2305
+ var _excluded$3 = ["client"],
2306
+ _excluded2$1 = ["name", "logoUrl"];
2307
+ /**
2308
+ * @params T - The type of the client that the integration provides
2309
+ */
2310
+ var Integration = /*#__PURE__*/function () {
2311
+ function Integration(config) {
2312
+ var _this = this;
2313
+ this.name = void 0;
2314
+ this.logoUrl = void 0;
2315
+ this.categories = [];
2316
+ this.description = '';
2317
+ this.dataLayer = void 0;
2318
+ this.config = {};
2319
+ this.availableScopes = void 0;
2320
+ this.events = {};
2321
+ this.apis = {};
2322
+ this.entityTypes = {};
2323
+ this.corePresets = {
2324
+ redirectURI: ''
2325
+ };
2326
+ this._convertApiClientToSystemApis = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
2327
+ var _this$getBaseClient, client, clientMethods, clientSchema, clientComments, apis;
2328
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2329
+ while (1) switch (_context2.prev = _context2.next) {
2330
+ case 0:
2331
+ _this$getBaseClient = _this.getBaseClient(), client = _this$getBaseClient.client, clientMethods = _objectWithoutPropertiesLoose(_this$getBaseClient, _excluded$3);
2332
+ clientSchema = _this.getClientZodSchema();
2333
+ clientComments = _this.getCommentsForClientApis();
2334
+ apis = Object.entries(clientMethods).reduce(function (acc, _ref2) {
2335
+ var key = _ref2[0],
2336
+ value = _ref2[1];
2337
+ if (typeof value === 'function') {
2338
+ var _clientComments$key, _client$key, _extends2;
2339
+ var camelCasedKey = key.replace(/_([a-z])/g, function (match, letter) {
2340
+ return letter.toUpperCase();
2341
+ });
2342
+ var sentenceCasedKey = camelCasedKey.replace(/([A-Z])/g, ' $1');
2343
+ var schemaKey = camelCasedKey + "DataSchema";
2344
+ var schema = clientSchema[schemaKey];
2345
+ var comment = (_clientComments$key = clientComments[key]) == null ? void 0 : _clientComments$key.comment;
2346
+ var doc = (_client$key = client[key]) == null ? void 0 : _client$key.doc;
2347
+ var fallbackComment = "Execute " + sentenceCasedKey;
2348
+ var api = {
2349
+ integrationName: _this.name,
2350
+ type: key,
2351
+ icon: {
2352
+ alt: _this.name,
2353
+ icon: _this.logoUrl
2354
+ },
2355
+ label: sentenceCasedKey,
2356
+ schema: !schema ? z.object({}) : schema,
2357
+ executor: function () {
2358
+ var _executor = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref3) {
2359
+ var data, connectionId, client, value;
2360
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2361
+ while (1) switch (_context.prev = _context.next) {
2362
+ case 0:
2363
+ data = _ref3.data, connectionId = _ref3.ctx.connectionId;
2364
+ _context.next = 3;
2365
+ return _this.getApiClient({
2366
+ connectionId: connectionId
2367
+ });
2368
+ case 3:
2369
+ client = _context.sent;
2370
+ value = client[key];
2371
+ return _context.abrupt("return", value(_extends({}, data)));
2372
+ case 6:
2373
+ case "end":
2374
+ return _context.stop();
2375
+ }
2376
+ }, _callee);
2377
+ }));
2378
+ function executor(_x) {
2379
+ return _executor.apply(this, arguments);
2380
+ }
2381
+ return executor;
2382
+ }(),
2383
+ description: comment || fallbackComment,
2384
+ documentation: doc || fallbackComment
2385
+ };
2386
+ return _extends({}, acc, (_extends2 = {}, _extends2[key] = api, _extends2));
2387
+ } else {
2388
+ return acc;
2389
+ }
2390
+ }, {});
2391
+ _this.apis = apis;
2392
+ case 5:
2393
+ case "end":
2394
+ return _context2.stop();
2395
+ }
2396
+ }, _callee2);
2397
+ }));
2398
+ this.makeClient = /*#__PURE__*/function () {
2399
+ var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(params) {
2400
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
2401
+ while (1) switch (_context3.prev = _context3.next) {
2402
+ case 0:
2403
+ throw new IntegrationError('Client not implemented');
2404
+ case 1:
2405
+ case "end":
2406
+ return _context3.stop();
2407
+ }
2408
+ }, _callee3);
2409
+ }));
2410
+ return function (_x2) {
2411
+ return _ref4.apply(this, arguments);
2412
+ };
2413
+ }();
2414
+ this.getEventHandlers = function (_ref5) {
2415
+ var makeWebhookUrl = _ref5.makeWebhookUrl;
2416
+ return Object.keys(_this.events).map(function (eventKey) {
2417
+ var _this$events$eventKey;
2418
+ var eventHandler = (_this$events$eventKey = _this.events[eventKey]) == null ? void 0 : _this$events$eventKey.handler;
2419
+ if (!eventHandler) return null;
2420
+ return eventHandler({
2421
+ integrationInstance: _this,
2422
+ eventKey: eventKey,
2423
+ makeWebhookUrl: makeWebhookUrl
2424
+ });
2425
+ }).filter(Boolean);
2426
+ };
2427
+ if (!(config != null && config.name)) {
2428
+ throw new IntegrationError('Integration name must be defined');
2429
+ }
2430
+ if (!(config != null && config.logoUrl)) {
2431
+ throw new IntegrationError('Integration logoUrl must be defined');
2432
+ }
2433
+ var name = config.name,
2434
+ logoUrl = config.logoUrl,
2435
+ others = _objectWithoutPropertiesLoose(config, _excluded2$1);
2436
+ this.name = name;
2437
+ this.logoUrl = logoUrl;
2438
+ this.config = others;
2439
+ }
2440
+ var _proto = Integration.prototype;
2441
+ _proto.getConfig = function getConfig() {
2442
+ return this.config;
2443
+ };
2444
+ _proto.getClientZodSchema = function getClientZodSchema() {
2445
+ return {};
2446
+ };
2447
+ _proto.getCommentsForClientApis = function getCommentsForClientApis() {
2448
+ return {};
2449
+ };
2450
+ _proto.getBaseClient = function getBaseClient() {
2451
+ return {};
2452
+ };
2453
+ _proto.getApiClient = /*#__PURE__*/function () {
2454
+ var _getApiClient = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(params) {
2455
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
2456
+ while (1) switch (_context4.prev = _context4.next) {
2457
+ case 0:
2458
+ throw new IntegrationError('API not implemented');
2459
+ case 1:
2460
+ case "end":
2461
+ return _context4.stop();
2462
+ }
2463
+ }, _callee4);
2464
+ }));
2465
+ function getApiClient(_x3) {
2466
+ return _getApiClient.apply(this, arguments);
2467
+ }
2468
+ return getApiClient;
2469
+ }();
2470
+ _proto.getApi = /*#__PURE__*/function () {
2471
+ var _getApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref6) {
2472
+ var connectionId;
2473
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2474
+ while (1) switch (_context5.prev = _context5.next) {
2475
+ case 0:
2476
+ connectionId = _ref6.connectionId;
2477
+ _context5.next = 3;
2478
+ return this.getApiClient({
2479
+ connectionId: connectionId
2480
+ });
2481
+ case 3:
2482
+ _context5.t0 = _context5.sent;
2483
+ return _context5.abrupt("return", {
2484
+ client: _context5.t0
2485
+ });
2486
+ case 5:
2487
+ case "end":
2488
+ return _context5.stop();
2489
+ }
2490
+ }, _callee5, this);
2491
+ }));
2492
+ function getApi(_x4) {
2493
+ return _getApi.apply(this, arguments);
2494
+ }
2495
+ return getApi;
2496
+ }();
2497
+ _proto.getAuthenticator = function getAuthenticator() {
2498
+ throw new IntegrationError('Authenticator not implemented');
2499
+ };
2500
+ _proto.attachDataLayer = function attachDataLayer(_ref7) {
2501
+ var dataLayer = _ref7.dataLayer;
2502
+ this.dataLayer = dataLayer;
2503
+ };
2504
+ _proto.registerApis = function registerApis() {
2505
+ return {};
2506
+ };
2507
+ _proto.getApis = function getApis() {
2508
+ return this.apis;
2509
+ };
2510
+ _proto.registerEvents = function registerEvents() {
2511
+ return {};
2512
+ };
2513
+ _proto.getEvents = function getEvents() {
2514
+ return this.events;
2515
+ };
2516
+ _proto.query = /*#__PURE__*/function () {
2517
+ var _query = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(props) {
2518
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
2519
+ while (1) switch (_context6.prev = _context6.next) {
2520
+ case 0:
2521
+ return _context6.abrupt("return", []);
2522
+ case 1:
2523
+ case "end":
2524
+ return _context6.stop();
2525
+ }
2526
+ }, _callee6);
2527
+ }));
2528
+ function query(_x5) {
2529
+ return _query.apply(this, arguments);
2530
+ }
2531
+ return query;
2532
+ }();
2533
+ _proto.getEvent = function getEvent(name) {
2534
+ var event = this.events[name];
2535
+ if (!event) {
2536
+ throw new Error("No event exists for this name: " + name);
2537
+ }
2538
+ return event;
2539
+ };
2540
+ _proto.processWebhookRequest = /*#__PURE__*/function () {
2541
+ var _processWebhookRequest = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(params) {
2542
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
2543
+ while (1) switch (_context7.prev = _context7.next) {
2544
+ case 0:
2545
+ throw new Error('Not implemented');
2546
+ case 1:
2547
+ case "end":
2548
+ return _context7.stop();
2549
+ }
2550
+ }, _callee7);
2551
+ }));
2552
+ function processWebhookRequest(_x6) {
2553
+ return _processWebhookRequest.apply(this, arguments);
2554
+ }
2555
+ return processWebhookRequest;
2556
+ }();
2557
+ _proto.triggerEvent = /*#__PURE__*/function () {
2558
+ var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref8) {
2559
+ var key, data, user, event;
2560
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
2561
+ while (1) switch (_context8.prev = _context8.next) {
2562
+ case 0:
2563
+ key = _ref8.key, data = _ref8.data, user = _ref8.user;
2564
+ _context8.next = 3;
2565
+ return client.send({
2566
+ name: key,
2567
+ data: data,
2568
+ user: user
2569
+ });
2570
+ case 3:
2571
+ event = _context8.sent;
2572
+ return _context8.abrupt("return", event);
2573
+ case 5:
2574
+ case "end":
2575
+ return _context8.stop();
2576
+ }
2577
+ }, _callee8);
2578
+ }));
2579
+ function triggerEvent(_x7) {
2580
+ return _triggerEvent.apply(this, arguments);
2581
+ }
2582
+ return triggerEvent;
2583
+ }();
2584
+ _proto.test = /*#__PURE__*/function () {
2585
+ var _test = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref9) {
2586
+ var _this$dataLayer;
2587
+ var connectionId, connection, _this$config$scopes, authenticator, bearer, desiredScopes, _bearer$scope, actualScopes, isMissingScopes;
2588
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
2589
+ while (1) switch (_context9.prev = _context9.next) {
2590
+ case 0:
2591
+ connectionId = _ref9.connectionId;
2592
+ _context9.next = 3;
2593
+ return (_this$dataLayer = this.dataLayer) == null ? void 0 : _this$dataLayer.getConnection({
2594
+ connectionId: connectionId,
2595
+ name: this.name
2596
+ });
2597
+ case 3:
2598
+ connection = _context9.sent;
2599
+ _context9.prev = 4;
2600
+ authenticator = this.getAuthenticator();
2601
+ _context9.next = 8;
2602
+ return authenticator.getAuthToken({
2603
+ k_id: connection == null ? void 0 : connection.id
2604
+ });
2605
+ case 8:
2606
+ bearer = _context9.sent;
2607
+ desiredScopes = (_this$config$scopes = this == null ? void 0 : this.config.scopes) != null ? _this$config$scopes : [];
2608
+ if (!desiredScopes.length) {
2609
+ _context9.next = 15;
2610
+ break;
2611
+ }
2612
+ actualScopes = (_bearer$scope = bearer.scope) != null ? _bearer$scope : [];
2613
+ isMissingScopes = !desiredScopes.every(function (desired) {
2614
+ return actualScopes.includes(desired);
2615
+ });
2616
+ if (!isMissingScopes) {
2617
+ _context9.next = 15;
2618
+ break;
2619
+ }
2620
+ return _context9.abrupt("return", IntegrationErrors.MISSING_SCOPES);
2621
+ case 15:
2622
+ _context9.next = 20;
2623
+ break;
2624
+ case 17:
2625
+ _context9.prev = 17;
2626
+ _context9.t0 = _context9["catch"](4);
2627
+ return _context9.abrupt("return", IntegrationErrors.BROKEN_CONNECTION);
2628
+ case 20:
2629
+ return _context9.abrupt("return", null);
2630
+ case 21:
2631
+ case "end":
2632
+ return _context9.stop();
2633
+ }
2634
+ }, _callee9, this, [[4, 17]]);
2635
+ }));
2636
+ function test(_x8) {
2637
+ return _test.apply(this, arguments);
2638
+ }
2639
+ return test;
2640
+ }();
2641
+ _proto.onConnectionCreated = /*#__PURE__*/function () {
2642
+ var _onConnectionCreated = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref10) {
2643
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
2644
+ while (1) switch (_context10.prev = _context10.next) {
2645
+ case 0:
2646
+ case 1:
2647
+ case "end":
2648
+ return _context10.stop();
2649
+ }
2650
+ }, _callee10);
2651
+ }));
2652
+ function onConnectionCreated(_x9) {
2653
+ return _onConnectionCreated.apply(this, arguments);
2654
+ }
2655
+ return onConnectionCreated;
2656
+ }();
2657
+ _proto.onDisconnect = /*#__PURE__*/function () {
2658
+ var _onDisconnect = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref11) {
2659
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
2660
+ while (1) switch (_context11.prev = _context11.next) {
2661
+ case 0:
2662
+ case 1:
2663
+ case "end":
2664
+ return _context11.stop();
2665
+ }
2666
+ }, _callee11);
2667
+ }));
2668
+ function onDisconnect(_x10) {
2669
+ return _onDisconnect.apply(this, arguments);
2670
+ }
2671
+ return onDisconnect;
2672
+ }();
2673
+ return Integration;
2674
+ }();
2675
+
2676
+ var _excluded$2 = ["accessToken", "expiresAt", "refreshToken"];
2677
+ var IntegrationAuth = /*#__PURE__*/function () {
2678
+ function IntegrationAuth(_ref) {
2679
+ var config = _ref.config,
2680
+ dataAccess = _ref.dataAccess,
2681
+ onConnectionCreated = _ref.onConnectionCreated;
2682
+ this.config = void 0;
2683
+ this.client = void 0;
2684
+ this.dataAccess = void 0;
2685
+ this.onConnectionCreated = void 0;
2686
+ this.config = config;
2687
+ this.onConnectionCreated = onConnectionCreated;
2688
+ this.dataAccess = dataAccess;
2689
+ }
2690
+ var _proto = IntegrationAuth.prototype;
2691
+ _proto.getClient = function getClient() {
2692
+ if (this.config.AUTH_TYPE === IntegrationCredentialType.API_KEY) {
2693
+ throw new Error('Integrations using API Key authentication do not support OAuth2Client');
2694
+ }
2695
+ var _this$config = this.config,
2696
+ SERVER = _this$config.SERVER,
2697
+ CLIENT_ID = _this$config.CLIENT_ID,
2698
+ CLIENT_SECRET = _this$config.CLIENT_SECRET,
2699
+ DISCOVERY_ENDPOINT = _this$config.DISCOVERY_ENDPOINT,
2700
+ AUTHORIZATION_ENDPOINT = _this$config.AUTHORIZATION_ENDPOINT,
2701
+ REVOCATION_ENDPOINT = _this$config.REVOCATION_ENDPOINT,
2702
+ TOKEN_ENDPOINT = _this$config.TOKEN_ENDPOINT,
2703
+ AUTHENTICATION_METHOD = _this$config.AUTHENTICATION_METHOD;
2704
+ if (!this.client) {
2705
+ try {
2706
+ this.client = new OAuth2Client({
2707
+ server: SERVER,
2708
+ clientId: CLIENT_ID,
2709
+ clientSecret: CLIENT_SECRET,
2710
+ discoveryEndpoint: DISCOVERY_ENDPOINT,
2711
+ authorizationEndpoint: AUTHORIZATION_ENDPOINT,
2712
+ tokenEndpoint: TOKEN_ENDPOINT,
2713
+ revocationEndpoint: REVOCATION_ENDPOINT,
2714
+ authenticationMethod: AUTHENTICATION_METHOD
2715
+ });
2716
+ return this.client;
2717
+ } catch (error) {
2718
+ console.log('Error creating OAuth2Client', error);
2719
+ throw error;
2720
+ }
2721
+ }
2722
+ return this.client;
2723
+ };
2724
+ _proto.getScopes = function getScopes() {
2725
+ if (this.config.AUTH_TYPE === IntegrationCredentialType.API_KEY) {
2726
+ return [];
2727
+ }
2728
+ return this.config.SCOPES;
2729
+ };
2730
+ _proto.getRedirectUri = /*#__PURE__*/function () {
2731
+ var _getRedirectUri = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(state) {
2732
+ var _this$config$EXTRA_AU;
2733
+ var client, redirectUri, scopes, name;
2734
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2735
+ while (1) switch (_context.prev = _context.next) {
2736
+ case 0:
2737
+ if (!(this.config.AUTH_TYPE === IntegrationCredentialType.API_KEY)) {
2738
+ _context.next = 2;
2739
+ break;
2740
+ }
2741
+ throw new Error('Integrations using API Key authentication do not use redirect URIs');
2742
+ case 2:
2743
+ client = this.getClient();
2744
+ redirectUri = this.config.REDIRECT_URI;
2745
+ scopes = this.config.SCOPES;
2746
+ name = this.config.INTEGRATION_NAME;
2747
+ _context.next = 8;
2748
+ return client.authorizationCode.getAuthorizeUri({
2749
+ redirectUri: redirectUri,
2750
+ scope: scopes,
2751
+ state: Buffer.from(JSON.stringify(_extends({
2752
+ name: name
2753
+ }, state))).toString('base64'),
2754
+ extraParams: (_this$config$EXTRA_AU = this.config.EXTRA_AUTH_PARAMS) != null ? _this$config$EXTRA_AU : {}
2755
+ });
2756
+ case 8:
2757
+ return _context.abrupt("return", _context.sent);
2758
+ case 9:
2759
+ case "end":
2760
+ return _context.stop();
2761
+ }
2762
+ }, _callee, this);
2763
+ }));
2764
+ function getRedirectUri(_x) {
2765
+ return _getRedirectUri.apply(this, arguments);
2766
+ }
2767
+ return getRedirectUri;
2768
+ }();
2769
+ _proto.getTokenFromCodeRedirect = /*#__PURE__*/function () {
2770
+ var _getTokenFromCodeRedirect = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(url) {
2771
+ var client, _this$config$EXTRA_AU2, res;
2772
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2773
+ while (1) switch (_context2.prev = _context2.next) {
2774
+ case 0:
2775
+ if (!(this.config.AUTH_TYPE === IntegrationCredentialType.API_KEY)) {
2776
+ _context2.next = 2;
2777
+ break;
2778
+ }
2779
+ throw new Error('Integrations using API Key authentication do not use authorization codes');
2780
+ case 2:
2781
+ client = this.getClient();
2782
+ _context2.prev = 3;
2783
+ _context2.next = 6;
2784
+ return client.authorizationCode.getTokenFromCodeRedirect(url, {
2785
+ redirectUri: this.config.REDIRECT_URI,
2786
+ codeVerifier: (_this$config$EXTRA_AU2 = this.config.EXTRA_AUTH_PARAMS) == null ? void 0 : _this$config$EXTRA_AU2.code_challenge
2787
+ });
2788
+ case 6:
2789
+ res = _context2.sent;
2790
+ return _context2.abrupt("return", res);
2791
+ case 10:
2792
+ _context2.prev = 10;
2793
+ _context2.t0 = _context2["catch"](3);
2794
+ throw new Error(_context2.t0 == null ? void 0 : _context2.t0.message);
2795
+ case 13:
2796
+ case "end":
2797
+ return _context2.stop();
2798
+ }
2799
+ }, _callee2, this, [[3, 10]]);
2800
+ }));
2801
+ function getTokenFromCodeRedirect(_x2) {
2802
+ return _getTokenFromCodeRedirect.apply(this, arguments);
2803
+ }
2804
+ return getTokenFromCodeRedirect;
2805
+ }();
2806
+ _proto.getStateFromRedirect = /*#__PURE__*/function () {
2807
+ var _getStateFromRedirect = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(url) {
2808
+ var state;
2809
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
2810
+ while (1) switch (_context3.prev = _context3.next) {
2811
+ case 0:
2812
+ state = new URL(url).searchParams.get('state');
2813
+ if (state) {
2814
+ _context3.next = 3;
2815
+ break;
2816
+ }
2817
+ throw new Error('No state found in redirect');
2818
+ case 3:
2819
+ return _context3.abrupt("return", oauthState.parse(JSON.parse(Buffer.from(state, 'base64').toString())));
2820
+ case 4:
2821
+ case "end":
2822
+ return _context3.stop();
2823
+ }
2824
+ }, _callee3);
2825
+ }));
2826
+ function getStateFromRedirect(_x3) {
2827
+ return _getStateFromRedirect.apply(this, arguments);
2828
+ }
2829
+ return getStateFromRedirect;
2830
+ }();
2831
+ _proto.processCallback = /*#__PURE__*/function () {
2832
+ var _processCallback = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(url) {
2833
+ var tokenFromRedirect, state, connection, token;
2834
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
2835
+ while (1) switch (_context4.prev = _context4.next) {
2836
+ case 0:
2837
+ _context4.next = 2;
2838
+ return this.getTokenFromCodeRedirect(url);
2839
+ case 2:
2840
+ tokenFromRedirect = _context4.sent;
2841
+ _context4.next = 5;
2842
+ return this.getStateFromRedirect(url);
2843
+ case 5:
2844
+ state = _context4.sent;
2845
+ _context4.next = 8;
2846
+ return this.dataAccess.createConnection({
2847
+ connection: {
2848
+ connectionId: state.connectionId,
2849
+ name: this.config.INTEGRATION_NAME
2850
+ },
2851
+ credential: {
2852
+ type: this.config.AUTH_TYPE,
2853
+ value: tokenFromRedirect,
2854
+ scope: this.getScopes()
2855
+ }
2856
+ });
2857
+ case 8:
2858
+ connection = _context4.sent;
2859
+ _context4.next = 11;
2860
+ return this.getAuthToken({
2861
+ k_id: connection.id
2862
+ });
2863
+ case 11:
2864
+ token = _context4.sent;
2865
+ if (!this.onConnectionCreated) {
2866
+ _context4.next = 15;
2867
+ break;
2868
+ }
2869
+ _context4.next = 15;
2870
+ return Promise.resolve(this.onConnectionCreated(connection, token));
2871
+ case 15:
2872
+ case "end":
2873
+ return _context4.stop();
2874
+ }
2875
+ }, _callee4, this);
2876
+ }));
2877
+ function processCallback(_x4) {
2878
+ return _processCallback.apply(this, arguments);
2879
+ }
2880
+ return processCallback;
2881
+ }();
2882
+ _proto.getAuthToken = /*#__PURE__*/function () {
2883
+ var _getAuthToken = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref2) {
2884
+ var k_id, credential, token, accessToken, expiresAt, rest, minTokenLifetime, now, refreshedToken;
2885
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2886
+ while (1) switch (_context5.prev = _context5.next) {
2887
+ case 0:
2888
+ k_id = _ref2.k_id;
2889
+ _context5.next = 3;
2890
+ return this.dataAccess.getCredentialsByConnection(k_id);
2891
+ case 3:
2892
+ credential = _context5.sent;
2893
+ if (!(credential.type === IntegrationCredentialType.API_KEY)) {
2894
+ _context5.next = 6;
2895
+ break;
2896
+ }
2897
+ return _context5.abrupt("return", credential.value);
2898
+ case 6:
2899
+ token = credential.value;
2900
+ accessToken = token.accessToken, expiresAt = token.expiresAt, rest = _objectWithoutPropertiesLoose(token, _excluded$2);
2901
+ minTokenLifetime = 60 * 5 * 1000; // 5 minutes
2902
+ now = Date.now(); // If the token has no expiration date, it can be assumed it never expires
2903
+ if (expiresAt) {
2904
+ _context5.next = 12;
2905
+ break;
2906
+ }
2907
+ return _context5.abrupt("return", _extends({
2908
+ accessToken: accessToken,
2909
+ expiresAt: expiresAt
2910
+ }, rest));
2911
+ case 12:
2912
+ if (!(expiresAt - now > minTokenLifetime)) {
2913
+ _context5.next = 14;
2914
+ break;
2915
+ }
2916
+ return _context5.abrupt("return", _extends({
2917
+ accessToken: accessToken,
2918
+ expiresAt: expiresAt
2919
+ }, rest));
2920
+ case 14:
2921
+ _context5.next = 16;
2922
+ return this._refreshAuth({
2923
+ token: token,
2924
+ k_id: k_id
2925
+ });
2926
+ case 16:
2927
+ refreshedToken = _context5.sent;
2928
+ return _context5.abrupt("return", _extends({
2929
+ accessToken: refreshedToken.accessToken,
2930
+ expiresAt: refreshedToken.expiresAt
2931
+ }, rest));
2932
+ case 18:
2933
+ case "end":
2934
+ return _context5.stop();
2935
+ }
2936
+ }, _callee5, this);
2937
+ }));
2938
+ function getAuthToken(_x5) {
2939
+ return _getAuthToken.apply(this, arguments);
2940
+ }
2941
+ return getAuthToken;
2942
+ }();
2943
+ _proto._refreshAuth = /*#__PURE__*/function () {
2944
+ var _refreshAuth2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref3) {
2945
+ var token, k_id, oauthClient, newToken, existingRefreshToken, accessToken, expiresAt;
2946
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
2947
+ while (1) switch (_context6.prev = _context6.next) {
2948
+ case 0:
2949
+ token = _ref3.token, k_id = _ref3.k_id;
2950
+ oauthClient = this.getClient();
2951
+ _context6.next = 4;
2952
+ return oauthClient.refreshToken(token);
2953
+ case 4:
2954
+ newToken = _context6.sent;
2955
+ existingRefreshToken = token.refreshToken;
2956
+ accessToken = newToken.accessToken, expiresAt = newToken.expiresAt;
2957
+ _context6.next = 9;
2958
+ return this.dataAccess.updateConnectionCredential({
2959
+ k_id: k_id,
2960
+ token: {
2961
+ accessToken: accessToken,
2962
+ refreshToken: existingRefreshToken,
2963
+ expiresAt: expiresAt
2964
+ }
2965
+ });
2966
+ case 9:
2967
+ return _context6.abrupt("return", newToken);
2968
+ case 10:
2969
+ case "end":
2970
+ return _context6.stop();
2971
+ }
2972
+ }, _callee6, this);
2973
+ }));
2974
+ function _refreshAuth(_x6) {
2975
+ return _refreshAuth2.apply(this, arguments);
2976
+ }
2977
+ return _refreshAuth;
2978
+ }();
2979
+ _proto.revokeAuth = /*#__PURE__*/function () {
2980
+ var _revokeAuth = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref4) {
2981
+ var k_id, oauthClient, credential, token;
2982
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
2983
+ while (1) switch (_context7.prev = _context7.next) {
2984
+ case 0:
2985
+ k_id = _ref4.k_id;
2986
+ oauthClient = this.getClient();
2987
+ _context7.next = 4;
2988
+ return this.dataAccess.getCredentialsByConnection(k_id);
2989
+ case 4:
2990
+ credential = _context7.sent;
2991
+ token = credential.value;
2992
+ _context7.next = 8;
2993
+ return oauthClient.getEndpoint('revocationEndpoint');
2994
+ case 8:
2995
+ if (!_context7.sent) {
2996
+ _context7.next = 17;
2997
+ break;
2998
+ }
2999
+ _context7.prev = 9;
3000
+ _context7.next = 12;
3001
+ return oauthClient.revoke(token, 'refresh_token');
3002
+ case 12:
3003
+ _context7.next = 17;
3004
+ break;
3005
+ case 14:
3006
+ _context7.prev = 14;
3007
+ _context7.t0 = _context7["catch"](9);
3008
+ console.log('Error revoking token', _context7.t0);
3009
+ case 17:
3010
+ case "end":
3011
+ return _context7.stop();
3012
+ }
3013
+ }, _callee7, this, [[9, 14]]);
3014
+ }));
3015
+ function revokeAuth(_x7) {
3016
+ return _revokeAuth.apply(this, arguments);
3017
+ }
3018
+ return revokeAuth;
3019
+ }();
3020
+ return IntegrationAuth;
3021
+ }();
3022
+
3023
+ /**
3024
+ * Extract schema options for the provided schema - Builds a map of fieldname to field options
3025
+ * @param schema - schema
3026
+ * @param dataCtx - data context - this is an object of options for each field that isn't enum (meaning string fields) but should have options
3027
+ * @returns schema options
3028
+ * */
3029
+ function extractSchemaOptions(_ref) {
3030
+ var schema = _ref.schema,
3031
+ dataCtx = _ref.dataCtx;
3032
+ return Object.entries(schema.shape).reduce(function (acc, _ref2) {
3033
+ var field = _ref2[0],
3034
+ schema = _ref2[1];
3035
+ setFieldOptions({
3036
+ schema: schema,
3037
+ acc: acc,
3038
+ field: field,
3039
+ dataCtxList: dataCtx == null ? void 0 : dataCtx[field]
3040
+ });
3041
+ return acc;
3042
+ }, {});
3043
+ }
3044
+ /**
3045
+ * Set field options for the schema - Recursively populate the accumulator with field options for the provided field
3046
+ * if the schema is an enum or an array of enums, or an array of strings and has dataCtxList
3047
+ * @param schema - schema
3048
+ * @param acc - accumulator
3049
+ * @param field - field
3050
+ * @param dataCtxList - data context list - custom options for the field
3051
+ * @returns void
3052
+ * */
3053
+ function setFieldOptions(_ref3) {
3054
+ var schema = _ref3.schema,
3055
+ acc = _ref3.acc,
3056
+ field = _ref3.field,
3057
+ dataCtxList = _ref3.dataCtxList;
3058
+ if (schema instanceof z.ZodEnum) {
3059
+ acc[field] = {
3060
+ options: schema.options.map(function (value) {
3061
+ return {
3062
+ value: value,
3063
+ label: _.capitalize(value)
3064
+ };
3065
+ })
3066
+ };
3067
+ } else if (schema instanceof z.ZodArray) {
3068
+ if (schema.element instanceof z.ZodEnum) {
3069
+ acc[field] = {
3070
+ options: schema.element.options.map(function (value) {
3071
+ return {
3072
+ value: value,
3073
+ label: _.capitalize(value)
3074
+ };
3075
+ })
3076
+ };
3077
+ } else if (schema.element instanceof z.ZodString && dataCtxList) {
3078
+ acc[field] = dataCtxList || {
3079
+ options: undefined
3080
+ };
3081
+ }
3082
+ } else if (schema instanceof z.ZodString && dataCtxList) {
3083
+ acc[field] = dataCtxList || {
3084
+ options: undefined
3085
+ };
3086
+ } else if (schema instanceof z.ZodOptional) {
3087
+ setFieldOptions({
3088
+ schema: schema._def.innerType,
3089
+ dataCtxList: dataCtxList,
3090
+ field: field,
3091
+ acc: acc
3092
+ });
3093
+ } else {
3094
+ acc[field] = {
3095
+ options: undefined
3096
+ };
3097
+ }
3098
+ }
3099
+
3100
+ function zodToPropertType(zodType) {
3101
+ if (zodType instanceof z.ZodString) {
3102
+ return PropertyType.SINGLE_LINE_TEXT;
3103
+ }
3104
+ if (zodType instanceof z.ZodBoolean) {
3105
+ return PropertyType.BOOLEAN;
3106
+ }
3107
+ if (zodType instanceof z.ZodRecord) {
3108
+ return PropertyType.JSON_OBJECT;
3109
+ }
3110
+ if (zodType instanceof z.ZodNumber) {
3111
+ return PropertyType.NUMBER;
3112
+ }
3113
+ if (zodType instanceof z.ZodArray) {
3114
+ return PropertyType.JSON_ARRAY;
3115
+ }
3116
+ if (zodType instanceof z.ZodOptional) {
3117
+ return zodToPropertType(zodType._def.innerType);
3118
+ }
3119
+ if (zodType instanceof z.ZodNullable) {
3120
+ return zodToPropertType(zodType._def.innerType);
3121
+ }
3122
+ if (zodType instanceof z.ZodLiteral) {
3123
+ return PropertyType.SINGLE_LINE_TEXT;
3124
+ }
3125
+ if (zodType instanceof z.ZodObject) {
3126
+ return PropertyType.JSON_OBJECT;
3127
+ }
3128
+ // TODO UNIONS
3129
+ return undefined;
3130
+ }
3131
+ function getResponseDataKey(_ref) {
3132
+ var responseSchema = _ref.responseSchema,
3133
+ listDataKey = _ref.listDataKey;
3134
+ var fields = [];
3135
+ var obj = responseSchema;
3136
+ if (obj && obj instanceof z.ZodArray) {
3137
+ obj = obj._def.type;
3138
+ }
3139
+ if (obj && obj instanceof z.ZodLazy) {
3140
+ obj = responseSchema._def.getter();
3141
+ if (obj instanceof z.ZodLazy) {
3142
+ obj = obj._def.getter();
3143
+ }
3144
+ }
3145
+ if (obj instanceof z.ZodObject) {
3146
+ var shape = obj._def.shape();
3147
+ var keys = Object.keys(shape);
3148
+ var listData = keys.find(function (k) {
3149
+ return k === listDataKey;
3150
+ });
3151
+ if (listData) {
3152
+ var def = shape[listData];
3153
+ if (def instanceof z.ZodArray) {
3154
+ var innerDef = def._def.type;
3155
+ if (innerDef && innerDef instanceof z.ZodLazy) {
3156
+ var _obj = innerDef._def.getter();
3157
+ if (_obj instanceof z.ZodObject) {
3158
+ var _shape = _obj._def.shape();
3159
+ Object.entries(_shape).forEach(function (_ref2) {
3160
+ var k = _ref2[0],
3161
+ v = _ref2[1];
3162
+ var type = zodToPropertType(v);
3163
+ if (type) {
3164
+ fields.push({
3165
+ name: k,
3166
+ type: type,
3167
+ displayName: k,
3168
+ visible: true,
3169
+ order: 1,
3170
+ modifiable: false
3171
+ });
3172
+ }
3173
+ });
3174
+ }
3175
+ }
3176
+ }
3177
+ } else {
3178
+ Object.entries(shape).forEach(function (_ref3) {
3179
+ var k = _ref3[0],
3180
+ v = _ref3[1];
3181
+ var type = zodToPropertType(v);
3182
+ if (type) {
3183
+ fields.push({
3184
+ name: k,
3185
+ type: type,
3186
+ displayName: k,
3187
+ visible: true,
3188
+ order: 1,
3189
+ modifiable: false
3190
+ });
3191
+ }
3192
+ });
3193
+ }
3194
+ }
3195
+ return fields;
3196
+ }
3197
+ function allowedKey(key) {
3198
+ if (key.startsWith('get')) {
3199
+ return true;
3200
+ }
3201
+ if (/List/.test(key)) {
3202
+ return true;
3203
+ }
3204
+ if (/Get/.test(key)) {
3205
+ return true;
3206
+ }
3207
+ return false;
3208
+ }
3209
+ function transformKey(input) {
3210
+ // Use a regular expression to match 'get', followed by any characters and then the first uppercase letter
3211
+ return input.replace(/^(get|Get)([A-Z][a-z]*)/, function (_, __, firstPart) {
3212
+ // Convert the first meaningful part to lowercase
3213
+ return firstPart.toLowerCase();
3214
+ }).replace(/^([a-z]+)([A-Z].*)?$/, function (_, firstPart) {
3215
+ // Return the first part in lowercase
3216
+ return firstPart.toLowerCase();
3217
+ }).replace(/^([a-z]+)([A-Z].*)?$/, function (_, firstPart) {
3218
+ // Return the first part in lowercase
3219
+ return firstPart.toLowerCase();
3220
+ });
3221
+ }
3222
+ function extractPlural(input) {
3223
+ // Use a regular expression to match the pattern
3224
+ var regex = /^get([A-Z][a-z]*(?:[A-Z][a-z]*)*)(?:([A-Z][a-z]+))?$/;
3225
+ var match = input.match(regex);
3226
+ // If there's a match, return the plural part (first capturing group)
3227
+ if (match) {
3228
+ var returnS = match[1].toLowerCase(); // Convert to lowercase to match your output requirements
3229
+ if (!returnS.endsWith('s')) {
3230
+ return returnS + 's';
3231
+ }
3232
+ return returnS;
3233
+ }
3234
+ // Return null if the input does not match the pattern
3235
+ return '';
3236
+ }
3237
+ function removeDuplicateWord(input) {
3238
+ // Use a regular expression to match duplicated words
3239
+ var regex = /^(.*?)(\1)$/;
3240
+ var match = input.match(regex);
3241
+ // If there's a match, return the first part (original word)
3242
+ if (match) {
3243
+ return match[1];
3244
+ }
3245
+ // Return the original string if no duplicates are found
3246
+ return input;
3247
+ }
3248
+ function getEntityKey(key) {
3249
+ if (key.startsWith('list')) {
3250
+ return key.replace('list', '').toLowerCase();
3251
+ }
3252
+ if (key.startsWith('get')) {
3253
+ var pluralS = extractPlural(key);
3254
+ if (!pluralS) {
3255
+ return key.replace('get', '').toLowerCase();
3256
+ }
3257
+ return removeDuplicateWord(pluralS.toLowerCase());
3258
+ }
3259
+ return transformKey(key);
3260
+ }
3261
+ function generateSyncs(_ref4) {
3262
+ var client = _ref4.client,
3263
+ schema = _ref4.schema,
3264
+ name = _ref4.name,
3265
+ idKey = _ref4.idKey,
3266
+ listDataKey = _ref4.listDataKey;
3267
+ var events = {};
3268
+ Object.keys(client).filter(function (k) {
3269
+ return k !== 'client';
3270
+ }).forEach(function (key) {
3271
+ if (allowedKey(key)) {
3272
+ var _schema$schemaKey, _schema$responseSchem;
3273
+ var apiKey = key;
3274
+ var entityKey = getEntityKey(key);
3275
+ var schemaKey = key + "DataSchema";
3276
+ var responseSchemaKey = key + "ResponseSchema";
3277
+ var inputSchema = (_schema$schemaKey = schema == null ? void 0 : schema[schemaKey]) != null ? _schema$schemaKey : z.object({});
3278
+ var responseSchema = (_schema$responseSchem = schema == null ? void 0 : schema[responseSchemaKey]) != null ? _schema$responseSchem : z.object({});
3279
+ var properties = getResponseDataKey({
3280
+ listDataKey: listDataKey,
3281
+ responseSchema: responseSchema
3282
+ });
3283
+ var handler = function handler(_ref5) {
3284
+ var eventKey = _ref5.eventKey,
3285
+ _ref5$integrationInst = _ref5.integrationInstance,
3286
+ name = _ref5$integrationInst.name,
3287
+ getApiClient = _ref5$integrationInst.getApiClient,
3288
+ dataLayer = _ref5$integrationInst.dataLayer;
3289
+ return {
3290
+ id: name + "-sync-" + entityKey,
3291
+ event: eventKey,
3292
+ executor: function () {
3293
+ var _executor = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref6) {
3294
+ var event, connectionId, options, api, result, resultData, records;
3295
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3296
+ while (1) switch (_context.prev = _context.next) {
3297
+ case 0:
3298
+ event = _ref6.event;
3299
+ connectionId = event.user.connectionId;
3300
+ options = {};
3301
+ if (inputSchema && inputSchema instanceof z.ZodObject) {
3302
+ Object.keys(inputSchema._def.shape()).forEach(function (k) {
3303
+ var _event$data;
3304
+ options[k] = event == null || (_event$data = event.data) == null ? void 0 : _event$data[k];
3305
+ });
3306
+ }
3307
+ _context.next = 6;
3308
+ return getApiClient({
3309
+ connectionId: connectionId
3310
+ });
3311
+ case 6:
3312
+ api = _context.sent;
3313
+ _context.next = 9;
3314
+ return api[apiKey](options);
3315
+ case 9:
3316
+ result = _context.sent;
3317
+ // First see if we are getting the list data
3318
+ resultData = (result == null ? void 0 : result[listDataKey]) || [result];
3319
+ records = resultData == null ? void 0 : resultData.map(function (d) {
3320
+ return {
3321
+ externalId: d[idKey],
3322
+ data: d,
3323
+ entityType: entityKey.toUpperCase()
3324
+ };
3325
+ });
3326
+ _context.next = 14;
3327
+ return dataLayer == null ? void 0 : dataLayer.syncData({
3328
+ name: name,
3329
+ connectionId: connectionId,
3330
+ data: records,
3331
+ properties: properties,
3332
+ type: entityKey.toUpperCase(),
3333
+ lastSyncId: event == null ? void 0 : event.id
3334
+ });
3335
+ case 14:
3336
+ case "end":
3337
+ return _context.stop();
3338
+ }
3339
+ }, _callee);
3340
+ }));
3341
+ function executor(_x) {
3342
+ return _executor.apply(this, arguments);
3343
+ }
3344
+ return executor;
3345
+ }()
3346
+ };
3347
+ };
3348
+ events[name + "." + entityKey + "/sync"] = {
3349
+ schema: inputSchema,
3350
+ handler: handler
3351
+ };
3352
+ }
3353
+ });
3354
+ return events;
3355
+ }
3356
+
3357
+ var FilterOpToValueMapEnum = {
3358
+ EQUAL: 'EQUAL',
3359
+ NOT_EQUAL: 'NOT_EQUAL',
3360
+ CONTAINS: 'CONTAINS',
3361
+ IS: 'IS',
3362
+ IS_NOT: 'IS_NOT',
3363
+ NOT_CONTAINS: 'NOT_CONTAINS',
3364
+ IS_ANY_OF: 'IS_ANY_OF',
3365
+ GREATER_THAN: 'GREATER_THAN',
3366
+ LESS_THAN: 'LESS_THAN',
3367
+ DOES_NOT_CONTAIN: 'DOES_NOT_CONTAIN',
3368
+ GREATER_THAN_OR_EQUAL: 'GREATER_THAN_OR_EQUAL',
3369
+ LESS_THAN_OR_EQUAL: 'LESS_THAN_OR_EQUAL',
3370
+ SET: 'SET',
3371
+ NOT_SET: 'NOT_SET'
3372
+ };
3373
+
3374
+ var _excluded$1 = ["trigger", "actions"],
3375
+ _excluded2 = ["subActions"],
3376
+ _excluded3 = ["subActions"];
3377
+ var getOutputSchemaServer = /*#__PURE__*/function () {
3378
+ var _ref4 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref3) {
3379
+ var _outputSchema$_def, _outputSchema$_def2, _outputSchema$_def3;
3380
+ var ctx, block, payload, blockType, body, outputSchema, schema, blockSchemaTypeName, discriminatedUnionSchemaOptions, discriminatedUnionSchemaDiscriminator, discriminatorValue, discriminatedUnionSchema, resolvedSchema;
3381
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3382
+ while (1) switch (_context.prev = _context.next) {
3383
+ case 0:
3384
+ ctx = _ref3.ctx, block = _ref3.block, payload = _ref3.payload, blockType = _ref3.blockType;
3385
+ body = blockType === 'trigger' ? payload == null ? void 0 : payload.value : payload;
3386
+ if (!(typeof (block == null ? void 0 : block.schema) === 'function')) {
3387
+ _context.next = 8;
3388
+ break;
3389
+ }
3390
+ _context.next = 5;
3391
+ return block == null ? void 0 : block.schema({
3392
+ ctx: ctx
3393
+ });
3394
+ case 5:
3395
+ _context.t0 = _context.sent;
3396
+ _context.next = 9;
3397
+ break;
3398
+ case 8:
3399
+ _context.t0 = block == null ? void 0 : block.schema;
3400
+ case 9:
3401
+ outputSchema = _context.t0;
3402
+ if (!(typeof (block == null ? void 0 : block.schema) === 'function')) {
3403
+ _context.next = 16;
3404
+ break;
3405
+ }
3406
+ _context.next = 13;
3407
+ return block == null ? void 0 : block.schema({
3408
+ ctx: ctx
3409
+ });
3410
+ case 13:
3411
+ _context.t1 = _context.sent;
3412
+ _context.next = 17;
3413
+ break;
3414
+ case 16:
3415
+ _context.t1 = block == null ? void 0 : block.schema;
3416
+ case 17:
3417
+ schema = _context.t1;
3418
+ blockSchemaTypeName = outputSchema == null || (_outputSchema$_def = outputSchema._def) == null ? void 0 : _outputSchema$_def.typeName;
3419
+ discriminatedUnionSchemaOptions = outputSchema == null || (_outputSchema$_def2 = outputSchema._def) == null ? void 0 : _outputSchema$_def2.options;
3420
+ discriminatedUnionSchemaDiscriminator = outputSchema == null || (_outputSchema$_def3 = outputSchema._def) == null ? void 0 : _outputSchema$_def3.discriminator;
3421
+ discriminatorValue = discriminatedUnionSchemaDiscriminator ? body == null ? void 0 : body[discriminatedUnionSchemaDiscriminator] : undefined;
3422
+ discriminatedUnionSchema = discriminatedUnionSchemaOptions == null ? void 0 : discriminatedUnionSchemaOptions.find(function (option) {
3423
+ var _option$shape2;
3424
+ return (option == null || (_option$shape2 = option.shape) == null || (_option$shape2 = _option$shape2[discriminatedUnionSchemaDiscriminator]) == null || (_option$shape2 = _option$shape2._def) == null ? void 0 : _option$shape2.value) === discriminatorValue;
3425
+ });
3426
+ resolvedSchema = blockSchemaTypeName === 'ZodDiscriminatedUnion' ? discriminatedUnionSchema : outputSchema || schema;
3427
+ return _context.abrupt("return", resolvedSchema);
3428
+ case 25:
3429
+ case "end":
3430
+ return _context.stop();
3431
+ }
3432
+ }, _callee);
3433
+ }));
3434
+ return function getOutputSchemaServer(_x) {
3435
+ return _ref4.apply(this, arguments);
3436
+ };
3437
+ }();
3438
+ var getSchemaServer = /*#__PURE__*/function () {
3439
+ var _ref6 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref5) {
3440
+ var _outputSchema$_def4, _outputSchema$_def5, _outputSchema$_def6;
3441
+ var ctx, block, payload, blockType, body, outputSchema, schema, blockSchemaTypeName, discriminatedUnionSchemaOptions, discriminatedUnionSchemaDiscriminator, discriminatorValue, discriminatedUnionSchema, resolvedSchema;
3442
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3443
+ while (1) switch (_context2.prev = _context2.next) {
3444
+ case 0:
3445
+ ctx = _ref5.ctx, block = _ref5.block, payload = _ref5.payload, blockType = _ref5.blockType;
3446
+ body = blockType === 'trigger' ? payload == null ? void 0 : payload.value : payload;
3447
+ if (!(typeof block.schema === 'function')) {
3448
+ _context2.next = 8;
3449
+ break;
3450
+ }
3451
+ _context2.next = 5;
3452
+ return block.schema({
3453
+ ctx: ctx
3454
+ });
3455
+ case 5:
3456
+ _context2.t0 = _context2.sent;
3457
+ _context2.next = 9;
3458
+ break;
3459
+ case 8:
3460
+ _context2.t0 = block.schema;
3461
+ case 9:
3462
+ outputSchema = _context2.t0;
3463
+ if (!(typeof block.schema === 'function')) {
3464
+ _context2.next = 16;
3465
+ break;
3466
+ }
3467
+ _context2.next = 13;
3468
+ return block.schema({
3469
+ ctx: ctx
3470
+ });
3471
+ case 13:
3472
+ _context2.t1 = _context2.sent;
3473
+ _context2.next = 17;
3474
+ break;
3475
+ case 16:
3476
+ _context2.t1 = block.schema;
3477
+ case 17:
3478
+ schema = _context2.t1;
3479
+ blockSchemaTypeName = outputSchema == null || (_outputSchema$_def4 = outputSchema._def) == null ? void 0 : _outputSchema$_def4.typeName;
3480
+ discriminatedUnionSchemaOptions = outputSchema == null || (_outputSchema$_def5 = outputSchema._def) == null ? void 0 : _outputSchema$_def5.options;
3481
+ discriminatedUnionSchemaDiscriminator = outputSchema == null || (_outputSchema$_def6 = outputSchema._def) == null ? void 0 : _outputSchema$_def6.discriminator;
3482
+ discriminatorValue = discriminatedUnionSchemaDiscriminator ? body == null ? void 0 : body[discriminatedUnionSchemaDiscriminator] : undefined;
3483
+ discriminatedUnionSchema = discriminatedUnionSchemaOptions == null ? void 0 : discriminatedUnionSchemaOptions.find(function (option) {
3484
+ var _option$shape3;
3485
+ return (option == null || (_option$shape3 = option.shape) == null || (_option$shape3 = _option$shape3[discriminatedUnionSchemaDiscriminator]) == null || (_option$shape3 = _option$shape3._def) == null ? void 0 : _option$shape3.value) === discriminatorValue;
3486
+ });
3487
+ resolvedSchema = blockSchemaTypeName === 'ZodDiscriminatedUnion' ? discriminatedUnionSchema : schema || outputSchema;
3488
+ return _context2.abrupt("return", resolvedSchema);
3489
+ case 25:
3490
+ case "end":
3491
+ return _context2.stop();
3492
+ }
3493
+ }, _callee2);
3494
+ }));
3495
+ return function getSchemaServer(_x2) {
3496
+ return _ref6.apply(this, arguments);
3497
+ };
3498
+ }();
3499
+ var filterChecks = {
3500
+ stringCheck: function stringCheck(_ref8) {
3501
+ var filterField = _ref8.filterField,
3502
+ operator = _ref8.operator,
3503
+ comparator = _ref8.comparator;
3504
+ if (!filterField) return false;
3505
+ if (typeof filterField !== 'string') return false;
3506
+ switch (operator) {
3507
+ case FilterOpToValueMapEnum.EQUAL:
3508
+ return filterField.trim().toLowerCase() === comparator.trim().toLowerCase();
3509
+ case FilterOpToValueMapEnum.NOT_EQUAL:
3510
+ return filterField.trim().toLowerCase() !== comparator.trim().toLowerCase();
3511
+ case FilterOpToValueMapEnum.CONTAINS:
3512
+ return filterField.trim().toLowerCase().includes(comparator.trim().toLowerCase());
3513
+ case FilterOpToValueMapEnum.DOES_NOT_CONTAIN:
3514
+ return !filterField.trim().toLowerCase().includes(comparator.trim());
3515
+ case FilterOpToValueMapEnum.SET:
3516
+ return !!filterField;
3517
+ case FilterOpToValueMapEnum.NOT_SET:
3518
+ return !filterField;
3519
+ default:
3520
+ return false;
3521
+ }
3522
+ },
3523
+ numberCheck: function numberCheck(_ref9) {
3524
+ var filterField = _ref9.filterField,
3525
+ operator = _ref9.operator,
3526
+ comparator = _ref9.comparator;
3527
+ if (!filterField) return false;
3528
+ if (typeof filterField !== 'number') return false;
3529
+ switch (operator) {
3530
+ case 'EQUAL':
3531
+ return filterField === comparator;
3532
+ case 'NOT_EQUAL':
3533
+ return filterField !== comparator;
3534
+ case 'GREATER_THAN':
3535
+ return filterField > comparator;
3536
+ case 'LESS_THAN':
3537
+ return filterField < comparator;
3538
+ case 'GREATER_THAN_OR_EQUAL':
3539
+ return filterField >= comparator;
3540
+ case 'LESS_THAN_OR_EQUAL':
3541
+ return filterField <= comparator;
3542
+ default:
3543
+ return false;
3544
+ }
3545
+ },
3546
+ dateCheck: function dateCheck(_ref10) {
3547
+ var filterField = _ref10.filterField,
3548
+ operator = _ref10.operator,
3549
+ comparator = _ref10.comparator;
3550
+ if (!filterField) return false;
3551
+ var datesAreEqual = dateFns.isEqual(filterField, new Date(comparator).toDateString());
3552
+ var dateIsAfter = dateFns.isAfter(filterField, new Date(comparator).toDateString());
3553
+ var dateIsBefore = dateFns.isBefore(filterField, new Date(comparator).toDateString());
3554
+ switch (operator) {
3555
+ case 'EQUAL':
3556
+ return datesAreEqual;
3557
+ case 'NOT_EQUAL':
3558
+ return !datesAreEqual;
3559
+ case 'GREATER_THAN':
3560
+ return dateIsAfter;
3561
+ case 'LESS_THAN':
3562
+ return dateIsBefore;
3563
+ default:
3564
+ return false;
3565
+ }
3566
+ },
3567
+ booleanCheck: function booleanCheck(_ref11) {
3568
+ var filterField = _ref11.filterField,
3569
+ operator = _ref11.operator,
3570
+ comparator = _ref11.comparator;
3571
+ switch (operator) {
3572
+ case 'IS':
3573
+ return filterField === Boolean(comparator);
3574
+ case 'IS_NOT':
3575
+ return filterField !== Boolean(comparator);
3576
+ default:
3577
+ return false;
3578
+ }
3579
+ }
3580
+ };
3581
+ var constructWorkflowContextBluePrint = function constructWorkflowContextBluePrint(blueprint) {
3582
+ var _workflowContextActio;
3583
+ var trigger = blueprint.trigger,
3584
+ actions = blueprint.actions,
3585
+ blueprintInfo = _objectWithoutPropertiesLoose(blueprint, _excluded$1);
3586
+ var rootAction = actions[0];
3587
+ if (!rootAction) return {
3588
+ trigger: trigger,
3589
+ blueprintInfo: blueprintInfo,
3590
+ actions: {}
3591
+ };
3592
+ var subActions = rootAction.subActions,
3593
+ rest = _objectWithoutPropertiesLoose(rootAction, _excluded2);
3594
+ var workflowContextActions = (_workflowContextActio = {}, _workflowContextActio[rootAction.id] = rest, _workflowContextActio);
3595
+ function recurse(_ref12) {
3596
+ var action = _ref12.action,
3597
+ parentActionId = _ref12.parentActionId;
3598
+ var subActions = action.subActions;
3599
+ _objectWithoutPropertiesLoose(action, _excluded3);
3600
+ action.parentActionId = parentActionId;
3601
+ workflowContextActions[action.id] = action;
3602
+ if (subActions != null && subActions.length) {
3603
+ subActions.forEach(function (sub) {
3604
+ recurse({
3605
+ action: sub,
3606
+ parentActionId: action.id
3607
+ });
3608
+ });
3609
+ }
3610
+ }
3611
+ subActions.forEach(function (action) {
3612
+ recurse({
3613
+ action: action,
3614
+ parentActionId: rootAction.id
3615
+ });
3616
+ });
3617
+ return {
3618
+ trigger: trigger,
3619
+ blueprintInfo: blueprintInfo,
3620
+ actions: workflowContextActions
3621
+ };
3622
+ };
3623
+
3624
+ var _excluded = ["mastraConnectionId"];
3625
+ function evaluateCondition(_ref) {
3626
+ var _c$and, _c$or;
3627
+ var c = _ref.c,
3628
+ dataCtx = _ref.dataCtx,
3629
+ schema = _ref.schema,
3630
+ triggerId = _ref.triggerId;
3631
+ var andBranchResult = true;
3632
+ var baseResult = true;
3633
+ var orBranchResult = true;
3634
+ if (c != null && c.field) {
3635
+ var targetSchema = resolveSchemaPath({
3636
+ currentPath: '',
3637
+ schema: schema,
3638
+ targetPath: c.field,
3639
+ finalMap: {}
3640
+ });
3641
+ baseResult = resolveCondition({
3642
+ c: omit(c, 'and', 'or'),
3643
+ dataCtx: dataCtx,
3644
+ schema: targetSchema,
3645
+ triggerId: c.blockId || triggerId
3646
+ }) === true;
3647
+ }
3648
+ if ((_c$and = c.and) != null && _c$and.length) {
3649
+ andBranchResult = c.and.map(function (andCond) {
3650
+ if (andCond.field) {
3651
+ var _targetSchema = resolveSchemaPath({
3652
+ currentPath: '',
3653
+ schema: schema,
3654
+ targetPath: andCond.field,
3655
+ finalMap: {}
3656
+ });
3657
+ return resolveCondition({
3658
+ c: andCond,
3659
+ dataCtx: dataCtx,
3660
+ schema: _targetSchema,
3661
+ triggerId: andCond.blockId || triggerId
3662
+ });
3663
+ }
3664
+ }).every(Boolean);
3665
+ }
3666
+ if ((_c$or = c.or) != null && _c$or.length) {
3667
+ orBranchResult = c.or.map(function (orCond) {
3668
+ if (orCond.field) {
3669
+ var _targetSchema2 = resolveSchemaPath({
3670
+ currentPath: '',
3671
+ schema: schema,
3672
+ targetPath: orCond.field,
3673
+ finalMap: {}
3674
+ });
3675
+ return resolveCondition({
3676
+ c: orCond,
3677
+ dataCtx: dataCtx,
3678
+ schema: _targetSchema2,
3679
+ triggerId: orCond.blockId || triggerId
3680
+ });
3681
+ }
3682
+ }).some(Boolean);
3683
+ }
3684
+ return baseResult && andBranchResult && orBranchResult;
3685
+ }
3686
+ function resolveSchemaPath(_ref2) {
3687
+ var currentPath = _ref2.currentPath,
3688
+ schema = _ref2.schema,
3689
+ targetPath = _ref2.targetPath,
3690
+ finalMap = _ref2.finalMap;
3691
+ finalMap[currentPath] = schema;
3692
+ // bail out if the target path is found
3693
+ if (finalMap[targetPath]) {
3694
+ return finalMap[targetPath];
3695
+ }
3696
+ for (var _i = 0, _Object$entries = Object.entries(schema.shape); _i < _Object$entries.length; _i++) {
3697
+ var _Object$entries$_i = _Object$entries[_i],
3698
+ field = _Object$entries$_i[0],
3699
+ value = _Object$entries$_i[1];
3700
+ if (value instanceof z.ZodObject) {
3701
+ var nestedPathToSchemaMap = resolveSchemaPath({
3702
+ currentPath: currentPath ? currentPath.concat('.', field) : field,
3703
+ schema: value,
3704
+ targetPath: targetPath,
3705
+ finalMap: finalMap
3706
+ });
3707
+ if (nestedPathToSchemaMap) {
3708
+ // bail out if the target path is found
3709
+ return nestedPathToSchemaMap;
3710
+ }
3711
+ } else {
3712
+ finalMap[currentPath ? currentPath.concat('.', field) : field] = value;
3713
+ // bail out if the target path is found
3714
+ if (finalMap[targetPath]) {
3715
+ return finalMap[targetPath];
3716
+ }
3717
+ }
3718
+ }
3719
+ return finalMap[targetPath];
3720
+ }
3721
+ function replacePayloadVariables(_ref3) {
3722
+ var value = _ref3.value,
3723
+ stringContainingVariables = _ref3.stringContainingVariables,
3724
+ variable = _ref3.variable;
3725
+ return Array.isArray(stringContainingVariables) ? stringContainingVariables.map(function (v) {
3726
+ return v.replace("{{" + variable + "}}", value);
3727
+ }) : stringContainingVariables.replace("{{" + variable + "}}", value);
3728
+ }
3729
+ function resolveCondition(_ref4) {
3730
+ var c = _ref4.c,
3731
+ dataCtx = _ref4.dataCtx,
3732
+ schema = _ref4.schema,
3733
+ triggerId = _ref4.triggerId;
3734
+ var relevantBlock = dataCtx[(c == null ? void 0 : c.blockId) || triggerId || ''];
3735
+ if (c.isDefault) {
3736
+ return true;
3737
+ }
3738
+ if (!relevantBlock) {
3739
+ // treat as invalid filter, and move onto other filters
3740
+ // we return `true` so that it doesn't invalidate other filters in the same group
3741
+ return true;
3742
+ }
3743
+ var blockValue = resolvePath({
3744
+ path: c.field || '',
3745
+ replacementDataPayload: relevantBlock
3746
+ });
3747
+ var operator = c.operator;
3748
+ if (schema instanceof z.ZodString) {
3749
+ return filterChecks.stringCheck({
3750
+ filterField: blockValue,
3751
+ operator: operator,
3752
+ comparator: c.value
3753
+ });
3754
+ } else if (schema instanceof z.ZodNumber) {
3755
+ return filterChecks.numberCheck({
3756
+ filterField: blockValue,
3757
+ operator: operator,
3758
+ comparator: c.value
3759
+ });
3760
+ } else if (schema instanceof z.ZodBoolean) {
3761
+ return filterChecks.booleanCheck({
3762
+ filterField: blockValue,
3763
+ operator: operator,
3764
+ comparator: c.value
3765
+ });
3766
+ } else if (schema instanceof z.ZodDate) {
3767
+ return filterChecks.dateCheck({
3768
+ filterField: blockValue,
3769
+ operator: operator,
3770
+ comparator: c.value
3771
+ });
3772
+ } else if (schema instanceof z.ZodOptional) {
3773
+ var optionalSchema = schema._def.innerType;
3774
+ return resolveCondition({
3775
+ c: c,
3776
+ dataCtx: dataCtx,
3777
+ schema: optionalSchema,
3778
+ triggerId: triggerId
3779
+ });
3780
+ }
3781
+ }
3782
+ function resolvePath(_ref5) {
3783
+ var path = _ref5.path,
3784
+ replacementDataPayload = _ref5.replacementDataPayload;
3785
+ var pathParts = path.split('.');
3786
+ var resolvedValue = replacementDataPayload;
3787
+ for (var _iterator = _createForOfIteratorHelperLoose(pathParts), _step; !(_step = _iterator()).done;) {
3788
+ var part = _step.value;
3789
+ resolvedValue = resolvedValue[part];
3790
+ }
3791
+ return resolvedValue;
3792
+ }
3793
+ function resolvePayload(_ref6) {
3794
+ var payload = _ref6.payload,
3795
+ dataContext = _ref6.dataContext,
3796
+ variables = _ref6.variables,
3797
+ parentKey = _ref6.parentKey;
3798
+ var resolvedPayload = Object.assign({}, payload);
3799
+ for (var _i2 = 0, _Object$entries2 = Object.entries(resolvedPayload); _i2 < _Object$entries2.length; _i2++) {
3800
+ var _Object$entries2$_i = _Object$entries2[_i2],
3801
+ key = _Object$entries2$_i[0],
3802
+ value = _Object$entries2$_i[1];
3803
+ if (typeof value === 'object' && !Array.isArray(value)) {
3804
+ resolvedPayload[key] = resolvePayload({
3805
+ payload: value,
3806
+ dataContext: dataContext,
3807
+ variables: variables,
3808
+ parentKey: key
3809
+ });
3810
+ }
3811
+ if (!variables) continue;
3812
+ var currentKey = parentKey ? parentKey + "." + key : key;
3813
+ var variableMap = variables[currentKey];
3814
+ // variableMap = { [variable]: { refBlockId, path }, [variable]: {refBlockId, path} }
3815
+ if (!variableMap) {
3816
+ continue;
3817
+ }
3818
+ var tempValue = value;
3819
+ for (var _i3 = 0, _Object$entries3 = Object.entries(variableMap); _i3 < _Object$entries3.length; _i3++) {
3820
+ var _Object$entries3$_i = _Object$entries3[_i3],
3821
+ variable = _Object$entries3$_i[0],
3822
+ _Object$entries3$_i$ = _Object$entries3$_i[1],
3823
+ refBlockId = _Object$entries3$_i$.refBlockId,
3824
+ path = _Object$entries3$_i$.path;
3825
+ var replacementDataPayload = dataContext[refBlockId]; // get the payload returned by the relevant previous action
3826
+ if (!replacementDataPayload) {
3827
+ // if the reference block to get data from does not exist, skip
3828
+ continue;
3829
+ }
3830
+ // get the value from the replacement data payload at the path specified in the variable map
3831
+ var replacementValue = resolvePath({
3832
+ path: path,
3833
+ replacementDataPayload: replacementDataPayload
3834
+ });
3835
+ tempValue = replacePayloadVariables({
3836
+ value: replacementValue,
3837
+ stringContainingVariables: tempValue,
3838
+ variable: variable
3839
+ });
3840
+ }
3841
+ resolvedPayload[key] = tempValue;
3842
+ }
3843
+ return resolvedPayload;
3844
+ }
3845
+ function runActionsRecursively(_x) {
3846
+ return _runActionsRecursively.apply(this, arguments);
3847
+ }
3848
+ function _runActionsRecursively() {
3849
+ _runActionsRecursively = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref7) {
3850
+ var blueprintActions, frameworkApis, frameworkEvents, dataContext, blueprintId, runId, ctx, blueprintActionKVMap, _loop, _ret, _iterator2, _step2;
3851
+ return _regeneratorRuntime().wrap(function _callee$(_context3) {
3852
+ while (1) switch (_context3.prev = _context3.next) {
3853
+ case 0:
3854
+ blueprintActions = _ref7.blueprintActions, frameworkApis = _ref7.frameworkApis, frameworkEvents = _ref7.frameworkEvents, dataContext = _ref7.dataContext, blueprintId = _ref7.blueprintId, runId = _ref7.runId, ctx = _ref7.ctx, blueprintActionKVMap = _ref7.blueprintActionKVMap;
3855
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
3856
+ var _action$subActions;
3857
+ var action, concreteAction, hasValidBranch, _loop2, _ret2, _iterator3, _step3, defaultCondition, defaultAction, actionExecutor, _ref9, mastraConnectionId, actionPayload, resolvedPayload, resolvedSchema, data, executorResult, _ctx, subActions;
3858
+ return _regeneratorRuntime().wrap(function _loop$(_context2) {
3859
+ while (1) switch (_context2.prev = _context2.next) {
3860
+ case 0:
3861
+ action = _step2.value;
3862
+ concreteAction = frameworkApis[action.type];
3863
+ console.log('==========', "Running action " + action.type, {
3864
+ dataContext: JSON.stringify(dataContext, null, 2)
3865
+ }, '=======');
3866
+ // check action conditions
3867
+ if (!(action.type === 'CONDITIONS')) {
3868
+ _context2.next = 32;
3869
+ break;
3870
+ }
3871
+ if (action.condition) {
3872
+ _context2.next = 6;
3873
+ break;
3874
+ }
3875
+ return _context2.abrupt("return", 0);
3876
+ case 6:
3877
+ hasValidBranch = false;
3878
+ _loop2 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop2() {
3879
+ var cond, refBlock, currentConcreteBlock, isAction, actionToRun, resolvedSchema, shouldRunAction, executorResult;
3880
+ return _regeneratorRuntime().wrap(function _loop2$(_context) {
3881
+ while (1) switch (_context.prev = _context.next) {
3882
+ case 0:
3883
+ cond = _step3.value;
3884
+ if (!cond.isDefault) {
3885
+ _context.next = 3;
3886
+ break;
3887
+ }
3888
+ return _context.abrupt("return", 0);
3889
+ case 3:
3890
+ console.log('==========', "Found action condition", '=======');
3891
+ refBlock = blueprintActionKVMap.actions[cond.blockId || ''] || blueprintActionKVMap.trigger;
3892
+ currentConcreteBlock = frameworkApis[(refBlock == null ? void 0 : refBlock.type) || ''] || frameworkEvents[(refBlock == null ? void 0 : refBlock.type) || ''];
3893
+ isAction = !!frameworkApis[(refBlock == null ? void 0 : refBlock.type) || ''];
3894
+ if (currentConcreteBlock) {
3895
+ _context.next = 9;
3896
+ break;
3897
+ }
3898
+ return _context.abrupt("return", 0);
3899
+ case 9:
3900
+ actionToRun = action.subActions.find(function (a) {
3901
+ return a.id === cond.actionId;
3902
+ });
3903
+ if (actionToRun) {
3904
+ _context.next = 12;
3905
+ break;
3906
+ }
3907
+ return _context.abrupt("return", 0);
3908
+ case 12:
3909
+ _context.next = 14;
3910
+ return getOutputSchemaServer({
3911
+ block: currentConcreteBlock,
3912
+ payload: (refBlock == null ? void 0 : refBlock.payload) || {},
3913
+ blockType: isAction ? 'action' : 'trigger',
3914
+ ctx: ctx
3915
+ });
3916
+ case 14:
3917
+ resolvedSchema = _context.sent;
3918
+ shouldRunAction = evaluateCondition({
3919
+ c: cond,
3920
+ dataCtx: dataContext,
3921
+ schema: resolvedSchema
3922
+ });
3923
+ console.log('==========', {
3924
+ shouldRunAction: shouldRunAction
3925
+ }, '=======');
3926
+ if (shouldRunAction) {
3927
+ _context.next = 19;
3928
+ break;
3929
+ }
3930
+ return _context.abrupt("return", 0);
3931
+ case 19:
3932
+ hasValidBranch = true;
3933
+ _context.next = 22;
3934
+ return runActionsRecursively({
3935
+ blueprintActions: [actionToRun],
3936
+ frameworkApis: frameworkApis,
3937
+ frameworkEvents: frameworkEvents,
3938
+ dataContext: dataContext,
3939
+ blueprintId: blueprintId,
3940
+ runId: runId,
3941
+ ctx: ctx,
3942
+ blueprintActionKVMap: blueprintActionKVMap
3943
+ });
3944
+ case 22:
3945
+ executorResult = _context.sent;
3946
+ if (executorResult) {
3947
+ _context.next = 25;
3948
+ break;
3949
+ }
3950
+ return _context.abrupt("return", {
3951
+ v: {
3952
+ v: false
3953
+ }
3954
+ });
3955
+ case 25:
3956
+ case "end":
3957
+ return _context.stop();
3958
+ }
3959
+ }, _loop2);
3960
+ });
3961
+ _iterator3 = _createForOfIteratorHelperLoose(action.condition);
3962
+ case 9:
3963
+ if ((_step3 = _iterator3()).done) {
3964
+ _context2.next = 18;
3965
+ break;
3966
+ }
3967
+ return _context2.delegateYield(_loop2(), "t0", 11);
3968
+ case 11:
3969
+ _ret2 = _context2.t0;
3970
+ if (!(_ret2 === 0)) {
3971
+ _context2.next = 14;
3972
+ break;
3973
+ }
3974
+ return _context2.abrupt("continue", 16);
3975
+ case 14:
3976
+ if (!_ret2) {
3977
+ _context2.next = 16;
3978
+ break;
3979
+ }
3980
+ return _context2.abrupt("return", _ret2.v);
3981
+ case 16:
3982
+ _context2.next = 9;
3983
+ break;
3984
+ case 18:
3985
+ if (hasValidBranch) {
3986
+ _context2.next = 32;
3987
+ break;
3988
+ }
3989
+ console.log('======== No valid branch found for action ============');
3990
+ // run default branch if available
3991
+ defaultCondition = action.condition.find(function (c) {
3992
+ return c.isDefault;
3993
+ });
3994
+ defaultAction = action.subActions.find(function (a) {
3995
+ return a.id === (defaultCondition == null ? void 0 : defaultCondition.actionId);
3996
+ });
3997
+ if (!defaultAction) {
3998
+ _context2.next = 30;
3999
+ break;
4000
+ }
4001
+ console.log('========= running default action =============');
4002
+ _context2.next = 26;
4003
+ return runActionsRecursively({
4004
+ blueprintActions: [defaultAction],
4005
+ dataContext: dataContext,
4006
+ frameworkApis: frameworkApis,
4007
+ frameworkEvents: frameworkEvents,
4008
+ runId: runId,
4009
+ ctx: ctx,
4010
+ blueprintId: blueprintId,
4011
+ blueprintActionKVMap: blueprintActionKVMap
4012
+ });
4013
+ case 26:
4014
+ _context2.t1 = _context2.sent;
4015
+ return _context2.abrupt("return", {
4016
+ v: _context2.t1
4017
+ });
4018
+ case 30:
4019
+ console.log('========= No default branch found =============');
4020
+ return _context2.abrupt("return", {
4021
+ v: false
4022
+ });
4023
+ case 32:
4024
+ actionExecutor = concreteAction == null ? void 0 : concreteAction.executor;
4025
+ if (actionExecutor) {
4026
+ _context2.next = 36;
4027
+ break;
4028
+ }
4029
+ console.log("No executor found for " + action.type);
4030
+ return _context2.abrupt("return", 0);
4031
+ case 36:
4032
+ _ref9 = action.payload || {}, mastraConnectionId = _ref9.mastraConnectionId, actionPayload = _objectWithoutPropertiesLoose(_ref9, _excluded);
4033
+ resolvedPayload = resolvePayload({
4034
+ payload: actionPayload,
4035
+ dataContext: dataContext,
4036
+ variables: action.variables
4037
+ });
4038
+ console.log('====Resolved payload====', {
4039
+ resolvedPayload: resolvedPayload
4040
+ });
4041
+ _context2.next = 41;
4042
+ return getSchemaServer({
4043
+ block: concreteAction,
4044
+ payload: resolvedPayload,
4045
+ blockType: 'action',
4046
+ ctx: ctx
4047
+ });
4048
+ case 41:
4049
+ resolvedSchema = _context2.sent;
4050
+ data = resolvedSchema.parse(resolvedPayload);
4051
+ console.log('====Parsed data====', {
4052
+ data: data
4053
+ });
4054
+ executorResult = {};
4055
+ _ctx = mastraConnectionId ? {
4056
+ connectionId: mastraConnectionId
4057
+ } : ctx;
4058
+ _context2.prev = 46;
4059
+ _context2.next = 49;
4060
+ return actionExecutor({
4061
+ data: data,
4062
+ ctx: _ctx
4063
+ });
4064
+ case 49:
4065
+ executorResult = _context2.sent;
4066
+ console.log('executed successfully');
4067
+ _context2.next = 57;
4068
+ break;
4069
+ case 53:
4070
+ _context2.prev = 53;
4071
+ _context2.t2 = _context2["catch"](46);
4072
+ console.log('===Error executing action===', {
4073
+ e: _context2.t2
4074
+ });
4075
+ // TODO: Update workflows runs for failed actions
4076
+ return _context2.abrupt("return", {
4077
+ v: false
4078
+ });
4079
+ case 57:
4080
+ dataContext[action.id] = executorResult;
4081
+ if (!(action.type === "CONDITIONS" || (_action$subActions = action.subActions) != null && _action$subActions.length)) {
4082
+ _context2.next = 65;
4083
+ break;
4084
+ }
4085
+ subActions = action.subActions;
4086
+ if (!(subActions != null && subActions.length)) {
4087
+ _context2.next = 65;
4088
+ break;
4089
+ }
4090
+ _context2.next = 63;
4091
+ return runActionsRecursively({
4092
+ blueprintActions: subActions,
4093
+ frameworkApis: frameworkApis,
4094
+ frameworkEvents: frameworkEvents,
4095
+ dataContext: dataContext,
4096
+ runId: runId,
4097
+ ctx: ctx,
4098
+ blueprintId: blueprintId,
4099
+ blueprintActionKVMap: blueprintActionKVMap
4100
+ });
4101
+ case 63:
4102
+ _context2.t3 = _context2.sent;
4103
+ return _context2.abrupt("return", {
4104
+ v: _context2.t3
4105
+ });
4106
+ case 65:
4107
+ case "end":
4108
+ return _context2.stop();
4109
+ }
4110
+ }, _loop, null, [[46, 53]]);
4111
+ });
4112
+ _iterator2 = _createForOfIteratorHelperLoose(blueprintActions);
4113
+ case 3:
4114
+ if ((_step2 = _iterator2()).done) {
4115
+ _context3.next = 12;
4116
+ break;
4117
+ }
4118
+ return _context3.delegateYield(_loop(), "t0", 5);
4119
+ case 5:
4120
+ _ret = _context3.t0;
4121
+ if (!(_ret === 0)) {
4122
+ _context3.next = 8;
4123
+ break;
4124
+ }
4125
+ return _context3.abrupt("continue", 10);
4126
+ case 8:
4127
+ if (!_ret) {
4128
+ _context3.next = 10;
4129
+ break;
4130
+ }
4131
+ return _context3.abrupt("return", _ret.v);
4132
+ case 10:
4133
+ _context3.next = 3;
4134
+ break;
4135
+ case 12:
4136
+ return _context3.abrupt("return", true);
4137
+ case 13:
4138
+ case "end":
4139
+ return _context3.stop();
4140
+ }
4141
+ }, _callee);
4142
+ }));
4143
+ return _runActionsRecursively.apply(this, arguments);
4144
+ }
4145
+ function blueprintRunner(_x2) {
4146
+ return _blueprintRunner.apply(this, arguments);
4147
+ }
4148
+ function _blueprintRunner() {
4149
+ _blueprintRunner = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref8) {
4150
+ var _fullCtx, _blueprint$trigger;
4151
+ var ctx, dataCtx, blueprint, frameworkEvents, frameworkApis, fullCtx, triggerCondition, concreteTrigger, resolvedSchema, shouldRunWorkflow, blueprintActionKVMap, ranSuccessfully;
4152
+ return _regeneratorRuntime().wrap(function _callee2$(_context4) {
4153
+ while (1) switch (_context4.prev = _context4.next) {
4154
+ case 0:
4155
+ ctx = _ref8.ctx, dataCtx = _ref8.dataCtx, blueprint = _ref8.blueprint, frameworkEvents = _ref8.frameworkEvents, frameworkApis = _ref8.frameworkApis;
4156
+ console.log("Running blueprint " + blueprint.id);
4157
+ fullCtx = (_fullCtx = {}, _fullCtx[blueprint.trigger.id] = dataCtx, _fullCtx);
4158
+ triggerCondition = blueprint.trigger.condition;
4159
+ concreteTrigger = frameworkEvents[blueprint.trigger.type || ''];
4160
+ _context4.next = 8;
4161
+ return getOutputSchemaServer({
4162
+ block: concreteTrigger,
4163
+ payload: ((_blueprint$trigger = blueprint.trigger) == null ? void 0 : _blueprint$trigger.payload) || {},
4164
+ blockType: 'trigger',
4165
+ ctx: ctx
4166
+ });
4167
+ case 8:
4168
+ resolvedSchema = _context4.sent;
4169
+ if (isEmpty(triggerCondition)) {
4170
+ _context4.next = 16;
4171
+ break;
4172
+ }
4173
+ console.log("Found trigger condition", {
4174
+ triggerCondition: triggerCondition
4175
+ });
4176
+ shouldRunWorkflow = evaluateCondition({
4177
+ c: triggerCondition,
4178
+ dataCtx: fullCtx,
4179
+ triggerId: blueprint.trigger.id,
4180
+ schema: resolvedSchema
4181
+ });
4182
+ console.log("Should run workflow", {
4183
+ shouldRunWorkflow: shouldRunWorkflow
4184
+ });
4185
+ if (shouldRunWorkflow) {
4186
+ _context4.next = 16;
4187
+ break;
4188
+ }
4189
+ return _context4.abrupt("return");
4190
+ case 16:
4191
+ blueprintActionKVMap = constructWorkflowContextBluePrint(blueprint);
4192
+ _context4.next = 20;
4193
+ return runActionsRecursively({
4194
+ blueprintActions: blueprint.actions,
4195
+ frameworkApis: frameworkApis,
4196
+ ctx: ctx,
4197
+ frameworkEvents: frameworkEvents,
4198
+ dataContext: fullCtx,
4199
+ blueprintActionKVMap: blueprintActionKVMap,
4200
+ blueprintId: blueprint.id,
4201
+ runId: ''
4202
+ });
4203
+ case 20:
4204
+ ranSuccessfully = _context4.sent;
4205
+ try {
4206
+ if (ranSuccessfully) {
4207
+ // await automationRunService.updateAutomationRun({
4208
+ // runId: blueprintRun?.id || '',
4209
+ // blueprintId: blueprint.id,
4210
+ // completedAt: new Date(),
4211
+ // status: AutomationRunStatus.COMPLETED,
4212
+ // });
4213
+ }
4214
+ } catch (e) {}
4215
+ case 22:
4216
+ case "end":
4217
+ return _context4.stop();
4218
+ }
4219
+ }, _callee2);
4220
+ }));
4221
+ return _blueprintRunner.apply(this, arguments);
4222
+ }
4223
+
4224
+ var Framework = /*#__PURE__*/function () {
4225
+ function Framework(_ref) {
4226
+ var _this = this;
4227
+ var dataLayer = _ref.dataLayer,
4228
+ config = _ref.config;
4229
+ //global events grouped by Integration
4230
+ this.globalEvents = new Map();
4231
+ // global event handlers
4232
+ this.globalEventHandlers = [];
4233
+ // global apis grouped by Integration
4234
+ this.globalApis = new Map();
4235
+ this.integrations = new Map();
4236
+ this.dataLayer = void 0;
4237
+ this.config = void 0;
4238
+ this.runBlueprint = /*#__PURE__*/function () {
4239
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
4240
+ var _this$availableIntegr;
4241
+ var blueprint, _ref2$dataCtx, dataCtx, ctx, systemApis, systemEvents, availableIntegrations, availableIntegrationApis, availableIntegrationEvents, frameworkApis, frameworkEvents;
4242
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4243
+ while (1) switch (_context.prev = _context.next) {
4244
+ case 0:
4245
+ blueprint = _ref2.blueprint, _ref2$dataCtx = _ref2.dataCtx, dataCtx = _ref2$dataCtx === void 0 ? {} : _ref2$dataCtx, ctx = _ref2.ctx;
4246
+ systemApis = _this.getSystemApis();
4247
+ systemEvents = _this.getSystemEvents();
4248
+ availableIntegrations = (_this$availableIntegr = _this.availableIntegrations()) == null ? void 0 : _this$availableIntegr.map(function (_ref4) {
4249
+ var integration = _ref4.integration;
4250
+ return integration;
4251
+ });
4252
+ availableIntegrationApis = availableIntegrations.reduce(function (acc, _ref5) {
4253
+ var name = _ref5.name;
4254
+ var apis = _this.getApisByIntegration(name);
4255
+ return _extends({}, acc, apis);
4256
+ }, {});
4257
+ availableIntegrationEvents = availableIntegrations.reduce(function (acc, _ref6) {
4258
+ var name = _ref6.name;
4259
+ var events = _this.getEventsByIntegration(name);
4260
+ return _extends({}, acc, events);
4261
+ }, {});
4262
+ frameworkApis = _extends({}, systemApis, availableIntegrationApis);
4263
+ frameworkEvents = _extends({}, systemEvents, availableIntegrationEvents);
4264
+ _context.next = 10;
4265
+ return blueprintRunner({
4266
+ dataCtx: dataCtx,
4267
+ blueprint: blueprint,
4268
+ frameworkApis: frameworkApis,
4269
+ frameworkEvents: frameworkEvents,
4270
+ ctx: ctx
4271
+ });
4272
+ case 10:
4273
+ case "end":
4274
+ return _context.stop();
4275
+ }
4276
+ }, _callee);
4277
+ }));
4278
+ return function (_x) {
4279
+ return _ref3.apply(this, arguments);
4280
+ };
4281
+ }();
4282
+ this.dataLayer = dataLayer;
4283
+ this.config = config;
4284
+ }
4285
+ Framework.init = function init(config) {
4286
+ var _config$workflows$sys;
4287
+ if (!config.db.uri) {
4288
+ throw new Error('No database config/provider found');
4289
+ }
4290
+ var dataLayer = new DataLayer({
4291
+ url: config.db.uri,
4292
+ provider: config.db.provider
4293
+ });
4294
+ var framework = new Framework({
4295
+ config: config,
4296
+ dataLayer: dataLayer
4297
+ });
4298
+ // Register integrations
4299
+ config.integrations.forEach(function (integration) {
4300
+ framework.__registerIntgeration(integration);
4301
+ });
4302
+ // Register System apis
4303
+ framework.__registerApis({
4304
+ apis: (_config$workflows$sys = config.workflows.systemApis) == null ? void 0 : _config$workflows$sys.map(function (api) {
4305
+ return _extends({}, api, {
4306
+ integrationName: config.name
4307
+ });
4308
+ })
4309
+ });
4310
+ // Register System events
4311
+ framework.__registerEvents({
4312
+ events: config.workflows.systemEvents
4313
+ });
4314
+ return framework;
4315
+ };
4316
+ var _proto = Framework.prototype;
4317
+ _proto.connectedIntegrations = /*#__PURE__*/function () {
4318
+ var _connectedIntegrations = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref7) {
4319
+ var _this2 = this;
4320
+ var context, ints, connectionChecks;
4321
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
4322
+ while (1) switch (_context3.prev = _context3.next) {
4323
+ case 0:
4324
+ context = _ref7.context;
4325
+ ints = this.availableIntegrations();
4326
+ _context3.next = 4;
4327
+ return Promise.all(ints.map(/*#__PURE__*/function () {
4328
+ var _ref9 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref8) {
4329
+ var integration, connection;
4330
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
4331
+ while (1) switch (_context2.prev = _context2.next) {
4332
+ case 0:
4333
+ integration = _ref8.integration;
4334
+ _context2.next = 3;
4335
+ return _this2.dataLayer.getConnection({
4336
+ connectionId: context.connectionId,
4337
+ name: integration.name
4338
+ });
4339
+ case 3:
4340
+ connection = _context2.sent;
4341
+ return _context2.abrupt("return", {
4342
+ integration: integration,
4343
+ connected: !!connection
4344
+ });
4345
+ case 5:
4346
+ case "end":
4347
+ return _context2.stop();
4348
+ }
4349
+ }, _callee2);
4350
+ }));
4351
+ return function (_x3) {
4352
+ return _ref9.apply(this, arguments);
4353
+ };
4354
+ }()));
4355
+ case 4:
4356
+ connectionChecks = _context3.sent;
4357
+ return _context3.abrupt("return", connectionChecks.filter(function (_ref10) {
4358
+ var connected = _ref10.connected;
4359
+ return connected;
4360
+ }).map(function (_ref11) {
4361
+ var integration = _ref11.integration;
4362
+ return integration;
4363
+ }));
4364
+ case 6:
4365
+ case "end":
4366
+ return _context3.stop();
4367
+ }
4368
+ }, _callee3, this);
4369
+ }));
4370
+ function connectedIntegrations(_x2) {
4371
+ return _connectedIntegrations.apply(this, arguments);
4372
+ }
4373
+ return connectedIntegrations;
4374
+ }();
4375
+ _proto.__registerIntgeration = function __registerIntgeration(definition) {
4376
+ var _this$globalEventHand;
4377
+ var name = definition.name;
4378
+ definition.attachDataLayer({
4379
+ dataLayer: this.dataLayer
4380
+ });
4381
+ var router = this.createRouter();
4382
+ definition.corePresets = {
4383
+ redirectURI: router.makeRedirectURI()
4384
+ };
4385
+ this.integrations.set(name, definition);
4386
+ definition.registerEvents();
4387
+ this.__registerEvents({
4388
+ events: definition.getEvents(),
4389
+ integrationName: name
4390
+ });
4391
+ definition.registerApis();
4392
+ definition._convertApiClientToSystemApis();
4393
+ this.__registerApis({
4394
+ apis: Object.values(definition.getApis()),
4395
+ integrationName: name
4396
+ });
4397
+ (_this$globalEventHand = this.globalEventHandlers).push.apply(_this$globalEventHand, definition.getEventHandlers({
4398
+ makeWebhookUrl: router.makeWebhookUrl
4399
+ }));
4400
+ };
4401
+ _proto.__registerEvents = function __registerEvents(_ref12) {
4402
+ var events = _ref12.events,
4403
+ _ref12$integrationNam = _ref12.integrationName,
4404
+ integrationName = _ref12$integrationNam === void 0 ? this.config.name : _ref12$integrationNam;
4405
+ var integrationEvents = this.globalEvents.get(integrationName) || {};
4406
+ this.globalEvents.set(integrationName, _extends({}, integrationEvents, events));
4407
+ };
4408
+ _proto.__registerApis = function __registerApis(_ref13) {
4409
+ var apis = _ref13.apis,
4410
+ _ref13$integrationNam = _ref13.integrationName,
4411
+ integrationName = _ref13$integrationNam === void 0 ? this.config.name : _ref13$integrationNam;
4412
+ var integrationApis = this.globalApis.get(integrationName) || {};
4413
+ this.globalApis.set(integrationName, _extends({}, integrationApis, apis.reduce(function (acc, api) {
4414
+ var _extends2;
4415
+ return _extends({}, acc, (_extends2 = {}, _extends2[api.type] = api, _extends2));
4416
+ }, {})));
4417
+ };
4418
+ _proto.availableIntegrations = function availableIntegrations() {
4419
+ return Array.from(this.integrations.entries()).map(function (_ref14) {
4420
+ var name = _ref14[0],
4421
+ integration = _ref14[1];
4422
+ return {
4423
+ name: name,
4424
+ integration: integration
4425
+ };
4426
+ });
4427
+ };
4428
+ _proto.getIntegration = function getIntegration(name) {
4429
+ return this.integrations.get(name);
4430
+ };
4431
+ _proto.getGlobalEvents = function getGlobalEvents() {
4432
+ return this.globalEvents;
4433
+ };
4434
+ _proto.getSystemEvents = function getSystemEvents() {
4435
+ var events = this.globalEvents.get(this.config.name);
4436
+ return events || {};
4437
+ };
4438
+ _proto.getEventsByIntegration = function getEventsByIntegration(name) {
4439
+ return this.globalEvents.get(name);
4440
+ };
4441
+ _proto.getGlobalEventHandlers = function getGlobalEventHandlers() {
4442
+ return this.globalEventHandlers;
4443
+ };
4444
+ _proto.getApis = function getApis() {
4445
+ return this.globalApis;
4446
+ };
4447
+ _proto.getSystemApis = function getSystemApis() {
4448
+ return this.globalApis.get(this.config.name);
4449
+ };
4450
+ _proto.getApisByIntegration = function getApisByIntegration(name, includeHidden) {
4451
+ var integrationApis = this.globalApis.get(name);
4452
+ if (includeHidden) {
4453
+ return integrationApis;
4454
+ }
4455
+ return omitBy(integrationApis, function (value) {
4456
+ return value.isHidden;
4457
+ });
4458
+ };
4459
+ _proto.authenticatableIntegrations = function authenticatableIntegrations() {
4460
+ return this.availableIntegrations().filter(function (_ref15) {
4461
+ var integration = _ref15.integration;
4462
+ try {
4463
+ integration.getAuthenticator();
4464
+ return true;
4465
+ } catch (e) {
4466
+ return false;
4467
+ }
4468
+ });
4469
+ };
4470
+ _proto.authenticator = function authenticator(name) {
4471
+ var _int = this.getIntegration(name);
4472
+ if (!_int) {
4473
+ throw new Error("No integration exists for " + name);
4474
+ }
4475
+ return _int.getAuthenticator();
4476
+ };
4477
+ _proto.connectIntegrationByCredential = /*#__PURE__*/function () {
4478
+ var _connectIntegrationByCredential = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref16) {
4479
+ var name, connectionId, credential, authenticator, integration;
4480
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
4481
+ while (1) switch (_context4.prev = _context4.next) {
4482
+ case 0:
4483
+ name = _ref16.name, connectionId = _ref16.connectionId, credential = _ref16.credential;
4484
+ authenticator = this.authenticator(name);
4485
+ if (authenticator) {
4486
+ _context4.next = 4;
4487
+ break;
4488
+ }
4489
+ throw new Error("Authenticator for " + name + " not found");
4490
+ case 4:
4491
+ _context4.next = 6;
4492
+ return authenticator.dataAccess.createConnection({
4493
+ connection: {
4494
+ name: name,
4495
+ connectionId: connectionId
4496
+ },
4497
+ credential: credential
4498
+ });
4499
+ case 6:
4500
+ integration = _context4.sent;
4501
+ if (!authenticator.onConnectionCreated) {
4502
+ _context4.next = 10;
4503
+ break;
4504
+ }
4505
+ _context4.next = 10;
4506
+ return authenticator.onConnectionCreated(integration, credential);
4507
+ case 10:
4508
+ case "end":
4509
+ return _context4.stop();
4510
+ }
4511
+ }, _callee4, this);
4512
+ }));
4513
+ function connectIntegrationByCredential(_x4) {
4514
+ return _connectIntegrationByCredential.apply(this, arguments);
4515
+ }
4516
+ return connectIntegrationByCredential;
4517
+ }();
4518
+ _proto.disconnectIntegration = /*#__PURE__*/function () {
4519
+ var _disconnectIntegration = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref17) {
4520
+ var _yield$this$dataLayer;
4521
+ var name, connectionId, integration, k_id, authenticator;
4522
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
4523
+ while (1) switch (_context5.prev = _context5.next) {
4524
+ case 0:
4525
+ name = _ref17.name, connectionId = _ref17.connectionId;
4526
+ integration = this.getIntegration(name);
4527
+ _context5.next = 4;
4528
+ return this.dataLayer.getConnection({
4529
+ name: name,
4530
+ connectionId: connectionId
4531
+ });
4532
+ case 4:
4533
+ _context5.t0 = _yield$this$dataLayer = _context5.sent;
4534
+ if (!(_context5.t0 == null)) {
4535
+ _context5.next = 9;
4536
+ break;
4537
+ }
4538
+ _context5.t1 = void 0;
4539
+ _context5.next = 10;
4540
+ break;
4541
+ case 9:
4542
+ _context5.t1 = _yield$this$dataLayer.id;
4543
+ case 10:
4544
+ k_id = _context5.t1;
4545
+ if (k_id) {
4546
+ _context5.next = 13;
4547
+ break;
4548
+ }
4549
+ throw new Error("No connection found for " + name);
4550
+ case 13:
4551
+ if (!(integration != null && integration.dataLayer)) {
4552
+ _context5.next = 16;
4553
+ break;
4554
+ }
4555
+ _context5.next = 16;
4556
+ return integration.onDisconnect({
4557
+ connectionId: connectionId
4558
+ });
4559
+ case 16:
4560
+ if (!((integration == null ? void 0 : integration.config.authType) === IntegrationCredentialType.OAUTH)) {
4561
+ _context5.next = 20;
4562
+ break;
4563
+ }
4564
+ authenticator = this.authenticator(name);
4565
+ _context5.next = 20;
4566
+ return authenticator.revokeAuth({
4567
+ k_id: k_id
4568
+ });
4569
+ case 20:
4570
+ _context5.next = 22;
4571
+ return this.dataLayer.deleteConnection({
4572
+ connectionId: connectionId
4573
+ });
4574
+ case 22:
4575
+ case "end":
4576
+ return _context5.stop();
4577
+ }
4578
+ }, _callee5, this);
4579
+ }));
4580
+ function disconnectIntegration(_x5) {
4581
+ return _disconnectIntegration.apply(this, arguments);
4582
+ }
4583
+ return disconnectIntegration;
4584
+ }();
4585
+ _proto.callApi = /*#__PURE__*/function () {
4586
+ var _callApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref18) {
4587
+ var _int2$getApis;
4588
+ var _ref18$integrationNam, integrationName, api, payload, _this$globalApis$get, _apiExecutor, _int2, apiExecutor;
4589
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
4590
+ while (1) switch (_context6.prev = _context6.next) {
4591
+ case 0:
4592
+ _ref18$integrationNam = _ref18.integrationName, integrationName = _ref18$integrationNam === void 0 ? this.config.name : _ref18$integrationNam, api = _ref18.api, payload = _ref18.payload;
4593
+ if (!(integrationName === this.config.name)) {
4594
+ _context6.next = 6;
4595
+ break;
4596
+ }
4597
+ _apiExecutor = (_this$globalApis$get = this.globalApis.get(this.config.name)) == null ? void 0 : _this$globalApis$get[api];
4598
+ if (_apiExecutor) {
4599
+ _context6.next = 5;
4600
+ break;
4601
+ }
4602
+ throw new Error("No global api exists for " + api);
4603
+ case 5:
4604
+ return _context6.abrupt("return", _apiExecutor.executor(payload));
4605
+ case 6:
4606
+ _int2 = this.getIntegration(integrationName);
4607
+ if (_int2) {
4608
+ _context6.next = 9;
4609
+ break;
4610
+ }
4611
+ throw new Error("No Integration exists for " + integrationName);
4612
+ case 9:
4613
+ apiExecutor = (_int2$getApis = _int2.getApis()) == null ? void 0 : _int2$getApis[api];
4614
+ if (apiExecutor) {
4615
+ _context6.next = 12;
4616
+ break;
4617
+ }
4618
+ throw new Error("No api exists for " + api + " in " + integrationName);
4619
+ case 12:
4620
+ return _context6.abrupt("return", apiExecutor.executor(payload));
4621
+ case 13:
4622
+ case "end":
4623
+ return _context6.stop();
4624
+ }
4625
+ }, _callee6, this);
4626
+ }));
4627
+ function callApi(_x6) {
4628
+ return _callApi.apply(this, arguments);
4629
+ }
4630
+ return callApi;
4631
+ }();
4632
+ _proto.subscribeEvent = /*#__PURE__*/function () {
4633
+ var _subscribeEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref19) {
4634
+ var _process$env$INNGEST_;
4635
+ var id, _ref19$interval, interval, _ref19$timeout, timeout, inngestApiUrl, inngestApiToken, startTime, _poll;
4636
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
4637
+ while (1) switch (_context8.prev = _context8.next) {
4638
+ case 0:
4639
+ id = _ref19.id, _ref19$interval = _ref19.interval, interval = _ref19$interval === void 0 ? 5000 : _ref19$interval, _ref19$timeout = _ref19.timeout, timeout = _ref19$timeout === void 0 ? 60000 : _ref19$timeout;
4640
+ inngestApiUrl = process.env.INNGEST_URL;
4641
+ inngestApiToken = (_process$env$INNGEST_ = process.env.INNGEST_SIGNING_KEY) != null ? _process$env$INNGEST_ : '123';
4642
+ startTime = Date.now();
4643
+ _poll = /*#__PURE__*/function () {
4644
+ var _ref20 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
4645
+ var response, _yield$response$json, data, error, lastRun, elapsedTime;
4646
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
4647
+ while (1) switch (_context7.prev = _context7.next) {
4648
+ case 0:
4649
+ _context7.prev = 0;
4650
+ _context7.next = 3;
4651
+ return fetch(inngestApiUrl + "/v1/events/" + id + "/runs", {
4652
+ method: 'GET',
4653
+ headers: {
4654
+ Accept: 'application/json',
4655
+ Authorization: "Bearer " + inngestApiToken
4656
+ }
4657
+ });
4658
+ case 3:
4659
+ response = _context7.sent;
4660
+ if (!response.ok) {
4661
+ _context7.next = 16;
4662
+ break;
4663
+ }
4664
+ _context7.next = 7;
4665
+ return response.json();
4666
+ case 7:
4667
+ _yield$response$json = _context7.sent;
4668
+ data = _yield$response$json.data;
4669
+ error = _yield$response$json.error;
4670
+ if (!error) {
4671
+ _context7.next = 12;
4672
+ break;
4673
+ }
4674
+ return _context7.abrupt("return", null);
4675
+ case 12:
4676
+ lastRun = data == null ? void 0 : data[0];
4677
+ if (lastRun) {
4678
+ _context7.next = 15;
4679
+ break;
4680
+ }
4681
+ return _context7.abrupt("return", null);
4682
+ case 15:
4683
+ return _context7.abrupt("return", {
4684
+ status: lastRun.status,
4685
+ startedAt: lastRun.run_started_at,
4686
+ endedAt: lastRun.ended_at
4687
+ });
4688
+ case 16:
4689
+ _context7.next = 21;
4690
+ break;
4691
+ case 18:
4692
+ _context7.prev = 18;
4693
+ _context7.t0 = _context7["catch"](0);
4694
+ console.error("Request failed: " + _context7.t0);
4695
+ case 21:
4696
+ // Check if timeout has been reached
4697
+ elapsedTime = Date.now() - startTime;
4698
+ if (!(elapsedTime >= timeout)) {
4699
+ _context7.next = 25;
4700
+ break;
4701
+ }
4702
+ console.log('Polling timeout reached.');
4703
+ return _context7.abrupt("return", null);
4704
+ case 25:
4705
+ _context7.next = 27;
4706
+ return new Promise(function (resolve) {
4707
+ return setTimeout(resolve, interval);
4708
+ });
4709
+ case 27:
4710
+ return _context7.abrupt("return", _poll());
4711
+ case 28:
4712
+ case "end":
4713
+ return _context7.stop();
4714
+ }
4715
+ }, _callee7, null, [[0, 18]]);
4716
+ }));
4717
+ return function poll() {
4718
+ return _ref20.apply(this, arguments);
4719
+ };
4720
+ }();
4721
+ return _context8.abrupt("return", _poll());
4722
+ case 6:
4723
+ case "end":
4724
+ return _context8.stop();
4725
+ }
4726
+ }, _callee8);
4727
+ }));
4728
+ function subscribeEvent(_x7) {
4729
+ return _subscribeEvent.apply(this, arguments);
4730
+ }
4731
+ return subscribeEvent;
4732
+ }();
4733
+ _proto.triggerEvent = /*#__PURE__*/function () {
4734
+ var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref21) {
4735
+ var _this3 = this;
4736
+ var key, data, user, _ref21$integrationNam, integrationName, returnObj, integrationEvents, integrationEvent, event, workflowEvent;
4737
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
4738
+ while (1) switch (_context11.prev = _context11.next) {
4739
+ case 0:
4740
+ key = _ref21.key, data = _ref21.data, user = _ref21.user, _ref21$integrationNam = _ref21.integrationName, integrationName = _ref21$integrationNam === void 0 ? this.config.name : _ref21$integrationNam;
4741
+ _context11.prev = 1;
4742
+ returnObj = {
4743
+ event: {}
4744
+ };
4745
+ integrationEvents = this.globalEvents.get(integrationName);
4746
+ if (integrationEvents) {
4747
+ _context11.next = 6;
4748
+ break;
4749
+ }
4750
+ throw new Error("No events exists for " + integrationName);
4751
+ case 6:
4752
+ integrationEvent = integrationEvents[key];
4753
+ if (integrationEvent) {
4754
+ _context11.next = 9;
4755
+ break;
4756
+ }
4757
+ throw new Error("No event exists for " + key + " in " + integrationName);
4758
+ case 9:
4759
+ _context11.next = 11;
4760
+ return client.send({
4761
+ name: key,
4762
+ data: data,
4763
+ user: user
4764
+ });
4765
+ case 11:
4766
+ event = _context11.sent;
4767
+ returnObj['event'] = _extends({}, event, {
4768
+ subscribe: function () {
4769
+ var _subscribe = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_temp) {
4770
+ var _event$ids;
4771
+ var _ref22, interval, timeout;
4772
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
4773
+ while (1) switch (_context9.prev = _context9.next) {
4774
+ case 0:
4775
+ _ref22 = _temp === void 0 ? {} : _temp, interval = _ref22.interval, timeout = _ref22.timeout;
4776
+ return _context9.abrupt("return", _this3.subscribeEvent({
4777
+ id: (_event$ids = event.ids) == null ? void 0 : _event$ids[0],
4778
+ interval: interval,
4779
+ timeout: timeout
4780
+ }));
4781
+ case 2:
4782
+ case "end":
4783
+ return _context9.stop();
4784
+ }
4785
+ }, _callee9);
4786
+ }));
4787
+ function subscribe(_x9) {
4788
+ return _subscribe.apply(this, arguments);
4789
+ }
4790
+ return subscribe;
4791
+ }()
4792
+ });
4793
+ _context11.next = 15;
4794
+ return client.send({
4795
+ name: 'workflow/run-automations',
4796
+ data: {
4797
+ trigger: key,
4798
+ payload: data
4799
+ },
4800
+ user: user
4801
+ });
4802
+ case 15:
4803
+ workflowEvent = _context11.sent;
4804
+ returnObj['workflowEvent'] = _extends({}, workflowEvent, {
4805
+ subscribe: function () {
4806
+ var _subscribe2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_temp2) {
4807
+ var _workflowEvent$ids;
4808
+ var _ref23, interval, timeout;
4809
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
4810
+ while (1) switch (_context10.prev = _context10.next) {
4811
+ case 0:
4812
+ _ref23 = _temp2 === void 0 ? {} : _temp2, interval = _ref23.interval, timeout = _ref23.timeout;
4813
+ return _context10.abrupt("return", _this3.subscribeEvent({
4814
+ id: (_workflowEvent$ids = workflowEvent.ids) == null ? void 0 : _workflowEvent$ids[0],
4815
+ interval: interval,
4816
+ timeout: timeout
4817
+ }));
4818
+ case 2:
4819
+ case "end":
4820
+ return _context10.stop();
4821
+ }
4822
+ }, _callee10);
4823
+ }));
4824
+ function subscribe(_x10) {
4825
+ return _subscribe2.apply(this, arguments);
4826
+ }
4827
+ return subscribe;
4828
+ }()
4829
+ });
4830
+ return _context11.abrupt("return", returnObj);
4831
+ case 20:
4832
+ _context11.prev = 20;
4833
+ _context11.t0 = _context11["catch"](1);
4834
+ throw new Error("Error triggering event: " + _context11.t0);
4835
+ case 23:
4836
+ case "end":
4837
+ return _context11.stop();
4838
+ }
4839
+ }, _callee11, this, [[1, 20]]);
4840
+ }));
4841
+ function triggerEvent(_x8) {
4842
+ return _triggerEvent.apply(this, arguments);
4843
+ }
4844
+ return triggerEvent;
4845
+ }() //TODO: Rename to triggerWorkflowEvent maybe ?
4846
+ ;
4847
+ _proto.triggerSystemEvent =
4848
+ /*#__PURE__*/
4849
+ function () {
4850
+ var _triggerSystemEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(_ref24) {
4851
+ var key, data, user, event, systemEvent;
4852
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
4853
+ while (1) switch (_context12.prev = _context12.next) {
4854
+ case 0:
4855
+ key = _ref24.key, data = _ref24.data, user = _ref24.user;
4856
+ _context12.next = 3;
4857
+ return client.send({
4858
+ name: key,
4859
+ data: data,
4860
+ user: user
4861
+ });
4862
+ case 3:
4863
+ event = _context12.sent;
4864
+ systemEvent = this.getSystemEvents()[key];
4865
+ if (!systemEvent) {
4866
+ _context12.next = 8;
4867
+ break;
4868
+ }
4869
+ _context12.next = 8;
4870
+ return client.send({
4871
+ name: 'workflow/run-automations',
4872
+ data: {
4873
+ trigger: key,
4874
+ payload: data
4875
+ },
4876
+ user: user
4877
+ });
4878
+ case 8:
4879
+ return _context12.abrupt("return", event);
4880
+ case 9:
4881
+ case "end":
4882
+ return _context12.stop();
4883
+ }
4884
+ }, _callee12, this);
4885
+ }));
4886
+ function triggerSystemEvent(_x11) {
4887
+ return _triggerSystemEvent.apply(this, arguments);
4888
+ }
4889
+ return triggerSystemEvent;
4890
+ }();
4891
+ _proto.createRouter = function createRouter() {
4892
+ var self = this;
4893
+ var makeWebhookUrl = function makeWebhookUrl(_ref25) {
4894
+ var _self$config;
4895
+ var event = _ref25.event,
4896
+ name = _ref25.name;
4897
+ return encodeURI("" + (self == null || (_self$config = self.config) == null ? void 0 : _self$config.systemHostURL) + self.routes.webhook + "?name=" + name + "&event=" + event);
4898
+ };
4899
+ var makeRedirectURI = function makeRedirectURI() {
4900
+ return new URL(self.routes.callback, self.config.systemHostURL).toString();
4901
+ };
4902
+ var makeConnectURI = function makeConnectURI(props) {
4903
+ var params = new URLSearchParams(props);
4904
+ return new URL(self.routes.connect + "?" + params.toString(), self.config.systemHostURL).toString();
4905
+ };
4906
+ var registerRoutes = function registerRoutes() {
4907
+ var _registry;
4908
+ var registry = (_registry = {}, _registry[self.routes.connect] = makeConnect(self), _registry[self.routes.callback] = makeCallback(self), _registry[self.routes.inngest] = makeInngest(self), _registry[self.routes.webhook] = makeWebhook(self), _registry);
4909
+ return function (req) {
4910
+ var route = req.nextUrl.pathname;
4911
+ if (req.nextUrl.pathname in registry) {
4912
+ return registry[route](req);
4913
+ }
4914
+ return NextResponse.json(null, {
4915
+ status: 404
4916
+ });
4917
+ };
4918
+ };
4919
+ return {
4920
+ makeWebhookUrl: makeWebhookUrl,
4921
+ makeRedirectURI: makeRedirectURI,
4922
+ makeConnectURI: makeConnectURI,
4923
+ registerRoutes: registerRoutes
4924
+ };
4925
+ };
4926
+ return _createClass(Framework, [{
4927
+ key: "routes",
4928
+ get: function get() {
4929
+ var _this4 = this;
4930
+ var registry = {
4931
+ connect: '/connect',
4932
+ callback: '/connect/callback',
4933
+ inngest: '/inngest',
4934
+ webhook: '/webhook'
4935
+ };
4936
+ return Object.entries(registry).reduce(function (acc, _ref26) {
4937
+ var _extends3;
4938
+ var key = _ref26[0],
4939
+ value = _ref26[1];
4940
+ return _extends({}, acc, (_extends3 = {}, _extends3[key] = "" + _this4.config.routeRegistrationPath + value, _extends3));
4941
+ }, {});
4942
+ }
4943
+ }]);
4944
+ }();
4945
+
4946
+ export { DataLayer, FieldTypePrimitiveMap, FilterOperatorToSQL, FilterOperators, Framework, Integration, IntegrationAuth, IntegrationCredentialType, IntegrationError, IntegrationErrors, IntegrationFieldTypeEnum, RunStatus, SORT_MODE_TO_ABBR, WorkflowStatusEnum, allowedKey, apiKeyConnectionOptions, buildQueryString, callbackParams, connectParams, constructObjFromStringPath, extractSchemaOptions, fieldsWithCommaSeparatedValues, filterQuerySchema, flattenObject, generateSyncs, getEntityKey, getJSONField, getPath, getResponseDataKey, isLiteralObject, isObjectEmpty, mergeWithDefinedOnly, nextHeaders, oauthState, parseQueryParams, recordHasData, registerRoutes, sortQuerySchema, splitAndStripQuotes, transformFilterValueArray, transformFilterValueBoolean, webhookQueryParams };
4947
+ //# sourceMappingURL=core.esm.js.map