@drawbridge/drawbridge-utils 0.0.117 → 0.0.121
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/connections/index.cjs +1182 -75
- package/dist/connections/index.d.cts +1832 -95
- package/dist/connections/index.d.ts +1832 -95
- package/dist/connections/index.js +1175 -73
- package/dist/phone.d.cts +1 -1
- package/dist/phone.d.ts +1 -1
- package/dist/providers.cjs +4395 -0
- package/dist/providers.d.cts +326 -0
- package/dist/providers.d.ts +326 -0
- package/dist/providers.js +4350 -0
- package/dist/sendgrid.cjs +4 -6
- package/dist/sendgrid.d.cts +19 -14
- package/dist/sendgrid.d.ts +19 -14
- package/dist/sendgrid.js +4 -6
- package/dist/twilio.cjs +2 -3
- package/dist/twilio.d.cts +11 -3
- package/dist/twilio.d.ts +11 -3
- package/dist/twilio.js +2 -3
- package/package.json +6 -1
|
@@ -176,6 +176,89 @@ var HOOKS = Object.freeze({
|
|
|
176
176
|
"promotions"
|
|
177
177
|
])
|
|
178
178
|
});
|
|
179
|
+
var HOOK_EFFECTS = Object.freeze(["enqueues", "events", "writes"]);
|
|
180
|
+
var WRITE_OPERATIONS = Object.freeze(["create", "update"]);
|
|
181
|
+
var HOOK_PROPS = Object.freeze([
|
|
182
|
+
"channel",
|
|
183
|
+
"clientId",
|
|
184
|
+
"clientSecret",
|
|
185
|
+
"connection",
|
|
186
|
+
"contact",
|
|
187
|
+
"context",
|
|
188
|
+
"cursor",
|
|
189
|
+
"declaration",
|
|
190
|
+
"doc",
|
|
191
|
+
"email",
|
|
192
|
+
"event",
|
|
193
|
+
"headers",
|
|
194
|
+
"id",
|
|
195
|
+
"lead",
|
|
196
|
+
"limit",
|
|
197
|
+
"manifest",
|
|
198
|
+
"payload",
|
|
199
|
+
"scope",
|
|
200
|
+
"search",
|
|
201
|
+
"secret",
|
|
202
|
+
"settings",
|
|
203
|
+
"sort",
|
|
204
|
+
"step",
|
|
205
|
+
"suppressed",
|
|
206
|
+
"token",
|
|
207
|
+
"tokens",
|
|
208
|
+
"workflow"
|
|
209
|
+
]);
|
|
210
|
+
var HOOK_OPTIONS = Object.freeze([
|
|
211
|
+
"adminToken",
|
|
212
|
+
"canSend",
|
|
213
|
+
"chunkSize",
|
|
214
|
+
"dispatch",
|
|
215
|
+
"fetcher",
|
|
216
|
+
"logger",
|
|
217
|
+
"mintId",
|
|
218
|
+
"read",
|
|
219
|
+
"reconcileScopes",
|
|
220
|
+
"request",
|
|
221
|
+
"resolveContact",
|
|
222
|
+
"resolveSettings",
|
|
223
|
+
"rotateToken",
|
|
224
|
+
"shopify"
|
|
225
|
+
]);
|
|
226
|
+
var effectsOf = (answer) => {
|
|
227
|
+
for (const key of HOOK_EFFECTS) {
|
|
228
|
+
if ((answer == null ? void 0 : answer[key]) !== void 0 && !Array.isArray(answer[key])) {
|
|
229
|
+
throw new Error("A hook returned " + key + " that is not an array");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const enqueues = (answer == null ? void 0 : answer.enqueues) || [];
|
|
233
|
+
const events = (answer == null ? void 0 : answer.events) || [];
|
|
234
|
+
const writes = (answer == null ? void 0 : answer.writes) || [];
|
|
235
|
+
for (const write of writes) {
|
|
236
|
+
if (!(write == null ? void 0 : write.collection)) throw new Error("A described write names no collection");
|
|
237
|
+
if (!WRITE_OPERATIONS.includes(write == null ? void 0 : write.operation)) {
|
|
238
|
+
throw new Error("A described write on " + write.collection + " needs an operation \u2014 one of " + WRITE_OPERATIONS.join(", "));
|
|
239
|
+
}
|
|
240
|
+
if (!(write == null ? void 0 : write.data)) throw new Error("A described write on " + write.collection + " carries no data");
|
|
241
|
+
if (write.operation === "update" && !write.query) {
|
|
242
|
+
throw new Error("A described update on " + write.collection + " has no query \u2014 that is every document in it");
|
|
243
|
+
}
|
|
244
|
+
if (write.operation === "create" && write.query) {
|
|
245
|
+
throw new Error("A described create on " + write.collection + " carries a query \u2014 create does not filter");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
for (const enqueue of enqueues) {
|
|
249
|
+
if (!(enqueue == null ? void 0 : enqueue.queue)) throw new Error("A described enqueue names no queue");
|
|
250
|
+
if (!(enqueue == null ? void 0 : enqueue.name)) throw new Error("A described enqueue on the " + enqueue.queue + " queue names no job");
|
|
251
|
+
}
|
|
252
|
+
for (const event of events) {
|
|
253
|
+
if (!(event == null ? void 0 : event.event)) throw new Error("A described event has no name");
|
|
254
|
+
if (!(event == null ? void 0 : event.room)) throw new Error("A described " + event.event + " event has no room");
|
|
255
|
+
}
|
|
256
|
+
const transaction = Boolean(answer == null ? void 0 : answer.transaction);
|
|
257
|
+
if (transaction && !writes.length) {
|
|
258
|
+
throw new Error("A hook asked for a transaction and described no writes");
|
|
259
|
+
}
|
|
260
|
+
return { enqueues, events, transaction, writes };
|
|
261
|
+
};
|
|
179
262
|
var STEPS = Object.freeze({
|
|
180
263
|
"commerce.code.issue": "Issue discount code",
|
|
181
264
|
"commerce.customer.insert": "Create customer",
|
|
@@ -385,13 +468,16 @@ var attentive_default = `<svg width="500" height="500" viewBox="0 0 500 500" fil
|
|
|
385
468
|
<path d="M166.04 261.805C180.228 259.107 195.528 261.893 207.581 269.971C218.512 277.079 226.908 288.136 230.604 300.657C234.835 314.103 233.614 329.124 227.485 341.788C220.097 356.875 205.782 368.543 189.317 372.089C173.957 375.652 157.089 372.386 144.304 363.103C132.971 355.295 124.912 342.989 121.891 329.581C118.943 316.636 120.725 302.656 127.002 290.938C134.699 275.951 149.503 264.933 166.046 261.811" fill="#1E1C1C"/>
|
|
386
469
|
</svg>`;
|
|
387
470
|
|
|
388
|
-
// lib/connections/attentive.js
|
|
471
|
+
// lib/connections/providers/attentive.js
|
|
389
472
|
var attentive_default2 = {
|
|
390
473
|
auth: {
|
|
391
474
|
oauth: {
|
|
392
|
-
// NAMES of the
|
|
393
|
-
//
|
|
394
|
-
//
|
|
475
|
+
// NAMES of the credentials holding OUR app's client — keys into the map
|
|
476
|
+
// the provider collection answers, entered on the admin screen at
|
|
477
|
+
// registration, never before. (The names are the env vars they once
|
|
478
|
+
// were; the vocabulary stayed when the storage moved.) No `headers` on
|
|
479
|
+
// the client: Attentive takes credentials as form fields, which is the
|
|
480
|
+
// runner's default.
|
|
395
481
|
client: {
|
|
396
482
|
id: "ATTENTIVE_OAUTH_CLIENT_ID",
|
|
397
483
|
secret: "ATTENTIVE_OAUTH_CLIENT_SECRET"
|
|
@@ -496,7 +582,7 @@ var attentive_default2 = {
|
|
|
496
582
|
// show a picker quietly missing most of a real account. The response's
|
|
497
583
|
// only identifier is `externalId`, so an entry without one cannot be
|
|
498
584
|
// stored and is dropped.
|
|
499
|
-
audiences: async ({ cursor,
|
|
585
|
+
audiences: async ({ cursor, limit = 100, search, token }, { fetcher = fetch } = {}) => {
|
|
500
586
|
const query = new URLSearchParams({
|
|
501
587
|
limit: String(Math.min(limit, 1e3)),
|
|
502
588
|
...cursor && { cursor },
|
|
@@ -612,10 +698,11 @@ var request = async ({
|
|
|
612
698
|
// lib/hubspot.js
|
|
613
699
|
var HUBSPOT_BASE = "https://api.hubapi.com";
|
|
614
700
|
var hubspotRequest = ({ body, fetcher, method, path, query, token }) => {
|
|
701
|
+
if (!token) throw new Error("HubSpot access token missing \u2014 pass token (the drawbridge provider's hubspotToken)");
|
|
615
702
|
return (fetcher || request)({
|
|
616
703
|
body,
|
|
617
704
|
headers: {
|
|
618
|
-
"Authorization": "Bearer " +
|
|
705
|
+
"Authorization": "Bearer " + token
|
|
619
706
|
},
|
|
620
707
|
method,
|
|
621
708
|
query,
|
|
@@ -717,16 +804,15 @@ var contacts = {
|
|
|
717
804
|
// FORGET A CONTACT, by id or by email. Account deletion — the caller had
|
|
718
805
|
// to search then remove, which is one round trip it should not have to
|
|
719
806
|
// know about.
|
|
720
|
-
remove: async ({ email,
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
const contact = id || await lookup({ email, fetcher, token: key });
|
|
807
|
+
remove: async ({ email, id, token }, { fetcher } = {}) => {
|
|
808
|
+
if (!token) return;
|
|
809
|
+
const contact = id || await lookup({ email, fetcher, token });
|
|
724
810
|
if (!contact) return;
|
|
725
811
|
return hubspotRequest({
|
|
726
812
|
fetcher,
|
|
727
813
|
method: "DELETE",
|
|
728
814
|
path: "/crm/v3/objects/contacts/" + contact,
|
|
729
|
-
token
|
|
815
|
+
token
|
|
730
816
|
});
|
|
731
817
|
},
|
|
732
818
|
// Connect an account to its contact by email, creating it if absent, and
|
|
@@ -735,24 +821,23 @@ var contacts = {
|
|
|
735
821
|
// no delete-old-then-create-new.
|
|
736
822
|
//
|
|
737
823
|
// Prefer the cached hubspotId; fall back to a search; create last.
|
|
738
|
-
sync: async ({ doc,
|
|
824
|
+
sync: async ({ doc, token }, { fetcher } = {}) => {
|
|
739
825
|
var _a, _b;
|
|
740
|
-
|
|
741
|
-
if (!key) return;
|
|
826
|
+
if (!token) return;
|
|
742
827
|
if (doc == null ? void 0 : doc.hubspotId) {
|
|
743
828
|
try {
|
|
744
|
-
return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token
|
|
829
|
+
return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token })) == null ? void 0 : _a.id;
|
|
745
830
|
} catch (error) {
|
|
746
831
|
if ((error == null ? void 0 : error.status) !== 404) throw error;
|
|
747
832
|
}
|
|
748
833
|
}
|
|
749
|
-
const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token
|
|
834
|
+
const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token });
|
|
750
835
|
return (_b = await send({
|
|
751
836
|
doc,
|
|
752
837
|
fetcher,
|
|
753
838
|
method: existing ? "PATCH" : "POST",
|
|
754
839
|
path: existing ? "/crm/v3/objects/contacts/" + existing : "/crm/v3/objects/contacts",
|
|
755
|
-
token
|
|
840
|
+
token
|
|
756
841
|
})) == null ? void 0 : _b.id;
|
|
757
842
|
}
|
|
758
843
|
};
|
|
@@ -1208,6 +1293,36 @@ var plans = {
|
|
|
1208
1293
|
conversion: 0.5
|
|
1209
1294
|
}
|
|
1210
1295
|
};
|
|
1296
|
+
var resolvePlan = (subscription) => {
|
|
1297
|
+
var _a, _b;
|
|
1298
|
+
const custom = subscription == null ? void 0 : subscription.custom;
|
|
1299
|
+
if (!custom) return plans[subscription == null ? void 0 : subscription.plan] ?? free;
|
|
1300
|
+
return {
|
|
1301
|
+
// Reusing all.features / all.limits is what keeps a custom plan the same
|
|
1302
|
+
// SHAPE as a catalog one: the base feature grants every plan carries, the
|
|
1303
|
+
// campaign limits that are always infinite, and members defaulting to
|
|
1304
|
+
// infinite when a deal does not name it.
|
|
1305
|
+
conversion: custom.conversion ?? free.conversion,
|
|
1306
|
+
custom: true,
|
|
1307
|
+
// A custom plan is a negotiated PAID deal, so it carries the paid-tier
|
|
1308
|
+
// baseline whether or not the deal thought to name it. Today that is the
|
|
1309
|
+
// sending domain: every catalog paid tier grants it, and a custom plan
|
|
1310
|
+
// silently lacking it would be a support ticket, not a pricing decision.
|
|
1311
|
+
features: all.features([organization.networking.key, ...((_a = custom.features) == null ? void 0 : _a.granted) || []]),
|
|
1312
|
+
limits: all.limits(((_b = custom.limits) == null ? void 0 : _b.organization) || {}),
|
|
1313
|
+
// A custom plan stores its overage BARE on `custom.overages` — a different
|
|
1314
|
+
// shape from the catalog's nested one. Number() so a deal stored as a string
|
|
1315
|
+
// still resolves to cents-per-action; an unnamed overage stays undefined
|
|
1316
|
+
// (it bills nothing) rather than becoming NaN.
|
|
1317
|
+
actionCents: custom.overages == null ? void 0 : Number(custom.overages),
|
|
1318
|
+
overages: { actions: custom.overages },
|
|
1319
|
+
title: custom.title || "Custom"
|
|
1320
|
+
};
|
|
1321
|
+
};
|
|
1322
|
+
var conversionRate = (subscription) => {
|
|
1323
|
+
var _a;
|
|
1324
|
+
return ((_a = resolvePlan(subscription)) == null ? void 0 : _a.conversion) ?? free.conversion;
|
|
1325
|
+
};
|
|
1211
1326
|
|
|
1212
1327
|
// lib/transactions.js
|
|
1213
1328
|
import { currentTraceId } from "@drawbridge/drawbridge-telemetry";
|
|
@@ -1362,7 +1477,36 @@ var channels = {
|
|
|
1362
1477
|
}
|
|
1363
1478
|
};
|
|
1364
1479
|
|
|
1365
|
-
// lib/connections/drawbridge.js
|
|
1480
|
+
// lib/connections/providers/drawbridge.js
|
|
1481
|
+
var interpolate = (template, data2) => {
|
|
1482
|
+
if (!template) return template;
|
|
1483
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => (data2 == null ? void 0 : data2[key]) != null ? String(data2[key]) : "{{" + key + "}}");
|
|
1484
|
+
};
|
|
1485
|
+
var teamRecipients = async ({ memberIds = [], organization: organization2, read }) => {
|
|
1486
|
+
const org = await read.get({ collection: "organization", query: { id: organization2 } });
|
|
1487
|
+
const owner = (org == null ? void 0 : org.owner) ? await read.get({ collection: "user", query: { id: org.owner } }) : null;
|
|
1488
|
+
const members = memberIds.length ? await read.aggregate({
|
|
1489
|
+
collection: "member",
|
|
1490
|
+
pipeline: [
|
|
1491
|
+
{
|
|
1492
|
+
$match: {
|
|
1493
|
+
id: { $in: memberIds },
|
|
1494
|
+
organization: organization2,
|
|
1495
|
+
status: "accepted"
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
]
|
|
1499
|
+
}) : [];
|
|
1500
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1501
|
+
return [owner, ...members].filter((member) => {
|
|
1502
|
+
if (!(member == null ? void 0 : member.id) || !(member == null ? void 0 : member.email)) return false;
|
|
1503
|
+
const address = member.email.toLowerCase();
|
|
1504
|
+
if (seen.has(address)) return false;
|
|
1505
|
+
seen.add(address);
|
|
1506
|
+
return true;
|
|
1507
|
+
});
|
|
1508
|
+
};
|
|
1509
|
+
var queueNotification = (data2) => ({ collection: "notification", data: data2, operation: "create" });
|
|
1366
1510
|
var drawbridge_default2 = {
|
|
1367
1511
|
auth: {
|
|
1368
1512
|
type: "none"
|
|
@@ -1380,10 +1524,15 @@ var drawbridge_default2 = {
|
|
|
1380
1524
|
exclusive: false,
|
|
1381
1525
|
fields: [],
|
|
1382
1526
|
group: "developer",
|
|
1383
|
-
//
|
|
1384
|
-
//
|
|
1385
|
-
//
|
|
1386
|
-
//
|
|
1527
|
+
// THE BODIES LIVE HERE, beside the declarations that name them. They used to
|
|
1528
|
+
// live in drawbridge-sync because they touch the database, the queues and the
|
|
1529
|
+
// sockets — and a published package cannot carry a controller.
|
|
1530
|
+
//
|
|
1531
|
+
// It does not have to. A hook is a function, so everything it needs is PASSED
|
|
1532
|
+
// IN: `read` for the reads, `canSend` for the opt-out floor, `resolveContact`
|
|
1533
|
+
// for the one write whose RESULT the hook has to count. Everything else a hook
|
|
1534
|
+
// wants done it DESCRIBES — `writes`, `enqueues`, `events` — and the shell
|
|
1535
|
+
// performs it. See lib/connections/contract.js for that shape.
|
|
1387
1536
|
hooks: {
|
|
1388
1537
|
auth: {
|
|
1389
1538
|
// Nothing to connect, revoke, probe or re-scope.
|
|
@@ -1404,13 +1553,157 @@ var drawbridge_default2 = {
|
|
|
1404
1553
|
// accounts DRAWBRIDGE holds rather than ones a merchant connects.
|
|
1405
1554
|
contacts,
|
|
1406
1555
|
email: {
|
|
1407
|
-
|
|
1408
|
-
//
|
|
1409
|
-
//
|
|
1410
|
-
//
|
|
1411
|
-
|
|
1412
|
-
//
|
|
1413
|
-
|
|
1556
|
+
// A PERIODIC SUMMARY to the team, on a schedule trigger rather than per
|
|
1557
|
+
// lead.
|
|
1558
|
+
//
|
|
1559
|
+
// The count is the point: `email.notify` tells the owner one lead arrived
|
|
1560
|
+
// and dampens a spike to one message per bucket, which is deliberately not
|
|
1561
|
+
// a count. This is where "you got 43 entries this week" comes from.
|
|
1562
|
+
digest: async ({ context, step, workflow }, { read } = {}) => {
|
|
1563
|
+
var _a, _b, _c, _d;
|
|
1564
|
+
const days = { day: 1, month: 30, week: 7 }[(_a = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _a.event] || 7;
|
|
1565
|
+
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
|
|
1566
|
+
const campaign = ((_c = (_b = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _b.filters) == null ? void 0 : _c.campaign) || null;
|
|
1567
|
+
const [counted] = await read.aggregate({
|
|
1568
|
+
collection: "lead",
|
|
1569
|
+
pipeline: [
|
|
1570
|
+
{
|
|
1571
|
+
$match: {
|
|
1572
|
+
createdAt: { $gte: since },
|
|
1573
|
+
organization: workflow.organization,
|
|
1574
|
+
...campaign && { campaigns: { $in: [campaign] } }
|
|
1575
|
+
}
|
|
1576
|
+
},
|
|
1577
|
+
{ $count: "count" }
|
|
1578
|
+
]
|
|
1579
|
+
});
|
|
1580
|
+
const count = Number((counted == null ? void 0 : counted.count) || 0);
|
|
1581
|
+
const request2 = { campaign, count, days };
|
|
1582
|
+
if (!count) return { message: "No new leads in the period \u2014 digest skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1583
|
+
const recipients = await teamRecipients({
|
|
1584
|
+
memberIds: ((_d = step.settings) == null ? void 0 : _d.members) || [],
|
|
1585
|
+
organization: workflow.organization,
|
|
1586
|
+
read
|
|
1587
|
+
});
|
|
1588
|
+
const values = { ...context, count };
|
|
1589
|
+
return {
|
|
1590
|
+
message: "Digest of " + count + " new lead(s) queued for " + recipients.length + " recipient(s).",
|
|
1591
|
+
request: request2,
|
|
1592
|
+
response: { count, notified: recipients.length },
|
|
1593
|
+
writes: recipients.map((member) => {
|
|
1594
|
+
var _a2, _b2;
|
|
1595
|
+
return queueNotification({
|
|
1596
|
+
audience: "member",
|
|
1597
|
+
message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, values),
|
|
1598
|
+
organization: workflow.organization,
|
|
1599
|
+
send: { type: "email", email: member.email },
|
|
1600
|
+
title: interpolate((_b2 = step.settings) == null ? void 0 : _b2.subject, values),
|
|
1601
|
+
workflow: workflow.id
|
|
1602
|
+
});
|
|
1603
|
+
})
|
|
1604
|
+
};
|
|
1605
|
+
},
|
|
1606
|
+
// To the organization's OWN PEOPLE. Never suppressed, never
|
|
1607
|
+
// subscription-gated, no unsubscribe footer — telling an org's staff about
|
|
1608
|
+
// their own leads is not commercial mail to a stranger.
|
|
1609
|
+
//
|
|
1610
|
+
// FREE, permanently. The lead that triggered this run already consumed the
|
|
1611
|
+
// billable action, and `members` is a list — billing here would turn one
|
|
1612
|
+
// lead into five more charges and the org would be paying to read its own
|
|
1613
|
+
// mail. The declaration prices it at zero; the shell bills nothing for
|
|
1614
|
+
// zero.
|
|
1615
|
+
notify: async ({ context, step, workflow }, { read } = {}) => {
|
|
1616
|
+
var _a;
|
|
1617
|
+
const memberIds = ((_a = step.settings) == null ? void 0 : _a.members) || [];
|
|
1618
|
+
const request2 = { members: memberIds.length };
|
|
1619
|
+
const recipients = await teamRecipients({ memberIds, organization: workflow.organization, read });
|
|
1620
|
+
if (!recipients.length) {
|
|
1621
|
+
return {
|
|
1622
|
+
message: "No owner or accepted member with an email address \u2014 team notification skipped.",
|
|
1623
|
+
request: request2,
|
|
1624
|
+
response: { skipped: true },
|
|
1625
|
+
skipped: true
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
const bucket = Math.floor(Date.now() / (15 * 60 * 1e3));
|
|
1629
|
+
return {
|
|
1630
|
+
message: "Team notification queued for " + recipients.length + " recipient(s).",
|
|
1631
|
+
request: request2,
|
|
1632
|
+
response: { notified: recipients.length },
|
|
1633
|
+
writes: recipients.map((member) => {
|
|
1634
|
+
var _a2, _b;
|
|
1635
|
+
return {
|
|
1636
|
+
...queueNotification({
|
|
1637
|
+
audience: "member",
|
|
1638
|
+
// Per workflow, recipient AND bucket, so one recipient's damper
|
|
1639
|
+
// can never swallow another's mail and a later bucket is never
|
|
1640
|
+
// mistaken for a duplicate of an earlier one.
|
|
1641
|
+
key: "team.notify." + workflow.id + "." + member.id + "." + bucket,
|
|
1642
|
+
message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, context),
|
|
1643
|
+
organization: workflow.organization,
|
|
1644
|
+
send: { type: "email", email: member.email },
|
|
1645
|
+
title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
|
|
1646
|
+
workflow: workflow.id
|
|
1647
|
+
}),
|
|
1648
|
+
// E11000 IS THE DAMPER WORKING: this recipient has already been
|
|
1649
|
+
// told within the bucket. Declared per write rather than assumed by
|
|
1650
|
+
// the shell, because on every other write here a duplicate key is a
|
|
1651
|
+
// real failure.
|
|
1652
|
+
ignoreDuplicate: true
|
|
1653
|
+
};
|
|
1654
|
+
})
|
|
1655
|
+
};
|
|
1656
|
+
},
|
|
1657
|
+
// Drawbridge sends lead-facing email itself — no merchant provider gates
|
|
1658
|
+
// it.
|
|
1659
|
+
//
|
|
1660
|
+
// This QUEUES rather than sends: queue/notification.js owns delivery, the
|
|
1661
|
+
// unsubscribe token and the CAN-SPAM footer. The step's job is to say who
|
|
1662
|
+
// and what, correctly, and to refuse early when it must not send at all.
|
|
1663
|
+
send: async ({ context, step, workflow }, { canSend, read } = {}) => {
|
|
1664
|
+
var _a, _b;
|
|
1665
|
+
const to = context == null ? void 0 : context.email;
|
|
1666
|
+
if (!to) throw new Error("No email address on context (context.email is required)");
|
|
1667
|
+
const request2 = { to };
|
|
1668
|
+
const { ok: sendable } = await canSend({ channel: "email", to });
|
|
1669
|
+
if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1670
|
+
const organization2 = await read.get({ collection: "organization", query: { id: workflow.organization } });
|
|
1671
|
+
const subscription = (organization2 == null ? void 0 : organization2.subscription) ? await read.get({ collection: "subscription", query: { id: organization2.subscription } }) : null;
|
|
1672
|
+
if ((subscription == null ? void 0 : subscription.status) !== "active") {
|
|
1673
|
+
return {
|
|
1674
|
+
message: "Organization has no active subscription \u2014 workflow-step email skipped.",
|
|
1675
|
+
request: request2,
|
|
1676
|
+
response: { skipped: true },
|
|
1677
|
+
skipped: true
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
return {
|
|
1681
|
+
message: "Email queued for delivery to " + to + ".",
|
|
1682
|
+
request: request2,
|
|
1683
|
+
response: { queued: true },
|
|
1684
|
+
// NO `connection` FIELD, deliberately: the platform sends this.
|
|
1685
|
+
// `audience : 'lead'` states what the queue would otherwise infer from
|
|
1686
|
+
// shape.
|
|
1687
|
+
//
|
|
1688
|
+
// `campaign` is not decoration. queue/notification.js mints the
|
|
1689
|
+
// unsubscribe token with it, so it decides whether opting out is
|
|
1690
|
+
// scoped to this campaign or the whole organization, and it names the
|
|
1691
|
+
// campaign in the footer. Sending without it silently broadens every
|
|
1692
|
+
// opt-out to the entire organization.
|
|
1693
|
+
writes: [
|
|
1694
|
+
queueNotification({
|
|
1695
|
+
audience: "lead",
|
|
1696
|
+
campaign: (context == null ? void 0 : context.campaign) || null,
|
|
1697
|
+
lead: (context == null ? void 0 : context.lead) || null,
|
|
1698
|
+
message: interpolate((_a = step.settings) == null ? void 0 : _a.message, context),
|
|
1699
|
+
organization: workflow.organization,
|
|
1700
|
+
send: { type: "email", email: to },
|
|
1701
|
+
title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
|
|
1702
|
+
workflow: workflow.id
|
|
1703
|
+
})
|
|
1704
|
+
]
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1414
1707
|
},
|
|
1415
1708
|
inbound: false,
|
|
1416
1709
|
lifecycle: false,
|
|
@@ -1420,8 +1713,174 @@ var drawbridge_default2 = {
|
|
|
1420
1713
|
products: false,
|
|
1421
1714
|
promotions: false
|
|
1422
1715
|
},
|
|
1423
|
-
segment: {
|
|
1424
|
-
|
|
1716
|
+
segment: {
|
|
1717
|
+
// RECALCULATE SEGMENT MEMBERSHIP. The one FAN-OUT hook: it evaluates every
|
|
1718
|
+
// contact in an organization against every segment, which is too much for
|
|
1719
|
+
// one job, so it returns chunks and the shell defers completion.
|
|
1720
|
+
//
|
|
1721
|
+
// Returning `chunks` is the only thing that makes it different. The
|
|
1722
|
+
// declaration, the guards, the step document and the price are the shell's,
|
|
1723
|
+
// exactly as they are for a step that finishes in one go.
|
|
1724
|
+
sync: async ({ context, step }, { chunkSize, logger: logger2, read, resolveContact } = {}) => {
|
|
1725
|
+
var _a, _b, _c;
|
|
1726
|
+
if (!chunkSize) throw new Error("segment.sync needs chunkSize from the shell");
|
|
1727
|
+
const organization2 = context == null ? void 0 : context.organization;
|
|
1728
|
+
const configured = (_a = step == null ? void 0 : step.settings) == null ? void 0 : _a.segment;
|
|
1729
|
+
const request2 = { organization: organization2 || null, segmentId: configured || null };
|
|
1730
|
+
const release = (ids, status = "active") => {
|
|
1731
|
+
const released = (ids || []).filter(Boolean);
|
|
1732
|
+
return {
|
|
1733
|
+
events: organization2 ? released.map((id) => ({
|
|
1734
|
+
event: "organization.segments",
|
|
1735
|
+
payload: { id, status },
|
|
1736
|
+
room: "organization." + organization2
|
|
1737
|
+
})) : [],
|
|
1738
|
+
writes: released.map((id) => ({
|
|
1739
|
+
collection: "segment",
|
|
1740
|
+
data: { $set: { status } },
|
|
1741
|
+
operation: "update",
|
|
1742
|
+
query: { id }
|
|
1743
|
+
}))
|
|
1744
|
+
};
|
|
1745
|
+
};
|
|
1746
|
+
if (!organization2) {
|
|
1747
|
+
return {
|
|
1748
|
+
...release([configured]),
|
|
1749
|
+
message: "Trigger data missing organization id \u2014 cannot sync segments.",
|
|
1750
|
+
request: request2,
|
|
1751
|
+
response: { skipped: true },
|
|
1752
|
+
skipped: true
|
|
1753
|
+
};
|
|
1754
|
+
}
|
|
1755
|
+
const segments = await read.aggregate({
|
|
1756
|
+
collection: "segment",
|
|
1757
|
+
pipeline: [{ $match: configured ? { id: configured, organization: organization2 } : { organization: organization2 } }]
|
|
1758
|
+
});
|
|
1759
|
+
if (!segments.length) {
|
|
1760
|
+
return {
|
|
1761
|
+
...release([configured]),
|
|
1762
|
+
message: "No segments matched the request \u2014 nothing to sync.",
|
|
1763
|
+
request: request2,
|
|
1764
|
+
response: { skipped: true },
|
|
1765
|
+
skipped: true
|
|
1766
|
+
};
|
|
1767
|
+
}
|
|
1768
|
+
const segmentIds = segments.map((entry) => entry.id);
|
|
1769
|
+
try {
|
|
1770
|
+
let backfilled = 0;
|
|
1771
|
+
if (segments.some((entry) => entry.system)) {
|
|
1772
|
+
const contacted = await read.aggregate({
|
|
1773
|
+
collection: "contact",
|
|
1774
|
+
pipeline: [
|
|
1775
|
+
{ $match: { organization: organization2 } },
|
|
1776
|
+
{ $project: { _id: 0, leads: 1 } },
|
|
1777
|
+
{ $unwind: "$leads" },
|
|
1778
|
+
{ $group: { _id: null, ids: { $addToSet: "$leads" } } }
|
|
1779
|
+
]
|
|
1780
|
+
});
|
|
1781
|
+
const uncontacted = await read.aggregate({
|
|
1782
|
+
collection: "lead",
|
|
1783
|
+
pipeline: [
|
|
1784
|
+
{ $match: { id: { $nin: ((_b = contacted[0]) == null ? void 0 : _b.ids) || [] }, organization: organization2 } },
|
|
1785
|
+
{ $project: { _id: 0, id: 1 } }
|
|
1786
|
+
]
|
|
1787
|
+
});
|
|
1788
|
+
for (const lead of uncontacted) {
|
|
1789
|
+
try {
|
|
1790
|
+
await resolveContact({ leadId: lead.id });
|
|
1791
|
+
backfilled += 1;
|
|
1792
|
+
} catch (error) {
|
|
1793
|
+
if (error.code !== 11e3) throw error;
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
(_c = logger2 == null ? void 0 : logger2.info) == null ? void 0 : _c.call(logger2, "segment.sync.backfill", { backfilled, organization: organization2, uncontacted: uncontacted.length });
|
|
1797
|
+
}
|
|
1798
|
+
const contacts2 = await read.aggregate({
|
|
1799
|
+
collection: "contact",
|
|
1800
|
+
pipeline: [
|
|
1801
|
+
{ $match: { organization: organization2 } },
|
|
1802
|
+
{ $project: { _id: 0, id: 1 } },
|
|
1803
|
+
{ $sort: { id: 1 } }
|
|
1804
|
+
]
|
|
1805
|
+
});
|
|
1806
|
+
if (!contacts2.length) {
|
|
1807
|
+
return {
|
|
1808
|
+
...release(segmentIds),
|
|
1809
|
+
message: "Organization has no contacts to evaluate against segments.",
|
|
1810
|
+
request: request2,
|
|
1811
|
+
response: { skipped: true },
|
|
1812
|
+
skipped: true
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
const contactIds = contacts2.map((contact) => contact.id);
|
|
1816
|
+
const org = await read.get({ collection: "organization", query: { id: organization2 } });
|
|
1817
|
+
const chunks = [];
|
|
1818
|
+
for (let index = 0; index < contactIds.length; index += chunkSize) {
|
|
1819
|
+
chunks.push({
|
|
1820
|
+
contactIds: contactIds.slice(index, index + chunkSize),
|
|
1821
|
+
organization: organization2,
|
|
1822
|
+
segments: segmentIds,
|
|
1823
|
+
// A BACKFILL IS NOT BILLABLE. It creates the contacts this run
|
|
1824
|
+
// then evaluates, so charging for it would bill an organization
|
|
1825
|
+
// for work its own history made necessary.
|
|
1826
|
+
usage: (context == null ? void 0 : context.billable) === true && backfilled === 0 ? (org == null ? void 0 : org.usage) || null : null
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
return {
|
|
1830
|
+
chunks,
|
|
1831
|
+
...configured && { extra: { segment: configured } },
|
|
1832
|
+
message: "Queued " + contactIds.length + " contacts across " + chunks.length + " chunks for segment evaluation.",
|
|
1833
|
+
queue: "segment",
|
|
1834
|
+
request: { ...request2, segments: segmentIds },
|
|
1835
|
+
response: { chunks: chunks.length, contacts: contactIds.length, segments: segments.length }
|
|
1836
|
+
};
|
|
1837
|
+
} catch (error) {
|
|
1838
|
+
throw Object.assign(error, release(segmentIds, "error"));
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
},
|
|
1842
|
+
sms: {
|
|
1843
|
+
// SMS TO A LEAD, through the merchant's own Twilio connection.
|
|
1844
|
+
//
|
|
1845
|
+
// WITHDRAWN from the builder — twilio went, and a connection-gated step
|
|
1846
|
+
// with no connection to gate on could only ever render permanently
|
|
1847
|
+
// disabled. Stored workflows still carry it, so it still runs.
|
|
1848
|
+
//
|
|
1849
|
+
// It looks its own connection up rather than relying on the shell, because
|
|
1850
|
+
// the step is declared by the PRIVATE drawbridge connection (which has
|
|
1851
|
+
// none) while the credential belongs to twilio (which has no manifest).
|
|
1852
|
+
// Platform SMS will remove that split the way it did for email.
|
|
1853
|
+
send: async ({ context, step, workflow }, { canSend, read } = {}) => {
|
|
1854
|
+
var _a, _b, _c;
|
|
1855
|
+
const to = (_a = context == null ? void 0 : context.phone) == null ? void 0 : _a.number;
|
|
1856
|
+
if (!to) throw new Error("No phone number on context (context.phone.number is required)");
|
|
1857
|
+
const request2 = { to };
|
|
1858
|
+
const connection2 = await read.get({
|
|
1859
|
+
collection: "connection",
|
|
1860
|
+
query: { organization: workflow.organization, slug: "twilio", status: "active" }
|
|
1861
|
+
});
|
|
1862
|
+
if (!connection2) return { message: "No active Twilio SMS connection \u2014 workflow-step SMS skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1863
|
+
const { ok: sendable } = await canSend({ channel: "sms", to: context.phone });
|
|
1864
|
+
if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1865
|
+
return {
|
|
1866
|
+
message: "SMS queued for delivery to " + to + " via twilio.",
|
|
1867
|
+
request: request2,
|
|
1868
|
+
response: { provider: "twilio", queued: true },
|
|
1869
|
+
// QUEUES rather than sends: queue/notification.js owns delivery, the
|
|
1870
|
+
// carrier opt-out line and the segment count this is billed on.
|
|
1871
|
+
writes: [
|
|
1872
|
+
queueNotification({
|
|
1873
|
+
connection: connection2.id,
|
|
1874
|
+
message: interpolate((_b = step.settings) == null ? void 0 : _b.message, context),
|
|
1875
|
+
organization: workflow.organization,
|
|
1876
|
+
send: { phone: { number: to }, type: "phone" },
|
|
1877
|
+
title: interpolate((_c = step.settings) == null ? void 0 : _c.subject, context),
|
|
1878
|
+
workflow: workflow.id
|
|
1879
|
+
})
|
|
1880
|
+
]
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
},
|
|
1425
1884
|
webhook: false
|
|
1426
1885
|
},
|
|
1427
1886
|
icon: drawbridge_default,
|
|
@@ -1463,11 +1922,11 @@ var drawbridge_default2 = {
|
|
|
1463
1922
|
key: "Email \u2014 Digest",
|
|
1464
1923
|
queue: "notification",
|
|
1465
1924
|
settings: {
|
|
1466
|
-
// The organization OWNER is always a recipient, resolved
|
|
1467
|
-
// so this is additional recipients rather than the list. It
|
|
1468
|
-
// be required: the members endpoint is owner-gated and the
|
|
1469
|
-
// not a member document, so a solo merchant has nothing to
|
|
1470
|
-
// could never save the step.
|
|
1925
|
+
// The organization OWNER is always a recipient, resolved by the
|
|
1926
|
+
// hook, so this is additional recipients rather than the list. It
|
|
1927
|
+
// cannot be required: the members endpoint is owner-gated and the
|
|
1928
|
+
// owner is not a member document, so a solo merchant has nothing to
|
|
1929
|
+
// pick and could never save the step.
|
|
1471
1930
|
members: { of: "string", type: "array" },
|
|
1472
1931
|
message: { required: true, type: "string" },
|
|
1473
1932
|
subject: { required: true, type: "string" }
|
|
@@ -1567,7 +2026,7 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
|
|
|
1567
2026
|
<path d="M365.047 327.038H134.954V172.964H365.047L316.856 250.001L365.047 327.038Z" fill="#232121"/>
|
|
1568
2027
|
</svg>`;
|
|
1569
2028
|
|
|
1570
|
-
// lib/connections/klaviyo.js
|
|
2029
|
+
// lib/connections/providers/klaviyo.js
|
|
1571
2030
|
var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
|
|
1572
2031
|
const response = await fetcher("https://a.klaviyo.com/api" + path, {
|
|
1573
2032
|
...payload && { body: JSON.stringify(payload) },
|
|
@@ -1604,7 +2063,8 @@ var klaviyo_default2 = {
|
|
|
1604
2063
|
// differently, and it says so in hooks.auth.token rather than as a flag here.
|
|
1605
2064
|
auth: {
|
|
1606
2065
|
oauth: {
|
|
1607
|
-
// NAMES the
|
|
2066
|
+
// NAMES the credentials holding OUR application's client — keys into
|
|
2067
|
+
// the stored provider credentials, not env vars. One identity,
|
|
1608
2068
|
// every merchant — the token is the merchant's and arrives from their
|
|
1609
2069
|
// own consent, which is what stops one organization reading another's
|
|
1610
2070
|
// data.
|
|
@@ -1744,7 +2204,7 @@ var klaviyo_default2 = {
|
|
|
1744
2204
|
// renders an empty "Klaviyo account" field, because the merchant is
|
|
1745
2205
|
// never asked which account they connected — the consent already
|
|
1746
2206
|
// decided it, and asking again would be a question we can answer.
|
|
1747
|
-
connect: async ({
|
|
2207
|
+
connect: async ({ tokens }, { fetcher } = {}) => {
|
|
1748
2208
|
var _a, _b, _c;
|
|
1749
2209
|
const body = await api("/accounts", { fetcher, token: tokens.accessToken });
|
|
1750
2210
|
const account = (_a = body == null ? void 0 : body.data) == null ? void 0 : _a[0];
|
|
@@ -1759,7 +2219,7 @@ var klaviyo_default2 = {
|
|
|
1759
2219
|
//
|
|
1760
2220
|
// Basic auth with our client, exactly like the token exchange — the
|
|
1761
2221
|
// token being revoked is the subject, not the credential.
|
|
1762
|
-
disconnect: async ({ clientId, clientSecret, fetcher = fetch
|
|
2222
|
+
disconnect: async ({ clientId, clientSecret, manifest, settings }, { fetcher = fetch } = {}) => {
|
|
1763
2223
|
const token = (settings == null ? void 0 : settings.refreshToken) || (settings == null ? void 0 : settings.accessToken);
|
|
1764
2224
|
if (!token) return { revoked: false };
|
|
1765
2225
|
const response = await fetcher(manifest.auth.oauth.urls.revoke, {
|
|
@@ -1782,7 +2242,7 @@ var klaviyo_default2 = {
|
|
|
1782
2242
|
// the refresh token is the only thing that asks Klaviyo.
|
|
1783
2243
|
//
|
|
1784
2244
|
// It also keeps the grant warm against the 90-day idle window above.
|
|
1785
|
-
probe: async ({ clientId, clientSecret,
|
|
2245
|
+
probe: async ({ clientId, clientSecret, manifest, settings }, { fetcher } = {}) => {
|
|
1786
2246
|
const token = await accessToken({
|
|
1787
2247
|
clientId,
|
|
1788
2248
|
clientSecret,
|
|
@@ -1812,12 +2272,11 @@ var klaviyo_default2 = {
|
|
|
1812
2272
|
// the store's.
|
|
1813
2273
|
commerce: false,
|
|
1814
2274
|
// The verb the contacts.sync step points at. It does the work — including
|
|
1815
|
-
// writing the profile id back onto the lead — and returns what happened.
|
|
1816
2275
|
contacts: {
|
|
1817
2276
|
// Not yet. Suppression syncs an opt-out as unsubscribed, which is a
|
|
1818
2277
|
// different thing from deleting the profile.
|
|
1819
2278
|
remove: false,
|
|
1820
|
-
sync: async ({ contact,
|
|
2279
|
+
sync: async ({ contact, lead, settings, suppressed, token }, { fetcher } = {}) => {
|
|
1821
2280
|
var _a, _b, _c;
|
|
1822
2281
|
const list = settings == null ? void 0 : settings.list;
|
|
1823
2282
|
if (!list) return { message: "No Klaviyo list is chosen for this connection.", skipped: true };
|
|
@@ -1909,7 +2368,7 @@ var klaviyo_default2 = {
|
|
|
1909
2368
|
// it, so one call quietly returns the first ten lists and an account
|
|
1910
2369
|
// with more shows a picker missing the one they wanted, with nothing to
|
|
1911
2370
|
// indicate anything was cut.
|
|
1912
|
-
audiences: async ({ cursor,
|
|
2371
|
+
audiences: async ({ cursor, limit = 100, search, token }, { fetcher } = {}) => {
|
|
1913
2372
|
var _a, _b;
|
|
1914
2373
|
const audiences = [];
|
|
1915
2374
|
let next = cursor ? "/lists?page%5Bsize%5D=10&page%5Bcursor%5D=" + encodeURIComponent(cursor) : "/lists?page%5Bsize%5D=10";
|
|
@@ -2021,7 +2480,7 @@ var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fil
|
|
|
2021
2480
|
<path d="M360.476 284.243C360.35 283.835 359.618 281.204 358.647 278.052L356.621 272.648C360.575 266.696 360.645 261.405 360.124 258.393C359.531 254.519 357.693 250.944 354.89 248.205C351.766 244.94 345.363 241.563 336.385 239.044L331.671 237.736C331.643 237.524 331.418 226.619 331.235 221.933C331.08 218.555 330.798 213.264 329.152 208.058C327.182 200.993 323.791 194.858 319.527 190.876C331.277 178.717 338.594 165.307 338.58 153.81C338.538 131.703 311.379 124.976 277.902 138.851L270.824 141.863C270.795 141.835 258.004 129.283 257.821 129.128C219.63 95.8334 100.327 228.476 138.49 260.687L146.835 267.737C144.581 273.775 143.781 280.259 144.499 286.664C145.414 295.543 149.973 304.029 157.375 310.6C164.411 316.82 173.684 320.788 182.648 320.774C197.494 354.998 231.408 375.965 271.175 377.161C313.842 378.427 349.641 358.403 364.67 322.435C365.641 319.916 369.806 308.546 369.806 298.513C369.792 288.409 364.093 284.229 360.476 284.243ZM185.913 311.149C184.613 311.381 183.293 311.48 181.973 311.445C169.083 311.079 155.166 299.483 153.787 285.735C152.253 270.537 160.02 258.829 173.783 256.071C175.415 255.72 177.414 255.537 179.552 255.635C187.264 256.085 198.606 261.996 201.209 278.784C203.517 293.63 199.858 308.785 185.913 311.149ZM171.545 246.953C163.179 248.499 155.744 253.244 150.817 260.18C148.045 257.873 142.909 253.426 142.008 251.681C134.635 237.693 150.043 210.478 160.823 195.111C187.405 157.145 229.086 128.424 248.393 133.603C251.517 134.503 261.902 146.563 261.902 146.563C261.902 146.563 242.623 157.244 224.724 172.16C200.646 190.735 182.423 217.697 171.545 246.953ZM306.792 305.464C306.937 305.403 307.057 305.295 307.134 305.157C307.211 305.019 307.239 304.86 307.214 304.704C307.205 304.61 307.178 304.519 307.133 304.436C307.088 304.353 307.027 304.28 306.954 304.221C306.88 304.162 306.796 304.118 306.705 304.092C306.614 304.066 306.519 304.059 306.426 304.071C306.426 304.071 286.246 307.054 267.179 300.089C269.247 293.348 274.792 295.754 283.137 296.444C296.108 297.209 309.116 295.802 321.623 292.279C330.25 289.788 341.592 284.905 350.401 277.953C353.384 284.497 354.425 291.674 354.425 291.674C354.425 291.674 356.719 291.265 358.647 292.447C360.476 293.573 361.799 295.895 360.898 301.89C359.027 313.119 354.271 322.224 346.235 330.611C341.236 336.036 335.277 340.492 328.659 343.754C324.983 345.691 321.151 347.32 317.205 348.623C286.964 358.487 256.006 347.638 246.029 324.321C245.224 322.535 244.556 320.691 244.03 318.804C239.781 303.438 243.383 285.032 254.655 273.408C255.372 272.676 256.09 271.804 256.09 270.706C256.09 269.806 255.499 268.835 255.007 268.131C251.066 262.418 237.374 252.666 240.132 233.795C242.088 220.23 253.951 210.689 265.012 211.252L267.826 211.421C272.611 211.702 276.79 212.307 280.73 212.49C287.344 212.758 293.268 211.801 300.304 205.947C302.683 203.949 304.582 202.246 307.791 201.711C308.128 201.627 308.973 201.359 310.647 201.416C312.365 201.485 314.032 202.015 315.474 202.949C321.103 206.693 321.905 215.783 322.214 222.439C322.383 226.225 322.848 235.414 322.988 238.031C323.354 244.054 324.944 244.912 328.125 245.954C329.94 246.573 331.615 246.995 334.077 247.713C341.521 249.781 345.968 251.934 348.754 254.65C350.198 256.049 351.13 257.893 351.4 259.885C352.315 266.316 346.432 274.252 330.925 281.457C313.954 289.324 293.367 291.322 279.154 289.732L274.173 289.169C262.774 287.649 256.315 302.34 263.14 312.402C267.545 318.889 279.52 323.11 291.523 323.11C319.006 323.139 340.142 311.402 348.023 301.242L348.642 300.356C349.008 299.765 348.712 299.469 348.22 299.779C341.817 304.169 313.279 321.619 282.771 316.384C282.771 316.384 279.056 315.765 275.678 314.442C273.005 313.429 267.362 310.811 266.686 305.042C291.27 312.683 306.792 305.478 306.792 305.464ZM220.671 194.971C230.127 184.051 241.765 174.538 252.206 169.219C252.558 169.022 252.938 169.43 252.741 169.754C251.46 172 250.476 174.403 249.814 176.902C249.73 177.282 250.138 177.592 250.461 177.353C256.963 172.934 268.248 168.192 278.155 167.601C278.251 167.584 278.351 167.601 278.436 167.65C278.521 167.698 278.586 167.775 278.621 167.866C278.656 167.957 278.658 168.058 278.627 168.151C278.596 168.244 278.533 168.323 278.451 168.375C276.809 169.634 275.342 171.105 274.088 172.751C273.891 173.032 274.074 173.44 274.426 173.44C281.378 173.483 291.186 175.903 297.56 179.491C297.982 179.745 297.673 180.575 297.209 180.462C287.527 178.253 271.724 176.564 255.288 180.575C240.597 184.149 229.396 189.666 221.248 195.618C220.826 195.899 220.333 195.351 220.671 194.971Z" fill="#231E15"/>
|
|
2022
2481
|
</svg>`;
|
|
2023
2482
|
|
|
2024
|
-
// lib/connections/mailchimp.js
|
|
2483
|
+
// lib/connections/providers/mailchimp.js
|
|
2025
2484
|
var base = (dc) => {
|
|
2026
2485
|
if (!dc) throw new Error("This Mailchimp connection has no data centre stored, so there is no host to call");
|
|
2027
2486
|
return "https://" + dc + ".api.mailchimp.com/3.0";
|
|
@@ -2110,7 +2569,7 @@ var mailchimp_default2 = {
|
|
|
2110
2569
|
// The header here is `OAuth <token>`, not Bearer — that is specific to
|
|
2111
2570
|
// the metadata endpoint. Marketing API calls take Bearer; see the
|
|
2112
2571
|
// audiences hook.
|
|
2113
|
-
connect: async ({ fetcher = fetch
|
|
2572
|
+
connect: async ({ tokens }, { fetcher = fetch } = {}) => {
|
|
2114
2573
|
const response = await fetcher("https://login.mailchimp.com/oauth2/metadata", {
|
|
2115
2574
|
headers: {
|
|
2116
2575
|
authorization: "OAuth " + (tokens == null ? void 0 : tokens.accessToken)
|
|
@@ -2162,7 +2621,7 @@ var mailchimp_default2 = {
|
|
|
2162
2621
|
// successful — the same silent truncation Klaviyo has, at a different
|
|
2163
2622
|
// number. Paged against total_items so an account past a thousand still
|
|
2164
2623
|
// resolves.
|
|
2165
|
-
audiences: async ({ cursor,
|
|
2624
|
+
audiences: async ({ cursor, limit = 100, search, settings, token }, { fetcher = fetch } = {}) => {
|
|
2166
2625
|
const dc = settings == null ? void 0 : settings.dc;
|
|
2167
2626
|
const count = Math.min(limit, 1e3);
|
|
2168
2627
|
const offset = Number(cursor || 0);
|
|
@@ -2241,6 +2700,10 @@ var mailchimp_default2 = {
|
|
|
2241
2700
|
title: "Mailchimp"
|
|
2242
2701
|
};
|
|
2243
2702
|
|
|
2703
|
+
// lib/connections/providers/shopify.js
|
|
2704
|
+
import { randomUUID } from "crypto";
|
|
2705
|
+
import { customAlphabet as customAlphabet2 } from "nanoid";
|
|
2706
|
+
|
|
2244
2707
|
// lib/connections/icons/shopify.js
|
|
2245
2708
|
var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2246
2709
|
<rect width="500" height="500" fill="white"/>
|
|
@@ -2251,12 +2714,15 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
|
|
|
2251
2714
|
|
|
2252
2715
|
// lib/connections/inbound.js
|
|
2253
2716
|
import { createHmac, timingSafeEqual } from "crypto";
|
|
2254
|
-
var verifySignature = ({ body, descriptor, headers }) => {
|
|
2717
|
+
var verifySignature = ({ body, descriptor, headers, secret }) => {
|
|
2718
|
+
if (!secret) {
|
|
2719
|
+
throw Object.assign(new Error("Missing webhook secret: " + descriptor.signature.secret), { status: 500 });
|
|
2720
|
+
}
|
|
2255
2721
|
const provided = headers[descriptor.headers.signature];
|
|
2256
2722
|
if (!provided) {
|
|
2257
2723
|
throw Object.assign(new Error("Missing webhook signature"), { status: 401 });
|
|
2258
2724
|
}
|
|
2259
|
-
const digest = createHmac(descriptor.signature.algorithm,
|
|
2725
|
+
const digest = createHmac(descriptor.signature.algorithm, secret).update(body).digest(descriptor.signature.encoding);
|
|
2260
2726
|
const digestBuffer = Buffer.from(digest, descriptor.signature.encoding);
|
|
2261
2727
|
const providedBuffer = Buffer.from(provided, descriptor.signature.encoding);
|
|
2262
2728
|
if (digestBuffer.length !== providedBuffer.length || !timingSafeEqual(digestBuffer, providedBuffer)) {
|
|
@@ -2266,7 +2732,72 @@ var verifySignature = ({ body, descriptor, headers }) => {
|
|
|
2266
2732
|
};
|
|
2267
2733
|
var readEventHeader = ({ descriptor, headers }) => headers[descriptor.headers.event];
|
|
2268
2734
|
|
|
2269
|
-
// lib/
|
|
2735
|
+
// lib/email.js
|
|
2736
|
+
var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
|
|
2737
|
+
var toCanonicalEmail = (value) => {
|
|
2738
|
+
if (!value || typeof value !== "string") return null;
|
|
2739
|
+
const email = value.trim().toLowerCase();
|
|
2740
|
+
const at = email.lastIndexOf("@");
|
|
2741
|
+
if (at < 1 || at === email.length - 1) return null;
|
|
2742
|
+
let local = email.slice(0, at);
|
|
2743
|
+
const domain = email.slice(at + 1);
|
|
2744
|
+
const plus = local.indexOf("+");
|
|
2745
|
+
if (plus > 0) local = local.slice(0, plus);
|
|
2746
|
+
if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
|
|
2747
|
+
if (!local) return null;
|
|
2748
|
+
return local + "@" + domain;
|
|
2749
|
+
};
|
|
2750
|
+
|
|
2751
|
+
// lib/phone.js
|
|
2752
|
+
import { AsYouType, parsePhoneNumberFromString, isValidPhoneNumber } from "libphonenumber-js";
|
|
2753
|
+
var toE164 = (value, country) => {
|
|
2754
|
+
if (!value) return null;
|
|
2755
|
+
try {
|
|
2756
|
+
const parsed = parsePhoneNumberFromString(String(value), country);
|
|
2757
|
+
return parsed ? parsed.number : null;
|
|
2758
|
+
} catch {
|
|
2759
|
+
return null;
|
|
2760
|
+
}
|
|
2761
|
+
};
|
|
2762
|
+
|
|
2763
|
+
// lib/connections/providers/shopify.js
|
|
2764
|
+
var toLine = ({
|
|
2765
|
+
price,
|
|
2766
|
+
product_id: productId,
|
|
2767
|
+
quantity,
|
|
2768
|
+
title,
|
|
2769
|
+
variant_id: variantId,
|
|
2770
|
+
variant_title: variantTitle
|
|
2771
|
+
}) => ({
|
|
2772
|
+
price: parseFloat(price) || 0,
|
|
2773
|
+
productId: productId ? "gid://shopify/Product/" + productId : null,
|
|
2774
|
+
quantity: quantity || 1,
|
|
2775
|
+
title: title || null,
|
|
2776
|
+
variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
|
|
2777
|
+
variantTitle: variantTitle || null
|
|
2778
|
+
});
|
|
2779
|
+
var attributeLineItems = (lineItems = []) => lineItems.reduce(
|
|
2780
|
+
(acc, item) => {
|
|
2781
|
+
const attrs = (item.properties || []).reduce(
|
|
2782
|
+
(map, { name, value }) => {
|
|
2783
|
+
map[name] = value;
|
|
2784
|
+
return map;
|
|
2785
|
+
},
|
|
2786
|
+
{}
|
|
2787
|
+
);
|
|
2788
|
+
if (!attrs["_drwbrdg_ca"]) return acc;
|
|
2789
|
+
if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
|
|
2790
|
+
const line = toLine(item);
|
|
2791
|
+
acc.attributedGross += line.price * line.quantity;
|
|
2792
|
+
acc.attributedLines.push(line);
|
|
2793
|
+
return acc;
|
|
2794
|
+
},
|
|
2795
|
+
{ attrMap: {}, attributedGross: 0, attributedLines: [] }
|
|
2796
|
+
);
|
|
2797
|
+
var generateDiscountCode = customAlphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
|
|
2798
|
+
var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
|
|
2799
|
+
var OAUTH_ERROR_SOURCE = "oauth";
|
|
2800
|
+
var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
|
|
2270
2801
|
var inbound = {
|
|
2271
2802
|
headers: {
|
|
2272
2803
|
event: "x-shopify-topic",
|
|
@@ -2383,20 +2914,476 @@ var shopify_default2 = {
|
|
|
2383
2914
|
//
|
|
2384
2915
|
// `shopify` is injected for the same reason it is everywhere else — this
|
|
2385
2916
|
// package cannot import @drawbridge/shopify, which depends on it.
|
|
2386
|
-
scopes: ({ scope, shopify }) => scope ? shopify.oauth.missingScopes(scope) : null,
|
|
2917
|
+
scopes: ({ scope }, { shopify } = {}) => scope ? shopify.oauth.missingScopes(scope) : null,
|
|
2387
2918
|
// Shopify's install grant is exchanged inside its own app flow, not
|
|
2388
2919
|
// through the shared OAuth runner.
|
|
2389
2920
|
token: false
|
|
2390
2921
|
},
|
|
2391
|
-
//
|
|
2392
|
-
//
|
|
2393
|
-
//
|
|
2394
|
-
//
|
|
2922
|
+
// THE VENDOR'S OWN WORK, here in full. Every body describes its writes,
|
|
2923
|
+
// enqueues and events for the shell to perform — see contract.js — and
|
|
2924
|
+
// everything it needs arrives as an argument: `read` (the controller's
|
|
2925
|
+
// read methods, nothing that writes), `shopify` (the SDK, injected because
|
|
2926
|
+
// this package cannot import what depends on it), `adminToken` (minted by
|
|
2927
|
+
// the shell, which persists rotations), `mintId` (so one described write
|
|
2928
|
+
// can reference another), `dispatch` (the caller's own coordinator table,
|
|
2929
|
+
// for the hooks that are dispatches).
|
|
2395
2930
|
commerce: {
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2931
|
+
// MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
|
|
2932
|
+
// one lead — which is what lets an order that redeems it be attributed
|
|
2933
|
+
// back.
|
|
2934
|
+
code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
|
|
2935
|
+
var _a;
|
|
2936
|
+
const discount = (_a = step.settings) == null ? void 0 : _a.discount;
|
|
2937
|
+
const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
|
|
2938
|
+
if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing.", request: request2, response: { skipped: true }, skipped: true };
|
|
2939
|
+
if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing.", request: request2, response: { skipped: true }, skipped: true };
|
|
2940
|
+
if (!(discount == null ? void 0 : discount.id)) return { message: "Discount is not configured on this step.", request: request2, response: { skipped: true }, skipped: true };
|
|
2941
|
+
const adminAccessToken = await adminToken();
|
|
2942
|
+
if (!context.shopifyCustomerId) {
|
|
2943
|
+
const customer = await shopify.admin.getOrCreateCustomer({ adminAccessToken, domain: connection2.shop, email: context.email });
|
|
2944
|
+
if (!(customer == null ? void 0 : customer.id)) return { message: "Shopify did not return a customer id \u2014 create/lookup failed.", request: request2, response: { skipped: true }, skipped: true };
|
|
2945
|
+
}
|
|
2946
|
+
const discountCode = await shopify.admin.createDiscountCode({
|
|
2947
|
+
adminAccessToken,
|
|
2948
|
+
code: "DB-" + generateDiscountCode(),
|
|
2949
|
+
discountId: discount.id,
|
|
2950
|
+
domain: connection2.shop
|
|
2951
|
+
});
|
|
2952
|
+
if (!discountCode) return { message: "Shopify did not return a discount code \u2014 create failed.", request: request2, response: { skipped: true }, skipped: true };
|
|
2953
|
+
return {
|
|
2954
|
+
context: {
|
|
2955
|
+
shopifyDiscountCode: discountCode.code,
|
|
2956
|
+
shopifyDiscountId: String(discountCode.id)
|
|
2957
|
+
},
|
|
2958
|
+
message: "Discount code created and linked to lead.",
|
|
2959
|
+
request: request2,
|
|
2960
|
+
response: { code: discountCode.code, id: String(discountCode.id) },
|
|
2961
|
+
// bypassDocumentValidation because these are vendor ids on a
|
|
2962
|
+
// Drawbridge document the schema does not declare — the
|
|
2963
|
+
// canonical-identity work resolves it properly.
|
|
2964
|
+
writes: [{
|
|
2965
|
+
collection: "lead",
|
|
2966
|
+
data: {
|
|
2967
|
+
$set: {
|
|
2968
|
+
shopifyDiscountCode: discountCode.code,
|
|
2969
|
+
shopifyDiscountId: String(discountCode.id)
|
|
2970
|
+
}
|
|
2971
|
+
},
|
|
2972
|
+
operation: "update",
|
|
2973
|
+
options: { bypassDocumentValidation: true },
|
|
2974
|
+
query: { id: context.lead }
|
|
2975
|
+
}]
|
|
2976
|
+
};
|
|
2977
|
+
},
|
|
2978
|
+
// CREATE THE BUYER AT THE STORE, so an order can be attributed to them.
|
|
2979
|
+
//
|
|
2980
|
+
// IDEMPOTENT THREE WAYS, because this runs on every entry and a duplicate
|
|
2981
|
+
// customer at the store is a support ticket: the context may already
|
|
2982
|
+
// carry the id from an earlier step, the lead may already be linked from
|
|
2983
|
+
// an earlier run, and Shopify's own get-or-create settles the rest.
|
|
2984
|
+
customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
|
|
2985
|
+
const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
|
|
2986
|
+
if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing \u2014 cannot create Shopify customer.", request: request2, response: { skipped: true }, skipped: true };
|
|
2987
|
+
if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing \u2014 cannot create Shopify customer.", request: request2, response: { skipped: true }, skipped: true };
|
|
2988
|
+
if (context.shopifyCustomerId) {
|
|
2989
|
+
return {
|
|
2990
|
+
context: { shopifyCustomerId: context.shopifyCustomerId },
|
|
2991
|
+
message: "Trigger data already includes a Shopify customer id \u2014 reusing.",
|
|
2992
|
+
request: request2,
|
|
2993
|
+
response: { shopifyCustomerId: context.shopifyCustomerId },
|
|
2994
|
+
// Reusing an id is not a creation, so it does not bill.
|
|
2995
|
+
skipped: true
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
2998
|
+
const lead = await read.get({ collection: "lead", query: { id: context.lead } });
|
|
2999
|
+
if (lead == null ? void 0 : lead.shopifyCustomerId) {
|
|
3000
|
+
return {
|
|
3001
|
+
context: { shopifyCustomerId: lead.shopifyCustomerId },
|
|
3002
|
+
message: "Lead already has a Shopify customer id \u2014 reusing.",
|
|
3003
|
+
request: request2,
|
|
3004
|
+
response: { shopifyCustomerId: lead.shopifyCustomerId },
|
|
3005
|
+
skipped: true
|
|
3006
|
+
};
|
|
3007
|
+
}
|
|
3008
|
+
const adminAccessToken = await adminToken();
|
|
3009
|
+
const parts = ((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
|
|
3010
|
+
const customer = await shopify.admin.getOrCreateCustomer({
|
|
3011
|
+
adminAccessToken,
|
|
3012
|
+
domain: connection2.shop,
|
|
3013
|
+
email: context.email,
|
|
3014
|
+
firstName: parts.length ? parts[0] : null,
|
|
3015
|
+
lastName: parts.length > 1 ? parts.slice(1).join(" ") : null,
|
|
3016
|
+
source: "drawbridge"
|
|
3017
|
+
});
|
|
3018
|
+
if (!(customer == null ? void 0 : customer.id)) return { message: "Shopify did not return a customer id \u2014 create/lookup failed.", request: request2, response: { skipped: true }, skipped: true };
|
|
3019
|
+
return {
|
|
3020
|
+
context: { shopifyCustomerId: customer.id },
|
|
3021
|
+
message: "Shopify customer created/linked to lead.",
|
|
3022
|
+
request: request2,
|
|
3023
|
+
response: { shopifyCustomerId: customer.id },
|
|
3024
|
+
// The hook's own result, described beside the call that produced it.
|
|
3025
|
+
writes: [{
|
|
3026
|
+
collection: "lead",
|
|
3027
|
+
data: { $set: { shopifyCustomerId: customer.id } },
|
|
3028
|
+
operation: "update",
|
|
3029
|
+
options: { bypassDocumentValidation: true },
|
|
3030
|
+
query: { id: context.lead }
|
|
3031
|
+
}]
|
|
3032
|
+
};
|
|
3033
|
+
},
|
|
3034
|
+
// AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
|
|
3035
|
+
// attribution genuinely is: an order can reach Drawbridge two ways and
|
|
3036
|
+
// they bill differently.
|
|
3037
|
+
//
|
|
3038
|
+
// CONVERSION — a `_drwbrdg_ca` line-item property, injected at
|
|
3039
|
+
// add-to-cart. Causal: the campaign produced the sale, so
|
|
3040
|
+
// it carries a fee.
|
|
3041
|
+
// REDEMPTION — a DB- discount code matched to a lead. Associative: we
|
|
3042
|
+
// cannot claim we caused the purchase, so it is fee-free.
|
|
3043
|
+
//
|
|
3044
|
+
// Both can be true, and an order already recorded as a conversion can
|
|
3045
|
+
// later have a redemption backfilled onto it — `backfill` below.
|
|
3046
|
+
//
|
|
3047
|
+
// IDEMPOTENT THROUGH THE RETRY, one layer up: two deliveries of the same
|
|
3048
|
+
// order race, the loser's transaction hits a duplicate key, the step
|
|
3049
|
+
// fails and BullMQ redelivers — and the re-run's read at the top finds
|
|
3050
|
+
// what the winner wrote and skips instead of double-billing a merchant
|
|
3051
|
+
// for one purchase. The hook used to loop for this itself; describing
|
|
3052
|
+
// the writes moved the retry to the queue, with the same guarantee.
|
|
3053
|
+
order: async ({ connection: connection2, context }, { logger: logger2, mintId, read } = {}) => {
|
|
3054
|
+
var _a, _b, _c, _d, _e, _f;
|
|
3055
|
+
const {
|
|
3056
|
+
advertisement,
|
|
3057
|
+
created_at: createdAt,
|
|
3058
|
+
currency,
|
|
3059
|
+
customer: orderCustomer,
|
|
3060
|
+
email,
|
|
3061
|
+
id: orderId,
|
|
3062
|
+
line_items: lineItems = [],
|
|
3063
|
+
organization: organization2,
|
|
3064
|
+
phone
|
|
3065
|
+
} = context || {};
|
|
3066
|
+
const request2 = { orderId: orderId ? String(orderId) : null, organization: organization2 };
|
|
3067
|
+
const [existingOrder, existingRedemption] = await Promise.all([
|
|
3068
|
+
read.get({ collection: "order", query: { "provider.id": String(orderId), "provider.slug": "shopify" } }),
|
|
3069
|
+
read.get({ collection: "redemption", query: { "provider.id": String(orderId), "provider.slug": "shopify" } })
|
|
3070
|
+
]);
|
|
3071
|
+
if (existingRedemption) {
|
|
3072
|
+
return {
|
|
3073
|
+
message: "Order/redemption already recorded \u2014 skipping duplicate.",
|
|
3074
|
+
request: request2,
|
|
3075
|
+
response: {
|
|
3076
|
+
existingOrderId: (existingOrder == null ? void 0 : existingOrder.id) || null,
|
|
3077
|
+
existingRedemptionId: existingRedemption.id,
|
|
3078
|
+
skipped: true
|
|
3079
|
+
},
|
|
3080
|
+
skipped: true
|
|
3081
|
+
};
|
|
3082
|
+
}
|
|
3083
|
+
const backfill = !!existingOrder;
|
|
3084
|
+
const { attrMap, attributedGross, attributedLines } = attributeLineItems(lineItems);
|
|
3085
|
+
const campaign = attrMap["_drwbrdg_ca"] || null;
|
|
3086
|
+
const discountCodes = Array.isArray(context == null ? void 0 : context.discount_codes) ? context.discount_codes : [];
|
|
3087
|
+
const codes = [...new Set(discountCodes.map((dc) => dc == null ? void 0 : dc.code).filter(Boolean))];
|
|
3088
|
+
const matchedLeads = codes.length ? await read.aggregate({
|
|
3089
|
+
collection: "lead",
|
|
3090
|
+
pipeline: [{ $match: { organization: organization2, shopifyDiscountCode: { $in: codes } } }]
|
|
3091
|
+
}) : [];
|
|
3092
|
+
const codeToLead = {};
|
|
3093
|
+
for (const found of matchedLeads) {
|
|
3094
|
+
if (found.shopifyDiscountCode) codeToLead[found.shopifyDiscountCode] = found;
|
|
3095
|
+
}
|
|
3096
|
+
const matchedDiscounts = discountCodes.filter((dc) => (dc == null ? void 0 : dc.code) && codeToLead[dc.code]).map((dc) => ({
|
|
3097
|
+
amount: parseFloat(dc.amount) || 0,
|
|
3098
|
+
code: dc.code,
|
|
3099
|
+
id: codeToLead[dc.code].shopifyDiscountId || null
|
|
3100
|
+
}));
|
|
3101
|
+
const matchedLead = matchedDiscounts.length ? codeToLead[matchedDiscounts[0].code] : null;
|
|
3102
|
+
const discount = matchedDiscounts.length ? {
|
|
3103
|
+
amount: matchedDiscounts.reduce((sum, entry) => sum + entry.amount, 0),
|
|
3104
|
+
codes: matchedDiscounts
|
|
3105
|
+
} : null;
|
|
3106
|
+
const matchedCodes = new Set(matchedDiscounts.map((entry) => entry.code));
|
|
3107
|
+
const unmatched = codes.filter((code2) => code2.startsWith("DB-") && !matchedCodes.has(code2));
|
|
3108
|
+
if (unmatched.length) {
|
|
3109
|
+
(_a = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _a.call(logger2, "shopify.order.discount.unmatched", {
|
|
3110
|
+
campaign: campaign || null,
|
|
3111
|
+
codes: JSON.stringify(unmatched),
|
|
3112
|
+
isConversion: !!campaign,
|
|
3113
|
+
orderId: String(orderId),
|
|
3114
|
+
organization: organization2
|
|
3115
|
+
});
|
|
3116
|
+
}
|
|
3117
|
+
if (!campaign && !discount || backfill && !discount) {
|
|
3118
|
+
return {
|
|
3119
|
+
message: backfill ? "Order already recorded and no Drawbridge discount code matched \u2014 nothing to backfill." : "Order has no Drawbridge attribution \u2014 not recording.",
|
|
3120
|
+
request: request2,
|
|
3121
|
+
response: { skipped: true },
|
|
3122
|
+
skipped: true
|
|
3123
|
+
};
|
|
3124
|
+
}
|
|
3125
|
+
let advertisementId = null;
|
|
3126
|
+
let affiliateId = null;
|
|
3127
|
+
let campaignOrganization = organization2;
|
|
3128
|
+
let gross = 0;
|
|
3129
|
+
let leadId = null;
|
|
3130
|
+
let lines = [];
|
|
3131
|
+
let orderCampaign = null;
|
|
3132
|
+
let pageId = null;
|
|
3133
|
+
const isConversion = !!campaign;
|
|
3134
|
+
const customerPhone = toE164((orderCustomer == null ? void 0 : orderCustomer.phone) || phone) || null;
|
|
3135
|
+
const matchPhones = [...new Set([
|
|
3136
|
+
customerPhone,
|
|
3137
|
+
toE164((_b = context == null ? void 0 : context.billing_address) == null ? void 0 : _b.phone),
|
|
3138
|
+
toE164((_c = context == null ? void 0 : context.shipping_address) == null ? void 0 : _c.phone)
|
|
3139
|
+
].filter(Boolean))];
|
|
3140
|
+
if (isConversion) {
|
|
3141
|
+
const campaignDoc = await read.get({ collection: "campaign", query: { id: campaign } });
|
|
3142
|
+
if (!campaignDoc || campaignDoc.organization !== organization2) {
|
|
3143
|
+
return {
|
|
3144
|
+
message: "Order carried a campaign attribution that does not belong to this store \u2014 not recording.",
|
|
3145
|
+
request: request2,
|
|
3146
|
+
response: { skipped: true },
|
|
3147
|
+
skipped: true
|
|
3148
|
+
};
|
|
3149
|
+
}
|
|
3150
|
+
advertisementId = attrMap["_drwbrdg_ad"] || advertisement || null;
|
|
3151
|
+
affiliateId = attrMap["_drwbrdg_af"] || null;
|
|
3152
|
+
campaignOrganization = campaignDoc.organization;
|
|
3153
|
+
gross = attributedGross;
|
|
3154
|
+
lines = attributedLines;
|
|
3155
|
+
orderCampaign = campaign;
|
|
3156
|
+
pageId = attrMap["_drwbrdg_pg"] || null;
|
|
3157
|
+
const identifiers = [];
|
|
3158
|
+
const canonicalEmail = toCanonicalEmail(email);
|
|
3159
|
+
if (email) identifiers.push({ email: email.toLowerCase() });
|
|
3160
|
+
if (canonicalEmail) identifiers.push({ "canonical.email.value": canonicalEmail });
|
|
3161
|
+
if (matchPhones.length) identifiers.push({ "phone.number": { $in: matchPhones } });
|
|
3162
|
+
if (matchPhones.length) identifiers.push({ "canonical.phone.value": { $in: matchPhones } });
|
|
3163
|
+
if (identifiers.length) {
|
|
3164
|
+
const lead = await read.get({
|
|
3165
|
+
collection: "lead",
|
|
3166
|
+
query: {
|
|
3167
|
+
campaigns: { $in: [campaign] },
|
|
3168
|
+
organization: campaignOrganization,
|
|
3169
|
+
$or: identifiers
|
|
3170
|
+
}
|
|
3171
|
+
});
|
|
3172
|
+
leadId = (lead == null ? void 0 : lead.id) || null;
|
|
3173
|
+
if (!leadId) {
|
|
3174
|
+
const orgLead = await read.get({
|
|
3175
|
+
collection: "lead",
|
|
3176
|
+
query: { organization: campaignOrganization, $or: identifiers }
|
|
3177
|
+
});
|
|
3178
|
+
leadId = (orgLead == null ? void 0 : orgLead.id) || null;
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
} else {
|
|
3182
|
+
leadId = matchedLead.id;
|
|
3183
|
+
orderCampaign = (matchedLead.campaigns || []).length === 1 ? matchedLead.campaigns[0] : null;
|
|
3184
|
+
gross = lineItems.reduce((sum, item) => {
|
|
3185
|
+
const line = toLine(item);
|
|
3186
|
+
return sum + line.price * line.quantity;
|
|
3187
|
+
}, 0);
|
|
3188
|
+
lines = lineItems.map(toLine);
|
|
3189
|
+
}
|
|
3190
|
+
const org = await read.get({ collection: "organization", query: { id: campaignOrganization } });
|
|
3191
|
+
let rate = 0;
|
|
3192
|
+
if (isConversion) {
|
|
3193
|
+
const subscription = await read.get({ collection: "subscription", query: { id: org == null ? void 0 : org.subscription } });
|
|
3194
|
+
rate = conversionRate(subscription);
|
|
3195
|
+
}
|
|
3196
|
+
const fee = isConversion ? Math.round(gross * rate) / 100 : 0;
|
|
3197
|
+
const net2 = Math.round((gross - fee) * 100) / 100;
|
|
3198
|
+
const currencyCode = (currency || "usd").toLowerCase();
|
|
3199
|
+
const purchasedAt = new Date(createdAt || Date.now());
|
|
3200
|
+
const customer = orderCustomer || email || phone ? {
|
|
3201
|
+
acceptsMarketing: ((_d = orderCustomer == null ? void 0 : orderCustomer.email_marketing_consent) == null ? void 0 : _d.state) ? orderCustomer.email_marketing_consent.state === "subscribed" : typeof (orderCustomer == null ? void 0 : orderCustomer.accepts_marketing) === "boolean" ? orderCustomer.accepts_marketing : null,
|
|
3202
|
+
email: (orderCustomer == null ? void 0 : orderCustomer.email) || email || null,
|
|
3203
|
+
firstName: (orderCustomer == null ? void 0 : orderCustomer.first_name) || null,
|
|
3204
|
+
id: (orderCustomer == null ? void 0 : orderCustomer.id) ? String(orderCustomer.id) : null,
|
|
3205
|
+
lastName: (orderCustomer == null ? void 0 : orderCustomer.last_name) || null,
|
|
3206
|
+
phone: customerPhone
|
|
3207
|
+
} : null;
|
|
3208
|
+
const source = (connection2 == null ? void 0 : connection2.source) ? { domain: connection2.source.domain, id: connection2.source.id } : void 0;
|
|
3209
|
+
const orderDocId = (existingOrder == null ? void 0 : existingOrder.id) || (isConversion && !backfill ? mintId() : null);
|
|
3210
|
+
const writes = [];
|
|
3211
|
+
if (isConversion && !backfill) {
|
|
3212
|
+
writes.push({
|
|
3213
|
+
collection: "order",
|
|
3214
|
+
data: {
|
|
3215
|
+
advertisement: advertisementId,
|
|
3216
|
+
affiliate: affiliateId,
|
|
3217
|
+
campaign: orderCampaign,
|
|
3218
|
+
currency: currencyCode,
|
|
3219
|
+
customer,
|
|
3220
|
+
discount,
|
|
3221
|
+
fee,
|
|
3222
|
+
gross,
|
|
3223
|
+
id: orderDocId,
|
|
3224
|
+
lead: leadId,
|
|
3225
|
+
lines,
|
|
3226
|
+
net: net2,
|
|
3227
|
+
organization: campaignOrganization,
|
|
3228
|
+
page: pageId,
|
|
3229
|
+
provider: { id: String(orderId), slug: "shopify" },
|
|
3230
|
+
purchasedAt,
|
|
3231
|
+
rate,
|
|
3232
|
+
source,
|
|
3233
|
+
status: "completed"
|
|
3234
|
+
},
|
|
3235
|
+
operation: "create"
|
|
3236
|
+
});
|
|
3237
|
+
if (org == null ? void 0 : org.usage) {
|
|
3238
|
+
writes.push({
|
|
3239
|
+
collection: "usage",
|
|
3240
|
+
data: { $inc: { "totals.revenue": gross } },
|
|
3241
|
+
operation: "update",
|
|
3242
|
+
query: { id: org.usage }
|
|
3243
|
+
});
|
|
3244
|
+
}
|
|
3245
|
+
if (leadId) {
|
|
3246
|
+
writes.push({
|
|
3247
|
+
collection: "lead",
|
|
3248
|
+
data: { $inc: { "totals.orders": 1 } },
|
|
3249
|
+
operation: "update",
|
|
3250
|
+
options: { bypassDocumentValidation: true },
|
|
3251
|
+
query: { id: leadId }
|
|
3252
|
+
});
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
if (discount) {
|
|
3256
|
+
writes.push({
|
|
3257
|
+
collection: "redemption",
|
|
3258
|
+
data: {
|
|
3259
|
+
advertisement: advertisementId,
|
|
3260
|
+
affiliate: affiliateId,
|
|
3261
|
+
campaign: orderCampaign,
|
|
3262
|
+
code: ((_e = matchedDiscounts[0]) == null ? void 0 : _e.code) || null,
|
|
3263
|
+
currency: currencyCode,
|
|
3264
|
+
customer,
|
|
3265
|
+
discount,
|
|
3266
|
+
gross,
|
|
3267
|
+
lead: leadId,
|
|
3268
|
+
order: orderDocId,
|
|
3269
|
+
organization: campaignOrganization,
|
|
3270
|
+
page: pageId,
|
|
3271
|
+
provider: { id: String(orderId), slug: "shopify" },
|
|
3272
|
+
purchasedAt,
|
|
3273
|
+
source,
|
|
3274
|
+
status: "completed"
|
|
3275
|
+
},
|
|
3276
|
+
operation: "create"
|
|
3277
|
+
});
|
|
3278
|
+
if (org == null ? void 0 : org.usage) {
|
|
3279
|
+
writes.push({
|
|
3280
|
+
collection: "usage",
|
|
3281
|
+
data: { $inc: { "totals.redemptions": 1 } },
|
|
3282
|
+
operation: "update",
|
|
3283
|
+
query: { id: org.usage }
|
|
3284
|
+
});
|
|
3285
|
+
}
|
|
3286
|
+
if (leadId) {
|
|
3287
|
+
writes.push({
|
|
3288
|
+
collection: "lead",
|
|
3289
|
+
data: { $inc: { "totals.redemptions": 1 } },
|
|
3290
|
+
operation: "update",
|
|
3291
|
+
options: { bypassDocumentValidation: true },
|
|
3292
|
+
query: { id: leadId }
|
|
3293
|
+
});
|
|
3294
|
+
}
|
|
3295
|
+
}
|
|
3296
|
+
const enqueues = (org == null ? void 0 : org.billingProvider) === "shopify" && fee > 0 && ((_f = connection2 == null ? void 0 : connection2.source) == null ? void 0 : _f.id) && !backfill ? [{
|
|
3297
|
+
data: {
|
|
3298
|
+
idempotencyKey: String(orderId),
|
|
3299
|
+
orderDocId,
|
|
3300
|
+
orderId: String(orderId),
|
|
3301
|
+
rate,
|
|
3302
|
+
shopId: connection2.source.id,
|
|
3303
|
+
// The App Events API returns no event id, so one is generated
|
|
3304
|
+
// here — the event handle plus the order id — and sent as the
|
|
3305
|
+
// event's `reference`. queue/usage.js stamps the same id onto
|
|
3306
|
+
// the order as billed.transaction.
|
|
3307
|
+
transaction: "drawbridge-orders." + orderId,
|
|
3308
|
+
value: Math.round(fee * 100)
|
|
3309
|
+
},
|
|
3310
|
+
name: "billing",
|
|
3311
|
+
options: { jobId: "shopify.usage." + orderId },
|
|
3312
|
+
queue: "usage"
|
|
3313
|
+
}] : [];
|
|
3314
|
+
return {
|
|
3315
|
+
enqueues,
|
|
3316
|
+
message: backfill ? "Redemption backfilled for an already-recorded order." : isConversion ? "Order recorded." : "Discount redemption recorded (fee-free).",
|
|
3317
|
+
request: request2,
|
|
3318
|
+
response: {
|
|
3319
|
+
campaign: orderCampaign,
|
|
3320
|
+
currency: currencyCode,
|
|
3321
|
+
discount,
|
|
3322
|
+
fee,
|
|
3323
|
+
gross,
|
|
3324
|
+
lead: leadId,
|
|
3325
|
+
lines: lines.length,
|
|
3326
|
+
net: net2,
|
|
3327
|
+
orderId: String(orderId)
|
|
3328
|
+
},
|
|
3329
|
+
// ONE TRANSACTION. The order, the redemption and both totals
|
|
3330
|
+
// counters land together or not at all — a half-written attribution
|
|
3331
|
+
// is revenue counted twice or not at all, and neither is
|
|
3332
|
+
// recoverable by hand.
|
|
3333
|
+
transaction: writes.length > 0,
|
|
3334
|
+
writes
|
|
3335
|
+
};
|
|
3336
|
+
},
|
|
3337
|
+
// A PRODUCT CHANGED AT THE STORE. Upserts the product row and hands it to
|
|
3338
|
+
// the product pipeline; the actual field sync happens there.
|
|
3339
|
+
//
|
|
3340
|
+
// The shell has already refused a missing or inactive Shopify connection,
|
|
3341
|
+
// so what is left is the two things only this hook can know are wrong.
|
|
3342
|
+
product: async ({ connection: connection2, context, workflow }, { mintId } = {}) => {
|
|
3343
|
+
const request2 = {
|
|
3344
|
+
numericId: (context == null ? void 0 : context.id) || null,
|
|
3345
|
+
organizationId: workflow.organization,
|
|
3346
|
+
title: (context == null ? void 0 : context.title) || null
|
|
3347
|
+
};
|
|
3348
|
+
if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
|
|
3349
|
+
if (!connection2.shop) return { message: "Skipped \u2014 Shopify connection is missing shop domain.", request: request2, response: { skipped: true }, skipped: true };
|
|
3350
|
+
const providerId = "gid://shopify/Product/" + context.id;
|
|
3351
|
+
const productId = mintId();
|
|
3352
|
+
return {
|
|
3353
|
+
enqueues: [{
|
|
3354
|
+
data: { product: productId, providerId, shop: connection2.shop },
|
|
3355
|
+
name: "workflow",
|
|
3356
|
+
options: { jobId: "product.workflow.shopify." + providerId + "." + Date.now() },
|
|
3357
|
+
queue: "product.shopify"
|
|
3358
|
+
}],
|
|
3359
|
+
message: "Product sync queued from Shopify webhook.",
|
|
3360
|
+
request: request2,
|
|
3361
|
+
response: { productId, providerId, title: (context == null ? void 0 : context.title) || null },
|
|
3362
|
+
// KEYED ON PROVIDER + SHOP, so the same product in two stores stays
|
|
3363
|
+
// two rows. `connections` accumulates rather than replaces: one
|
|
3364
|
+
// store can be linked to several organizations, and each keeps its
|
|
3365
|
+
// own claim on the row.
|
|
3366
|
+
writes: [{
|
|
3367
|
+
collection: "product",
|
|
3368
|
+
data: {
|
|
3369
|
+
$addToSet: { connections: connection2.id },
|
|
3370
|
+
$setOnInsert: {
|
|
3371
|
+
id: productId,
|
|
3372
|
+
provider: { id: providerId, slug: "shopify" },
|
|
3373
|
+
"source.id": connection2.id,
|
|
3374
|
+
status: "active"
|
|
3375
|
+
}
|
|
3376
|
+
},
|
|
3377
|
+
operation: "update",
|
|
3378
|
+
options: { upsert: true },
|
|
3379
|
+
query: {
|
|
3380
|
+
"provider.id": providerId,
|
|
3381
|
+
"provider.slug": "shopify",
|
|
3382
|
+
"source.domain": connection2.shop
|
|
3383
|
+
}
|
|
3384
|
+
}]
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
2400
3387
|
},
|
|
2401
3388
|
contacts: { remove: false, sync: false },
|
|
2402
3389
|
// verify and event lean entirely on the shared HMAC helper — Shopify's
|
|
@@ -2414,7 +3401,16 @@ var shopify_default2 = {
|
|
|
2414
3401
|
sms: false,
|
|
2415
3402
|
inbound: {
|
|
2416
3403
|
event: (args) => readEventHeader({ ...args, descriptor: inbound }),
|
|
2417
|
-
|
|
3404
|
+
// One hook over the whole topic table, because that is what this
|
|
3405
|
+
// manifest declares: Shopify processes its own buffered events. The
|
|
3406
|
+
// topic rides in on the context rather than being a second hook name per
|
|
3407
|
+
// topic; the caller's handler table arrives as a prop.
|
|
3408
|
+
process: async ({ context }, { dispatch } = {}) => {
|
|
3409
|
+
const key = "shopify." + (context == null ? void 0 : context.topic);
|
|
3410
|
+
const handled = await dispatch({ data: context == null ? void 0 : context.data, handler: key });
|
|
3411
|
+
if (!handled) return { message: "No handler for " + key, skipped: true };
|
|
3412
|
+
return { message: "Processed " + key, request: { topic: context == null ? void 0 : context.topic } };
|
|
3413
|
+
},
|
|
2418
3414
|
receive: ({ channel, event, headers, payload }) => {
|
|
2419
3415
|
if (channel === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
|
|
2420
3416
|
throw Object.assign(new Error("Unrecognized compliance topic: " + event), { status: 401 });
|
|
@@ -2430,7 +3426,107 @@ var shopify_default2 = {
|
|
|
2430
3426
|
},
|
|
2431
3427
|
verify: (args) => verifySignature({ ...args, descriptor: inbound })
|
|
2432
3428
|
},
|
|
2433
|
-
lifecycle: {
|
|
3429
|
+
lifecycle: {
|
|
3430
|
+
// DISPATCHES INTO THE CALLER'S OWN COORDINATORS. These three are
|
|
3431
|
+
// declarations made true: the work is queue orchestration over
|
|
3432
|
+
// Drawbridge's own collections, which is coordinator work and stays in
|
|
3433
|
+
// the repo that owns the queues. The hook receives the dispatch table as
|
|
3434
|
+
// a prop and picks the entry, so the manifest owns the SEAM — asking
|
|
3435
|
+
// Shopify whether it handles its own lifecycle now gets a real function
|
|
3436
|
+
// instead of `unimplemented` while the work happened anyway.
|
|
3437
|
+
cleanup: async ({ context }, { dispatch } = {}) => {
|
|
3438
|
+
await dispatch({ data: context, handler: "cleanup" });
|
|
3439
|
+
return { message: "Ran shopify lifecycle.cleanup", request: context || null };
|
|
3440
|
+
},
|
|
3441
|
+
// KEEP STORE ACCESS WORKING. Not a webhook monitor, despite the name the
|
|
3442
|
+
// step once carried — webhooks are declarative, declared in the app's
|
|
3443
|
+
// toml and applied by Shopify to every install, so nothing here registers
|
|
3444
|
+
// or checks them.
|
|
3445
|
+
//
|
|
3446
|
+
// It rotates the refresh token before its window closes, proves the
|
|
3447
|
+
// access token still works, reconciles the scopes the store granted
|
|
3448
|
+
// against the ones the app now needs, and queues a webhook
|
|
3449
|
+
// reconciliation.
|
|
3450
|
+
health: async ({ connection: connection2, workflow }, { adminToken, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
|
|
3451
|
+
const request2 = {
|
|
3452
|
+
connectionId: workflow.connection,
|
|
3453
|
+
organizationId: workflow.organization,
|
|
3454
|
+
shop: connection2.shop
|
|
3455
|
+
};
|
|
3456
|
+
const refreshTokenAtStart = (await resolveSettings()).refreshToken || null;
|
|
3457
|
+
try {
|
|
3458
|
+
const adminAccessToken = await adminToken();
|
|
3459
|
+
const settings = await resolveSettings();
|
|
3460
|
+
const refreshTokenExpiresAt = settings.refreshTokenExpiresAt;
|
|
3461
|
+
const needsRotation = refreshTokenExpiresAt && new Date(refreshTokenExpiresAt) < new Date(Date.now() + REFRESH_TOKEN_FRESHNESS_BUFFER_MS);
|
|
3462
|
+
let refreshTokenRotated = false;
|
|
3463
|
+
if (needsRotation) {
|
|
3464
|
+
await rotateToken();
|
|
3465
|
+
refreshTokenRotated = true;
|
|
3466
|
+
}
|
|
3467
|
+
await shopify.oauth.ping({ adminAccessToken, domain: connection2.shop });
|
|
3468
|
+
const scopesMissing = await reconcileScopes({ shop: connection2.shop });
|
|
3469
|
+
return {
|
|
3470
|
+
enqueues: [{
|
|
3471
|
+
data: {
|
|
3472
|
+
data: {
|
|
3473
|
+
connectionId: workflow.connection,
|
|
3474
|
+
organizationId: workflow.organization
|
|
3475
|
+
},
|
|
3476
|
+
event: "shopify.register.webhooks"
|
|
3477
|
+
},
|
|
3478
|
+
name: "register",
|
|
3479
|
+
options: { jobId: "connection.update.register." + workflow.connection + "." + randomUUID() },
|
|
3480
|
+
queue: "connection"
|
|
3481
|
+
}],
|
|
3482
|
+
message: (scopesMissing == null ? void 0 : scopesMissing.length) ? "Health check: ping ok, webhooks reconciled \u2014 connection errored, granted scopes are missing: " + scopesMissing.join(", ") + "." : refreshTokenRotated ? "Health check passed \u2014 refresh token rotated, ping ok, webhooks reconciled." : "Health check passed \u2014 ping ok, webhooks reconciled.",
|
|
3483
|
+
request: request2,
|
|
3484
|
+
response: {
|
|
3485
|
+
pingedAt: /* @__PURE__ */ new Date(),
|
|
3486
|
+
refreshTokenExpiresAt: refreshTokenExpiresAt || null,
|
|
3487
|
+
refreshTokenRotated,
|
|
3488
|
+
scopesMissing,
|
|
3489
|
+
webhookReconciliationQueued: true
|
|
3490
|
+
}
|
|
3491
|
+
};
|
|
3492
|
+
} catch (error) {
|
|
3493
|
+
if (OAUTH_GRANT_REVOKED_CODES.includes(error.code)) {
|
|
3494
|
+
const current = await read.get({ collection: "connection", query: { id: connection2.id } });
|
|
3495
|
+
const refreshTokenStored = current ? (await resolveSettings(current)).refreshToken || null : null;
|
|
3496
|
+
const rotated = error.code === "invalid_grant" && refreshTokenStored !== refreshTokenAtStart;
|
|
3497
|
+
if (current && !rotated) {
|
|
3498
|
+
const others = (current.errors || []).filter((entry) => entry.source !== OAUTH_ERROR_SOURCE);
|
|
3499
|
+
error.writes = [{
|
|
3500
|
+
collection: "connection",
|
|
3501
|
+
data: {
|
|
3502
|
+
$set: {
|
|
3503
|
+
errors: [
|
|
3504
|
+
...others,
|
|
3505
|
+
{
|
|
3506
|
+
message: "Shopify disconnected this store. Open the Drawbridge app in your Shopify admin to reconnect.",
|
|
3507
|
+
source: OAUTH_ERROR_SOURCE
|
|
3508
|
+
}
|
|
3509
|
+
],
|
|
3510
|
+
status: "error"
|
|
3511
|
+
}
|
|
3512
|
+
},
|
|
3513
|
+
operation: "update",
|
|
3514
|
+
query: { id: connection2.id }
|
|
3515
|
+
}];
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
throw error;
|
|
3519
|
+
}
|
|
3520
|
+
},
|
|
3521
|
+
register: async ({ context }, { dispatch } = {}) => {
|
|
3522
|
+
await dispatch({ data: context, handler: "register" });
|
|
3523
|
+
return { message: "Ran shopify lifecycle.register", request: context || null };
|
|
3524
|
+
},
|
|
3525
|
+
rehydrate: async ({ context }, { dispatch } = {}) => {
|
|
3526
|
+
await dispatch({ data: context, handler: "rehydrate" });
|
|
3527
|
+
return { message: "Ran shopify lifecycle.rehydrate", request: context || null };
|
|
3528
|
+
}
|
|
3529
|
+
},
|
|
2434
3530
|
resources: {
|
|
2435
3531
|
audiences: false,
|
|
2436
3532
|
// Shopify has no separate price resource — a price belongs to a product
|
|
@@ -2450,7 +3546,7 @@ var shopify_default2 = {
|
|
|
2450
3546
|
// credential is the caller's job because it is Drawbridge's job: the
|
|
2451
3547
|
// admin token refreshes and writes itself back, which is service work,
|
|
2452
3548
|
// not vendor work.
|
|
2453
|
-
products: async ({ cursor, limit = 100, search, settings,
|
|
3549
|
+
products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
|
|
2454
3550
|
var _a, _b, _c, _d;
|
|
2455
3551
|
const products = await shopify.storefront.getProducts({
|
|
2456
3552
|
cursor,
|
|
@@ -2470,7 +3566,7 @@ var shopify_default2 = {
|
|
|
2470
3566
|
}
|
|
2471
3567
|
};
|
|
2472
3568
|
},
|
|
2473
|
-
promotions: async ({ cursor, limit = 100, search, settings, shopify }) => {
|
|
3569
|
+
promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
|
|
2474
3570
|
var _a, _b;
|
|
2475
3571
|
const discounts = await shopify.admin.getDiscounts({
|
|
2476
3572
|
adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
|
|
@@ -2549,9 +3645,6 @@ var shopify_default2 = {
|
|
|
2549
3645
|
// workflow document, and those strings cannot be renamed without a backfill.
|
|
2550
3646
|
//
|
|
2551
3647
|
// EVERY LEAF IS A FUNCTION so a step can read the merchant's own connection.
|
|
2552
|
-
// The bodies these point at still live in drawbridge-sync; moving them is the
|
|
2553
|
-
// next unit, and commerce.order.record is the one that decides whether the
|
|
2554
|
-
// shape holds — 569 lines and 15 controller calls.
|
|
2555
3648
|
steps: {
|
|
2556
3649
|
commerce: {
|
|
2557
3650
|
code: {
|
|
@@ -2656,7 +3749,7 @@ var shopify_default2 = {
|
|
|
2656
3749
|
title: "Shopify"
|
|
2657
3750
|
};
|
|
2658
3751
|
|
|
2659
|
-
// lib/connections/webhook.js
|
|
3752
|
+
// lib/connections/providers/webhook.js
|
|
2660
3753
|
import crypto from "crypto";
|
|
2661
3754
|
|
|
2662
3755
|
// lib/safe-http.js
|
|
@@ -2794,7 +3887,7 @@ var safeRequest = async ({
|
|
|
2794
3887
|
}
|
|
2795
3888
|
};
|
|
2796
3889
|
|
|
2797
|
-
// lib/connections/webhook.js
|
|
3890
|
+
// lib/connections/providers/webhook.js
|
|
2798
3891
|
var webhook_default = {
|
|
2799
3892
|
// Connecting GENERATES the secret rather than storing one the merchant typed,
|
|
2800
3893
|
// so the buttons say what actually happens.
|
|
@@ -2881,11 +3974,10 @@ var webhook_default = {
|
|
|
2881
3974
|
// That is the rule the whole split runs on: a hook lives in sync only if it
|
|
2882
3975
|
// needs Drawbridge's own database, sockets or queues. This one does not.
|
|
2883
3976
|
webhook: {
|
|
2884
|
-
send: async ({ context,
|
|
3977
|
+
send: async ({ context, lead, settings, step }, { request: send2 = safeRequest } = {}) => {
|
|
2885
3978
|
const { headers = {}, method = "POST", url } = step.settings || {};
|
|
2886
3979
|
const request2 = { method, url: url || null };
|
|
2887
3980
|
if (!url) return { message: "Outgoing webhook URL is not configured for this step.", request: request2, response: { skipped: true }, skipped: true };
|
|
2888
|
-
const lead = (context == null ? void 0 : context.lead) ? await controller.get({ collection: "lead", query: { id: context.lead } }) : null;
|
|
2889
3981
|
const body = lead || context;
|
|
2890
3982
|
request2.body = body;
|
|
2891
3983
|
const outgoing = { ...headers };
|
|
@@ -3156,10 +4248,13 @@ var connectFields = (slug) => {
|
|
|
3156
4248
|
secret: Boolean(redact)
|
|
3157
4249
|
}));
|
|
3158
4250
|
};
|
|
3159
|
-
var runHook = async (slug, name,
|
|
4251
|
+
var runHook = async (slug, name, props = {}, options = {}) => {
|
|
3160
4252
|
const manifest = connections[slug];
|
|
3161
4253
|
if (!manifest) return { outcome: OUTCOMES.unsupported, reason: "no such connection: " + slug };
|
|
3162
|
-
const hook = name.split(".").reduce(
|
|
4254
|
+
const hook = name.split(".").reduce(
|
|
4255
|
+
(node, key) => node && typeof node === "object" && Object.hasOwn(node, key) ? node[key] : void 0,
|
|
4256
|
+
manifest.hooks
|
|
4257
|
+
);
|
|
3163
4258
|
if (hook === false || hook == null) {
|
|
3164
4259
|
return { outcome: OUTCOMES.unsupported, reason: slug + " does not implement " + name };
|
|
3165
4260
|
}
|
|
@@ -3167,7 +4262,9 @@ var runHook = async (slug, name, args = {}) => {
|
|
|
3167
4262
|
return { outcome: OUTCOMES.unimplemented, reason: slug + " implements " + name + " outside this package" };
|
|
3168
4263
|
}
|
|
3169
4264
|
try {
|
|
3170
|
-
|
|
4265
|
+
const result = await hook({ ...props, manifest }, options);
|
|
4266
|
+
effectsOf(result);
|
|
4267
|
+
return { outcome: OUTCOMES.answered, result };
|
|
3171
4268
|
} catch (error) {
|
|
3172
4269
|
return { error: (error == null ? void 0 : error.message) || "failed", outcome: OUTCOMES.failed, status: (error == null ? void 0 : error.status) || null };
|
|
3173
4270
|
}
|
|
@@ -3261,7 +4358,10 @@ export {
|
|
|
3261
4358
|
AUTH_TYPES,
|
|
3262
4359
|
GROUPS,
|
|
3263
4360
|
HOOKS,
|
|
4361
|
+
HOOK_EFFECTS,
|
|
3264
4362
|
HOOK_NAMES,
|
|
4363
|
+
HOOK_OPTIONS,
|
|
4364
|
+
HOOK_PROPS,
|
|
3265
4365
|
INPUTS,
|
|
3266
4366
|
OAUTH_FIELDS,
|
|
3267
4367
|
OUTCOMES,
|
|
@@ -3269,6 +4369,7 @@ export {
|
|
|
3269
4369
|
STATUSES,
|
|
3270
4370
|
STEPS,
|
|
3271
4371
|
STEP_TYPES,
|
|
4372
|
+
WRITE_OPERATIONS,
|
|
3272
4373
|
accessToken,
|
|
3273
4374
|
authToken,
|
|
3274
4375
|
availableConnections,
|
|
@@ -3278,6 +4379,7 @@ export {
|
|
|
3278
4379
|
connectionSteps,
|
|
3279
4380
|
connections,
|
|
3280
4381
|
consentUrl,
|
|
4382
|
+
effectsOf,
|
|
3281
4383
|
hookSupport,
|
|
3282
4384
|
isStale,
|
|
3283
4385
|
mergeSettings,
|