stripe-experiment-sync 1.0.3 → 1.0.7
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/README.md +25 -4
- package/dist/chunk-3P5TZKWU.js +595 -0
- package/dist/chunk-7JWRDXNB.js +3264 -0
- package/dist/chunk-SX3HLE4H.js +406 -0
- package/dist/{chunk-SNGEJHKN.js → chunk-YXQZXR7S.js} +18 -6
- package/dist/cli/index.cjs +4376 -0
- package/dist/cli/index.d.cts +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +55 -0
- package/dist/cli/lib.cjs +4359 -0
- package/dist/cli/lib.d.cts +70 -0
- package/dist/cli/lib.d.ts +70 -0
- package/dist/cli/lib.js +21 -0
- package/dist/index.cjs +48 -36
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +7 -3255
- package/dist/migrations/0057_rename_sync_tables.sql +57 -0
- package/dist/supabase/index.cjs +98 -50
- package/dist/supabase/index.d.cts +12 -4
- package/dist/supabase/index.d.ts +12 -4
- package/dist/supabase/index.js +18 -367
- package/package.json +18 -6
package/dist/cli/lib.cjs
ADDED
|
@@ -0,0 +1,4359 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/cli/lib.ts
|
|
31
|
+
var lib_exports = {};
|
|
32
|
+
__export(lib_exports, {
|
|
33
|
+
backfillCommand: () => backfillCommand,
|
|
34
|
+
createTunnel: () => createTunnel,
|
|
35
|
+
installCommand: () => installCommand,
|
|
36
|
+
loadConfig: () => loadConfig,
|
|
37
|
+
migrateCommand: () => migrateCommand,
|
|
38
|
+
syncCommand: () => syncCommand,
|
|
39
|
+
uninstallCommand: () => uninstallCommand
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(lib_exports);
|
|
42
|
+
|
|
43
|
+
// ../../node_modules/.pnpm/tsup@8.5.0_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js
|
|
44
|
+
var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
|
|
45
|
+
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
46
|
+
|
|
47
|
+
// src/cli/commands.ts
|
|
48
|
+
var import_chalk3 = __toESM(require("chalk"), 1);
|
|
49
|
+
var import_express = __toESM(require("express"), 1);
|
|
50
|
+
var import_dotenv2 = __toESM(require("dotenv"), 1);
|
|
51
|
+
|
|
52
|
+
// src/cli/config.ts
|
|
53
|
+
var import_dotenv = __toESM(require("dotenv"), 1);
|
|
54
|
+
var import_inquirer = __toESM(require("inquirer"), 1);
|
|
55
|
+
var import_chalk = __toESM(require("chalk"), 1);
|
|
56
|
+
async function loadConfig(options) {
|
|
57
|
+
import_dotenv.default.config();
|
|
58
|
+
const config = {};
|
|
59
|
+
config.stripeApiKey = options.stripeKey || process.env.STRIPE_API_KEY || "";
|
|
60
|
+
config.ngrokAuthToken = options.ngrokToken || process.env.NGROK_AUTH_TOKEN || "";
|
|
61
|
+
config.databaseUrl = options.databaseUrl || process.env.DATABASE_URL || "";
|
|
62
|
+
const questions = [];
|
|
63
|
+
if (!config.stripeApiKey) {
|
|
64
|
+
questions.push({
|
|
65
|
+
type: "password",
|
|
66
|
+
name: "stripeApiKey",
|
|
67
|
+
message: "Enter your Stripe API key:",
|
|
68
|
+
mask: "*",
|
|
69
|
+
validate: (input) => {
|
|
70
|
+
if (!input || input.trim() === "") {
|
|
71
|
+
return "Stripe API key is required";
|
|
72
|
+
}
|
|
73
|
+
if (!input.startsWith("sk_")) {
|
|
74
|
+
return 'Stripe API key should start with "sk_"';
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (!config.ngrokAuthToken) {
|
|
81
|
+
questions.push({
|
|
82
|
+
type: "password",
|
|
83
|
+
name: "ngrokAuthToken",
|
|
84
|
+
message: "Enter your ngrok auth token:",
|
|
85
|
+
mask: "*",
|
|
86
|
+
validate: (input) => {
|
|
87
|
+
if (!input || input.trim() === "") {
|
|
88
|
+
return "Ngrok auth token is required";
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
if (!config.databaseUrl) {
|
|
95
|
+
questions.push({
|
|
96
|
+
type: "password",
|
|
97
|
+
name: "databaseUrl",
|
|
98
|
+
message: "Enter your Postgres DATABASE_URL:",
|
|
99
|
+
mask: "*",
|
|
100
|
+
validate: (input) => {
|
|
101
|
+
if (!input || input.trim() === "") {
|
|
102
|
+
return "DATABASE_URL is required";
|
|
103
|
+
}
|
|
104
|
+
if (!input.startsWith("postgres://") && !input.startsWith("postgresql://")) {
|
|
105
|
+
return 'DATABASE_URL should start with "postgres://" or "postgresql://"';
|
|
106
|
+
}
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
if (questions.length > 0) {
|
|
112
|
+
console.log(import_chalk.default.yellow("\nMissing required configuration. Please provide:"));
|
|
113
|
+
const answers = await import_inquirer.default.prompt(questions);
|
|
114
|
+
Object.assign(config, answers);
|
|
115
|
+
}
|
|
116
|
+
return config;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// package.json
|
|
120
|
+
var package_default = {
|
|
121
|
+
name: "stripe-experiment-sync",
|
|
122
|
+
version: "1.0.7",
|
|
123
|
+
private: false,
|
|
124
|
+
description: "Stripe Sync Engine to sync Stripe data to Postgres",
|
|
125
|
+
type: "module",
|
|
126
|
+
main: "./dist/index.cjs",
|
|
127
|
+
bin: "./dist/cli/index.js",
|
|
128
|
+
exports: {
|
|
129
|
+
".": {
|
|
130
|
+
types: "./dist/index.d.ts",
|
|
131
|
+
import: "./dist/index.js",
|
|
132
|
+
require: "./dist/index.cjs"
|
|
133
|
+
},
|
|
134
|
+
"./supabase": {
|
|
135
|
+
types: "./dist/supabase/index.d.ts",
|
|
136
|
+
import: "./dist/supabase/index.js",
|
|
137
|
+
require: "./dist/supabase/index.cjs"
|
|
138
|
+
},
|
|
139
|
+
"./cli": {
|
|
140
|
+
types: "./dist/cli/lib.d.ts",
|
|
141
|
+
import: "./dist/cli/lib.js",
|
|
142
|
+
require: "./dist/cli/lib.cjs"
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
scripts: {
|
|
146
|
+
clean: "rimraf dist",
|
|
147
|
+
prebuild: "npm run clean",
|
|
148
|
+
build: "tsup src/index.ts src/supabase/index.ts src/cli/index.ts src/cli/lib.ts --format esm,cjs --dts --shims && cp -r src/database/migrations dist/migrations",
|
|
149
|
+
lint: "eslint src --ext .ts",
|
|
150
|
+
test: "vitest"
|
|
151
|
+
},
|
|
152
|
+
files: [
|
|
153
|
+
"dist"
|
|
154
|
+
],
|
|
155
|
+
dependencies: {
|
|
156
|
+
"@ngrok/ngrok": "^1.4.1",
|
|
157
|
+
chalk: "^5.3.0",
|
|
158
|
+
commander: "^12.1.0",
|
|
159
|
+
dotenv: "^16.4.7",
|
|
160
|
+
express: "^4.18.2",
|
|
161
|
+
inquirer: "^12.3.0",
|
|
162
|
+
pg: "^8.16.3",
|
|
163
|
+
"pg-node-migrations": "0.0.8",
|
|
164
|
+
stripe: "^17.7.0",
|
|
165
|
+
"supabase-management-js": "^0.1.6",
|
|
166
|
+
ws: "^8.18.0",
|
|
167
|
+
yesql: "^7.0.0"
|
|
168
|
+
},
|
|
169
|
+
devDependencies: {
|
|
170
|
+
"@types/express": "^4.17.21",
|
|
171
|
+
"@types/inquirer": "^9.0.7",
|
|
172
|
+
"@types/node": "^24.10.1",
|
|
173
|
+
"@types/pg": "^8.15.5",
|
|
174
|
+
"@types/ws": "^8.5.13",
|
|
175
|
+
"@types/yesql": "^4.1.4",
|
|
176
|
+
"@vitest/ui": "^4.0.9",
|
|
177
|
+
tsx: "^4.19.2",
|
|
178
|
+
vitest: "^3.2.4"
|
|
179
|
+
},
|
|
180
|
+
repository: {
|
|
181
|
+
type: "git",
|
|
182
|
+
url: "https://github.com/tx-stripe/stripe-sync-engine.git"
|
|
183
|
+
},
|
|
184
|
+
homepage: "https://github.com/tx-stripe/stripe-sync-engine#readme",
|
|
185
|
+
bugs: {
|
|
186
|
+
url: "https://github.com/tx-stripe/stripe-sync-engine/issues"
|
|
187
|
+
},
|
|
188
|
+
keywords: [
|
|
189
|
+
"stripe",
|
|
190
|
+
"postgres",
|
|
191
|
+
"sync",
|
|
192
|
+
"webhooks",
|
|
193
|
+
"supabase",
|
|
194
|
+
"billing",
|
|
195
|
+
"database",
|
|
196
|
+
"typescript"
|
|
197
|
+
],
|
|
198
|
+
author: "Supabase <https://supabase.com/>"
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
// src/stripeSync.ts
|
|
202
|
+
var import_stripe2 = __toESM(require("stripe"), 1);
|
|
203
|
+
var import_yesql2 = require("yesql");
|
|
204
|
+
|
|
205
|
+
// src/database/postgres.ts
|
|
206
|
+
var import_pg = __toESM(require("pg"), 1);
|
|
207
|
+
var import_yesql = require("yesql");
|
|
208
|
+
var ORDERED_STRIPE_TABLES = [
|
|
209
|
+
"subscription_items",
|
|
210
|
+
"subscriptions",
|
|
211
|
+
"subscription_schedules",
|
|
212
|
+
"checkout_session_line_items",
|
|
213
|
+
"checkout_sessions",
|
|
214
|
+
"tax_ids",
|
|
215
|
+
"charges",
|
|
216
|
+
"refunds",
|
|
217
|
+
"credit_notes",
|
|
218
|
+
"disputes",
|
|
219
|
+
"early_fraud_warnings",
|
|
220
|
+
"invoices",
|
|
221
|
+
"payment_intents",
|
|
222
|
+
"payment_methods",
|
|
223
|
+
"setup_intents",
|
|
224
|
+
"prices",
|
|
225
|
+
"plans",
|
|
226
|
+
"products",
|
|
227
|
+
"features",
|
|
228
|
+
"active_entitlements",
|
|
229
|
+
"reviews",
|
|
230
|
+
"_managed_webhooks",
|
|
231
|
+
"customers",
|
|
232
|
+
"_sync_obj_runs",
|
|
233
|
+
// Must be deleted before _sync_runs (foreign key)
|
|
234
|
+
"_sync_runs"
|
|
235
|
+
];
|
|
236
|
+
var TABLES_WITH_ACCOUNT_ID = /* @__PURE__ */ new Set(["_managed_webhooks"]);
|
|
237
|
+
var PostgresClient = class {
|
|
238
|
+
constructor(config) {
|
|
239
|
+
this.config = config;
|
|
240
|
+
this.pool = new import_pg.default.Pool(config.poolConfig);
|
|
241
|
+
}
|
|
242
|
+
pool;
|
|
243
|
+
async delete(table, id) {
|
|
244
|
+
const prepared = (0, import_yesql.pg)(`
|
|
245
|
+
delete from "${this.config.schema}"."${table}"
|
|
246
|
+
where id = :id
|
|
247
|
+
returning id;
|
|
248
|
+
`)({ id });
|
|
249
|
+
const { rows } = await this.query(prepared.text, prepared.values);
|
|
250
|
+
return rows.length > 0;
|
|
251
|
+
}
|
|
252
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
253
|
+
async query(text, params) {
|
|
254
|
+
return this.pool.query(text, params);
|
|
255
|
+
}
|
|
256
|
+
async upsertMany(entries, table) {
|
|
257
|
+
if (!entries.length) return [];
|
|
258
|
+
const chunkSize = 5;
|
|
259
|
+
const results = [];
|
|
260
|
+
for (let i = 0; i < entries.length; i += chunkSize) {
|
|
261
|
+
const chunk = entries.slice(i, i + chunkSize);
|
|
262
|
+
const queries = [];
|
|
263
|
+
chunk.forEach((entry) => {
|
|
264
|
+
const rawData = JSON.stringify(entry);
|
|
265
|
+
const upsertSql = `
|
|
266
|
+
INSERT INTO "${this.config.schema}"."${table}" ("_raw_data")
|
|
267
|
+
VALUES ($1::jsonb)
|
|
268
|
+
ON CONFLICT (id)
|
|
269
|
+
DO UPDATE SET
|
|
270
|
+
"_raw_data" = EXCLUDED."_raw_data"
|
|
271
|
+
RETURNING *
|
|
272
|
+
`;
|
|
273
|
+
queries.push(this.pool.query(upsertSql, [rawData]));
|
|
274
|
+
});
|
|
275
|
+
results.push(...await Promise.all(queries));
|
|
276
|
+
}
|
|
277
|
+
return results.flatMap((it) => it.rows);
|
|
278
|
+
}
|
|
279
|
+
async upsertManyWithTimestampProtection(entries, table, accountId, syncTimestamp) {
|
|
280
|
+
const timestamp = syncTimestamp || (/* @__PURE__ */ new Date()).toISOString();
|
|
281
|
+
if (!entries.length) return [];
|
|
282
|
+
const chunkSize = 5;
|
|
283
|
+
const results = [];
|
|
284
|
+
for (let i = 0; i < entries.length; i += chunkSize) {
|
|
285
|
+
const chunk = entries.slice(i, i + chunkSize);
|
|
286
|
+
const queries = [];
|
|
287
|
+
chunk.forEach((entry) => {
|
|
288
|
+
if (table.startsWith("_")) {
|
|
289
|
+
const columns = Object.keys(entry).filter(
|
|
290
|
+
(k) => k !== "last_synced_at" && k !== "account_id"
|
|
291
|
+
);
|
|
292
|
+
const upsertSql = `
|
|
293
|
+
INSERT INTO "${this.config.schema}"."${table}" (
|
|
294
|
+
${columns.map((c) => `"${c}"`).join(", ")}, "last_synced_at", "account_id"
|
|
295
|
+
)
|
|
296
|
+
VALUES (
|
|
297
|
+
${columns.map((c) => `:${c}`).join(", ")}, :last_synced_at, :account_id
|
|
298
|
+
)
|
|
299
|
+
ON CONFLICT ("id")
|
|
300
|
+
DO UPDATE SET
|
|
301
|
+
${columns.map((c) => `"${c}" = EXCLUDED."${c}"`).join(", ")},
|
|
302
|
+
"last_synced_at" = :last_synced_at,
|
|
303
|
+
"account_id" = EXCLUDED."account_id"
|
|
304
|
+
WHERE "${table}"."last_synced_at" IS NULL
|
|
305
|
+
OR "${table}"."last_synced_at" < :last_synced_at
|
|
306
|
+
RETURNING *
|
|
307
|
+
`;
|
|
308
|
+
const cleansed = this.cleanseArrayField(entry);
|
|
309
|
+
cleansed.last_synced_at = timestamp;
|
|
310
|
+
cleansed.account_id = accountId;
|
|
311
|
+
const prepared = (0, import_yesql.pg)(upsertSql, { useNullForMissing: true })(cleansed);
|
|
312
|
+
queries.push(this.pool.query(prepared.text, prepared.values));
|
|
313
|
+
} else {
|
|
314
|
+
const rawData = JSON.stringify(entry);
|
|
315
|
+
const upsertSql = `
|
|
316
|
+
INSERT INTO "${this.config.schema}"."${table}" ("_raw_data", "_last_synced_at", "_account_id")
|
|
317
|
+
VALUES ($1::jsonb, $2, $3)
|
|
318
|
+
ON CONFLICT (id)
|
|
319
|
+
DO UPDATE SET
|
|
320
|
+
"_raw_data" = EXCLUDED."_raw_data",
|
|
321
|
+
"_last_synced_at" = $2,
|
|
322
|
+
"_account_id" = EXCLUDED."_account_id"
|
|
323
|
+
WHERE "${table}"."_last_synced_at" IS NULL
|
|
324
|
+
OR "${table}"."_last_synced_at" < $2
|
|
325
|
+
RETURNING *
|
|
326
|
+
`;
|
|
327
|
+
queries.push(this.pool.query(upsertSql, [rawData, timestamp, accountId]));
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
results.push(...await Promise.all(queries));
|
|
331
|
+
}
|
|
332
|
+
return results.flatMap((it) => it.rows);
|
|
333
|
+
}
|
|
334
|
+
cleanseArrayField(obj) {
|
|
335
|
+
const cleansed = { ...obj };
|
|
336
|
+
Object.keys(cleansed).map((k) => {
|
|
337
|
+
const data = cleansed[k];
|
|
338
|
+
if (Array.isArray(data)) {
|
|
339
|
+
cleansed[k] = JSON.stringify(data);
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
return cleansed;
|
|
343
|
+
}
|
|
344
|
+
async findMissingEntries(table, ids) {
|
|
345
|
+
if (!ids.length) return [];
|
|
346
|
+
const prepared = (0, import_yesql.pg)(`
|
|
347
|
+
select id from "${this.config.schema}"."${table}"
|
|
348
|
+
where id=any(:ids::text[]);
|
|
349
|
+
`)({ ids });
|
|
350
|
+
const { rows } = await this.query(prepared.text, prepared.values);
|
|
351
|
+
const existingIds = rows.map((it) => it.id);
|
|
352
|
+
const missingIds = ids.filter((it) => !existingIds.includes(it));
|
|
353
|
+
return missingIds;
|
|
354
|
+
}
|
|
355
|
+
// Account management methods
|
|
356
|
+
async upsertAccount(accountData, apiKeyHash) {
|
|
357
|
+
const rawData = JSON.stringify(accountData.raw_data);
|
|
358
|
+
await this.query(
|
|
359
|
+
`INSERT INTO "${this.config.schema}"."accounts" ("_raw_data", "api_key_hashes", "first_synced_at", "_last_synced_at")
|
|
360
|
+
VALUES ($1::jsonb, ARRAY[$2], now(), now())
|
|
361
|
+
ON CONFLICT (id)
|
|
362
|
+
DO UPDATE SET
|
|
363
|
+
"_raw_data" = EXCLUDED."_raw_data",
|
|
364
|
+
"api_key_hashes" = (
|
|
365
|
+
SELECT ARRAY(
|
|
366
|
+
SELECT DISTINCT unnest(
|
|
367
|
+
COALESCE("${this.config.schema}"."accounts"."api_key_hashes", '{}') || ARRAY[$2]
|
|
368
|
+
)
|
|
369
|
+
)
|
|
370
|
+
),
|
|
371
|
+
"_last_synced_at" = now(),
|
|
372
|
+
"_updated_at" = now()`,
|
|
373
|
+
[rawData, apiKeyHash]
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
377
|
+
async getAllAccounts() {
|
|
378
|
+
const result = await this.query(
|
|
379
|
+
`SELECT _raw_data FROM "${this.config.schema}"."accounts"
|
|
380
|
+
ORDER BY _last_synced_at DESC`
|
|
381
|
+
);
|
|
382
|
+
return result.rows.map((row) => row._raw_data);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Looks up an account ID by API key hash
|
|
386
|
+
* Uses the GIN index on api_key_hashes for fast lookups
|
|
387
|
+
* @param apiKeyHash - SHA-256 hash of the Stripe API key
|
|
388
|
+
* @returns Account ID if found, null otherwise
|
|
389
|
+
*/
|
|
390
|
+
async getAccountIdByApiKeyHash(apiKeyHash) {
|
|
391
|
+
const result = await this.query(
|
|
392
|
+
`SELECT id FROM "${this.config.schema}"."accounts"
|
|
393
|
+
WHERE $1 = ANY(api_key_hashes)
|
|
394
|
+
LIMIT 1`,
|
|
395
|
+
[apiKeyHash]
|
|
396
|
+
);
|
|
397
|
+
return result.rows.length > 0 ? result.rows[0].id : null;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Looks up full account data by API key hash
|
|
401
|
+
* @param apiKeyHash - SHA-256 hash of the Stripe API key
|
|
402
|
+
* @returns Account raw data if found, null otherwise
|
|
403
|
+
*/
|
|
404
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
405
|
+
async getAccountByApiKeyHash(apiKeyHash) {
|
|
406
|
+
const result = await this.query(
|
|
407
|
+
`SELECT _raw_data FROM "${this.config.schema}"."accounts"
|
|
408
|
+
WHERE $1 = ANY(api_key_hashes)
|
|
409
|
+
LIMIT 1`,
|
|
410
|
+
[apiKeyHash]
|
|
411
|
+
);
|
|
412
|
+
return result.rows.length > 0 ? result.rows[0]._raw_data : null;
|
|
413
|
+
}
|
|
414
|
+
getAccountIdColumn(table) {
|
|
415
|
+
return TABLES_WITH_ACCOUNT_ID.has(table) ? "account_id" : "_account_id";
|
|
416
|
+
}
|
|
417
|
+
async getAccountRecordCounts(accountId) {
|
|
418
|
+
const counts = {};
|
|
419
|
+
for (const table of ORDERED_STRIPE_TABLES) {
|
|
420
|
+
const accountIdColumn = this.getAccountIdColumn(table);
|
|
421
|
+
const result = await this.query(
|
|
422
|
+
`SELECT COUNT(*) as count FROM "${this.config.schema}"."${table}"
|
|
423
|
+
WHERE "${accountIdColumn}" = $1`,
|
|
424
|
+
[accountId]
|
|
425
|
+
);
|
|
426
|
+
counts[table] = parseInt(result.rows[0].count);
|
|
427
|
+
}
|
|
428
|
+
return counts;
|
|
429
|
+
}
|
|
430
|
+
async deleteAccountWithCascade(accountId, useTransaction) {
|
|
431
|
+
const deletionCounts = {};
|
|
432
|
+
try {
|
|
433
|
+
if (useTransaction) {
|
|
434
|
+
await this.query("BEGIN");
|
|
435
|
+
}
|
|
436
|
+
for (const table of ORDERED_STRIPE_TABLES) {
|
|
437
|
+
const accountIdColumn = this.getAccountIdColumn(table);
|
|
438
|
+
const result = await this.query(
|
|
439
|
+
`DELETE FROM "${this.config.schema}"."${table}"
|
|
440
|
+
WHERE "${accountIdColumn}" = $1`,
|
|
441
|
+
[accountId]
|
|
442
|
+
);
|
|
443
|
+
deletionCounts[table] = result.rowCount || 0;
|
|
444
|
+
}
|
|
445
|
+
const accountResult = await this.query(
|
|
446
|
+
`DELETE FROM "${this.config.schema}"."accounts"
|
|
447
|
+
WHERE "id" = $1`,
|
|
448
|
+
[accountId]
|
|
449
|
+
);
|
|
450
|
+
deletionCounts["accounts"] = accountResult.rowCount || 0;
|
|
451
|
+
if (useTransaction) {
|
|
452
|
+
await this.query("COMMIT");
|
|
453
|
+
}
|
|
454
|
+
} catch (error) {
|
|
455
|
+
if (useTransaction) {
|
|
456
|
+
await this.query("ROLLBACK");
|
|
457
|
+
}
|
|
458
|
+
throw error;
|
|
459
|
+
}
|
|
460
|
+
return deletionCounts;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Hash a string to a 32-bit integer for use with PostgreSQL advisory locks.
|
|
464
|
+
* Uses a simple hash algorithm that produces consistent results.
|
|
465
|
+
*/
|
|
466
|
+
hashToInt32(key) {
|
|
467
|
+
let hash = 0;
|
|
468
|
+
for (let i = 0; i < key.length; i++) {
|
|
469
|
+
const char = key.charCodeAt(i);
|
|
470
|
+
hash = (hash << 5) - hash + char;
|
|
471
|
+
hash = hash & hash;
|
|
472
|
+
}
|
|
473
|
+
return hash;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Acquire a PostgreSQL advisory lock for the given key.
|
|
477
|
+
* This lock is automatically released when the connection is closed or explicitly released.
|
|
478
|
+
* Advisory locks are session-level and will block until the lock is available.
|
|
479
|
+
*
|
|
480
|
+
* @param key - A string key to lock on (will be hashed to an integer)
|
|
481
|
+
*/
|
|
482
|
+
async acquireAdvisoryLock(key) {
|
|
483
|
+
const lockId = this.hashToInt32(key);
|
|
484
|
+
await this.query("SELECT pg_advisory_lock($1)", [lockId]);
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Release a PostgreSQL advisory lock for the given key.
|
|
488
|
+
*
|
|
489
|
+
* @param key - The same string key used to acquire the lock
|
|
490
|
+
*/
|
|
491
|
+
async releaseAdvisoryLock(key) {
|
|
492
|
+
const lockId = this.hashToInt32(key);
|
|
493
|
+
await this.query("SELECT pg_advisory_unlock($1)", [lockId]);
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Execute a function while holding an advisory lock.
|
|
497
|
+
* The lock is automatically released after the function completes (success or error).
|
|
498
|
+
*
|
|
499
|
+
* IMPORTANT: This acquires a dedicated connection from the pool and holds it for the
|
|
500
|
+
* duration of the function execution. PostgreSQL advisory locks are session-level,
|
|
501
|
+
* so we must use the same connection for lock acquisition, operations, and release.
|
|
502
|
+
*
|
|
503
|
+
* @param key - A string key to lock on (will be hashed to an integer)
|
|
504
|
+
* @param fn - The function to execute while holding the lock
|
|
505
|
+
* @returns The result of the function
|
|
506
|
+
*/
|
|
507
|
+
async withAdvisoryLock(key, fn) {
|
|
508
|
+
const lockId = this.hashToInt32(key);
|
|
509
|
+
const client = await this.pool.connect();
|
|
510
|
+
try {
|
|
511
|
+
await client.query("SELECT pg_advisory_lock($1)", [lockId]);
|
|
512
|
+
return await fn();
|
|
513
|
+
} finally {
|
|
514
|
+
try {
|
|
515
|
+
await client.query("SELECT pg_advisory_unlock($1)", [lockId]);
|
|
516
|
+
} finally {
|
|
517
|
+
client.release();
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
// =============================================================================
|
|
522
|
+
// Observable Sync System Methods
|
|
523
|
+
// =============================================================================
|
|
524
|
+
// These methods support long-running syncs with full observability.
|
|
525
|
+
// Uses two tables: _sync_runs (parent) and _sync_obj_runs (children)
|
|
526
|
+
// RunKey = (accountId, runStartedAt) - natural composite key
|
|
527
|
+
/**
|
|
528
|
+
* Cancel stale runs (running but no object updated in 5 minutes).
|
|
529
|
+
* Called before creating a new run to clean up crashed syncs.
|
|
530
|
+
* Only cancels runs that have objects AND none have recent activity.
|
|
531
|
+
* Runs without objects yet (just created) are not considered stale.
|
|
532
|
+
*/
|
|
533
|
+
async cancelStaleRuns(accountId) {
|
|
534
|
+
await this.query(
|
|
535
|
+
`UPDATE "${this.config.schema}"."_sync_obj_runs" o
|
|
536
|
+
SET status = 'error',
|
|
537
|
+
error_message = 'Auto-cancelled: stale (no update in 5 min)',
|
|
538
|
+
completed_at = now()
|
|
539
|
+
WHERE o."_account_id" = $1
|
|
540
|
+
AND o.status = 'running'
|
|
541
|
+
AND o.updated_at < now() - interval '5 minutes'`,
|
|
542
|
+
[accountId]
|
|
543
|
+
);
|
|
544
|
+
await this.query(
|
|
545
|
+
`UPDATE "${this.config.schema}"."_sync_runs" r
|
|
546
|
+
SET closed_at = now()
|
|
547
|
+
WHERE r."_account_id" = $1
|
|
548
|
+
AND r.closed_at IS NULL
|
|
549
|
+
AND EXISTS (
|
|
550
|
+
SELECT 1 FROM "${this.config.schema}"."_sync_obj_runs" o
|
|
551
|
+
WHERE o."_account_id" = r."_account_id"
|
|
552
|
+
AND o.run_started_at = r.started_at
|
|
553
|
+
)
|
|
554
|
+
AND NOT EXISTS (
|
|
555
|
+
SELECT 1 FROM "${this.config.schema}"."_sync_obj_runs" o
|
|
556
|
+
WHERE o."_account_id" = r."_account_id"
|
|
557
|
+
AND o.run_started_at = r.started_at
|
|
558
|
+
AND o.status IN ('pending', 'running')
|
|
559
|
+
)`,
|
|
560
|
+
[accountId]
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Get or create a sync run for this account.
|
|
565
|
+
* Returns existing run if one is active, otherwise creates new one.
|
|
566
|
+
* Auto-cancels stale runs before checking.
|
|
567
|
+
*
|
|
568
|
+
* @returns RunKey with isNew flag, or null if constraint violation (race condition)
|
|
569
|
+
*/
|
|
570
|
+
async getOrCreateSyncRun(accountId, triggeredBy) {
|
|
571
|
+
await this.cancelStaleRuns(accountId);
|
|
572
|
+
const existing = await this.query(
|
|
573
|
+
`SELECT "_account_id", started_at FROM "${this.config.schema}"."_sync_runs"
|
|
574
|
+
WHERE "_account_id" = $1 AND closed_at IS NULL`,
|
|
575
|
+
[accountId]
|
|
576
|
+
);
|
|
577
|
+
if (existing.rows.length > 0) {
|
|
578
|
+
const row = existing.rows[0];
|
|
579
|
+
return { accountId: row._account_id, runStartedAt: row.started_at, isNew: false };
|
|
580
|
+
}
|
|
581
|
+
try {
|
|
582
|
+
const result = await this.query(
|
|
583
|
+
`INSERT INTO "${this.config.schema}"."_sync_runs" ("_account_id", triggered_by, started_at)
|
|
584
|
+
VALUES ($1, $2, date_trunc('milliseconds', now()))
|
|
585
|
+
RETURNING "_account_id", started_at`,
|
|
586
|
+
[accountId, triggeredBy ?? null]
|
|
587
|
+
);
|
|
588
|
+
const row = result.rows[0];
|
|
589
|
+
return { accountId: row._account_id, runStartedAt: row.started_at, isNew: true };
|
|
590
|
+
} catch (error) {
|
|
591
|
+
if (error instanceof Error && "code" in error && error.code === "23P01") {
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
throw error;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Get the active sync run for an account (if any).
|
|
599
|
+
*/
|
|
600
|
+
async getActiveSyncRun(accountId) {
|
|
601
|
+
const result = await this.query(
|
|
602
|
+
`SELECT "_account_id", started_at FROM "${this.config.schema}"."_sync_runs"
|
|
603
|
+
WHERE "_account_id" = $1 AND closed_at IS NULL`,
|
|
604
|
+
[accountId]
|
|
605
|
+
);
|
|
606
|
+
if (result.rows.length === 0) return null;
|
|
607
|
+
const row = result.rows[0];
|
|
608
|
+
return { accountId: row._account_id, runStartedAt: row.started_at };
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Get sync run config (for concurrency control).
|
|
612
|
+
* Status is derived from sync_runs view.
|
|
613
|
+
*/
|
|
614
|
+
async getSyncRun(accountId, runStartedAt) {
|
|
615
|
+
const result = await this.query(
|
|
616
|
+
`SELECT "_account_id", started_at, max_concurrent, closed_at
|
|
617
|
+
FROM "${this.config.schema}"."_sync_runs"
|
|
618
|
+
WHERE "_account_id" = $1 AND started_at = $2`,
|
|
619
|
+
[accountId, runStartedAt]
|
|
620
|
+
);
|
|
621
|
+
if (result.rows.length === 0) return null;
|
|
622
|
+
const row = result.rows[0];
|
|
623
|
+
return {
|
|
624
|
+
accountId: row._account_id,
|
|
625
|
+
runStartedAt: row.started_at,
|
|
626
|
+
maxConcurrent: row.max_concurrent,
|
|
627
|
+
closedAt: row.closed_at
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Close a sync run (mark as done).
|
|
632
|
+
* Status (complete/error) is derived from object run states.
|
|
633
|
+
*/
|
|
634
|
+
async closeSyncRun(accountId, runStartedAt) {
|
|
635
|
+
await this.query(
|
|
636
|
+
`UPDATE "${this.config.schema}"."_sync_runs"
|
|
637
|
+
SET closed_at = now()
|
|
638
|
+
WHERE "_account_id" = $1 AND started_at = $2 AND closed_at IS NULL`,
|
|
639
|
+
[accountId, runStartedAt]
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Create object run entries for a sync run.
|
|
644
|
+
* All objects start as 'pending'.
|
|
645
|
+
*/
|
|
646
|
+
async createObjectRuns(accountId, runStartedAt, objects) {
|
|
647
|
+
if (objects.length === 0) return;
|
|
648
|
+
const values = objects.map((_, i) => `($1, $2, $${i + 3})`).join(", ");
|
|
649
|
+
await this.query(
|
|
650
|
+
`INSERT INTO "${this.config.schema}"."_sync_obj_runs" ("_account_id", run_started_at, object)
|
|
651
|
+
VALUES ${values}
|
|
652
|
+
ON CONFLICT ("_account_id", run_started_at, object) DO NOTHING`,
|
|
653
|
+
[accountId, runStartedAt, ...objects]
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Try to start an object sync (respects max_concurrent).
|
|
658
|
+
* Returns true if claimed, false if already running or at concurrency limit.
|
|
659
|
+
*
|
|
660
|
+
* Note: There's a small race window where concurrent calls could result in
|
|
661
|
+
* max_concurrent + 1 objects running. This is acceptable behavior.
|
|
662
|
+
*/
|
|
663
|
+
async tryStartObjectSync(accountId, runStartedAt, object) {
|
|
664
|
+
const run = await this.getSyncRun(accountId, runStartedAt);
|
|
665
|
+
if (!run) return false;
|
|
666
|
+
const runningCount = await this.countRunningObjects(accountId, runStartedAt);
|
|
667
|
+
if (runningCount >= run.maxConcurrent) return false;
|
|
668
|
+
const result = await this.query(
|
|
669
|
+
`UPDATE "${this.config.schema}"."_sync_obj_runs"
|
|
670
|
+
SET status = 'running', started_at = now(), updated_at = now()
|
|
671
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND object = $3 AND status = 'pending'
|
|
672
|
+
RETURNING *`,
|
|
673
|
+
[accountId, runStartedAt, object]
|
|
674
|
+
);
|
|
675
|
+
return (result.rowCount ?? 0) > 0;
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Get object run details.
|
|
679
|
+
*/
|
|
680
|
+
async getObjectRun(accountId, runStartedAt, object) {
|
|
681
|
+
const result = await this.query(
|
|
682
|
+
`SELECT object, status, processed_count, cursor
|
|
683
|
+
FROM "${this.config.schema}"."_sync_obj_runs"
|
|
684
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND object = $3`,
|
|
685
|
+
[accountId, runStartedAt, object]
|
|
686
|
+
);
|
|
687
|
+
if (result.rows.length === 0) return null;
|
|
688
|
+
const row = result.rows[0];
|
|
689
|
+
return {
|
|
690
|
+
object: row.object,
|
|
691
|
+
status: row.status,
|
|
692
|
+
processedCount: row.processed_count,
|
|
693
|
+
cursor: row.cursor
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* Update progress for an object sync.
|
|
698
|
+
* Also touches updated_at for stale detection.
|
|
699
|
+
*/
|
|
700
|
+
async incrementObjectProgress(accountId, runStartedAt, object, count) {
|
|
701
|
+
await this.query(
|
|
702
|
+
`UPDATE "${this.config.schema}"."_sync_obj_runs"
|
|
703
|
+
SET processed_count = processed_count + $4, updated_at = now()
|
|
704
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND object = $3`,
|
|
705
|
+
[accountId, runStartedAt, object, count]
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Update the cursor for an object sync.
|
|
710
|
+
* Only updates if the new cursor is higher than the existing one (cursors should never decrease).
|
|
711
|
+
* For numeric cursors (timestamps), uses GREATEST to ensure monotonic increase.
|
|
712
|
+
* For non-numeric cursors, just sets the value directly.
|
|
713
|
+
*/
|
|
714
|
+
async updateObjectCursor(accountId, runStartedAt, object, cursor) {
|
|
715
|
+
const isNumeric = cursor !== null && /^\d+$/.test(cursor);
|
|
716
|
+
if (isNumeric) {
|
|
717
|
+
await this.query(
|
|
718
|
+
`UPDATE "${this.config.schema}"."_sync_obj_runs"
|
|
719
|
+
SET cursor = GREATEST(COALESCE(cursor::bigint, 0), $4::bigint)::text,
|
|
720
|
+
updated_at = now()
|
|
721
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND object = $3`,
|
|
722
|
+
[accountId, runStartedAt, object, cursor]
|
|
723
|
+
);
|
|
724
|
+
} else {
|
|
725
|
+
await this.query(
|
|
726
|
+
`UPDATE "${this.config.schema}"."_sync_obj_runs"
|
|
727
|
+
SET cursor = $4, updated_at = now()
|
|
728
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND object = $3`,
|
|
729
|
+
[accountId, runStartedAt, object, cursor]
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Get the highest cursor from previous syncs for an object type.
|
|
735
|
+
* This considers completed, error, AND running runs to ensure recovery syncs
|
|
736
|
+
* don't re-process data that was already synced before a crash.
|
|
737
|
+
* A 'running' status with a cursor means the process was killed mid-sync.
|
|
738
|
+
*/
|
|
739
|
+
async getLastCompletedCursor(accountId, object) {
|
|
740
|
+
const result = await this.query(
|
|
741
|
+
`SELECT MAX(o.cursor::bigint)::text as cursor
|
|
742
|
+
FROM "${this.config.schema}"."_sync_obj_runs" o
|
|
743
|
+
WHERE o."_account_id" = $1
|
|
744
|
+
AND o.object = $2
|
|
745
|
+
AND o.cursor IS NOT NULL`,
|
|
746
|
+
[accountId, object]
|
|
747
|
+
);
|
|
748
|
+
return result.rows[0]?.cursor ?? null;
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Delete all sync runs and object runs for an account.
|
|
752
|
+
* Useful for testing or resetting sync state.
|
|
753
|
+
*/
|
|
754
|
+
async deleteSyncRuns(accountId) {
|
|
755
|
+
await this.query(
|
|
756
|
+
`DELETE FROM "${this.config.schema}"."_sync_obj_runs" WHERE "_account_id" = $1`,
|
|
757
|
+
[accountId]
|
|
758
|
+
);
|
|
759
|
+
await this.query(`DELETE FROM "${this.config.schema}"."_sync_runs" WHERE "_account_id" = $1`, [
|
|
760
|
+
accountId
|
|
761
|
+
]);
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Mark an object sync as complete.
|
|
765
|
+
* Auto-closes the run when all objects are done.
|
|
766
|
+
*/
|
|
767
|
+
async completeObjectSync(accountId, runStartedAt, object) {
|
|
768
|
+
await this.query(
|
|
769
|
+
`UPDATE "${this.config.schema}"."_sync_obj_runs"
|
|
770
|
+
SET status = 'complete', completed_at = now()
|
|
771
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND object = $3`,
|
|
772
|
+
[accountId, runStartedAt, object]
|
|
773
|
+
);
|
|
774
|
+
const allDone = await this.areAllObjectsComplete(accountId, runStartedAt);
|
|
775
|
+
if (allDone) {
|
|
776
|
+
await this.closeSyncRun(accountId, runStartedAt);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Mark an object sync as failed.
|
|
781
|
+
* Auto-closes the run when all objects are done.
|
|
782
|
+
*/
|
|
783
|
+
async failObjectSync(accountId, runStartedAt, object, errorMessage) {
|
|
784
|
+
await this.query(
|
|
785
|
+
`UPDATE "${this.config.schema}"."_sync_obj_runs"
|
|
786
|
+
SET status = 'error', error_message = $4, completed_at = now()
|
|
787
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND object = $3`,
|
|
788
|
+
[accountId, runStartedAt, object, errorMessage]
|
|
789
|
+
);
|
|
790
|
+
const allDone = await this.areAllObjectsComplete(accountId, runStartedAt);
|
|
791
|
+
if (allDone) {
|
|
792
|
+
await this.closeSyncRun(accountId, runStartedAt);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Check if any object in a run has errored.
|
|
797
|
+
*/
|
|
798
|
+
async hasAnyObjectErrors(accountId, runStartedAt) {
|
|
799
|
+
const result = await this.query(
|
|
800
|
+
`SELECT COUNT(*) as count FROM "${this.config.schema}"."_sync_obj_runs"
|
|
801
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND status = 'error'`,
|
|
802
|
+
[accountId, runStartedAt]
|
|
803
|
+
);
|
|
804
|
+
return parseInt(result.rows[0].count) > 0;
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Count running objects in a run.
|
|
808
|
+
*/
|
|
809
|
+
async countRunningObjects(accountId, runStartedAt) {
|
|
810
|
+
const result = await this.query(
|
|
811
|
+
`SELECT COUNT(*) as count FROM "${this.config.schema}"."_sync_obj_runs"
|
|
812
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND status = 'running'`,
|
|
813
|
+
[accountId, runStartedAt]
|
|
814
|
+
);
|
|
815
|
+
return parseInt(result.rows[0].count);
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Get the next pending object to process.
|
|
819
|
+
* Returns null if no pending objects or at concurrency limit.
|
|
820
|
+
*/
|
|
821
|
+
async getNextPendingObject(accountId, runStartedAt) {
|
|
822
|
+
const run = await this.getSyncRun(accountId, runStartedAt);
|
|
823
|
+
if (!run) return null;
|
|
824
|
+
const runningCount = await this.countRunningObjects(accountId, runStartedAt);
|
|
825
|
+
if (runningCount >= run.maxConcurrent) return null;
|
|
826
|
+
const result = await this.query(
|
|
827
|
+
`SELECT object FROM "${this.config.schema}"."_sync_obj_runs"
|
|
828
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND status = 'pending'
|
|
829
|
+
ORDER BY object
|
|
830
|
+
LIMIT 1`,
|
|
831
|
+
[accountId, runStartedAt]
|
|
832
|
+
);
|
|
833
|
+
return result.rows.length > 0 ? result.rows[0].object : null;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Check if all objects in a run are complete (or error).
|
|
837
|
+
*/
|
|
838
|
+
async areAllObjectsComplete(accountId, runStartedAt) {
|
|
839
|
+
const result = await this.query(
|
|
840
|
+
`SELECT COUNT(*) as count FROM "${this.config.schema}"."_sync_obj_runs"
|
|
841
|
+
WHERE "_account_id" = $1 AND run_started_at = $2 AND status IN ('pending', 'running')`,
|
|
842
|
+
[accountId, runStartedAt]
|
|
843
|
+
);
|
|
844
|
+
return parseInt(result.rows[0].count) === 0;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Closes the database connection pool and cleans up resources.
|
|
848
|
+
* Call this when you're done using the PostgresClient instance.
|
|
849
|
+
*/
|
|
850
|
+
async close() {
|
|
851
|
+
await this.pool.end();
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
|
|
855
|
+
// src/schemas/managed_webhook.ts
|
|
856
|
+
var managedWebhookSchema = {
|
|
857
|
+
properties: [
|
|
858
|
+
"id",
|
|
859
|
+
"object",
|
|
860
|
+
"url",
|
|
861
|
+
"enabled_events",
|
|
862
|
+
"description",
|
|
863
|
+
"enabled",
|
|
864
|
+
"livemode",
|
|
865
|
+
"metadata",
|
|
866
|
+
"secret",
|
|
867
|
+
"status",
|
|
868
|
+
"api_version",
|
|
869
|
+
"created",
|
|
870
|
+
"account_id"
|
|
871
|
+
]
|
|
872
|
+
};
|
|
873
|
+
|
|
874
|
+
// src/utils/retry.ts
|
|
875
|
+
var import_stripe = __toESM(require("stripe"), 1);
|
|
876
|
+
var DEFAULT_RETRY_CONFIG = {
|
|
877
|
+
maxRetries: 5,
|
|
878
|
+
initialDelayMs: 1e3,
|
|
879
|
+
// 1 second
|
|
880
|
+
maxDelayMs: 6e4,
|
|
881
|
+
// 60 seconds
|
|
882
|
+
jitterMs: 500
|
|
883
|
+
// randomization to prevent thundering herd
|
|
884
|
+
};
|
|
885
|
+
function isRetryableError(error) {
|
|
886
|
+
if (error instanceof import_stripe.default.errors.StripeRateLimitError) {
|
|
887
|
+
return true;
|
|
888
|
+
}
|
|
889
|
+
if (error instanceof import_stripe.default.errors.StripeAPIError) {
|
|
890
|
+
const statusCode = error.statusCode;
|
|
891
|
+
if (statusCode && [500, 502, 503, 504, 424].includes(statusCode)) {
|
|
892
|
+
return true;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
if (error instanceof import_stripe.default.errors.StripeConnectionError) {
|
|
896
|
+
return true;
|
|
897
|
+
}
|
|
898
|
+
return false;
|
|
899
|
+
}
|
|
900
|
+
function getRetryAfterMs(error) {
|
|
901
|
+
if (!(error instanceof import_stripe.default.errors.StripeRateLimitError)) {
|
|
902
|
+
return null;
|
|
903
|
+
}
|
|
904
|
+
const retryAfterHeader = error.headers?.["retry-after"];
|
|
905
|
+
if (!retryAfterHeader) {
|
|
906
|
+
return null;
|
|
907
|
+
}
|
|
908
|
+
const retryAfterSeconds = Number(retryAfterHeader);
|
|
909
|
+
if (isNaN(retryAfterSeconds) || retryAfterSeconds <= 0) {
|
|
910
|
+
return null;
|
|
911
|
+
}
|
|
912
|
+
return retryAfterSeconds * 1e3;
|
|
913
|
+
}
|
|
914
|
+
function calculateDelay(attempt, config, retryAfterMs) {
|
|
915
|
+
if (retryAfterMs !== null && retryAfterMs !== void 0) {
|
|
916
|
+
const jitter2 = Math.random() * config.jitterMs;
|
|
917
|
+
return retryAfterMs + jitter2;
|
|
918
|
+
}
|
|
919
|
+
const exponentialDelay = Math.min(config.initialDelayMs * Math.pow(2, attempt), config.maxDelayMs);
|
|
920
|
+
const jitter = Math.random() * config.jitterMs;
|
|
921
|
+
return exponentialDelay + jitter;
|
|
922
|
+
}
|
|
923
|
+
function sleep(ms) {
|
|
924
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
925
|
+
}
|
|
926
|
+
function getErrorType(error) {
|
|
927
|
+
if (error instanceof import_stripe.default.errors.StripeRateLimitError) {
|
|
928
|
+
return "rate_limit";
|
|
929
|
+
}
|
|
930
|
+
if (error instanceof import_stripe.default.errors.StripeAPIError) {
|
|
931
|
+
return `api_error_${error.statusCode}`;
|
|
932
|
+
}
|
|
933
|
+
if (error instanceof import_stripe.default.errors.StripeConnectionError) {
|
|
934
|
+
return "connection_error";
|
|
935
|
+
}
|
|
936
|
+
return "unknown";
|
|
937
|
+
}
|
|
938
|
+
async function withRetry(fn, config = {}, logger) {
|
|
939
|
+
const retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
|
|
940
|
+
let lastError;
|
|
941
|
+
for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
|
|
942
|
+
try {
|
|
943
|
+
return await fn();
|
|
944
|
+
} catch (error) {
|
|
945
|
+
lastError = error;
|
|
946
|
+
if (!isRetryableError(error)) {
|
|
947
|
+
throw error;
|
|
948
|
+
}
|
|
949
|
+
if (attempt >= retryConfig.maxRetries) {
|
|
950
|
+
logger?.error(
|
|
951
|
+
{
|
|
952
|
+
error: error instanceof Error ? error.message : String(error),
|
|
953
|
+
errorType: getErrorType(error),
|
|
954
|
+
attempt: attempt + 1,
|
|
955
|
+
maxRetries: retryConfig.maxRetries
|
|
956
|
+
},
|
|
957
|
+
"Max retries exhausted for Stripe error"
|
|
958
|
+
);
|
|
959
|
+
throw error;
|
|
960
|
+
}
|
|
961
|
+
const retryAfterMs = getRetryAfterMs(error);
|
|
962
|
+
const delay = calculateDelay(attempt, retryConfig, retryAfterMs);
|
|
963
|
+
logger?.warn(
|
|
964
|
+
{
|
|
965
|
+
error: error instanceof Error ? error.message : String(error),
|
|
966
|
+
errorType: getErrorType(error),
|
|
967
|
+
attempt: attempt + 1,
|
|
968
|
+
maxRetries: retryConfig.maxRetries,
|
|
969
|
+
delayMs: Math.round(delay),
|
|
970
|
+
retryAfterMs: retryAfterMs ?? void 0,
|
|
971
|
+
nextAttempt: attempt + 2
|
|
972
|
+
},
|
|
973
|
+
"Transient Stripe error, retrying after delay"
|
|
974
|
+
);
|
|
975
|
+
await sleep(delay);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
throw lastError;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// src/utils/stripeClientWrapper.ts
|
|
982
|
+
function createRetryableStripeClient(stripe, retryConfig = {}, logger) {
|
|
983
|
+
return new Proxy(stripe, {
|
|
984
|
+
get(target, prop, receiver) {
|
|
985
|
+
const original = Reflect.get(target, prop, receiver);
|
|
986
|
+
if (original && typeof original === "object" && !isPromise(original)) {
|
|
987
|
+
return wrapResource(original, retryConfig, logger);
|
|
988
|
+
}
|
|
989
|
+
return original;
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
function wrapResource(resource, retryConfig, logger) {
|
|
994
|
+
return new Proxy(resource, {
|
|
995
|
+
get(target, prop, receiver) {
|
|
996
|
+
const original = Reflect.get(target, prop, receiver);
|
|
997
|
+
if (typeof original === "function") {
|
|
998
|
+
return function(...args) {
|
|
999
|
+
const result = original.apply(target, args);
|
|
1000
|
+
if (result && typeof result === "object" && Symbol.asyncIterator in result) {
|
|
1001
|
+
return result;
|
|
1002
|
+
}
|
|
1003
|
+
if (isPromise(result)) {
|
|
1004
|
+
return withRetry(() => Promise.resolve(result), retryConfig, logger);
|
|
1005
|
+
}
|
|
1006
|
+
return result;
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
if (original && typeof original === "object" && !isPromise(original)) {
|
|
1010
|
+
return wrapResource(original, retryConfig, logger);
|
|
1011
|
+
}
|
|
1012
|
+
return original;
|
|
1013
|
+
}
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
function isPromise(value) {
|
|
1017
|
+
return value !== null && typeof value === "object" && typeof value.then === "function";
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// src/utils/hashApiKey.ts
|
|
1021
|
+
var import_crypto = require("crypto");
|
|
1022
|
+
function hashApiKey(apiKey) {
|
|
1023
|
+
return (0, import_crypto.createHash)("sha256").update(apiKey).digest("hex");
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
// src/stripeSync.ts
|
|
1027
|
+
function getUniqueIds(entries, key) {
|
|
1028
|
+
const set = new Set(
|
|
1029
|
+
entries.map((subscription) => subscription?.[key]?.toString()).filter((it) => Boolean(it))
|
|
1030
|
+
);
|
|
1031
|
+
return Array.from(set);
|
|
1032
|
+
}
|
|
1033
|
+
var StripeSync = class {
|
|
1034
|
+
constructor(config) {
|
|
1035
|
+
this.config = config;
|
|
1036
|
+
const baseStripe = new import_stripe2.default(config.stripeSecretKey, {
|
|
1037
|
+
// https://github.com/stripe/stripe-node#configuration
|
|
1038
|
+
// @ts-ignore
|
|
1039
|
+
apiVersion: config.stripeApiVersion,
|
|
1040
|
+
appInfo: {
|
|
1041
|
+
name: "Stripe Postgres Sync"
|
|
1042
|
+
}
|
|
1043
|
+
});
|
|
1044
|
+
this.stripe = createRetryableStripeClient(baseStripe, {}, config.logger);
|
|
1045
|
+
this.config.logger = config.logger ?? console;
|
|
1046
|
+
this.config.logger?.info(
|
|
1047
|
+
{ autoExpandLists: config.autoExpandLists, stripeApiVersion: config.stripeApiVersion },
|
|
1048
|
+
"StripeSync initialized"
|
|
1049
|
+
);
|
|
1050
|
+
const poolConfig = config.poolConfig ?? {};
|
|
1051
|
+
if (config.databaseUrl) {
|
|
1052
|
+
poolConfig.connectionString = config.databaseUrl;
|
|
1053
|
+
}
|
|
1054
|
+
if (config.maxPostgresConnections) {
|
|
1055
|
+
poolConfig.max = config.maxPostgresConnections;
|
|
1056
|
+
}
|
|
1057
|
+
if (poolConfig.max === void 0) {
|
|
1058
|
+
poolConfig.max = 10;
|
|
1059
|
+
}
|
|
1060
|
+
if (poolConfig.keepAlive === void 0) {
|
|
1061
|
+
poolConfig.keepAlive = true;
|
|
1062
|
+
}
|
|
1063
|
+
this.postgresClient = new PostgresClient({
|
|
1064
|
+
schema: "stripe",
|
|
1065
|
+
poolConfig
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
stripe;
|
|
1069
|
+
postgresClient;
|
|
1070
|
+
/**
|
|
1071
|
+
* Get the Stripe account ID. Delegates to getCurrentAccount() for the actual lookup.
|
|
1072
|
+
*/
|
|
1073
|
+
async getAccountId(objectAccountId) {
|
|
1074
|
+
const account = await this.getCurrentAccount(objectAccountId);
|
|
1075
|
+
if (!account) {
|
|
1076
|
+
throw new Error("Failed to retrieve Stripe account. Please ensure API key is valid.");
|
|
1077
|
+
}
|
|
1078
|
+
return account.id;
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Upsert Stripe account information to the database
|
|
1082
|
+
* @param account - Stripe account object
|
|
1083
|
+
* @param apiKeyHash - SHA-256 hash of API key to store for fast lookups
|
|
1084
|
+
*/
|
|
1085
|
+
async upsertAccount(account, apiKeyHash) {
|
|
1086
|
+
try {
|
|
1087
|
+
await this.postgresClient.upsertAccount(
|
|
1088
|
+
{
|
|
1089
|
+
id: account.id,
|
|
1090
|
+
raw_data: account
|
|
1091
|
+
},
|
|
1092
|
+
apiKeyHash
|
|
1093
|
+
);
|
|
1094
|
+
} catch (error) {
|
|
1095
|
+
this.config.logger?.error(error, "Failed to upsert account to database");
|
|
1096
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
1097
|
+
throw new Error(`Failed to upsert account to database: ${errorMessage}`);
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Get the current account being synced. Uses database lookup by API key hash,
|
|
1102
|
+
* with fallback to Stripe API if not found (first-time setup or new API key).
|
|
1103
|
+
* @param objectAccountId - Optional account ID from event data (Connect scenarios)
|
|
1104
|
+
*/
|
|
1105
|
+
async getCurrentAccount(objectAccountId) {
|
|
1106
|
+
const apiKeyHash = hashApiKey(this.config.stripeSecretKey);
|
|
1107
|
+
try {
|
|
1108
|
+
const account = await this.postgresClient.getAccountByApiKeyHash(apiKeyHash);
|
|
1109
|
+
if (account) {
|
|
1110
|
+
return account;
|
|
1111
|
+
}
|
|
1112
|
+
} catch (error) {
|
|
1113
|
+
this.config.logger?.warn(
|
|
1114
|
+
error,
|
|
1115
|
+
"Failed to lookup account by API key hash, falling back to API"
|
|
1116
|
+
);
|
|
1117
|
+
}
|
|
1118
|
+
try {
|
|
1119
|
+
const accountIdParam = objectAccountId || this.config.stripeAccountId;
|
|
1120
|
+
const account = accountIdParam ? await this.stripe.accounts.retrieve(accountIdParam) : await this.stripe.accounts.retrieve();
|
|
1121
|
+
await this.upsertAccount(account, apiKeyHash);
|
|
1122
|
+
return account;
|
|
1123
|
+
} catch (error) {
|
|
1124
|
+
this.config.logger?.error(error, "Failed to retrieve account from Stripe API");
|
|
1125
|
+
return null;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* Get all accounts that have been synced to the database
|
|
1130
|
+
*/
|
|
1131
|
+
async getAllSyncedAccounts() {
|
|
1132
|
+
try {
|
|
1133
|
+
const accountsData = await this.postgresClient.getAllAccounts();
|
|
1134
|
+
return accountsData;
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
this.config.logger?.error(error, "Failed to retrieve accounts from database");
|
|
1137
|
+
throw new Error("Failed to retrieve synced accounts from database");
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* DANGEROUS: Delete an account and all associated data from the database
|
|
1142
|
+
* This operation cannot be undone!
|
|
1143
|
+
*
|
|
1144
|
+
* @param accountId - The Stripe account ID to delete
|
|
1145
|
+
* @param options - Options for deletion behavior
|
|
1146
|
+
* @param options.dryRun - If true, only count records without deleting (default: false)
|
|
1147
|
+
* @param options.useTransaction - If true, use transaction for atomic deletion (default: true)
|
|
1148
|
+
* @returns Deletion summary with counts and warnings
|
|
1149
|
+
*/
|
|
1150
|
+
async dangerouslyDeleteSyncedAccountData(accountId, options) {
|
|
1151
|
+
const dryRun = options?.dryRun ?? false;
|
|
1152
|
+
const useTransaction = options?.useTransaction ?? true;
|
|
1153
|
+
this.config.logger?.info(
|
|
1154
|
+
`${dryRun ? "Preview" : "Deleting"} account ${accountId} (transaction: ${useTransaction})`
|
|
1155
|
+
);
|
|
1156
|
+
try {
|
|
1157
|
+
const counts = await this.postgresClient.getAccountRecordCounts(accountId);
|
|
1158
|
+
const warnings = [];
|
|
1159
|
+
let totalRecords = 0;
|
|
1160
|
+
for (const [table, count] of Object.entries(counts)) {
|
|
1161
|
+
if (count > 0) {
|
|
1162
|
+
totalRecords += count;
|
|
1163
|
+
warnings.push(`Will delete ${count} ${table} record${count !== 1 ? "s" : ""}`);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
if (totalRecords > 1e5) {
|
|
1167
|
+
warnings.push(
|
|
1168
|
+
`Large dataset detected (${totalRecords} total records). Consider using useTransaction: false for better performance.`
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
1171
|
+
if (dryRun) {
|
|
1172
|
+
this.config.logger?.info(`Dry-run complete: ${totalRecords} total records would be deleted`);
|
|
1173
|
+
return {
|
|
1174
|
+
deletedAccountId: accountId,
|
|
1175
|
+
deletedRecordCounts: counts,
|
|
1176
|
+
warnings
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
const deletionCounts = await this.postgresClient.deleteAccountWithCascade(
|
|
1180
|
+
accountId,
|
|
1181
|
+
useTransaction
|
|
1182
|
+
);
|
|
1183
|
+
this.config.logger?.info(
|
|
1184
|
+
`Successfully deleted account ${accountId} with ${totalRecords} total records`
|
|
1185
|
+
);
|
|
1186
|
+
return {
|
|
1187
|
+
deletedAccountId: accountId,
|
|
1188
|
+
deletedRecordCounts: deletionCounts,
|
|
1189
|
+
warnings
|
|
1190
|
+
};
|
|
1191
|
+
} catch (error) {
|
|
1192
|
+
this.config.logger?.error(error, `Failed to delete account ${accountId}`);
|
|
1193
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
1194
|
+
throw new Error(`Failed to delete account ${accountId}: ${errorMessage}`);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
async processWebhook(payload, signature) {
|
|
1198
|
+
let webhookSecret = this.config.stripeWebhookSecret;
|
|
1199
|
+
if (!webhookSecret) {
|
|
1200
|
+
const accountId = await this.getAccountId();
|
|
1201
|
+
const result = await this.postgresClient.query(
|
|
1202
|
+
`SELECT secret FROM "stripe"."_managed_webhooks" WHERE account_id = $1 LIMIT 1`,
|
|
1203
|
+
[accountId]
|
|
1204
|
+
);
|
|
1205
|
+
if (result.rows.length > 0) {
|
|
1206
|
+
webhookSecret = result.rows[0].secret;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
if (!webhookSecret) {
|
|
1210
|
+
throw new Error(
|
|
1211
|
+
"No webhook secret provided. Either create a managed webhook or configure stripeWebhookSecret."
|
|
1212
|
+
);
|
|
1213
|
+
}
|
|
1214
|
+
const event = await this.stripe.webhooks.constructEventAsync(payload, signature, webhookSecret);
|
|
1215
|
+
return this.processEvent(event);
|
|
1216
|
+
}
|
|
1217
|
+
// Event handler registry - maps event types to handler functions
|
|
1218
|
+
// Note: Uses 'any' for event parameter to allow handlers with specific Stripe event types
|
|
1219
|
+
// (e.g., CustomerDeletedEvent, ProductDeletedEvent) which TypeScript won't accept
|
|
1220
|
+
// as contravariant parameters when using the base Stripe.Event type
|
|
1221
|
+
eventHandlers = {
|
|
1222
|
+
"charge.captured": this.handleChargeEvent.bind(this),
|
|
1223
|
+
"charge.expired": this.handleChargeEvent.bind(this),
|
|
1224
|
+
"charge.failed": this.handleChargeEvent.bind(this),
|
|
1225
|
+
"charge.pending": this.handleChargeEvent.bind(this),
|
|
1226
|
+
"charge.refunded": this.handleChargeEvent.bind(this),
|
|
1227
|
+
"charge.succeeded": this.handleChargeEvent.bind(this),
|
|
1228
|
+
"charge.updated": this.handleChargeEvent.bind(this),
|
|
1229
|
+
"customer.deleted": this.handleCustomerDeletedEvent.bind(this),
|
|
1230
|
+
"customer.created": this.handleCustomerEvent.bind(this),
|
|
1231
|
+
"customer.updated": this.handleCustomerEvent.bind(this),
|
|
1232
|
+
"checkout.session.async_payment_failed": this.handleCheckoutSessionEvent.bind(this),
|
|
1233
|
+
"checkout.session.async_payment_succeeded": this.handleCheckoutSessionEvent.bind(this),
|
|
1234
|
+
"checkout.session.completed": this.handleCheckoutSessionEvent.bind(this),
|
|
1235
|
+
"checkout.session.expired": this.handleCheckoutSessionEvent.bind(this),
|
|
1236
|
+
"customer.subscription.created": this.handleSubscriptionEvent.bind(this),
|
|
1237
|
+
"customer.subscription.deleted": this.handleSubscriptionEvent.bind(this),
|
|
1238
|
+
"customer.subscription.paused": this.handleSubscriptionEvent.bind(this),
|
|
1239
|
+
"customer.subscription.pending_update_applied": this.handleSubscriptionEvent.bind(this),
|
|
1240
|
+
"customer.subscription.pending_update_expired": this.handleSubscriptionEvent.bind(this),
|
|
1241
|
+
"customer.subscription.trial_will_end": this.handleSubscriptionEvent.bind(this),
|
|
1242
|
+
"customer.subscription.resumed": this.handleSubscriptionEvent.bind(this),
|
|
1243
|
+
"customer.subscription.updated": this.handleSubscriptionEvent.bind(this),
|
|
1244
|
+
"customer.tax_id.updated": this.handleTaxIdEvent.bind(this),
|
|
1245
|
+
"customer.tax_id.created": this.handleTaxIdEvent.bind(this),
|
|
1246
|
+
"customer.tax_id.deleted": this.handleTaxIdDeletedEvent.bind(this),
|
|
1247
|
+
"invoice.created": this.handleInvoiceEvent.bind(this),
|
|
1248
|
+
"invoice.deleted": this.handleInvoiceEvent.bind(this),
|
|
1249
|
+
"invoice.finalized": this.handleInvoiceEvent.bind(this),
|
|
1250
|
+
"invoice.finalization_failed": this.handleInvoiceEvent.bind(this),
|
|
1251
|
+
"invoice.paid": this.handleInvoiceEvent.bind(this),
|
|
1252
|
+
"invoice.payment_action_required": this.handleInvoiceEvent.bind(this),
|
|
1253
|
+
"invoice.payment_failed": this.handleInvoiceEvent.bind(this),
|
|
1254
|
+
"invoice.payment_succeeded": this.handleInvoiceEvent.bind(this),
|
|
1255
|
+
"invoice.upcoming": this.handleInvoiceEvent.bind(this),
|
|
1256
|
+
"invoice.sent": this.handleInvoiceEvent.bind(this),
|
|
1257
|
+
"invoice.voided": this.handleInvoiceEvent.bind(this),
|
|
1258
|
+
"invoice.marked_uncollectible": this.handleInvoiceEvent.bind(this),
|
|
1259
|
+
"invoice.updated": this.handleInvoiceEvent.bind(this),
|
|
1260
|
+
"product.created": this.handleProductEvent.bind(this),
|
|
1261
|
+
"product.updated": this.handleProductEvent.bind(this),
|
|
1262
|
+
"product.deleted": this.handleProductDeletedEvent.bind(this),
|
|
1263
|
+
"price.created": this.handlePriceEvent.bind(this),
|
|
1264
|
+
"price.updated": this.handlePriceEvent.bind(this),
|
|
1265
|
+
"price.deleted": this.handlePriceDeletedEvent.bind(this),
|
|
1266
|
+
"plan.created": this.handlePlanEvent.bind(this),
|
|
1267
|
+
"plan.updated": this.handlePlanEvent.bind(this),
|
|
1268
|
+
"plan.deleted": this.handlePlanDeletedEvent.bind(this),
|
|
1269
|
+
"setup_intent.canceled": this.handleSetupIntentEvent.bind(this),
|
|
1270
|
+
"setup_intent.created": this.handleSetupIntentEvent.bind(this),
|
|
1271
|
+
"setup_intent.requires_action": this.handleSetupIntentEvent.bind(this),
|
|
1272
|
+
"setup_intent.setup_failed": this.handleSetupIntentEvent.bind(this),
|
|
1273
|
+
"setup_intent.succeeded": this.handleSetupIntentEvent.bind(this),
|
|
1274
|
+
"subscription_schedule.aborted": this.handleSubscriptionScheduleEvent.bind(this),
|
|
1275
|
+
"subscription_schedule.canceled": this.handleSubscriptionScheduleEvent.bind(this),
|
|
1276
|
+
"subscription_schedule.completed": this.handleSubscriptionScheduleEvent.bind(this),
|
|
1277
|
+
"subscription_schedule.created": this.handleSubscriptionScheduleEvent.bind(this),
|
|
1278
|
+
"subscription_schedule.expiring": this.handleSubscriptionScheduleEvent.bind(this),
|
|
1279
|
+
"subscription_schedule.released": this.handleSubscriptionScheduleEvent.bind(this),
|
|
1280
|
+
"subscription_schedule.updated": this.handleSubscriptionScheduleEvent.bind(this),
|
|
1281
|
+
"payment_method.attached": this.handlePaymentMethodEvent.bind(this),
|
|
1282
|
+
"payment_method.automatically_updated": this.handlePaymentMethodEvent.bind(this),
|
|
1283
|
+
"payment_method.detached": this.handlePaymentMethodEvent.bind(this),
|
|
1284
|
+
"payment_method.updated": this.handlePaymentMethodEvent.bind(this),
|
|
1285
|
+
"charge.dispute.created": this.handleDisputeEvent.bind(this),
|
|
1286
|
+
"charge.dispute.funds_reinstated": this.handleDisputeEvent.bind(this),
|
|
1287
|
+
"charge.dispute.funds_withdrawn": this.handleDisputeEvent.bind(this),
|
|
1288
|
+
"charge.dispute.updated": this.handleDisputeEvent.bind(this),
|
|
1289
|
+
"charge.dispute.closed": this.handleDisputeEvent.bind(this),
|
|
1290
|
+
"payment_intent.amount_capturable_updated": this.handlePaymentIntentEvent.bind(this),
|
|
1291
|
+
"payment_intent.canceled": this.handlePaymentIntentEvent.bind(this),
|
|
1292
|
+
"payment_intent.created": this.handlePaymentIntentEvent.bind(this),
|
|
1293
|
+
"payment_intent.partially_funded": this.handlePaymentIntentEvent.bind(this),
|
|
1294
|
+
"payment_intent.payment_failed": this.handlePaymentIntentEvent.bind(this),
|
|
1295
|
+
"payment_intent.processing": this.handlePaymentIntentEvent.bind(this),
|
|
1296
|
+
"payment_intent.requires_action": this.handlePaymentIntentEvent.bind(this),
|
|
1297
|
+
"payment_intent.succeeded": this.handlePaymentIntentEvent.bind(this),
|
|
1298
|
+
"credit_note.created": this.handleCreditNoteEvent.bind(this),
|
|
1299
|
+
"credit_note.updated": this.handleCreditNoteEvent.bind(this),
|
|
1300
|
+
"credit_note.voided": this.handleCreditNoteEvent.bind(this),
|
|
1301
|
+
"radar.early_fraud_warning.created": this.handleEarlyFraudWarningEvent.bind(this),
|
|
1302
|
+
"radar.early_fraud_warning.updated": this.handleEarlyFraudWarningEvent.bind(this),
|
|
1303
|
+
"refund.created": this.handleRefundEvent.bind(this),
|
|
1304
|
+
"refund.failed": this.handleRefundEvent.bind(this),
|
|
1305
|
+
"refund.updated": this.handleRefundEvent.bind(this),
|
|
1306
|
+
"charge.refund.updated": this.handleRefundEvent.bind(this),
|
|
1307
|
+
"review.closed": this.handleReviewEvent.bind(this),
|
|
1308
|
+
"review.opened": this.handleReviewEvent.bind(this),
|
|
1309
|
+
"entitlements.active_entitlement_summary.updated": this.handleEntitlementSummaryEvent.bind(this)
|
|
1310
|
+
};
|
|
1311
|
+
// Resource registry - maps SyncObject → list/upsert operations for processNext()
|
|
1312
|
+
// Complements eventHandlers which maps event types → handlers for webhooks
|
|
1313
|
+
// Both registries share the same underlying upsert methods
|
|
1314
|
+
// Order field determines backfill sequence - parents before children for FK dependencies
|
|
1315
|
+
resourceRegistry = {
|
|
1316
|
+
product: {
|
|
1317
|
+
order: 1,
|
|
1318
|
+
// No dependencies
|
|
1319
|
+
listFn: (p) => this.stripe.products.list(p),
|
|
1320
|
+
upsertFn: (items, id) => this.upsertProducts(items, id),
|
|
1321
|
+
supportsCreatedFilter: true
|
|
1322
|
+
},
|
|
1323
|
+
price: {
|
|
1324
|
+
order: 2,
|
|
1325
|
+
// Depends on product
|
|
1326
|
+
listFn: (p) => this.stripe.prices.list(p),
|
|
1327
|
+
upsertFn: (items, id, bf) => this.upsertPrices(items, id, bf),
|
|
1328
|
+
supportsCreatedFilter: true
|
|
1329
|
+
},
|
|
1330
|
+
plan: {
|
|
1331
|
+
order: 3,
|
|
1332
|
+
// Depends on product
|
|
1333
|
+
listFn: (p) => this.stripe.plans.list(p),
|
|
1334
|
+
upsertFn: (items, id, bf) => this.upsertPlans(items, id, bf),
|
|
1335
|
+
supportsCreatedFilter: true
|
|
1336
|
+
},
|
|
1337
|
+
customer: {
|
|
1338
|
+
order: 4,
|
|
1339
|
+
// No dependencies
|
|
1340
|
+
listFn: (p) => this.stripe.customers.list(p),
|
|
1341
|
+
upsertFn: (items, id) => this.upsertCustomers(items, id),
|
|
1342
|
+
supportsCreatedFilter: true
|
|
1343
|
+
},
|
|
1344
|
+
subscription: {
|
|
1345
|
+
order: 5,
|
|
1346
|
+
// Depends on customer, price
|
|
1347
|
+
listFn: (p) => this.stripe.subscriptions.list(p),
|
|
1348
|
+
upsertFn: (items, id, bf) => this.upsertSubscriptions(items, id, bf),
|
|
1349
|
+
supportsCreatedFilter: true
|
|
1350
|
+
},
|
|
1351
|
+
subscription_schedules: {
|
|
1352
|
+
order: 6,
|
|
1353
|
+
// Depends on customer
|
|
1354
|
+
listFn: (p) => this.stripe.subscriptionSchedules.list(p),
|
|
1355
|
+
upsertFn: (items, id, bf) => this.upsertSubscriptionSchedules(items, id, bf),
|
|
1356
|
+
supportsCreatedFilter: true
|
|
1357
|
+
},
|
|
1358
|
+
invoice: {
|
|
1359
|
+
order: 7,
|
|
1360
|
+
// Depends on customer, subscription
|
|
1361
|
+
listFn: (p) => this.stripe.invoices.list(p),
|
|
1362
|
+
upsertFn: (items, id, bf) => this.upsertInvoices(items, id, bf),
|
|
1363
|
+
supportsCreatedFilter: true
|
|
1364
|
+
},
|
|
1365
|
+
charge: {
|
|
1366
|
+
order: 8,
|
|
1367
|
+
// Depends on customer, invoice
|
|
1368
|
+
listFn: (p) => this.stripe.charges.list(p),
|
|
1369
|
+
upsertFn: (items, id, bf) => this.upsertCharges(items, id, bf),
|
|
1370
|
+
supportsCreatedFilter: true
|
|
1371
|
+
},
|
|
1372
|
+
setup_intent: {
|
|
1373
|
+
order: 9,
|
|
1374
|
+
// Depends on customer
|
|
1375
|
+
listFn: (p) => this.stripe.setupIntents.list(p),
|
|
1376
|
+
upsertFn: (items, id, bf) => this.upsertSetupIntents(items, id, bf),
|
|
1377
|
+
supportsCreatedFilter: true
|
|
1378
|
+
},
|
|
1379
|
+
payment_method: {
|
|
1380
|
+
order: 10,
|
|
1381
|
+
// Depends on customer (special: iterates customers)
|
|
1382
|
+
listFn: (p) => this.stripe.paymentMethods.list(p),
|
|
1383
|
+
upsertFn: (items, id, bf) => this.upsertPaymentMethods(items, id, bf),
|
|
1384
|
+
supportsCreatedFilter: false
|
|
1385
|
+
// Requires customer param, can't filter by created
|
|
1386
|
+
},
|
|
1387
|
+
payment_intent: {
|
|
1388
|
+
order: 11,
|
|
1389
|
+
// Depends on customer
|
|
1390
|
+
listFn: (p) => this.stripe.paymentIntents.list(p),
|
|
1391
|
+
upsertFn: (items, id, bf) => this.upsertPaymentIntents(items, id, bf),
|
|
1392
|
+
supportsCreatedFilter: true
|
|
1393
|
+
},
|
|
1394
|
+
tax_id: {
|
|
1395
|
+
order: 12,
|
|
1396
|
+
// Depends on customer
|
|
1397
|
+
listFn: (p) => this.stripe.taxIds.list(p),
|
|
1398
|
+
upsertFn: (items, id, bf) => this.upsertTaxIds(items, id, bf),
|
|
1399
|
+
supportsCreatedFilter: false
|
|
1400
|
+
// taxIds don't support created filter
|
|
1401
|
+
},
|
|
1402
|
+
credit_note: {
|
|
1403
|
+
order: 13,
|
|
1404
|
+
// Depends on invoice
|
|
1405
|
+
listFn: (p) => this.stripe.creditNotes.list(p),
|
|
1406
|
+
upsertFn: (items, id, bf) => this.upsertCreditNotes(items, id, bf),
|
|
1407
|
+
supportsCreatedFilter: true
|
|
1408
|
+
// credit_notes support created filter
|
|
1409
|
+
},
|
|
1410
|
+
dispute: {
|
|
1411
|
+
order: 14,
|
|
1412
|
+
// Depends on charge
|
|
1413
|
+
listFn: (p) => this.stripe.disputes.list(p),
|
|
1414
|
+
upsertFn: (items, id, bf) => this.upsertDisputes(items, id, bf),
|
|
1415
|
+
supportsCreatedFilter: true
|
|
1416
|
+
},
|
|
1417
|
+
early_fraud_warning: {
|
|
1418
|
+
order: 15,
|
|
1419
|
+
// Depends on charge
|
|
1420
|
+
listFn: (p) => this.stripe.radar.earlyFraudWarnings.list(p),
|
|
1421
|
+
upsertFn: (items, id) => this.upsertEarlyFraudWarning(items, id),
|
|
1422
|
+
supportsCreatedFilter: true
|
|
1423
|
+
},
|
|
1424
|
+
refund: {
|
|
1425
|
+
order: 16,
|
|
1426
|
+
// Depends on charge
|
|
1427
|
+
listFn: (p) => this.stripe.refunds.list(p),
|
|
1428
|
+
upsertFn: (items, id, bf) => this.upsertRefunds(items, id, bf),
|
|
1429
|
+
supportsCreatedFilter: true
|
|
1430
|
+
},
|
|
1431
|
+
checkout_sessions: {
|
|
1432
|
+
order: 17,
|
|
1433
|
+
// Depends on customer (optional)
|
|
1434
|
+
listFn: (p) => this.stripe.checkout.sessions.list(p),
|
|
1435
|
+
upsertFn: (items, id) => this.upsertCheckoutSessions(items, id),
|
|
1436
|
+
supportsCreatedFilter: true
|
|
1437
|
+
}
|
|
1438
|
+
};
|
|
1439
|
+
async processEvent(event) {
|
|
1440
|
+
const objectAccountId = event.data?.object && typeof event.data.object === "object" && "account" in event.data.object ? event.data.object.account : void 0;
|
|
1441
|
+
const accountId = await this.getAccountId(objectAccountId);
|
|
1442
|
+
await this.getCurrentAccount();
|
|
1443
|
+
const handler = this.eventHandlers[event.type];
|
|
1444
|
+
if (handler) {
|
|
1445
|
+
const entityId = event.data?.object && typeof event.data.object === "object" && "id" in event.data.object ? event.data.object.id : "unknown";
|
|
1446
|
+
this.config.logger?.info(`Received webhook ${event.id}: ${event.type} for ${entityId}`);
|
|
1447
|
+
await handler(event, accountId);
|
|
1448
|
+
} else {
|
|
1449
|
+
this.config.logger?.warn(
|
|
1450
|
+
`Received unhandled webhook event: ${event.type} (${event.id}). Ignoring.`
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Returns an array of all webhook event types that this sync engine can handle.
|
|
1456
|
+
* Useful for configuring webhook endpoints with specific event subscriptions.
|
|
1457
|
+
*/
|
|
1458
|
+
getSupportedEventTypes() {
|
|
1459
|
+
return Object.keys(
|
|
1460
|
+
this.eventHandlers
|
|
1461
|
+
).sort();
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Returns an array of all object types that can be synced via processNext/processUntilDone.
|
|
1465
|
+
* Ordered for backfill: parents before children (products before prices, customers before subscriptions).
|
|
1466
|
+
* Order is determined by the `order` field in resourceRegistry.
|
|
1467
|
+
*/
|
|
1468
|
+
getSupportedSyncObjects() {
|
|
1469
|
+
return Object.entries(this.resourceRegistry).sort(([, a], [, b]) => a.order - b.order).map(([key]) => key);
|
|
1470
|
+
}
|
|
1471
|
+
// Event handler methods
|
|
1472
|
+
async handleChargeEvent(event, accountId) {
|
|
1473
|
+
const { entity: charge, refetched } = await this.fetchOrUseWebhookData(
|
|
1474
|
+
event.data.object,
|
|
1475
|
+
(id) => this.stripe.charges.retrieve(id),
|
|
1476
|
+
(charge2) => charge2.status === "failed" || charge2.status === "succeeded"
|
|
1477
|
+
);
|
|
1478
|
+
await this.upsertCharges([charge], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1479
|
+
}
|
|
1480
|
+
async handleCustomerDeletedEvent(event, accountId) {
|
|
1481
|
+
const customer = {
|
|
1482
|
+
id: event.data.object.id,
|
|
1483
|
+
object: "customer",
|
|
1484
|
+
deleted: true
|
|
1485
|
+
};
|
|
1486
|
+
await this.upsertCustomers([customer], accountId, this.getSyncTimestamp(event, false));
|
|
1487
|
+
}
|
|
1488
|
+
async handleCustomerEvent(event, accountId) {
|
|
1489
|
+
const { entity: customer, refetched } = await this.fetchOrUseWebhookData(
|
|
1490
|
+
event.data.object,
|
|
1491
|
+
(id) => this.stripe.customers.retrieve(id),
|
|
1492
|
+
(customer2) => customer2.deleted === true
|
|
1493
|
+
);
|
|
1494
|
+
await this.upsertCustomers([customer], accountId, this.getSyncTimestamp(event, refetched));
|
|
1495
|
+
}
|
|
1496
|
+
async handleCheckoutSessionEvent(event, accountId) {
|
|
1497
|
+
const { entity: checkoutSession, refetched } = await this.fetchOrUseWebhookData(
|
|
1498
|
+
event.data.object,
|
|
1499
|
+
(id) => this.stripe.checkout.sessions.retrieve(id)
|
|
1500
|
+
);
|
|
1501
|
+
await this.upsertCheckoutSessions(
|
|
1502
|
+
[checkoutSession],
|
|
1503
|
+
accountId,
|
|
1504
|
+
false,
|
|
1505
|
+
this.getSyncTimestamp(event, refetched)
|
|
1506
|
+
);
|
|
1507
|
+
}
|
|
1508
|
+
async handleSubscriptionEvent(event, accountId) {
|
|
1509
|
+
const { entity: subscription, refetched } = await this.fetchOrUseWebhookData(
|
|
1510
|
+
event.data.object,
|
|
1511
|
+
(id) => this.stripe.subscriptions.retrieve(id),
|
|
1512
|
+
(subscription2) => subscription2.status === "canceled" || subscription2.status === "incomplete_expired"
|
|
1513
|
+
);
|
|
1514
|
+
await this.upsertSubscriptions(
|
|
1515
|
+
[subscription],
|
|
1516
|
+
accountId,
|
|
1517
|
+
false,
|
|
1518
|
+
this.getSyncTimestamp(event, refetched)
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
async handleTaxIdEvent(event, accountId) {
|
|
1522
|
+
const { entity: taxId, refetched } = await this.fetchOrUseWebhookData(
|
|
1523
|
+
event.data.object,
|
|
1524
|
+
(id) => this.stripe.taxIds.retrieve(id)
|
|
1525
|
+
);
|
|
1526
|
+
await this.upsertTaxIds([taxId], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1527
|
+
}
|
|
1528
|
+
async handleTaxIdDeletedEvent(event, _accountId) {
|
|
1529
|
+
const taxId = event.data.object;
|
|
1530
|
+
await this.deleteTaxId(taxId.id);
|
|
1531
|
+
}
|
|
1532
|
+
async handleInvoiceEvent(event, accountId) {
|
|
1533
|
+
const { entity: invoice, refetched } = await this.fetchOrUseWebhookData(
|
|
1534
|
+
event.data.object,
|
|
1535
|
+
(id) => this.stripe.invoices.retrieve(id),
|
|
1536
|
+
(invoice2) => invoice2.status === "void"
|
|
1537
|
+
);
|
|
1538
|
+
await this.upsertInvoices([invoice], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1539
|
+
}
|
|
1540
|
+
async handleProductEvent(event, accountId) {
|
|
1541
|
+
try {
|
|
1542
|
+
const { entity: product, refetched } = await this.fetchOrUseWebhookData(
|
|
1543
|
+
event.data.object,
|
|
1544
|
+
(id) => this.stripe.products.retrieve(id)
|
|
1545
|
+
);
|
|
1546
|
+
await this.upsertProducts([product], accountId, this.getSyncTimestamp(event, refetched));
|
|
1547
|
+
} catch (err) {
|
|
1548
|
+
if (err instanceof import_stripe2.default.errors.StripeAPIError && err.code === "resource_missing") {
|
|
1549
|
+
const product = event.data.object;
|
|
1550
|
+
await this.deleteProduct(product.id);
|
|
1551
|
+
} else {
|
|
1552
|
+
throw err;
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
async handleProductDeletedEvent(event, _accountId) {
|
|
1557
|
+
const product = event.data.object;
|
|
1558
|
+
await this.deleteProduct(product.id);
|
|
1559
|
+
}
|
|
1560
|
+
async handlePriceEvent(event, accountId) {
|
|
1561
|
+
try {
|
|
1562
|
+
const { entity: price, refetched } = await this.fetchOrUseWebhookData(
|
|
1563
|
+
event.data.object,
|
|
1564
|
+
(id) => this.stripe.prices.retrieve(id)
|
|
1565
|
+
);
|
|
1566
|
+
await this.upsertPrices([price], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1567
|
+
} catch (err) {
|
|
1568
|
+
if (err instanceof import_stripe2.default.errors.StripeAPIError && err.code === "resource_missing") {
|
|
1569
|
+
const price = event.data.object;
|
|
1570
|
+
await this.deletePrice(price.id);
|
|
1571
|
+
} else {
|
|
1572
|
+
throw err;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
async handlePriceDeletedEvent(event, _accountId) {
|
|
1577
|
+
const price = event.data.object;
|
|
1578
|
+
await this.deletePrice(price.id);
|
|
1579
|
+
}
|
|
1580
|
+
async handlePlanEvent(event, accountId) {
|
|
1581
|
+
try {
|
|
1582
|
+
const { entity: plan, refetched } = await this.fetchOrUseWebhookData(
|
|
1583
|
+
event.data.object,
|
|
1584
|
+
(id) => this.stripe.plans.retrieve(id)
|
|
1585
|
+
);
|
|
1586
|
+
await this.upsertPlans([plan], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1587
|
+
} catch (err) {
|
|
1588
|
+
if (err instanceof import_stripe2.default.errors.StripeAPIError && err.code === "resource_missing") {
|
|
1589
|
+
const plan = event.data.object;
|
|
1590
|
+
await this.deletePlan(plan.id);
|
|
1591
|
+
} else {
|
|
1592
|
+
throw err;
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
async handlePlanDeletedEvent(event, _accountId) {
|
|
1597
|
+
const plan = event.data.object;
|
|
1598
|
+
await this.deletePlan(plan.id);
|
|
1599
|
+
}
|
|
1600
|
+
async handleSetupIntentEvent(event, accountId) {
|
|
1601
|
+
const { entity: setupIntent, refetched } = await this.fetchOrUseWebhookData(
|
|
1602
|
+
event.data.object,
|
|
1603
|
+
(id) => this.stripe.setupIntents.retrieve(id),
|
|
1604
|
+
(setupIntent2) => setupIntent2.status === "canceled" || setupIntent2.status === "succeeded"
|
|
1605
|
+
);
|
|
1606
|
+
await this.upsertSetupIntents(
|
|
1607
|
+
[setupIntent],
|
|
1608
|
+
accountId,
|
|
1609
|
+
false,
|
|
1610
|
+
this.getSyncTimestamp(event, refetched)
|
|
1611
|
+
);
|
|
1612
|
+
}
|
|
1613
|
+
async handleSubscriptionScheduleEvent(event, accountId) {
|
|
1614
|
+
const { entity: subscriptionSchedule, refetched } = await this.fetchOrUseWebhookData(
|
|
1615
|
+
event.data.object,
|
|
1616
|
+
(id) => this.stripe.subscriptionSchedules.retrieve(id),
|
|
1617
|
+
(schedule) => schedule.status === "canceled" || schedule.status === "completed"
|
|
1618
|
+
);
|
|
1619
|
+
await this.upsertSubscriptionSchedules(
|
|
1620
|
+
[subscriptionSchedule],
|
|
1621
|
+
accountId,
|
|
1622
|
+
false,
|
|
1623
|
+
this.getSyncTimestamp(event, refetched)
|
|
1624
|
+
);
|
|
1625
|
+
}
|
|
1626
|
+
async handlePaymentMethodEvent(event, accountId) {
|
|
1627
|
+
const { entity: paymentMethod, refetched } = await this.fetchOrUseWebhookData(
|
|
1628
|
+
event.data.object,
|
|
1629
|
+
(id) => this.stripe.paymentMethods.retrieve(id)
|
|
1630
|
+
);
|
|
1631
|
+
await this.upsertPaymentMethods(
|
|
1632
|
+
[paymentMethod],
|
|
1633
|
+
accountId,
|
|
1634
|
+
false,
|
|
1635
|
+
this.getSyncTimestamp(event, refetched)
|
|
1636
|
+
);
|
|
1637
|
+
}
|
|
1638
|
+
async handleDisputeEvent(event, accountId) {
|
|
1639
|
+
const { entity: dispute, refetched } = await this.fetchOrUseWebhookData(
|
|
1640
|
+
event.data.object,
|
|
1641
|
+
(id) => this.stripe.disputes.retrieve(id),
|
|
1642
|
+
(dispute2) => dispute2.status === "won" || dispute2.status === "lost"
|
|
1643
|
+
);
|
|
1644
|
+
await this.upsertDisputes([dispute], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1645
|
+
}
|
|
1646
|
+
async handlePaymentIntentEvent(event, accountId) {
|
|
1647
|
+
const { entity: paymentIntent, refetched } = await this.fetchOrUseWebhookData(
|
|
1648
|
+
event.data.object,
|
|
1649
|
+
(id) => this.stripe.paymentIntents.retrieve(id),
|
|
1650
|
+
// Final states - do not re-fetch from API
|
|
1651
|
+
(entity) => entity.status === "canceled" || entity.status === "succeeded"
|
|
1652
|
+
);
|
|
1653
|
+
await this.upsertPaymentIntents(
|
|
1654
|
+
[paymentIntent],
|
|
1655
|
+
accountId,
|
|
1656
|
+
false,
|
|
1657
|
+
this.getSyncTimestamp(event, refetched)
|
|
1658
|
+
);
|
|
1659
|
+
}
|
|
1660
|
+
async handleCreditNoteEvent(event, accountId) {
|
|
1661
|
+
const { entity: creditNote, refetched } = await this.fetchOrUseWebhookData(
|
|
1662
|
+
event.data.object,
|
|
1663
|
+
(id) => this.stripe.creditNotes.retrieve(id),
|
|
1664
|
+
(creditNote2) => creditNote2.status === "void"
|
|
1665
|
+
);
|
|
1666
|
+
await this.upsertCreditNotes(
|
|
1667
|
+
[creditNote],
|
|
1668
|
+
accountId,
|
|
1669
|
+
false,
|
|
1670
|
+
this.getSyncTimestamp(event, refetched)
|
|
1671
|
+
);
|
|
1672
|
+
}
|
|
1673
|
+
async handleEarlyFraudWarningEvent(event, accountId) {
|
|
1674
|
+
const { entity: earlyFraudWarning, refetched } = await this.fetchOrUseWebhookData(
|
|
1675
|
+
event.data.object,
|
|
1676
|
+
(id) => this.stripe.radar.earlyFraudWarnings.retrieve(id)
|
|
1677
|
+
);
|
|
1678
|
+
await this.upsertEarlyFraudWarning(
|
|
1679
|
+
[earlyFraudWarning],
|
|
1680
|
+
accountId,
|
|
1681
|
+
false,
|
|
1682
|
+
this.getSyncTimestamp(event, refetched)
|
|
1683
|
+
);
|
|
1684
|
+
}
|
|
1685
|
+
async handleRefundEvent(event, accountId) {
|
|
1686
|
+
const { entity: refund, refetched } = await this.fetchOrUseWebhookData(
|
|
1687
|
+
event.data.object,
|
|
1688
|
+
(id) => this.stripe.refunds.retrieve(id)
|
|
1689
|
+
);
|
|
1690
|
+
await this.upsertRefunds([refund], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1691
|
+
}
|
|
1692
|
+
async handleReviewEvent(event, accountId) {
|
|
1693
|
+
const { entity: review, refetched } = await this.fetchOrUseWebhookData(
|
|
1694
|
+
event.data.object,
|
|
1695
|
+
(id) => this.stripe.reviews.retrieve(id)
|
|
1696
|
+
);
|
|
1697
|
+
await this.upsertReviews([review], accountId, false, this.getSyncTimestamp(event, refetched));
|
|
1698
|
+
}
|
|
1699
|
+
async handleEntitlementSummaryEvent(event, accountId) {
|
|
1700
|
+
const activeEntitlementSummary = event.data.object;
|
|
1701
|
+
let entitlements = activeEntitlementSummary.entitlements;
|
|
1702
|
+
let refetched = false;
|
|
1703
|
+
if (this.config.revalidateObjectsViaStripeApi?.includes("entitlements")) {
|
|
1704
|
+
const { lastResponse, ...rest } = await this.stripe.entitlements.activeEntitlements.list({
|
|
1705
|
+
customer: activeEntitlementSummary.customer
|
|
1706
|
+
});
|
|
1707
|
+
entitlements = rest;
|
|
1708
|
+
refetched = true;
|
|
1709
|
+
}
|
|
1710
|
+
await this.deleteRemovedActiveEntitlements(
|
|
1711
|
+
activeEntitlementSummary.customer,
|
|
1712
|
+
entitlements.data.map((entitlement) => entitlement.id)
|
|
1713
|
+
);
|
|
1714
|
+
await this.upsertActiveEntitlements(
|
|
1715
|
+
activeEntitlementSummary.customer,
|
|
1716
|
+
entitlements.data,
|
|
1717
|
+
accountId,
|
|
1718
|
+
false,
|
|
1719
|
+
this.getSyncTimestamp(event, refetched)
|
|
1720
|
+
);
|
|
1721
|
+
}
|
|
1722
|
+
getSyncTimestamp(event, refetched) {
|
|
1723
|
+
return refetched ? (/* @__PURE__ */ new Date()).toISOString() : new Date(event.created * 1e3).toISOString();
|
|
1724
|
+
}
|
|
1725
|
+
shouldRefetchEntity(entity) {
|
|
1726
|
+
return this.config.revalidateObjectsViaStripeApi?.includes(entity.object);
|
|
1727
|
+
}
|
|
1728
|
+
async fetchOrUseWebhookData(entity, fetchFn, entityInFinalState) {
|
|
1729
|
+
if (!entity.id) return { entity, refetched: false };
|
|
1730
|
+
if (entityInFinalState && entityInFinalState(entity)) return { entity, refetched: false };
|
|
1731
|
+
if (this.shouldRefetchEntity(entity)) {
|
|
1732
|
+
const fetchedEntity = await fetchFn(entity.id);
|
|
1733
|
+
return { entity: fetchedEntity, refetched: true };
|
|
1734
|
+
}
|
|
1735
|
+
return { entity, refetched: false };
|
|
1736
|
+
}
|
|
1737
|
+
async syncSingleEntity(stripeId) {
|
|
1738
|
+
const accountId = await this.getAccountId();
|
|
1739
|
+
if (stripeId.startsWith("cus_")) {
|
|
1740
|
+
return this.stripe.customers.retrieve(stripeId).then((it) => {
|
|
1741
|
+
if (!it || it.deleted) return;
|
|
1742
|
+
return this.upsertCustomers([it], accountId);
|
|
1743
|
+
});
|
|
1744
|
+
} else if (stripeId.startsWith("in_")) {
|
|
1745
|
+
return this.stripe.invoices.retrieve(stripeId).then((it) => this.upsertInvoices([it], accountId));
|
|
1746
|
+
} else if (stripeId.startsWith("price_")) {
|
|
1747
|
+
return this.stripe.prices.retrieve(stripeId).then((it) => this.upsertPrices([it], accountId));
|
|
1748
|
+
} else if (stripeId.startsWith("prod_")) {
|
|
1749
|
+
return this.stripe.products.retrieve(stripeId).then((it) => this.upsertProducts([it], accountId));
|
|
1750
|
+
} else if (stripeId.startsWith("sub_")) {
|
|
1751
|
+
return this.stripe.subscriptions.retrieve(stripeId).then((it) => this.upsertSubscriptions([it], accountId));
|
|
1752
|
+
} else if (stripeId.startsWith("seti_")) {
|
|
1753
|
+
return this.stripe.setupIntents.retrieve(stripeId).then((it) => this.upsertSetupIntents([it], accountId));
|
|
1754
|
+
} else if (stripeId.startsWith("pm_")) {
|
|
1755
|
+
return this.stripe.paymentMethods.retrieve(stripeId).then((it) => this.upsertPaymentMethods([it], accountId));
|
|
1756
|
+
} else if (stripeId.startsWith("dp_") || stripeId.startsWith("du_")) {
|
|
1757
|
+
return this.stripe.disputes.retrieve(stripeId).then((it) => this.upsertDisputes([it], accountId));
|
|
1758
|
+
} else if (stripeId.startsWith("ch_")) {
|
|
1759
|
+
return this.stripe.charges.retrieve(stripeId).then((it) => this.upsertCharges([it], accountId, true));
|
|
1760
|
+
} else if (stripeId.startsWith("pi_")) {
|
|
1761
|
+
return this.stripe.paymentIntents.retrieve(stripeId).then((it) => this.upsertPaymentIntents([it], accountId));
|
|
1762
|
+
} else if (stripeId.startsWith("txi_")) {
|
|
1763
|
+
return this.stripe.taxIds.retrieve(stripeId).then((it) => this.upsertTaxIds([it], accountId));
|
|
1764
|
+
} else if (stripeId.startsWith("cn_")) {
|
|
1765
|
+
return this.stripe.creditNotes.retrieve(stripeId).then((it) => this.upsertCreditNotes([it], accountId));
|
|
1766
|
+
} else if (stripeId.startsWith("issfr_")) {
|
|
1767
|
+
return this.stripe.radar.earlyFraudWarnings.retrieve(stripeId).then((it) => this.upsertEarlyFraudWarning([it], accountId));
|
|
1768
|
+
} else if (stripeId.startsWith("prv_")) {
|
|
1769
|
+
return this.stripe.reviews.retrieve(stripeId).then((it) => this.upsertReviews([it], accountId));
|
|
1770
|
+
} else if (stripeId.startsWith("re_")) {
|
|
1771
|
+
return this.stripe.refunds.retrieve(stripeId).then((it) => this.upsertRefunds([it], accountId));
|
|
1772
|
+
} else if (stripeId.startsWith("feat_")) {
|
|
1773
|
+
return this.stripe.entitlements.features.retrieve(stripeId).then((it) => this.upsertFeatures([it], accountId));
|
|
1774
|
+
} else if (stripeId.startsWith("cs_")) {
|
|
1775
|
+
return this.stripe.checkout.sessions.retrieve(stripeId).then((it) => this.upsertCheckoutSessions([it], accountId));
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* Process one page of items for the specified object type.
|
|
1780
|
+
* Returns the number of items processed and whether there are more pages.
|
|
1781
|
+
*
|
|
1782
|
+
* This method is designed for queue-based consumption where each page
|
|
1783
|
+
* is processed as a separate job. Uses the observable sync system for tracking.
|
|
1784
|
+
*
|
|
1785
|
+
* @param object - The Stripe object type to sync (e.g., 'customer', 'product')
|
|
1786
|
+
* @param params - Optional parameters for filtering and run context
|
|
1787
|
+
* @returns ProcessNextResult with processed count, hasMore flag, and runStartedAt
|
|
1788
|
+
*
|
|
1789
|
+
* @example
|
|
1790
|
+
* ```typescript
|
|
1791
|
+
* // Queue worker
|
|
1792
|
+
* const { hasMore, runStartedAt } = await stripeSync.processNext('customer')
|
|
1793
|
+
* if (hasMore) {
|
|
1794
|
+
* await queue.send({ object: 'customer', runStartedAt })
|
|
1795
|
+
* }
|
|
1796
|
+
* ```
|
|
1797
|
+
*/
|
|
1798
|
+
async processNext(object, params) {
|
|
1799
|
+
await this.getCurrentAccount();
|
|
1800
|
+
const accountId = await this.getAccountId();
|
|
1801
|
+
const resourceName = this.getResourceName(object);
|
|
1802
|
+
let runStartedAt;
|
|
1803
|
+
if (params?.runStartedAt) {
|
|
1804
|
+
runStartedAt = params.runStartedAt;
|
|
1805
|
+
} else {
|
|
1806
|
+
const runKey = await this.postgresClient.getOrCreateSyncRun(
|
|
1807
|
+
accountId,
|
|
1808
|
+
params?.triggeredBy ?? "processNext"
|
|
1809
|
+
);
|
|
1810
|
+
if (!runKey) {
|
|
1811
|
+
const activeRun = await this.postgresClient.getActiveSyncRun(accountId);
|
|
1812
|
+
if (!activeRun) {
|
|
1813
|
+
throw new Error("Failed to get or create sync run");
|
|
1814
|
+
}
|
|
1815
|
+
runStartedAt = activeRun.runStartedAt;
|
|
1816
|
+
} else {
|
|
1817
|
+
runStartedAt = runKey.runStartedAt;
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
await this.postgresClient.createObjectRuns(accountId, runStartedAt, [resourceName]);
|
|
1821
|
+
const objRun = await this.postgresClient.getObjectRun(accountId, runStartedAt, resourceName);
|
|
1822
|
+
if (objRun?.status === "complete" || objRun?.status === "error") {
|
|
1823
|
+
return {
|
|
1824
|
+
processed: 0,
|
|
1825
|
+
hasMore: false,
|
|
1826
|
+
runStartedAt
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
if (objRun?.status === "pending") {
|
|
1830
|
+
const started = await this.postgresClient.tryStartObjectSync(
|
|
1831
|
+
accountId,
|
|
1832
|
+
runStartedAt,
|
|
1833
|
+
resourceName
|
|
1834
|
+
);
|
|
1835
|
+
if (!started) {
|
|
1836
|
+
return {
|
|
1837
|
+
processed: 0,
|
|
1838
|
+
hasMore: true,
|
|
1839
|
+
runStartedAt
|
|
1840
|
+
};
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
let cursor = null;
|
|
1844
|
+
if (!params?.created) {
|
|
1845
|
+
if (objRun?.cursor) {
|
|
1846
|
+
cursor = parseInt(objRun.cursor);
|
|
1847
|
+
} else {
|
|
1848
|
+
const lastCursor = await this.postgresClient.getLastCompletedCursor(accountId, resourceName);
|
|
1849
|
+
cursor = lastCursor ? parseInt(lastCursor) : null;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
const result = await this.fetchOnePage(
|
|
1853
|
+
object,
|
|
1854
|
+
accountId,
|
|
1855
|
+
resourceName,
|
|
1856
|
+
runStartedAt,
|
|
1857
|
+
cursor,
|
|
1858
|
+
params
|
|
1859
|
+
);
|
|
1860
|
+
return result;
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* Get the database resource name for a SyncObject type
|
|
1864
|
+
*/
|
|
1865
|
+
getResourceName(object) {
|
|
1866
|
+
const mapping = {
|
|
1867
|
+
customer: "customers",
|
|
1868
|
+
invoice: "invoices",
|
|
1869
|
+
price: "prices",
|
|
1870
|
+
product: "products",
|
|
1871
|
+
subscription: "subscriptions",
|
|
1872
|
+
subscription_schedules: "subscription_schedules",
|
|
1873
|
+
setup_intent: "setup_intents",
|
|
1874
|
+
payment_method: "payment_methods",
|
|
1875
|
+
dispute: "disputes",
|
|
1876
|
+
charge: "charges",
|
|
1877
|
+
payment_intent: "payment_intents",
|
|
1878
|
+
plan: "plans",
|
|
1879
|
+
tax_id: "tax_ids",
|
|
1880
|
+
credit_note: "credit_notes",
|
|
1881
|
+
early_fraud_warning: "early_fraud_warnings",
|
|
1882
|
+
refund: "refunds",
|
|
1883
|
+
checkout_sessions: "checkout_sessions"
|
|
1884
|
+
};
|
|
1885
|
+
return mapping[object] || object;
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* Fetch one page of items from Stripe and upsert to database.
|
|
1889
|
+
* Uses resourceRegistry for DRY list/upsert operations.
|
|
1890
|
+
* Uses the observable sync system for tracking progress.
|
|
1891
|
+
*/
|
|
1892
|
+
async fetchOnePage(object, accountId, resourceName, runStartedAt, cursor, params) {
|
|
1893
|
+
const limit = 100;
|
|
1894
|
+
if (object === "payment_method" || object === "tax_id") {
|
|
1895
|
+
this.config.logger?.warn(`processNext for ${object} requires customer context`);
|
|
1896
|
+
await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
|
|
1897
|
+
return { processed: 0, hasMore: false, runStartedAt };
|
|
1898
|
+
}
|
|
1899
|
+
const config = this.resourceRegistry[object];
|
|
1900
|
+
if (!config) {
|
|
1901
|
+
throw new Error(`Unsupported object type for processNext: ${object}`);
|
|
1902
|
+
}
|
|
1903
|
+
try {
|
|
1904
|
+
const listParams = { limit };
|
|
1905
|
+
if (config.supportsCreatedFilter) {
|
|
1906
|
+
const created = params?.created ?? (cursor ? { gte: cursor } : void 0);
|
|
1907
|
+
if (created) {
|
|
1908
|
+
listParams.created = created;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
const response = await config.listFn(listParams);
|
|
1912
|
+
if (response.data.length > 0) {
|
|
1913
|
+
this.config.logger?.info(`processNext: upserting ${response.data.length} ${resourceName}`);
|
|
1914
|
+
await config.upsertFn(response.data, accountId, params?.backfillRelatedEntities);
|
|
1915
|
+
await this.postgresClient.incrementObjectProgress(
|
|
1916
|
+
accountId,
|
|
1917
|
+
runStartedAt,
|
|
1918
|
+
resourceName,
|
|
1919
|
+
response.data.length
|
|
1920
|
+
);
|
|
1921
|
+
const maxCreated = Math.max(
|
|
1922
|
+
...response.data.map((i) => i.created || 0)
|
|
1923
|
+
);
|
|
1924
|
+
if (maxCreated > 0) {
|
|
1925
|
+
await this.postgresClient.updateObjectCursor(
|
|
1926
|
+
accountId,
|
|
1927
|
+
runStartedAt,
|
|
1928
|
+
resourceName,
|
|
1929
|
+
String(maxCreated)
|
|
1930
|
+
);
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
if (!response.has_more) {
|
|
1934
|
+
await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
|
|
1935
|
+
}
|
|
1936
|
+
return {
|
|
1937
|
+
processed: response.data.length,
|
|
1938
|
+
hasMore: response.has_more,
|
|
1939
|
+
runStartedAt
|
|
1940
|
+
};
|
|
1941
|
+
} catch (error) {
|
|
1942
|
+
await this.postgresClient.failObjectSync(
|
|
1943
|
+
accountId,
|
|
1944
|
+
runStartedAt,
|
|
1945
|
+
resourceName,
|
|
1946
|
+
error instanceof Error ? error.message : "Unknown error"
|
|
1947
|
+
);
|
|
1948
|
+
throw error;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
/**
|
|
1952
|
+
* Process all pages for all (or specified) object types until complete.
|
|
1953
|
+
*
|
|
1954
|
+
* @param params - Optional parameters for filtering and specifying object types
|
|
1955
|
+
* @returns SyncBackfill with counts for each synced resource type
|
|
1956
|
+
*/
|
|
1957
|
+
/**
|
|
1958
|
+
* Process all pages for a single object type until complete.
|
|
1959
|
+
* Loops processNext() internally until hasMore is false.
|
|
1960
|
+
*
|
|
1961
|
+
* @param object - The object type to sync
|
|
1962
|
+
* @param runStartedAt - The sync run to use (for sharing across objects)
|
|
1963
|
+
* @param params - Optional sync parameters
|
|
1964
|
+
* @returns Sync result with count of synced items
|
|
1965
|
+
*/
|
|
1966
|
+
async processObjectUntilDone(object, runStartedAt, params) {
|
|
1967
|
+
let totalSynced = 0;
|
|
1968
|
+
while (true) {
|
|
1969
|
+
const result = await this.processNext(object, {
|
|
1970
|
+
...params,
|
|
1971
|
+
runStartedAt,
|
|
1972
|
+
triggeredBy: "processUntilDone"
|
|
1973
|
+
});
|
|
1974
|
+
totalSynced += result.processed;
|
|
1975
|
+
if (!result.hasMore) {
|
|
1976
|
+
break;
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
return { synced: totalSynced };
|
|
1980
|
+
}
|
|
1981
|
+
async processUntilDone(params) {
|
|
1982
|
+
const { object } = params ?? { object: "all" };
|
|
1983
|
+
await this.getCurrentAccount();
|
|
1984
|
+
const accountId = await this.getAccountId();
|
|
1985
|
+
const runKey = await this.postgresClient.getOrCreateSyncRun(accountId, "processUntilDone");
|
|
1986
|
+
if (!runKey) {
|
|
1987
|
+
const activeRun = await this.postgresClient.getActiveSyncRun(accountId);
|
|
1988
|
+
if (!activeRun) {
|
|
1989
|
+
throw new Error("Failed to get or create sync run");
|
|
1990
|
+
}
|
|
1991
|
+
return this.processUntilDoneWithRun(activeRun.runStartedAt, object, params);
|
|
1992
|
+
}
|
|
1993
|
+
return this.processUntilDoneWithRun(runKey.runStartedAt, object, params);
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* Internal implementation of processUntilDone with an existing run.
|
|
1997
|
+
*/
|
|
1998
|
+
async processUntilDoneWithRun(runStartedAt, object, params) {
|
|
1999
|
+
const accountId = await this.getAccountId();
|
|
2000
|
+
const results = {};
|
|
2001
|
+
try {
|
|
2002
|
+
const objectsToSync = object === "all" || object === void 0 ? this.getSupportedSyncObjects() : [object];
|
|
2003
|
+
for (const obj of objectsToSync) {
|
|
2004
|
+
this.config.logger?.info(`Syncing ${obj}`);
|
|
2005
|
+
if (obj === "payment_method") {
|
|
2006
|
+
results.paymentMethods = await this.syncPaymentMethodsWithRun(runStartedAt, params);
|
|
2007
|
+
} else {
|
|
2008
|
+
const result = await this.processObjectUntilDone(obj, runStartedAt, params);
|
|
2009
|
+
switch (obj) {
|
|
2010
|
+
case "product":
|
|
2011
|
+
results.products = result;
|
|
2012
|
+
break;
|
|
2013
|
+
case "price":
|
|
2014
|
+
results.prices = result;
|
|
2015
|
+
break;
|
|
2016
|
+
case "plan":
|
|
2017
|
+
results.plans = result;
|
|
2018
|
+
break;
|
|
2019
|
+
case "customer":
|
|
2020
|
+
results.customers = result;
|
|
2021
|
+
break;
|
|
2022
|
+
case "subscription":
|
|
2023
|
+
results.subscriptions = result;
|
|
2024
|
+
break;
|
|
2025
|
+
case "subscription_schedules":
|
|
2026
|
+
results.subscriptionSchedules = result;
|
|
2027
|
+
break;
|
|
2028
|
+
case "invoice":
|
|
2029
|
+
results.invoices = result;
|
|
2030
|
+
break;
|
|
2031
|
+
case "charge":
|
|
2032
|
+
results.charges = result;
|
|
2033
|
+
break;
|
|
2034
|
+
case "setup_intent":
|
|
2035
|
+
results.setupIntents = result;
|
|
2036
|
+
break;
|
|
2037
|
+
case "payment_intent":
|
|
2038
|
+
results.paymentIntents = result;
|
|
2039
|
+
break;
|
|
2040
|
+
case "tax_id":
|
|
2041
|
+
results.taxIds = result;
|
|
2042
|
+
break;
|
|
2043
|
+
case "credit_note":
|
|
2044
|
+
results.creditNotes = result;
|
|
2045
|
+
break;
|
|
2046
|
+
case "dispute":
|
|
2047
|
+
results.disputes = result;
|
|
2048
|
+
break;
|
|
2049
|
+
case "early_fraud_warning":
|
|
2050
|
+
results.earlyFraudWarnings = result;
|
|
2051
|
+
break;
|
|
2052
|
+
case "refund":
|
|
2053
|
+
results.refunds = result;
|
|
2054
|
+
break;
|
|
2055
|
+
case "checkout_sessions":
|
|
2056
|
+
results.checkoutSessions = result;
|
|
2057
|
+
break;
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
await this.postgresClient.closeSyncRun(accountId, runStartedAt);
|
|
2062
|
+
return results;
|
|
2063
|
+
} catch (error) {
|
|
2064
|
+
await this.postgresClient.closeSyncRun(accountId, runStartedAt);
|
|
2065
|
+
throw error;
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
/**
|
|
2069
|
+
* Sync payment methods with an existing run (special case - iterates customers)
|
|
2070
|
+
*/
|
|
2071
|
+
async syncPaymentMethodsWithRun(runStartedAt, syncParams) {
|
|
2072
|
+
const accountId = await this.getAccountId();
|
|
2073
|
+
const resourceName = "payment_methods";
|
|
2074
|
+
await this.postgresClient.createObjectRuns(accountId, runStartedAt, [resourceName]);
|
|
2075
|
+
await this.postgresClient.tryStartObjectSync(accountId, runStartedAt, resourceName);
|
|
2076
|
+
try {
|
|
2077
|
+
const prepared = (0, import_yesql2.pg)(
|
|
2078
|
+
`select id from "stripe"."customers" WHERE COALESCE(deleted, false) <> true;`
|
|
2079
|
+
)([]);
|
|
2080
|
+
const customerIds = await this.postgresClient.query(prepared.text, prepared.values).then(({ rows }) => rows.map((it) => it.id));
|
|
2081
|
+
this.config.logger?.info(`Getting payment methods for ${customerIds.length} customers`);
|
|
2082
|
+
let synced = 0;
|
|
2083
|
+
for (const customerIdChunk of chunkArray(customerIds, 10)) {
|
|
2084
|
+
await Promise.all(
|
|
2085
|
+
customerIdChunk.map(async (customerId) => {
|
|
2086
|
+
const CHECKPOINT_SIZE = 100;
|
|
2087
|
+
let currentBatch = [];
|
|
2088
|
+
for await (const item of this.stripe.paymentMethods.list({
|
|
2089
|
+
limit: 100,
|
|
2090
|
+
customer: customerId
|
|
2091
|
+
})) {
|
|
2092
|
+
currentBatch.push(item);
|
|
2093
|
+
if (currentBatch.length >= CHECKPOINT_SIZE) {
|
|
2094
|
+
await this.upsertPaymentMethods(
|
|
2095
|
+
currentBatch,
|
|
2096
|
+
accountId,
|
|
2097
|
+
syncParams?.backfillRelatedEntities
|
|
2098
|
+
);
|
|
2099
|
+
synced += currentBatch.length;
|
|
2100
|
+
await this.postgresClient.incrementObjectProgress(
|
|
2101
|
+
accountId,
|
|
2102
|
+
runStartedAt,
|
|
2103
|
+
resourceName,
|
|
2104
|
+
currentBatch.length
|
|
2105
|
+
);
|
|
2106
|
+
currentBatch = [];
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
if (currentBatch.length > 0) {
|
|
2110
|
+
await this.upsertPaymentMethods(
|
|
2111
|
+
currentBatch,
|
|
2112
|
+
accountId,
|
|
2113
|
+
syncParams?.backfillRelatedEntities
|
|
2114
|
+
);
|
|
2115
|
+
synced += currentBatch.length;
|
|
2116
|
+
await this.postgresClient.incrementObjectProgress(
|
|
2117
|
+
accountId,
|
|
2118
|
+
runStartedAt,
|
|
2119
|
+
resourceName,
|
|
2120
|
+
currentBatch.length
|
|
2121
|
+
);
|
|
2122
|
+
}
|
|
2123
|
+
})
|
|
2124
|
+
);
|
|
2125
|
+
}
|
|
2126
|
+
await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
|
|
2127
|
+
return { synced };
|
|
2128
|
+
} catch (error) {
|
|
2129
|
+
await this.postgresClient.failObjectSync(
|
|
2130
|
+
accountId,
|
|
2131
|
+
runStartedAt,
|
|
2132
|
+
resourceName,
|
|
2133
|
+
error instanceof Error ? error.message : "Unknown error"
|
|
2134
|
+
);
|
|
2135
|
+
throw error;
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
async syncProducts(syncParams) {
|
|
2139
|
+
this.config.logger?.info("Syncing products");
|
|
2140
|
+
return this.withSyncRun("products", "syncProducts", async (cursor, runStartedAt) => {
|
|
2141
|
+
const accountId = await this.getAccountId();
|
|
2142
|
+
const params = { limit: 100 };
|
|
2143
|
+
if (syncParams?.created) {
|
|
2144
|
+
params.created = syncParams.created;
|
|
2145
|
+
} else if (cursor) {
|
|
2146
|
+
params.created = { gte: cursor };
|
|
2147
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2148
|
+
}
|
|
2149
|
+
return this.fetchAndUpsert(
|
|
2150
|
+
() => this.stripe.products.list(params),
|
|
2151
|
+
(products) => this.upsertProducts(products, accountId),
|
|
2152
|
+
accountId,
|
|
2153
|
+
"products",
|
|
2154
|
+
runStartedAt
|
|
2155
|
+
);
|
|
2156
|
+
});
|
|
2157
|
+
}
|
|
2158
|
+
async syncPrices(syncParams) {
|
|
2159
|
+
this.config.logger?.info("Syncing prices");
|
|
2160
|
+
return this.withSyncRun("prices", "syncPrices", async (cursor, runStartedAt) => {
|
|
2161
|
+
const accountId = await this.getAccountId();
|
|
2162
|
+
const params = { limit: 100 };
|
|
2163
|
+
if (syncParams?.created) {
|
|
2164
|
+
params.created = syncParams.created;
|
|
2165
|
+
} else if (cursor) {
|
|
2166
|
+
params.created = { gte: cursor };
|
|
2167
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2168
|
+
}
|
|
2169
|
+
return this.fetchAndUpsert(
|
|
2170
|
+
() => this.stripe.prices.list(params),
|
|
2171
|
+
(prices) => this.upsertPrices(prices, accountId, syncParams?.backfillRelatedEntities),
|
|
2172
|
+
accountId,
|
|
2173
|
+
"prices",
|
|
2174
|
+
runStartedAt
|
|
2175
|
+
);
|
|
2176
|
+
});
|
|
2177
|
+
}
|
|
2178
|
+
async syncPlans(syncParams) {
|
|
2179
|
+
this.config.logger?.info("Syncing plans");
|
|
2180
|
+
return this.withSyncRun("plans", "syncPlans", async (cursor, runStartedAt) => {
|
|
2181
|
+
const accountId = await this.getAccountId();
|
|
2182
|
+
const params = { limit: 100 };
|
|
2183
|
+
if (syncParams?.created) {
|
|
2184
|
+
params.created = syncParams.created;
|
|
2185
|
+
} else if (cursor) {
|
|
2186
|
+
params.created = { gte: cursor };
|
|
2187
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2188
|
+
}
|
|
2189
|
+
return this.fetchAndUpsert(
|
|
2190
|
+
() => this.stripe.plans.list(params),
|
|
2191
|
+
(plans) => this.upsertPlans(plans, accountId, syncParams?.backfillRelatedEntities),
|
|
2192
|
+
accountId,
|
|
2193
|
+
"plans",
|
|
2194
|
+
runStartedAt
|
|
2195
|
+
);
|
|
2196
|
+
});
|
|
2197
|
+
}
|
|
2198
|
+
async syncCustomers(syncParams) {
|
|
2199
|
+
this.config.logger?.info("Syncing customers");
|
|
2200
|
+
return this.withSyncRun("customers", "syncCustomers", async (cursor, runStartedAt) => {
|
|
2201
|
+
const accountId = await this.getAccountId();
|
|
2202
|
+
const params = { limit: 100 };
|
|
2203
|
+
if (syncParams?.created) {
|
|
2204
|
+
params.created = syncParams.created;
|
|
2205
|
+
} else if (cursor) {
|
|
2206
|
+
params.created = { gte: cursor };
|
|
2207
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2208
|
+
}
|
|
2209
|
+
return this.fetchAndUpsert(
|
|
2210
|
+
() => this.stripe.customers.list(params),
|
|
2211
|
+
// @ts-expect-error
|
|
2212
|
+
(items) => this.upsertCustomers(items, accountId),
|
|
2213
|
+
accountId,
|
|
2214
|
+
"customers",
|
|
2215
|
+
runStartedAt
|
|
2216
|
+
);
|
|
2217
|
+
});
|
|
2218
|
+
}
|
|
2219
|
+
async syncSubscriptions(syncParams) {
|
|
2220
|
+
this.config.logger?.info("Syncing subscriptions");
|
|
2221
|
+
return this.withSyncRun("subscriptions", "syncSubscriptions", async (cursor, runStartedAt) => {
|
|
2222
|
+
const accountId = await this.getAccountId();
|
|
2223
|
+
const params = { status: "all", limit: 100 };
|
|
2224
|
+
if (syncParams?.created) {
|
|
2225
|
+
params.created = syncParams.created;
|
|
2226
|
+
} else if (cursor) {
|
|
2227
|
+
params.created = { gte: cursor };
|
|
2228
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2229
|
+
}
|
|
2230
|
+
return this.fetchAndUpsert(
|
|
2231
|
+
() => this.stripe.subscriptions.list(params),
|
|
2232
|
+
(items) => this.upsertSubscriptions(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2233
|
+
accountId,
|
|
2234
|
+
"subscriptions",
|
|
2235
|
+
runStartedAt
|
|
2236
|
+
);
|
|
2237
|
+
});
|
|
2238
|
+
}
|
|
2239
|
+
async syncSubscriptionSchedules(syncParams) {
|
|
2240
|
+
this.config.logger?.info("Syncing subscription schedules");
|
|
2241
|
+
return this.withSyncRun(
|
|
2242
|
+
"subscription_schedules",
|
|
2243
|
+
"syncSubscriptionSchedules",
|
|
2244
|
+
async (cursor, runStartedAt) => {
|
|
2245
|
+
const accountId = await this.getAccountId();
|
|
2246
|
+
const params = { limit: 100 };
|
|
2247
|
+
if (syncParams?.created) {
|
|
2248
|
+
params.created = syncParams.created;
|
|
2249
|
+
} else if (cursor) {
|
|
2250
|
+
params.created = { gte: cursor };
|
|
2251
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2252
|
+
}
|
|
2253
|
+
return this.fetchAndUpsert(
|
|
2254
|
+
() => this.stripe.subscriptionSchedules.list(params),
|
|
2255
|
+
(items) => this.upsertSubscriptionSchedules(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2256
|
+
accountId,
|
|
2257
|
+
"subscription_schedules",
|
|
2258
|
+
runStartedAt
|
|
2259
|
+
);
|
|
2260
|
+
}
|
|
2261
|
+
);
|
|
2262
|
+
}
|
|
2263
|
+
async syncInvoices(syncParams) {
|
|
2264
|
+
this.config.logger?.info("Syncing invoices");
|
|
2265
|
+
return this.withSyncRun("invoices", "syncInvoices", async (cursor, runStartedAt) => {
|
|
2266
|
+
const accountId = await this.getAccountId();
|
|
2267
|
+
const params = { limit: 100 };
|
|
2268
|
+
if (syncParams?.created) {
|
|
2269
|
+
params.created = syncParams.created;
|
|
2270
|
+
} else if (cursor) {
|
|
2271
|
+
params.created = { gte: cursor };
|
|
2272
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2273
|
+
}
|
|
2274
|
+
return this.fetchAndUpsert(
|
|
2275
|
+
() => this.stripe.invoices.list(params),
|
|
2276
|
+
(items) => this.upsertInvoices(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2277
|
+
accountId,
|
|
2278
|
+
"invoices",
|
|
2279
|
+
runStartedAt
|
|
2280
|
+
);
|
|
2281
|
+
});
|
|
2282
|
+
}
|
|
2283
|
+
async syncCharges(syncParams) {
|
|
2284
|
+
this.config.logger?.info("Syncing charges");
|
|
2285
|
+
return this.withSyncRun("charges", "syncCharges", async (cursor, runStartedAt) => {
|
|
2286
|
+
const accountId = await this.getAccountId();
|
|
2287
|
+
const params = { limit: 100 };
|
|
2288
|
+
if (syncParams?.created) {
|
|
2289
|
+
params.created = syncParams.created;
|
|
2290
|
+
} else if (cursor) {
|
|
2291
|
+
params.created = { gte: cursor };
|
|
2292
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2293
|
+
}
|
|
2294
|
+
return this.fetchAndUpsert(
|
|
2295
|
+
() => this.stripe.charges.list(params),
|
|
2296
|
+
(items) => this.upsertCharges(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2297
|
+
accountId,
|
|
2298
|
+
"charges",
|
|
2299
|
+
runStartedAt
|
|
2300
|
+
);
|
|
2301
|
+
});
|
|
2302
|
+
}
|
|
2303
|
+
async syncSetupIntents(syncParams) {
|
|
2304
|
+
this.config.logger?.info("Syncing setup_intents");
|
|
2305
|
+
return this.withSyncRun("setup_intents", "syncSetupIntents", async (cursor, runStartedAt) => {
|
|
2306
|
+
const accountId = await this.getAccountId();
|
|
2307
|
+
const params = { limit: 100 };
|
|
2308
|
+
if (syncParams?.created) {
|
|
2309
|
+
params.created = syncParams.created;
|
|
2310
|
+
} else if (cursor) {
|
|
2311
|
+
params.created = { gte: cursor };
|
|
2312
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2313
|
+
}
|
|
2314
|
+
return this.fetchAndUpsert(
|
|
2315
|
+
() => this.stripe.setupIntents.list(params),
|
|
2316
|
+
(items) => this.upsertSetupIntents(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2317
|
+
accountId,
|
|
2318
|
+
"setup_intents",
|
|
2319
|
+
runStartedAt
|
|
2320
|
+
);
|
|
2321
|
+
});
|
|
2322
|
+
}
|
|
2323
|
+
async syncPaymentIntents(syncParams) {
|
|
2324
|
+
this.config.logger?.info("Syncing payment_intents");
|
|
2325
|
+
return this.withSyncRun(
|
|
2326
|
+
"payment_intents",
|
|
2327
|
+
"syncPaymentIntents",
|
|
2328
|
+
async (cursor, runStartedAt) => {
|
|
2329
|
+
const accountId = await this.getAccountId();
|
|
2330
|
+
const params = { limit: 100 };
|
|
2331
|
+
if (syncParams?.created) {
|
|
2332
|
+
params.created = syncParams.created;
|
|
2333
|
+
} else if (cursor) {
|
|
2334
|
+
params.created = { gte: cursor };
|
|
2335
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2336
|
+
}
|
|
2337
|
+
return this.fetchAndUpsert(
|
|
2338
|
+
() => this.stripe.paymentIntents.list(params),
|
|
2339
|
+
(items) => this.upsertPaymentIntents(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2340
|
+
accountId,
|
|
2341
|
+
"payment_intents",
|
|
2342
|
+
runStartedAt
|
|
2343
|
+
);
|
|
2344
|
+
}
|
|
2345
|
+
);
|
|
2346
|
+
}
|
|
2347
|
+
async syncTaxIds(syncParams) {
|
|
2348
|
+
this.config.logger?.info("Syncing tax_ids");
|
|
2349
|
+
return this.withSyncRun("tax_ids", "syncTaxIds", async (_cursor, runStartedAt) => {
|
|
2350
|
+
const accountId = await this.getAccountId();
|
|
2351
|
+
const params = { limit: 100 };
|
|
2352
|
+
return this.fetchAndUpsert(
|
|
2353
|
+
() => this.stripe.taxIds.list(params),
|
|
2354
|
+
(items) => this.upsertTaxIds(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2355
|
+
accountId,
|
|
2356
|
+
"tax_ids",
|
|
2357
|
+
runStartedAt
|
|
2358
|
+
);
|
|
2359
|
+
});
|
|
2360
|
+
}
|
|
2361
|
+
async syncPaymentMethods(syncParams) {
|
|
2362
|
+
this.config.logger?.info("Syncing payment method");
|
|
2363
|
+
return this.withSyncRun(
|
|
2364
|
+
"payment_methods",
|
|
2365
|
+
"syncPaymentMethods",
|
|
2366
|
+
async (_cursor, runStartedAt) => {
|
|
2367
|
+
const accountId = await this.getAccountId();
|
|
2368
|
+
const prepared = (0, import_yesql2.pg)(
|
|
2369
|
+
`select id from "stripe"."customers" WHERE COALESCE(deleted, false) <> true;`
|
|
2370
|
+
)([]);
|
|
2371
|
+
const customerIds = await this.postgresClient.query(prepared.text, prepared.values).then(({ rows }) => rows.map((it) => it.id));
|
|
2372
|
+
this.config.logger?.info(`Getting payment methods for ${customerIds.length} customers`);
|
|
2373
|
+
let synced = 0;
|
|
2374
|
+
for (const customerIdChunk of chunkArray(customerIds, 10)) {
|
|
2375
|
+
await Promise.all(
|
|
2376
|
+
customerIdChunk.map(async (customerId) => {
|
|
2377
|
+
const CHECKPOINT_SIZE = 100;
|
|
2378
|
+
let currentBatch = [];
|
|
2379
|
+
for await (const item of this.stripe.paymentMethods.list({
|
|
2380
|
+
limit: 100,
|
|
2381
|
+
customer: customerId
|
|
2382
|
+
})) {
|
|
2383
|
+
currentBatch.push(item);
|
|
2384
|
+
if (currentBatch.length >= CHECKPOINT_SIZE) {
|
|
2385
|
+
await this.upsertPaymentMethods(
|
|
2386
|
+
currentBatch,
|
|
2387
|
+
accountId,
|
|
2388
|
+
syncParams?.backfillRelatedEntities
|
|
2389
|
+
);
|
|
2390
|
+
synced += currentBatch.length;
|
|
2391
|
+
await this.postgresClient.incrementObjectProgress(
|
|
2392
|
+
accountId,
|
|
2393
|
+
runStartedAt,
|
|
2394
|
+
"payment_methods",
|
|
2395
|
+
currentBatch.length
|
|
2396
|
+
);
|
|
2397
|
+
currentBatch = [];
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
if (currentBatch.length > 0) {
|
|
2401
|
+
await this.upsertPaymentMethods(
|
|
2402
|
+
currentBatch,
|
|
2403
|
+
accountId,
|
|
2404
|
+
syncParams?.backfillRelatedEntities
|
|
2405
|
+
);
|
|
2406
|
+
synced += currentBatch.length;
|
|
2407
|
+
await this.postgresClient.incrementObjectProgress(
|
|
2408
|
+
accountId,
|
|
2409
|
+
runStartedAt,
|
|
2410
|
+
"payment_methods",
|
|
2411
|
+
currentBatch.length
|
|
2412
|
+
);
|
|
2413
|
+
}
|
|
2414
|
+
})
|
|
2415
|
+
);
|
|
2416
|
+
}
|
|
2417
|
+
await this.postgresClient.completeObjectSync(accountId, runStartedAt, "payment_methods");
|
|
2418
|
+
return { synced };
|
|
2419
|
+
}
|
|
2420
|
+
);
|
|
2421
|
+
}
|
|
2422
|
+
async syncDisputes(syncParams) {
|
|
2423
|
+
this.config.logger?.info("Syncing disputes");
|
|
2424
|
+
return this.withSyncRun("disputes", "syncDisputes", async (cursor, runStartedAt) => {
|
|
2425
|
+
const accountId = await this.getAccountId();
|
|
2426
|
+
const params = { limit: 100 };
|
|
2427
|
+
if (syncParams?.created) {
|
|
2428
|
+
params.created = syncParams.created;
|
|
2429
|
+
} else if (cursor) {
|
|
2430
|
+
params.created = { gte: cursor };
|
|
2431
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2432
|
+
}
|
|
2433
|
+
return this.fetchAndUpsert(
|
|
2434
|
+
() => this.stripe.disputes.list(params),
|
|
2435
|
+
(items) => this.upsertDisputes(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2436
|
+
accountId,
|
|
2437
|
+
"disputes",
|
|
2438
|
+
runStartedAt
|
|
2439
|
+
);
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
async syncEarlyFraudWarnings(syncParams) {
|
|
2443
|
+
this.config.logger?.info("Syncing early fraud warnings");
|
|
2444
|
+
return this.withSyncRun(
|
|
2445
|
+
"early_fraud_warnings",
|
|
2446
|
+
"syncEarlyFraudWarnings",
|
|
2447
|
+
async (cursor, runStartedAt) => {
|
|
2448
|
+
const accountId = await this.getAccountId();
|
|
2449
|
+
const params = { limit: 100 };
|
|
2450
|
+
if (syncParams?.created) {
|
|
2451
|
+
params.created = syncParams.created;
|
|
2452
|
+
} else if (cursor) {
|
|
2453
|
+
params.created = { gte: cursor };
|
|
2454
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2455
|
+
}
|
|
2456
|
+
return this.fetchAndUpsert(
|
|
2457
|
+
() => this.stripe.radar.earlyFraudWarnings.list(params),
|
|
2458
|
+
(items) => this.upsertEarlyFraudWarning(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2459
|
+
accountId,
|
|
2460
|
+
"early_fraud_warnings",
|
|
2461
|
+
runStartedAt
|
|
2462
|
+
);
|
|
2463
|
+
}
|
|
2464
|
+
);
|
|
2465
|
+
}
|
|
2466
|
+
async syncRefunds(syncParams) {
|
|
2467
|
+
this.config.logger?.info("Syncing refunds");
|
|
2468
|
+
return this.withSyncRun("refunds", "syncRefunds", async (cursor, runStartedAt) => {
|
|
2469
|
+
const accountId = await this.getAccountId();
|
|
2470
|
+
const params = { limit: 100 };
|
|
2471
|
+
if (syncParams?.created) {
|
|
2472
|
+
params.created = syncParams.created;
|
|
2473
|
+
} else if (cursor) {
|
|
2474
|
+
params.created = { gte: cursor };
|
|
2475
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2476
|
+
}
|
|
2477
|
+
return this.fetchAndUpsert(
|
|
2478
|
+
() => this.stripe.refunds.list(params),
|
|
2479
|
+
(items) => this.upsertRefunds(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2480
|
+
accountId,
|
|
2481
|
+
"refunds",
|
|
2482
|
+
runStartedAt
|
|
2483
|
+
);
|
|
2484
|
+
});
|
|
2485
|
+
}
|
|
2486
|
+
async syncCreditNotes(syncParams) {
|
|
2487
|
+
this.config.logger?.info("Syncing credit notes");
|
|
2488
|
+
return this.withSyncRun("credit_notes", "syncCreditNotes", async (cursor, runStartedAt) => {
|
|
2489
|
+
const accountId = await this.getAccountId();
|
|
2490
|
+
const params = { limit: 100 };
|
|
2491
|
+
if (syncParams?.created) {
|
|
2492
|
+
params.created = syncParams.created;
|
|
2493
|
+
} else if (cursor) {
|
|
2494
|
+
params.created = { gte: cursor };
|
|
2495
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2496
|
+
}
|
|
2497
|
+
return this.fetchAndUpsert(
|
|
2498
|
+
() => this.stripe.creditNotes.list(params),
|
|
2499
|
+
(creditNotes) => this.upsertCreditNotes(creditNotes, accountId),
|
|
2500
|
+
accountId,
|
|
2501
|
+
"credit_notes",
|
|
2502
|
+
runStartedAt
|
|
2503
|
+
);
|
|
2504
|
+
});
|
|
2505
|
+
}
|
|
2506
|
+
async syncFeatures(syncParams) {
|
|
2507
|
+
this.config.logger?.info("Syncing features");
|
|
2508
|
+
return this.withSyncRun("features", "syncFeatures", async (cursor, runStartedAt) => {
|
|
2509
|
+
const accountId = await this.getAccountId();
|
|
2510
|
+
const params = {
|
|
2511
|
+
limit: 100,
|
|
2512
|
+
...syncParams?.pagination
|
|
2513
|
+
};
|
|
2514
|
+
return this.fetchAndUpsert(
|
|
2515
|
+
() => this.stripe.entitlements.features.list(params),
|
|
2516
|
+
(features) => this.upsertFeatures(features, accountId),
|
|
2517
|
+
accountId,
|
|
2518
|
+
"features",
|
|
2519
|
+
runStartedAt
|
|
2520
|
+
);
|
|
2521
|
+
});
|
|
2522
|
+
}
|
|
2523
|
+
async syncEntitlements(customerId, syncParams) {
|
|
2524
|
+
this.config.logger?.info("Syncing entitlements");
|
|
2525
|
+
return this.withSyncRun(
|
|
2526
|
+
"active_entitlements",
|
|
2527
|
+
"syncEntitlements",
|
|
2528
|
+
async (cursor, runStartedAt) => {
|
|
2529
|
+
const accountId = await this.getAccountId();
|
|
2530
|
+
const params = {
|
|
2531
|
+
customer: customerId,
|
|
2532
|
+
limit: 100,
|
|
2533
|
+
...syncParams?.pagination
|
|
2534
|
+
};
|
|
2535
|
+
return this.fetchAndUpsert(
|
|
2536
|
+
() => this.stripe.entitlements.activeEntitlements.list(params),
|
|
2537
|
+
(entitlements) => this.upsertActiveEntitlements(customerId, entitlements, accountId),
|
|
2538
|
+
accountId,
|
|
2539
|
+
"active_entitlements",
|
|
2540
|
+
runStartedAt
|
|
2541
|
+
);
|
|
2542
|
+
}
|
|
2543
|
+
);
|
|
2544
|
+
}
|
|
2545
|
+
async syncCheckoutSessions(syncParams) {
|
|
2546
|
+
this.config.logger?.info("Syncing checkout sessions");
|
|
2547
|
+
return this.withSyncRun(
|
|
2548
|
+
"checkout_sessions",
|
|
2549
|
+
"syncCheckoutSessions",
|
|
2550
|
+
async (cursor, runStartedAt) => {
|
|
2551
|
+
const accountId = await this.getAccountId();
|
|
2552
|
+
const params = { limit: 100 };
|
|
2553
|
+
if (syncParams?.created) {
|
|
2554
|
+
params.created = syncParams.created;
|
|
2555
|
+
} else if (cursor) {
|
|
2556
|
+
params.created = { gte: cursor };
|
|
2557
|
+
this.config.logger?.info(`Incremental sync from cursor: ${cursor}`);
|
|
2558
|
+
}
|
|
2559
|
+
return this.fetchAndUpsert(
|
|
2560
|
+
() => this.stripe.checkout.sessions.list(params),
|
|
2561
|
+
(items) => this.upsertCheckoutSessions(items, accountId, syncParams?.backfillRelatedEntities),
|
|
2562
|
+
accountId,
|
|
2563
|
+
"checkout_sessions",
|
|
2564
|
+
runStartedAt
|
|
2565
|
+
);
|
|
2566
|
+
}
|
|
2567
|
+
);
|
|
2568
|
+
}
|
|
2569
|
+
/**
|
|
2570
|
+
* Helper to wrap a sync operation in the observable sync system.
|
|
2571
|
+
* Creates/gets a sync run, sets up the object run, gets cursor, and handles completion.
|
|
2572
|
+
*
|
|
2573
|
+
* @param resourceName - The resource being synced (e.g., 'products', 'customers')
|
|
2574
|
+
* @param triggeredBy - What triggered this sync (for observability)
|
|
2575
|
+
* @param fn - The sync function to execute, receives cursor and runStartedAt
|
|
2576
|
+
* @returns The result of the sync function
|
|
2577
|
+
*/
|
|
2578
|
+
async withSyncRun(resourceName, triggeredBy, fn) {
|
|
2579
|
+
const accountId = await this.getAccountId();
|
|
2580
|
+
const lastCursor = await this.postgresClient.getLastCompletedCursor(accountId, resourceName);
|
|
2581
|
+
const cursor = lastCursor ? parseInt(lastCursor) : null;
|
|
2582
|
+
const runKey = await this.postgresClient.getOrCreateSyncRun(accountId, triggeredBy);
|
|
2583
|
+
if (!runKey) {
|
|
2584
|
+
const activeRun = await this.postgresClient.getActiveSyncRun(accountId);
|
|
2585
|
+
if (!activeRun) {
|
|
2586
|
+
throw new Error("Failed to get or create sync run");
|
|
2587
|
+
}
|
|
2588
|
+
throw new Error("Another sync is already running for this account");
|
|
2589
|
+
}
|
|
2590
|
+
const { runStartedAt } = runKey;
|
|
2591
|
+
await this.postgresClient.createObjectRuns(accountId, runStartedAt, [resourceName]);
|
|
2592
|
+
await this.postgresClient.tryStartObjectSync(accountId, runStartedAt, resourceName);
|
|
2593
|
+
try {
|
|
2594
|
+
const result = await fn(cursor, runStartedAt);
|
|
2595
|
+
await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
|
|
2596
|
+
return result;
|
|
2597
|
+
} catch (error) {
|
|
2598
|
+
await this.postgresClient.failObjectSync(
|
|
2599
|
+
accountId,
|
|
2600
|
+
runStartedAt,
|
|
2601
|
+
resourceName,
|
|
2602
|
+
error instanceof Error ? error.message : "Unknown error"
|
|
2603
|
+
);
|
|
2604
|
+
throw error;
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
async fetchAndUpsert(fetch2, upsert, accountId, resourceName, runStartedAt) {
|
|
2608
|
+
const CHECKPOINT_SIZE = 100;
|
|
2609
|
+
let totalSynced = 0;
|
|
2610
|
+
let currentBatch = [];
|
|
2611
|
+
try {
|
|
2612
|
+
this.config.logger?.info("Fetching items to sync from Stripe");
|
|
2613
|
+
try {
|
|
2614
|
+
for await (const item of fetch2()) {
|
|
2615
|
+
currentBatch.push(item);
|
|
2616
|
+
if (currentBatch.length >= CHECKPOINT_SIZE) {
|
|
2617
|
+
this.config.logger?.info(`Upserting batch of ${currentBatch.length} items`);
|
|
2618
|
+
await upsert(currentBatch, accountId);
|
|
2619
|
+
totalSynced += currentBatch.length;
|
|
2620
|
+
await this.postgresClient.incrementObjectProgress(
|
|
2621
|
+
accountId,
|
|
2622
|
+
runStartedAt,
|
|
2623
|
+
resourceName,
|
|
2624
|
+
currentBatch.length
|
|
2625
|
+
);
|
|
2626
|
+
const maxCreated = Math.max(
|
|
2627
|
+
...currentBatch.map((i) => i.created || 0)
|
|
2628
|
+
);
|
|
2629
|
+
if (maxCreated > 0) {
|
|
2630
|
+
await this.postgresClient.updateObjectCursor(
|
|
2631
|
+
accountId,
|
|
2632
|
+
runStartedAt,
|
|
2633
|
+
resourceName,
|
|
2634
|
+
String(maxCreated)
|
|
2635
|
+
);
|
|
2636
|
+
this.config.logger?.info(`Checkpoint: cursor updated to ${maxCreated}`);
|
|
2637
|
+
}
|
|
2638
|
+
currentBatch = [];
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
if (currentBatch.length > 0) {
|
|
2642
|
+
this.config.logger?.info(`Upserting final batch of ${currentBatch.length} items`);
|
|
2643
|
+
await upsert(currentBatch, accountId);
|
|
2644
|
+
totalSynced += currentBatch.length;
|
|
2645
|
+
await this.postgresClient.incrementObjectProgress(
|
|
2646
|
+
accountId,
|
|
2647
|
+
runStartedAt,
|
|
2648
|
+
resourceName,
|
|
2649
|
+
currentBatch.length
|
|
2650
|
+
);
|
|
2651
|
+
const maxCreated = Math.max(
|
|
2652
|
+
...currentBatch.map((i) => i.created || 0)
|
|
2653
|
+
);
|
|
2654
|
+
if (maxCreated > 0) {
|
|
2655
|
+
await this.postgresClient.updateObjectCursor(
|
|
2656
|
+
accountId,
|
|
2657
|
+
runStartedAt,
|
|
2658
|
+
resourceName,
|
|
2659
|
+
String(maxCreated)
|
|
2660
|
+
);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
} catch (error) {
|
|
2664
|
+
if (currentBatch.length > 0) {
|
|
2665
|
+
this.config.logger?.info(
|
|
2666
|
+
`Error occurred, saving partial progress: ${currentBatch.length} items`
|
|
2667
|
+
);
|
|
2668
|
+
await upsert(currentBatch, accountId);
|
|
2669
|
+
totalSynced += currentBatch.length;
|
|
2670
|
+
await this.postgresClient.incrementObjectProgress(
|
|
2671
|
+
accountId,
|
|
2672
|
+
runStartedAt,
|
|
2673
|
+
resourceName,
|
|
2674
|
+
currentBatch.length
|
|
2675
|
+
);
|
|
2676
|
+
const maxCreated = Math.max(
|
|
2677
|
+
...currentBatch.map((i) => i.created || 0)
|
|
2678
|
+
);
|
|
2679
|
+
if (maxCreated > 0) {
|
|
2680
|
+
await this.postgresClient.updateObjectCursor(
|
|
2681
|
+
accountId,
|
|
2682
|
+
runStartedAt,
|
|
2683
|
+
resourceName,
|
|
2684
|
+
String(maxCreated)
|
|
2685
|
+
);
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
throw error;
|
|
2689
|
+
}
|
|
2690
|
+
await this.postgresClient.completeObjectSync(accountId, runStartedAt, resourceName);
|
|
2691
|
+
this.config.logger?.info(`Sync complete: ${totalSynced} items synced`);
|
|
2692
|
+
return { synced: totalSynced };
|
|
2693
|
+
} catch (error) {
|
|
2694
|
+
await this.postgresClient.failObjectSync(
|
|
2695
|
+
accountId,
|
|
2696
|
+
runStartedAt,
|
|
2697
|
+
resourceName,
|
|
2698
|
+
error instanceof Error ? error.message : "Unknown error"
|
|
2699
|
+
);
|
|
2700
|
+
throw error;
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
async upsertCharges(charges, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2704
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2705
|
+
await Promise.all([
|
|
2706
|
+
this.backfillCustomers(getUniqueIds(charges, "customer"), accountId),
|
|
2707
|
+
this.backfillInvoices(getUniqueIds(charges, "invoice"), accountId)
|
|
2708
|
+
]);
|
|
2709
|
+
}
|
|
2710
|
+
await this.expandEntity(
|
|
2711
|
+
charges,
|
|
2712
|
+
"refunds",
|
|
2713
|
+
(id) => this.stripe.refunds.list({ charge: id, limit: 100 })
|
|
2714
|
+
);
|
|
2715
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2716
|
+
charges,
|
|
2717
|
+
"charges",
|
|
2718
|
+
accountId,
|
|
2719
|
+
syncTimestamp
|
|
2720
|
+
);
|
|
2721
|
+
}
|
|
2722
|
+
async backfillCharges(chargeIds, accountId) {
|
|
2723
|
+
const missingChargeIds = await this.postgresClient.findMissingEntries("charges", chargeIds);
|
|
2724
|
+
await this.fetchMissingEntities(
|
|
2725
|
+
missingChargeIds,
|
|
2726
|
+
(id) => this.stripe.charges.retrieve(id)
|
|
2727
|
+
).then((charges) => this.upsertCharges(charges, accountId));
|
|
2728
|
+
}
|
|
2729
|
+
async backfillPaymentIntents(paymentIntentIds, accountId) {
|
|
2730
|
+
const missingIds = await this.postgresClient.findMissingEntries(
|
|
2731
|
+
"payment_intents",
|
|
2732
|
+
paymentIntentIds
|
|
2733
|
+
);
|
|
2734
|
+
await this.fetchMissingEntities(
|
|
2735
|
+
missingIds,
|
|
2736
|
+
(id) => this.stripe.paymentIntents.retrieve(id)
|
|
2737
|
+
).then((paymentIntents) => this.upsertPaymentIntents(paymentIntents, accountId));
|
|
2738
|
+
}
|
|
2739
|
+
async upsertCreditNotes(creditNotes, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2740
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2741
|
+
await Promise.all([
|
|
2742
|
+
this.backfillCustomers(getUniqueIds(creditNotes, "customer"), accountId),
|
|
2743
|
+
this.backfillInvoices(getUniqueIds(creditNotes, "invoice"), accountId)
|
|
2744
|
+
]);
|
|
2745
|
+
}
|
|
2746
|
+
await this.expandEntity(
|
|
2747
|
+
creditNotes,
|
|
2748
|
+
"lines",
|
|
2749
|
+
(id) => this.stripe.creditNotes.listLineItems(id, { limit: 100 })
|
|
2750
|
+
);
|
|
2751
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2752
|
+
creditNotes,
|
|
2753
|
+
"credit_notes",
|
|
2754
|
+
accountId,
|
|
2755
|
+
syncTimestamp
|
|
2756
|
+
);
|
|
2757
|
+
}
|
|
2758
|
+
async upsertCheckoutSessions(checkoutSessions, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2759
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2760
|
+
await Promise.all([
|
|
2761
|
+
this.backfillCustomers(getUniqueIds(checkoutSessions, "customer"), accountId),
|
|
2762
|
+
this.backfillSubscriptions(getUniqueIds(checkoutSessions, "subscription"), accountId),
|
|
2763
|
+
this.backfillPaymentIntents(getUniqueIds(checkoutSessions, "payment_intent"), accountId),
|
|
2764
|
+
this.backfillInvoices(getUniqueIds(checkoutSessions, "invoice"), accountId)
|
|
2765
|
+
]);
|
|
2766
|
+
}
|
|
2767
|
+
const rows = await this.postgresClient.upsertManyWithTimestampProtection(
|
|
2768
|
+
checkoutSessions,
|
|
2769
|
+
"checkout_sessions",
|
|
2770
|
+
accountId,
|
|
2771
|
+
syncTimestamp
|
|
2772
|
+
);
|
|
2773
|
+
await this.fillCheckoutSessionsLineItems(
|
|
2774
|
+
checkoutSessions.map((cs) => cs.id),
|
|
2775
|
+
accountId,
|
|
2776
|
+
syncTimestamp
|
|
2777
|
+
);
|
|
2778
|
+
return rows;
|
|
2779
|
+
}
|
|
2780
|
+
async upsertEarlyFraudWarning(earlyFraudWarnings, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2781
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2782
|
+
await Promise.all([
|
|
2783
|
+
this.backfillPaymentIntents(getUniqueIds(earlyFraudWarnings, "payment_intent"), accountId),
|
|
2784
|
+
this.backfillCharges(getUniqueIds(earlyFraudWarnings, "charge"), accountId)
|
|
2785
|
+
]);
|
|
2786
|
+
}
|
|
2787
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2788
|
+
earlyFraudWarnings,
|
|
2789
|
+
"early_fraud_warnings",
|
|
2790
|
+
accountId,
|
|
2791
|
+
syncTimestamp
|
|
2792
|
+
);
|
|
2793
|
+
}
|
|
2794
|
+
async upsertRefunds(refunds, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2795
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2796
|
+
await Promise.all([
|
|
2797
|
+
this.backfillPaymentIntents(getUniqueIds(refunds, "payment_intent"), accountId),
|
|
2798
|
+
this.backfillCharges(getUniqueIds(refunds, "charge"), accountId)
|
|
2799
|
+
]);
|
|
2800
|
+
}
|
|
2801
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2802
|
+
refunds,
|
|
2803
|
+
"refunds",
|
|
2804
|
+
accountId,
|
|
2805
|
+
syncTimestamp
|
|
2806
|
+
);
|
|
2807
|
+
}
|
|
2808
|
+
async upsertReviews(reviews, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2809
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2810
|
+
await Promise.all([
|
|
2811
|
+
this.backfillPaymentIntents(getUniqueIds(reviews, "payment_intent"), accountId),
|
|
2812
|
+
this.backfillCharges(getUniqueIds(reviews, "charge"), accountId)
|
|
2813
|
+
]);
|
|
2814
|
+
}
|
|
2815
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2816
|
+
reviews,
|
|
2817
|
+
"reviews",
|
|
2818
|
+
accountId,
|
|
2819
|
+
syncTimestamp
|
|
2820
|
+
);
|
|
2821
|
+
}
|
|
2822
|
+
async upsertCustomers(customers, accountId, syncTimestamp) {
|
|
2823
|
+
const deletedCustomers = customers.filter((customer) => customer.deleted);
|
|
2824
|
+
const nonDeletedCustomers = customers.filter((customer) => !customer.deleted);
|
|
2825
|
+
await this.postgresClient.upsertManyWithTimestampProtection(
|
|
2826
|
+
nonDeletedCustomers,
|
|
2827
|
+
"customers",
|
|
2828
|
+
accountId,
|
|
2829
|
+
syncTimestamp
|
|
2830
|
+
);
|
|
2831
|
+
await this.postgresClient.upsertManyWithTimestampProtection(
|
|
2832
|
+
deletedCustomers,
|
|
2833
|
+
"customers",
|
|
2834
|
+
accountId,
|
|
2835
|
+
syncTimestamp
|
|
2836
|
+
);
|
|
2837
|
+
return customers;
|
|
2838
|
+
}
|
|
2839
|
+
async backfillCustomers(customerIds, accountId) {
|
|
2840
|
+
const missingIds = await this.postgresClient.findMissingEntries("customers", customerIds);
|
|
2841
|
+
await this.fetchMissingEntities(missingIds, (id) => this.stripe.customers.retrieve(id)).then((entries) => this.upsertCustomers(entries, accountId)).catch((err) => {
|
|
2842
|
+
this.config.logger?.error(err, "Failed to backfill");
|
|
2843
|
+
throw err;
|
|
2844
|
+
});
|
|
2845
|
+
}
|
|
2846
|
+
async upsertDisputes(disputes, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2847
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2848
|
+
await this.backfillCharges(getUniqueIds(disputes, "charge"), accountId);
|
|
2849
|
+
}
|
|
2850
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2851
|
+
disputes,
|
|
2852
|
+
"disputes",
|
|
2853
|
+
accountId,
|
|
2854
|
+
syncTimestamp
|
|
2855
|
+
);
|
|
2856
|
+
}
|
|
2857
|
+
async upsertInvoices(invoices, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2858
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2859
|
+
await Promise.all([
|
|
2860
|
+
this.backfillCustomers(getUniqueIds(invoices, "customer"), accountId),
|
|
2861
|
+
this.backfillSubscriptions(getUniqueIds(invoices, "subscription"), accountId)
|
|
2862
|
+
]);
|
|
2863
|
+
}
|
|
2864
|
+
await this.expandEntity(
|
|
2865
|
+
invoices,
|
|
2866
|
+
"lines",
|
|
2867
|
+
(id) => this.stripe.invoices.listLineItems(id, { limit: 100 })
|
|
2868
|
+
);
|
|
2869
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2870
|
+
invoices,
|
|
2871
|
+
"invoices",
|
|
2872
|
+
accountId,
|
|
2873
|
+
syncTimestamp
|
|
2874
|
+
);
|
|
2875
|
+
}
|
|
2876
|
+
backfillInvoices = async (invoiceIds, accountId) => {
|
|
2877
|
+
const missingIds = await this.postgresClient.findMissingEntries("invoices", invoiceIds);
|
|
2878
|
+
await this.fetchMissingEntities(missingIds, (id) => this.stripe.invoices.retrieve(id)).then(
|
|
2879
|
+
(entries) => this.upsertInvoices(entries, accountId)
|
|
2880
|
+
);
|
|
2881
|
+
};
|
|
2882
|
+
backfillPrices = async (priceIds, accountId) => {
|
|
2883
|
+
const missingIds = await this.postgresClient.findMissingEntries("prices", priceIds);
|
|
2884
|
+
await this.fetchMissingEntities(missingIds, (id) => this.stripe.prices.retrieve(id)).then(
|
|
2885
|
+
(entries) => this.upsertPrices(entries, accountId)
|
|
2886
|
+
);
|
|
2887
|
+
};
|
|
2888
|
+
async upsertPlans(plans, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2889
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2890
|
+
await this.backfillProducts(getUniqueIds(plans, "product"), accountId);
|
|
2891
|
+
}
|
|
2892
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2893
|
+
plans,
|
|
2894
|
+
"plans",
|
|
2895
|
+
accountId,
|
|
2896
|
+
syncTimestamp
|
|
2897
|
+
);
|
|
2898
|
+
}
|
|
2899
|
+
async deletePlan(id) {
|
|
2900
|
+
return this.postgresClient.delete("plans", id);
|
|
2901
|
+
}
|
|
2902
|
+
async upsertPrices(prices, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2903
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2904
|
+
await this.backfillProducts(getUniqueIds(prices, "product"), accountId);
|
|
2905
|
+
}
|
|
2906
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2907
|
+
prices,
|
|
2908
|
+
"prices",
|
|
2909
|
+
accountId,
|
|
2910
|
+
syncTimestamp
|
|
2911
|
+
);
|
|
2912
|
+
}
|
|
2913
|
+
async deletePrice(id) {
|
|
2914
|
+
return this.postgresClient.delete("prices", id);
|
|
2915
|
+
}
|
|
2916
|
+
async upsertProducts(products, accountId, syncTimestamp) {
|
|
2917
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2918
|
+
products,
|
|
2919
|
+
"products",
|
|
2920
|
+
accountId,
|
|
2921
|
+
syncTimestamp
|
|
2922
|
+
);
|
|
2923
|
+
}
|
|
2924
|
+
async deleteProduct(id) {
|
|
2925
|
+
return this.postgresClient.delete("products", id);
|
|
2926
|
+
}
|
|
2927
|
+
async backfillProducts(productIds, accountId) {
|
|
2928
|
+
const missingProductIds = await this.postgresClient.findMissingEntries("products", productIds);
|
|
2929
|
+
await this.fetchMissingEntities(
|
|
2930
|
+
missingProductIds,
|
|
2931
|
+
(id) => this.stripe.products.retrieve(id)
|
|
2932
|
+
).then((products) => this.upsertProducts(products, accountId));
|
|
2933
|
+
}
|
|
2934
|
+
async upsertPaymentIntents(paymentIntents, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2935
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2936
|
+
await Promise.all([
|
|
2937
|
+
this.backfillCustomers(getUniqueIds(paymentIntents, "customer"), accountId),
|
|
2938
|
+
this.backfillInvoices(getUniqueIds(paymentIntents, "invoice"), accountId)
|
|
2939
|
+
]);
|
|
2940
|
+
}
|
|
2941
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2942
|
+
paymentIntents,
|
|
2943
|
+
"payment_intents",
|
|
2944
|
+
accountId,
|
|
2945
|
+
syncTimestamp
|
|
2946
|
+
);
|
|
2947
|
+
}
|
|
2948
|
+
async upsertPaymentMethods(paymentMethods, accountId, backfillRelatedEntities = false, syncTimestamp) {
|
|
2949
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2950
|
+
await this.backfillCustomers(getUniqueIds(paymentMethods, "customer"), accountId);
|
|
2951
|
+
}
|
|
2952
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2953
|
+
paymentMethods,
|
|
2954
|
+
"payment_methods",
|
|
2955
|
+
accountId,
|
|
2956
|
+
syncTimestamp
|
|
2957
|
+
);
|
|
2958
|
+
}
|
|
2959
|
+
async upsertSetupIntents(setupIntents, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2960
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2961
|
+
await this.backfillCustomers(getUniqueIds(setupIntents, "customer"), accountId);
|
|
2962
|
+
}
|
|
2963
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2964
|
+
setupIntents,
|
|
2965
|
+
"setup_intents",
|
|
2966
|
+
accountId,
|
|
2967
|
+
syncTimestamp
|
|
2968
|
+
);
|
|
2969
|
+
}
|
|
2970
|
+
async upsertTaxIds(taxIds, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
2971
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
2972
|
+
await this.backfillCustomers(getUniqueIds(taxIds, "customer"), accountId);
|
|
2973
|
+
}
|
|
2974
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
2975
|
+
taxIds,
|
|
2976
|
+
"tax_ids",
|
|
2977
|
+
accountId,
|
|
2978
|
+
syncTimestamp
|
|
2979
|
+
);
|
|
2980
|
+
}
|
|
2981
|
+
async deleteTaxId(id) {
|
|
2982
|
+
return this.postgresClient.delete("tax_ids", id);
|
|
2983
|
+
}
|
|
2984
|
+
async upsertSubscriptionItems(subscriptionItems, accountId, syncTimestamp) {
|
|
2985
|
+
const modifiedSubscriptionItems = subscriptionItems.map((subscriptionItem) => {
|
|
2986
|
+
const priceId = subscriptionItem.price.id.toString();
|
|
2987
|
+
const deleted = subscriptionItem.deleted;
|
|
2988
|
+
const quantity = subscriptionItem.quantity;
|
|
2989
|
+
return {
|
|
2990
|
+
...subscriptionItem,
|
|
2991
|
+
price: priceId,
|
|
2992
|
+
deleted: deleted ?? false,
|
|
2993
|
+
quantity: quantity ?? null
|
|
2994
|
+
};
|
|
2995
|
+
});
|
|
2996
|
+
await this.postgresClient.upsertManyWithTimestampProtection(
|
|
2997
|
+
modifiedSubscriptionItems,
|
|
2998
|
+
"subscription_items",
|
|
2999
|
+
accountId,
|
|
3000
|
+
syncTimestamp
|
|
3001
|
+
);
|
|
3002
|
+
}
|
|
3003
|
+
async fillCheckoutSessionsLineItems(checkoutSessionIds, accountId, syncTimestamp) {
|
|
3004
|
+
for (const checkoutSessionId of checkoutSessionIds) {
|
|
3005
|
+
const lineItemResponses = [];
|
|
3006
|
+
for await (const lineItem of this.stripe.checkout.sessions.listLineItems(checkoutSessionId, {
|
|
3007
|
+
limit: 100
|
|
3008
|
+
})) {
|
|
3009
|
+
lineItemResponses.push(lineItem);
|
|
3010
|
+
}
|
|
3011
|
+
await this.upsertCheckoutSessionLineItems(
|
|
3012
|
+
lineItemResponses,
|
|
3013
|
+
checkoutSessionId,
|
|
3014
|
+
accountId,
|
|
3015
|
+
syncTimestamp
|
|
3016
|
+
);
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
async upsertCheckoutSessionLineItems(lineItems, checkoutSessionId, accountId, syncTimestamp) {
|
|
3020
|
+
await this.backfillPrices(
|
|
3021
|
+
lineItems.map((lineItem) => lineItem.price?.id?.toString() ?? void 0).filter((id) => id !== void 0),
|
|
3022
|
+
accountId
|
|
3023
|
+
);
|
|
3024
|
+
const modifiedLineItems = lineItems.map((lineItem) => {
|
|
3025
|
+
const priceId = typeof lineItem.price === "object" && lineItem.price?.id ? lineItem.price.id.toString() : lineItem.price?.toString() || null;
|
|
3026
|
+
return {
|
|
3027
|
+
...lineItem,
|
|
3028
|
+
price: priceId,
|
|
3029
|
+
checkout_session: checkoutSessionId
|
|
3030
|
+
};
|
|
3031
|
+
});
|
|
3032
|
+
await this.postgresClient.upsertManyWithTimestampProtection(
|
|
3033
|
+
modifiedLineItems,
|
|
3034
|
+
"checkout_session_line_items",
|
|
3035
|
+
accountId,
|
|
3036
|
+
syncTimestamp
|
|
3037
|
+
);
|
|
3038
|
+
}
|
|
3039
|
+
async markDeletedSubscriptionItems(subscriptionId, currentSubItemIds) {
|
|
3040
|
+
let prepared = (0, import_yesql2.pg)(`
|
|
3041
|
+
select id from "stripe"."subscription_items"
|
|
3042
|
+
where subscription = :subscriptionId and COALESCE(deleted, false) = false;
|
|
3043
|
+
`)({ subscriptionId });
|
|
3044
|
+
const { rows } = await this.postgresClient.query(prepared.text, prepared.values);
|
|
3045
|
+
const deletedIds = rows.filter(
|
|
3046
|
+
({ id }) => currentSubItemIds.includes(id) === false
|
|
3047
|
+
);
|
|
3048
|
+
if (deletedIds.length > 0) {
|
|
3049
|
+
const ids = deletedIds.map(({ id }) => id);
|
|
3050
|
+
prepared = (0, import_yesql2.pg)(`
|
|
3051
|
+
update "stripe"."subscription_items"
|
|
3052
|
+
set _raw_data = jsonb_set(_raw_data, '{deleted}', 'true'::jsonb)
|
|
3053
|
+
where id=any(:ids::text[]);
|
|
3054
|
+
`)({ ids });
|
|
3055
|
+
const { rowCount } = await this.postgresClient.query(prepared.text, prepared.values);
|
|
3056
|
+
return { rowCount: rowCount || 0 };
|
|
3057
|
+
} else {
|
|
3058
|
+
return { rowCount: 0 };
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
async upsertSubscriptionSchedules(subscriptionSchedules, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
3062
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
3063
|
+
const customerIds = getUniqueIds(subscriptionSchedules, "customer");
|
|
3064
|
+
await this.backfillCustomers(customerIds, accountId);
|
|
3065
|
+
}
|
|
3066
|
+
const rows = await this.postgresClient.upsertManyWithTimestampProtection(
|
|
3067
|
+
subscriptionSchedules,
|
|
3068
|
+
"subscription_schedules",
|
|
3069
|
+
accountId,
|
|
3070
|
+
syncTimestamp
|
|
3071
|
+
);
|
|
3072
|
+
return rows;
|
|
3073
|
+
}
|
|
3074
|
+
async upsertSubscriptions(subscriptions, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
3075
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
3076
|
+
const customerIds = getUniqueIds(subscriptions, "customer");
|
|
3077
|
+
await this.backfillCustomers(customerIds, accountId);
|
|
3078
|
+
}
|
|
3079
|
+
await this.expandEntity(
|
|
3080
|
+
subscriptions,
|
|
3081
|
+
"items",
|
|
3082
|
+
(id) => this.stripe.subscriptionItems.list({ subscription: id, limit: 100 })
|
|
3083
|
+
);
|
|
3084
|
+
const rows = await this.postgresClient.upsertManyWithTimestampProtection(
|
|
3085
|
+
subscriptions,
|
|
3086
|
+
"subscriptions",
|
|
3087
|
+
accountId,
|
|
3088
|
+
syncTimestamp
|
|
3089
|
+
);
|
|
3090
|
+
const allSubscriptionItems = subscriptions.flatMap((subscription) => subscription.items.data);
|
|
3091
|
+
await this.upsertSubscriptionItems(allSubscriptionItems, accountId, syncTimestamp);
|
|
3092
|
+
const markSubscriptionItemsDeleted = [];
|
|
3093
|
+
for (const subscription of subscriptions) {
|
|
3094
|
+
const subscriptionItems = subscription.items.data;
|
|
3095
|
+
const subItemIds = subscriptionItems.map((x) => x.id);
|
|
3096
|
+
markSubscriptionItemsDeleted.push(
|
|
3097
|
+
this.markDeletedSubscriptionItems(subscription.id, subItemIds)
|
|
3098
|
+
);
|
|
3099
|
+
}
|
|
3100
|
+
await Promise.all(markSubscriptionItemsDeleted);
|
|
3101
|
+
return rows;
|
|
3102
|
+
}
|
|
3103
|
+
async deleteRemovedActiveEntitlements(customerId, currentActiveEntitlementIds) {
|
|
3104
|
+
const prepared = (0, import_yesql2.pg)(`
|
|
3105
|
+
delete from "stripe"."active_entitlements"
|
|
3106
|
+
where customer = :customerId and id <> ALL(:currentActiveEntitlementIds::text[]);
|
|
3107
|
+
`)({ customerId, currentActiveEntitlementIds });
|
|
3108
|
+
const { rowCount } = await this.postgresClient.query(prepared.text, prepared.values);
|
|
3109
|
+
return { rowCount: rowCount || 0 };
|
|
3110
|
+
}
|
|
3111
|
+
async upsertFeatures(features, accountId, syncTimestamp) {
|
|
3112
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
3113
|
+
features,
|
|
3114
|
+
"features",
|
|
3115
|
+
accountId,
|
|
3116
|
+
syncTimestamp
|
|
3117
|
+
);
|
|
3118
|
+
}
|
|
3119
|
+
async backfillFeatures(featureIds, accountId) {
|
|
3120
|
+
const missingFeatureIds = await this.postgresClient.findMissingEntries("features", featureIds);
|
|
3121
|
+
await this.fetchMissingEntities(
|
|
3122
|
+
missingFeatureIds,
|
|
3123
|
+
(id) => this.stripe.entitlements.features.retrieve(id)
|
|
3124
|
+
).then((features) => this.upsertFeatures(features, accountId)).catch((err) => {
|
|
3125
|
+
this.config.logger?.error(err, "Failed to backfill features");
|
|
3126
|
+
throw err;
|
|
3127
|
+
});
|
|
3128
|
+
}
|
|
3129
|
+
async upsertActiveEntitlements(customerId, activeEntitlements, accountId, backfillRelatedEntities, syncTimestamp) {
|
|
3130
|
+
if (backfillRelatedEntities ?? this.config.backfillRelatedEntities) {
|
|
3131
|
+
await Promise.all([
|
|
3132
|
+
this.backfillCustomers(getUniqueIds(activeEntitlements, "customer"), accountId),
|
|
3133
|
+
this.backfillFeatures(getUniqueIds(activeEntitlements, "feature"), accountId)
|
|
3134
|
+
]);
|
|
3135
|
+
}
|
|
3136
|
+
const entitlements = activeEntitlements.map((entitlement) => ({
|
|
3137
|
+
id: entitlement.id,
|
|
3138
|
+
object: entitlement.object,
|
|
3139
|
+
feature: typeof entitlement.feature === "string" ? entitlement.feature : entitlement.feature.id,
|
|
3140
|
+
customer: customerId,
|
|
3141
|
+
livemode: entitlement.livemode,
|
|
3142
|
+
lookup_key: entitlement.lookup_key
|
|
3143
|
+
}));
|
|
3144
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
3145
|
+
entitlements,
|
|
3146
|
+
"active_entitlements",
|
|
3147
|
+
accountId,
|
|
3148
|
+
syncTimestamp
|
|
3149
|
+
);
|
|
3150
|
+
}
|
|
3151
|
+
async findOrCreateManagedWebhook(url, params) {
|
|
3152
|
+
const webhookParams = {
|
|
3153
|
+
enabled_events: this.getSupportedEventTypes(),
|
|
3154
|
+
...params
|
|
3155
|
+
};
|
|
3156
|
+
const accountId = await this.getAccountId();
|
|
3157
|
+
const lockKey = `webhook:${accountId}:${url}`;
|
|
3158
|
+
return this.postgresClient.withAdvisoryLock(lockKey, async () => {
|
|
3159
|
+
const existingWebhook = await this.getManagedWebhookByUrl(url);
|
|
3160
|
+
if (existingWebhook) {
|
|
3161
|
+
try {
|
|
3162
|
+
const stripeWebhook = await this.stripe.webhookEndpoints.retrieve(existingWebhook.id);
|
|
3163
|
+
if (stripeWebhook.status === "enabled") {
|
|
3164
|
+
return stripeWebhook;
|
|
3165
|
+
}
|
|
3166
|
+
this.config.logger?.info(
|
|
3167
|
+
{ webhookId: existingWebhook.id },
|
|
3168
|
+
"Webhook is disabled, deleting and will recreate"
|
|
3169
|
+
);
|
|
3170
|
+
await this.stripe.webhookEndpoints.del(existingWebhook.id);
|
|
3171
|
+
await this.postgresClient.delete("_managed_webhooks", existingWebhook.id);
|
|
3172
|
+
} catch (error) {
|
|
3173
|
+
const stripeError = error;
|
|
3174
|
+
if (stripeError?.statusCode === 404 || stripeError?.code === "resource_missing") {
|
|
3175
|
+
this.config.logger?.warn(
|
|
3176
|
+
{ error, webhookId: existingWebhook.id },
|
|
3177
|
+
"Webhook not found in Stripe (404), removing from database"
|
|
3178
|
+
);
|
|
3179
|
+
await this.postgresClient.delete("_managed_webhooks", existingWebhook.id);
|
|
3180
|
+
} else {
|
|
3181
|
+
this.config.logger?.error(
|
|
3182
|
+
{ error, webhookId: existingWebhook.id },
|
|
3183
|
+
"Error retrieving webhook from Stripe, keeping in database"
|
|
3184
|
+
);
|
|
3185
|
+
throw error;
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
}
|
|
3189
|
+
const allDbWebhooks = await this.listManagedWebhooks();
|
|
3190
|
+
for (const dbWebhook of allDbWebhooks) {
|
|
3191
|
+
if (dbWebhook.url !== url) {
|
|
3192
|
+
this.config.logger?.info(
|
|
3193
|
+
{ webhookId: dbWebhook.id, oldUrl: dbWebhook.url, newUrl: url },
|
|
3194
|
+
"Webhook URL mismatch, deleting"
|
|
3195
|
+
);
|
|
3196
|
+
try {
|
|
3197
|
+
await this.stripe.webhookEndpoints.del(dbWebhook.id);
|
|
3198
|
+
} catch (error) {
|
|
3199
|
+
this.config.logger?.warn(
|
|
3200
|
+
{ error, webhookId: dbWebhook.id },
|
|
3201
|
+
"Failed to delete old webhook from Stripe"
|
|
3202
|
+
);
|
|
3203
|
+
}
|
|
3204
|
+
await this.postgresClient.delete("_managed_webhooks", dbWebhook.id);
|
|
3205
|
+
}
|
|
3206
|
+
}
|
|
3207
|
+
try {
|
|
3208
|
+
const stripeWebhooks = await this.stripe.webhookEndpoints.list({ limit: 100 });
|
|
3209
|
+
for (const stripeWebhook of stripeWebhooks.data) {
|
|
3210
|
+
const isManagedByMetadata = stripeWebhook.metadata?.managed_by?.toLowerCase().replace(/[\s\-]+/g, "") === "stripesync";
|
|
3211
|
+
const normalizedDescription = stripeWebhook.description?.toLowerCase().replace(/[\s\-]+/g, "") || "";
|
|
3212
|
+
const isManagedByDescription = normalizedDescription.includes("stripesync");
|
|
3213
|
+
if (isManagedByMetadata || isManagedByDescription) {
|
|
3214
|
+
const existsInDb = allDbWebhooks.some((dbWebhook) => dbWebhook.id === stripeWebhook.id);
|
|
3215
|
+
if (!existsInDb) {
|
|
3216
|
+
this.config.logger?.warn(
|
|
3217
|
+
{ webhookId: stripeWebhook.id, url: stripeWebhook.url },
|
|
3218
|
+
"Found orphaned managed webhook in Stripe, deleting"
|
|
3219
|
+
);
|
|
3220
|
+
await this.stripe.webhookEndpoints.del(stripeWebhook.id);
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
}
|
|
3224
|
+
} catch (error) {
|
|
3225
|
+
this.config.logger?.warn({ error }, "Failed to check for orphaned webhooks");
|
|
3226
|
+
}
|
|
3227
|
+
const webhook = await this.stripe.webhookEndpoints.create({
|
|
3228
|
+
...webhookParams,
|
|
3229
|
+
url,
|
|
3230
|
+
// Always set metadata to identify managed webhooks
|
|
3231
|
+
metadata: {
|
|
3232
|
+
...webhookParams.metadata,
|
|
3233
|
+
managed_by: "stripe-sync",
|
|
3234
|
+
version: package_default.version
|
|
3235
|
+
}
|
|
3236
|
+
});
|
|
3237
|
+
const accountId2 = await this.getAccountId();
|
|
3238
|
+
await this.upsertManagedWebhooks([webhook], accountId2);
|
|
3239
|
+
return webhook;
|
|
3240
|
+
});
|
|
3241
|
+
}
|
|
3242
|
+
async getManagedWebhook(id) {
|
|
3243
|
+
const accountId = await this.getAccountId();
|
|
3244
|
+
const result = await this.postgresClient.query(
|
|
3245
|
+
`SELECT * FROM "stripe"."_managed_webhooks" WHERE id = $1 AND "account_id" = $2`,
|
|
3246
|
+
[id, accountId]
|
|
3247
|
+
);
|
|
3248
|
+
return result.rows.length > 0 ? result.rows[0] : null;
|
|
3249
|
+
}
|
|
3250
|
+
/**
|
|
3251
|
+
* Get a managed webhook by URL and account ID.
|
|
3252
|
+
* Used for race condition recovery: when createManagedWebhook hits a unique constraint
|
|
3253
|
+
* violation (another instance created the webhook), we need to fetch the existing webhook
|
|
3254
|
+
* by URL since we only know the URL, not the ID of the webhook that won the race.
|
|
3255
|
+
*/
|
|
3256
|
+
async getManagedWebhookByUrl(url) {
|
|
3257
|
+
const accountId = await this.getAccountId();
|
|
3258
|
+
const result = await this.postgresClient.query(
|
|
3259
|
+
`SELECT * FROM "stripe"."_managed_webhooks" WHERE url = $1 AND "account_id" = $2`,
|
|
3260
|
+
[url, accountId]
|
|
3261
|
+
);
|
|
3262
|
+
return result.rows.length > 0 ? result.rows[0] : null;
|
|
3263
|
+
}
|
|
3264
|
+
async listManagedWebhooks() {
|
|
3265
|
+
const accountId = await this.getAccountId();
|
|
3266
|
+
const result = await this.postgresClient.query(
|
|
3267
|
+
`SELECT * FROM "stripe"."_managed_webhooks" WHERE "account_id" = $1 ORDER BY created DESC`,
|
|
3268
|
+
[accountId]
|
|
3269
|
+
);
|
|
3270
|
+
return result.rows;
|
|
3271
|
+
}
|
|
3272
|
+
async updateManagedWebhook(id, params) {
|
|
3273
|
+
const webhook = await this.stripe.webhookEndpoints.update(id, params);
|
|
3274
|
+
const accountId = await this.getAccountId();
|
|
3275
|
+
await this.upsertManagedWebhooks([webhook], accountId);
|
|
3276
|
+
return webhook;
|
|
3277
|
+
}
|
|
3278
|
+
async deleteManagedWebhook(id) {
|
|
3279
|
+
await this.stripe.webhookEndpoints.del(id);
|
|
3280
|
+
return this.postgresClient.delete("_managed_webhooks", id);
|
|
3281
|
+
}
|
|
3282
|
+
async upsertManagedWebhooks(webhooks, accountId, syncTimestamp) {
|
|
3283
|
+
const filteredWebhooks = webhooks.map((webhook) => {
|
|
3284
|
+
const filtered = {};
|
|
3285
|
+
for (const prop of managedWebhookSchema.properties) {
|
|
3286
|
+
if (prop in webhook) {
|
|
3287
|
+
filtered[prop] = webhook[prop];
|
|
3288
|
+
}
|
|
3289
|
+
}
|
|
3290
|
+
return filtered;
|
|
3291
|
+
});
|
|
3292
|
+
return this.postgresClient.upsertManyWithTimestampProtection(
|
|
3293
|
+
filteredWebhooks,
|
|
3294
|
+
"_managed_webhooks",
|
|
3295
|
+
accountId,
|
|
3296
|
+
syncTimestamp
|
|
3297
|
+
);
|
|
3298
|
+
}
|
|
3299
|
+
async backfillSubscriptions(subscriptionIds, accountId) {
|
|
3300
|
+
const missingSubscriptionIds = await this.postgresClient.findMissingEntries(
|
|
3301
|
+
"subscriptions",
|
|
3302
|
+
subscriptionIds
|
|
3303
|
+
);
|
|
3304
|
+
await this.fetchMissingEntities(
|
|
3305
|
+
missingSubscriptionIds,
|
|
3306
|
+
(id) => this.stripe.subscriptions.retrieve(id)
|
|
3307
|
+
).then((subscriptions) => this.upsertSubscriptions(subscriptions, accountId));
|
|
3308
|
+
}
|
|
3309
|
+
backfillSubscriptionSchedules = async (subscriptionIds, accountId) => {
|
|
3310
|
+
const missingSubscriptionIds = await this.postgresClient.findMissingEntries(
|
|
3311
|
+
"subscription_schedules",
|
|
3312
|
+
subscriptionIds
|
|
3313
|
+
);
|
|
3314
|
+
await this.fetchMissingEntities(
|
|
3315
|
+
missingSubscriptionIds,
|
|
3316
|
+
(id) => this.stripe.subscriptionSchedules.retrieve(id)
|
|
3317
|
+
).then(
|
|
3318
|
+
(subscriptionSchedules) => this.upsertSubscriptionSchedules(subscriptionSchedules, accountId)
|
|
3319
|
+
);
|
|
3320
|
+
};
|
|
3321
|
+
/**
|
|
3322
|
+
* Stripe only sends the first 10 entries by default, the option will actively fetch all entries.
|
|
3323
|
+
*/
|
|
3324
|
+
async expandEntity(entities, property, listFn) {
|
|
3325
|
+
if (!this.config.autoExpandLists) return;
|
|
3326
|
+
for (const entity of entities) {
|
|
3327
|
+
if (entity[property]?.has_more) {
|
|
3328
|
+
const allData = [];
|
|
3329
|
+
for await (const fetchedEntity of listFn(entity.id)) {
|
|
3330
|
+
allData.push(fetchedEntity);
|
|
3331
|
+
}
|
|
3332
|
+
entity[property] = {
|
|
3333
|
+
...entity[property],
|
|
3334
|
+
data: allData,
|
|
3335
|
+
has_more: false
|
|
3336
|
+
};
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
async fetchMissingEntities(ids, fetch2) {
|
|
3341
|
+
if (!ids.length) return [];
|
|
3342
|
+
const entities = [];
|
|
3343
|
+
for (const id of ids) {
|
|
3344
|
+
const entity = await fetch2(id);
|
|
3345
|
+
entities.push(entity);
|
|
3346
|
+
}
|
|
3347
|
+
return entities;
|
|
3348
|
+
}
|
|
3349
|
+
/**
|
|
3350
|
+
* Closes the database connection pool and cleans up resources.
|
|
3351
|
+
* Call this when you're done using the StripeSync instance.
|
|
3352
|
+
*/
|
|
3353
|
+
async close() {
|
|
3354
|
+
await this.postgresClient.pool.end();
|
|
3355
|
+
}
|
|
3356
|
+
};
|
|
3357
|
+
function chunkArray(array, chunkSize) {
|
|
3358
|
+
const result = [];
|
|
3359
|
+
for (let i = 0; i < array.length; i += chunkSize) {
|
|
3360
|
+
result.push(array.slice(i, i + chunkSize));
|
|
3361
|
+
}
|
|
3362
|
+
return result;
|
|
3363
|
+
}
|
|
3364
|
+
|
|
3365
|
+
// src/database/migrate.ts
|
|
3366
|
+
var import_pg2 = require("pg");
|
|
3367
|
+
var import_pg_node_migrations = require("pg-node-migrations");
|
|
3368
|
+
var import_node_fs = __toESM(require("fs"), 1);
|
|
3369
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
3370
|
+
var import_node_url = require("url");
|
|
3371
|
+
var __filename2 = (0, import_node_url.fileURLToPath)(importMetaUrl);
|
|
3372
|
+
var __dirname = import_node_path.default.dirname(__filename2);
|
|
3373
|
+
async function doesTableExist(client, schema, tableName) {
|
|
3374
|
+
const result = await client.query(
|
|
3375
|
+
`SELECT EXISTS (
|
|
3376
|
+
SELECT 1
|
|
3377
|
+
FROM information_schema.tables
|
|
3378
|
+
WHERE table_schema = $1
|
|
3379
|
+
AND table_name = $2
|
|
3380
|
+
)`,
|
|
3381
|
+
[schema, tableName]
|
|
3382
|
+
);
|
|
3383
|
+
return result.rows[0]?.exists || false;
|
|
3384
|
+
}
|
|
3385
|
+
async function renameMigrationsTableIfNeeded(client, schema = "stripe", logger) {
|
|
3386
|
+
const oldTableExists = await doesTableExist(client, schema, "migrations");
|
|
3387
|
+
const newTableExists = await doesTableExist(client, schema, "_migrations");
|
|
3388
|
+
if (oldTableExists && !newTableExists) {
|
|
3389
|
+
logger?.info("Renaming migrations table to _migrations");
|
|
3390
|
+
await client.query(`ALTER TABLE "${schema}"."migrations" RENAME TO "_migrations"`);
|
|
3391
|
+
logger?.info("Successfully renamed migrations table");
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
async function cleanupSchema(client, schema, logger) {
|
|
3395
|
+
logger?.warn(`Migrations table is empty - dropping and recreating schema "${schema}"`);
|
|
3396
|
+
await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);
|
|
3397
|
+
await client.query(`CREATE SCHEMA "${schema}"`);
|
|
3398
|
+
logger?.info(`Schema "${schema}" has been reset`);
|
|
3399
|
+
}
|
|
3400
|
+
async function connectAndMigrate(client, migrationsDirectory, config, logOnError = false) {
|
|
3401
|
+
if (!import_node_fs.default.existsSync(migrationsDirectory)) {
|
|
3402
|
+
config.logger?.info(`Migrations directory ${migrationsDirectory} not found, skipping`);
|
|
3403
|
+
return;
|
|
3404
|
+
}
|
|
3405
|
+
const optionalConfig = {
|
|
3406
|
+
schemaName: "stripe",
|
|
3407
|
+
tableName: "_migrations"
|
|
3408
|
+
};
|
|
3409
|
+
try {
|
|
3410
|
+
await (0, import_pg_node_migrations.migrate)({ client }, migrationsDirectory, optionalConfig);
|
|
3411
|
+
} catch (error) {
|
|
3412
|
+
if (logOnError && error instanceof Error) {
|
|
3413
|
+
config.logger?.error(error, "Migration error:");
|
|
3414
|
+
} else {
|
|
3415
|
+
throw error;
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
}
|
|
3419
|
+
async function runMigrations(config) {
|
|
3420
|
+
const client = new import_pg2.Client({
|
|
3421
|
+
connectionString: config.databaseUrl,
|
|
3422
|
+
ssl: config.ssl,
|
|
3423
|
+
connectionTimeoutMillis: 1e4
|
|
3424
|
+
});
|
|
3425
|
+
const schema = "stripe";
|
|
3426
|
+
try {
|
|
3427
|
+
await client.connect();
|
|
3428
|
+
await client.query(`CREATE SCHEMA IF NOT EXISTS ${schema};`);
|
|
3429
|
+
await renameMigrationsTableIfNeeded(client, schema, config.logger);
|
|
3430
|
+
const tableExists = await doesTableExist(client, schema, "_migrations");
|
|
3431
|
+
if (tableExists) {
|
|
3432
|
+
const migrationCount = await client.query(
|
|
3433
|
+
`SELECT COUNT(*) as count FROM "${schema}"."_migrations"`
|
|
3434
|
+
);
|
|
3435
|
+
const isEmpty = migrationCount.rows[0]?.count === "0";
|
|
3436
|
+
if (isEmpty) {
|
|
3437
|
+
await cleanupSchema(client, schema, config.logger);
|
|
3438
|
+
}
|
|
3439
|
+
}
|
|
3440
|
+
config.logger?.info("Running migrations");
|
|
3441
|
+
await connectAndMigrate(client, import_node_path.default.resolve(__dirname, "./migrations"), config);
|
|
3442
|
+
} catch (err) {
|
|
3443
|
+
config.logger?.error(err, "Error running migrations");
|
|
3444
|
+
throw err;
|
|
3445
|
+
} finally {
|
|
3446
|
+
await client.end();
|
|
3447
|
+
config.logger?.info("Finished migrations");
|
|
3448
|
+
}
|
|
3449
|
+
}
|
|
3450
|
+
|
|
3451
|
+
// src/index.ts
|
|
3452
|
+
var VERSION = package_default.version;
|
|
3453
|
+
|
|
3454
|
+
// src/cli/ngrok.ts
|
|
3455
|
+
var import_ngrok = __toESM(require("@ngrok/ngrok"), 1);
|
|
3456
|
+
var import_chalk2 = __toESM(require("chalk"), 1);
|
|
3457
|
+
async function createTunnel(port, authToken) {
|
|
3458
|
+
try {
|
|
3459
|
+
console.log(import_chalk2.default.blue(`
|
|
3460
|
+
Creating ngrok tunnel for port ${port}...`));
|
|
3461
|
+
const listener = await import_ngrok.default.forward({
|
|
3462
|
+
addr: port,
|
|
3463
|
+
authtoken: authToken
|
|
3464
|
+
});
|
|
3465
|
+
const url = listener.url();
|
|
3466
|
+
if (!url) {
|
|
3467
|
+
throw new Error("Failed to get ngrok URL");
|
|
3468
|
+
}
|
|
3469
|
+
console.log(import_chalk2.default.green(`\u2713 ngrok tunnel created: ${url}`));
|
|
3470
|
+
return {
|
|
3471
|
+
url,
|
|
3472
|
+
close: async () => {
|
|
3473
|
+
console.log(import_chalk2.default.blue("\nClosing ngrok tunnel..."));
|
|
3474
|
+
await listener.close();
|
|
3475
|
+
console.log(import_chalk2.default.green("\u2713 ngrok tunnel closed"));
|
|
3476
|
+
}
|
|
3477
|
+
};
|
|
3478
|
+
} catch (error) {
|
|
3479
|
+
console.error(import_chalk2.default.red("\nFailed to create ngrok tunnel:"));
|
|
3480
|
+
if (error instanceof Error) {
|
|
3481
|
+
console.error(import_chalk2.default.red(error.message));
|
|
3482
|
+
}
|
|
3483
|
+
throw error;
|
|
3484
|
+
}
|
|
3485
|
+
}
|
|
3486
|
+
|
|
3487
|
+
// src/supabase/supabase.ts
|
|
3488
|
+
var import_supabase_management_js = require("supabase-management-js");
|
|
3489
|
+
|
|
3490
|
+
// raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-setup.ts
|
|
3491
|
+
var stripe_setup_default = "import { StripeSync, runMigrations } from 'npm:stripe-experiment-sync'\n\nDeno.serve(async (req) => {\n if (req.method !== 'POST') {\n return new Response('Method not allowed', { status: 405 })\n }\n\n const authHeader = req.headers.get('Authorization')\n if (!authHeader?.startsWith('Bearer ')) {\n return new Response('Unauthorized', { status: 401 })\n }\n\n let stripeSync = null\n try {\n // Get and validate database URL\n const rawDbUrl = Deno.env.get('SUPABASE_DB_URL')\n if (!rawDbUrl) {\n throw new Error('SUPABASE_DB_URL environment variable is not set')\n }\n // Remove sslmode from connection string (not supported by pg in Deno)\n const dbUrl = rawDbUrl.replace(/[?&]sslmode=[^&]*/g, '').replace(/[?&]$/, '')\n\n await runMigrations({ databaseUrl: dbUrl })\n\n stripeSync = new StripeSync({\n poolConfig: { connectionString: dbUrl, max: 2 }, // Need 2 for advisory lock + queries\n stripeSecretKey: Deno.env.get('STRIPE_SECRET_KEY'),\n })\n\n // Release any stale advisory locks from previous timeouts\n await stripeSync.postgresClient.query('SELECT pg_advisory_unlock_all()')\n\n // Construct webhook URL from SUPABASE_URL (available in all Edge Functions)\n const supabaseUrl = Deno.env.get('SUPABASE_URL')\n if (!supabaseUrl) {\n throw new Error('SUPABASE_URL environment variable is not set')\n }\n const webhookUrl = supabaseUrl + '/functions/v1/stripe-webhook'\n\n const webhook = await stripeSync.findOrCreateManagedWebhook(webhookUrl)\n\n await stripeSync.postgresClient.pool.end()\n\n return new Response(\n JSON.stringify({\n success: true,\n message: 'Setup complete',\n webhookId: webhook.id,\n }),\n {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n }\n )\n } catch (error) {\n console.error('Setup error:', error)\n // Cleanup on error\n if (stripeSync) {\n try {\n await stripeSync.postgresClient.query('SELECT pg_advisory_unlock_all()')\n await stripeSync.postgresClient.pool.end()\n } catch (cleanupErr) {\n console.warn('Cleanup failed:', cleanupErr)\n }\n }\n return new Response(JSON.stringify({ success: false, error: error.message }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n})\n";
|
|
3492
|
+
|
|
3493
|
+
// raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-webhook.ts
|
|
3494
|
+
var stripe_webhook_default = "import { StripeSync } from 'npm:stripe-experiment-sync'\n\nDeno.serve(async (req) => {\n if (req.method !== 'POST') {\n return new Response('Method not allowed', { status: 405 })\n }\n\n const sig = req.headers.get('stripe-signature')\n if (!sig) {\n return new Response('Missing stripe-signature header', { status: 400 })\n }\n\n const rawDbUrl = Deno.env.get('SUPABASE_DB_URL')\n if (!rawDbUrl) {\n return new Response(JSON.stringify({ error: 'SUPABASE_DB_URL not set' }), { status: 500 })\n }\n const dbUrl = rawDbUrl.replace(/[?&]sslmode=[^&]*/g, '').replace(/[?&]$/, '')\n\n const stripeSync = new StripeSync({\n poolConfig: { connectionString: dbUrl, max: 1 },\n stripeSecretKey: Deno.env.get('STRIPE_SECRET_KEY')!,\n })\n\n try {\n const rawBody = new Uint8Array(await req.arrayBuffer())\n await stripeSync.processWebhook(rawBody, sig)\n return new Response(JSON.stringify({ received: true }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n })\n } catch (error) {\n console.error('Webhook processing error:', error)\n const isSignatureError =\n error.message?.includes('signature') || error.type === 'StripeSignatureVerificationError'\n const status = isSignatureError ? 400 : 500\n return new Response(JSON.stringify({ error: error.message }), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n } finally {\n await stripeSync.postgresClient.pool.end()\n }\n})\n";
|
|
3495
|
+
|
|
3496
|
+
// raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-worker.ts
|
|
3497
|
+
var stripe_worker_default = "/**\n * Stripe Sync Worker\n *\n * Triggered by pg_cron every 10 seconds. Uses pgmq for durable work queue.\n *\n * Flow:\n * 1. Read batch of messages from pgmq (qty=10, vt=60s)\n * 2. If queue empty: enqueue all objects (continuous sync)\n * 3. Process messages in parallel (Promise.all):\n * - processNext(object)\n * - Delete message on success\n * - Re-enqueue if hasMore\n * 4. Return results summary\n *\n * Concurrency:\n * - Multiple workers can run concurrently via overlapping pg_cron triggers.\n * - Each worker processes its batch of messages in parallel (Promise.all).\n * - pgmq visibility timeout prevents duplicate message reads across workers.\n * - processNext() is idempotent (uses internal cursor tracking), so duplicate\n * processing on timeout/crash is safe.\n */\n\nimport { StripeSync } from 'npm:stripe-experiment-sync'\nimport postgres from 'npm:postgres'\n\nconst QUEUE_NAME = 'stripe_sync_work'\nconst VISIBILITY_TIMEOUT = 60 // seconds\nconst BATCH_SIZE = 10\n\nDeno.serve(async (req) => {\n const authHeader = req.headers.get('Authorization')\n if (!authHeader?.startsWith('Bearer ')) {\n return new Response('Unauthorized', { status: 401 })\n }\n\n const rawDbUrl = Deno.env.get('SUPABASE_DB_URL')\n if (!rawDbUrl) {\n return new Response(JSON.stringify({ error: 'SUPABASE_DB_URL not set' }), { status: 500 })\n }\n const dbUrl = rawDbUrl.replace(/[?&]sslmode=[^&]*/g, '').replace(/[?&]$/, '')\n\n let sql\n let stripeSync\n\n try {\n sql = postgres(dbUrl, { max: 1, prepare: false })\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: 'Failed to create postgres connection',\n details: error.message,\n stack: error.stack,\n }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n )\n }\n\n try {\n stripeSync = new StripeSync({\n poolConfig: { connectionString: dbUrl, max: 1 },\n stripeSecretKey: Deno.env.get('STRIPE_SECRET_KEY')!,\n })\n } catch (error) {\n await sql.end()\n return new Response(\n JSON.stringify({\n error: 'Failed to create StripeSync',\n details: error.message,\n stack: error.stack,\n }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n )\n }\n\n try {\n // Read batch of messages from queue\n const messages = await sql`\n SELECT * FROM pgmq.read(${QUEUE_NAME}::text, ${VISIBILITY_TIMEOUT}::int, ${BATCH_SIZE}::int)\n `\n\n // If queue empty, enqueue all objects for continuous sync\n if (messages.length === 0) {\n const objects = stripeSync.getSupportedSyncObjects()\n const msgs = objects.map((object) => JSON.stringify({ object }))\n\n await sql`\n SELECT pgmq.send_batch(\n ${QUEUE_NAME}::text,\n ${sql.array(msgs)}::jsonb[]\n )\n `\n\n return new Response(JSON.stringify({ enqueued: objects.length, objects }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n\n // Process messages in parallel\n const results = await Promise.all(\n messages.map(async (msg) => {\n const { object } = msg.message as { object: string }\n\n try {\n const result = await stripeSync.processNext(object)\n\n // Delete message on success (cast to bigint to disambiguate overloaded function)\n await sql`SELECT pgmq.delete(${QUEUE_NAME}::text, ${msg.msg_id}::bigint)`\n\n // Re-enqueue if more pages\n if (result.hasMore) {\n await sql`SELECT pgmq.send(${QUEUE_NAME}::text, ${sql.json({ object })}::jsonb)`\n }\n\n return { object, ...result }\n } catch (error) {\n // Log error but continue to next message\n // Message will become visible again after visibility timeout\n console.error(`Error processing ${object}:`, error)\n return {\n object,\n processed: 0,\n hasMore: false,\n error: error.message,\n stack: error.stack,\n }\n }\n })\n )\n\n return new Response(JSON.stringify({ results }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n })\n } catch (error) {\n console.error('Worker error:', error)\n return new Response(JSON.stringify({ error: error.message, stack: error.stack }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n } finally {\n if (sql) await sql.end()\n if (stripeSync) await stripeSync.postgresClient.pool.end()\n }\n})\n";
|
|
3498
|
+
|
|
3499
|
+
// src/supabase/edge-function-code.ts
|
|
3500
|
+
var setupFunctionCode = stripe_setup_default;
|
|
3501
|
+
var webhookFunctionCode = stripe_webhook_default;
|
|
3502
|
+
var workerFunctionCode = stripe_worker_default;
|
|
3503
|
+
|
|
3504
|
+
// src/supabase/supabase.ts
|
|
3505
|
+
var import_stripe3 = __toESM(require("stripe"), 1);
|
|
3506
|
+
var STRIPE_SCHEMA_COMMENT_PREFIX = "stripe-sync";
|
|
3507
|
+
var INSTALLATION_STARTED_SUFFIX = "installation:started";
|
|
3508
|
+
var INSTALLATION_ERROR_SUFFIX = "installation:error";
|
|
3509
|
+
var INSTALLATION_INSTALLED_SUFFIX = "installed";
|
|
3510
|
+
var SupabaseSetupClient = class {
|
|
3511
|
+
api;
|
|
3512
|
+
projectRef;
|
|
3513
|
+
projectBaseUrl;
|
|
3514
|
+
constructor(options) {
|
|
3515
|
+
this.api = new import_supabase_management_js.SupabaseManagementAPI({
|
|
3516
|
+
accessToken: options.accessToken,
|
|
3517
|
+
baseUrl: options.managementApiBaseUrl
|
|
3518
|
+
});
|
|
3519
|
+
this.projectRef = options.projectRef;
|
|
3520
|
+
this.projectBaseUrl = options.projectBaseUrl || process.env.SUPABASE_BASE_URL || "supabase.co";
|
|
3521
|
+
}
|
|
3522
|
+
/**
|
|
3523
|
+
* Validate that the project exists and we have access
|
|
3524
|
+
*/
|
|
3525
|
+
async validateProject() {
|
|
3526
|
+
const projects = await this.api.getProjects();
|
|
3527
|
+
const project = projects?.find((p) => p.id === this.projectRef);
|
|
3528
|
+
if (!project) {
|
|
3529
|
+
throw new Error(`Project ${this.projectRef} not found or you don't have access`);
|
|
3530
|
+
}
|
|
3531
|
+
return {
|
|
3532
|
+
id: project.id,
|
|
3533
|
+
name: project.name,
|
|
3534
|
+
region: project.region
|
|
3535
|
+
};
|
|
3536
|
+
}
|
|
3537
|
+
/**
|
|
3538
|
+
* Deploy an Edge Function
|
|
3539
|
+
*/
|
|
3540
|
+
async deployFunction(name, code) {
|
|
3541
|
+
const functions = await this.api.listFunctions(this.projectRef);
|
|
3542
|
+
const exists = functions?.some((f) => f.slug === name);
|
|
3543
|
+
if (exists) {
|
|
3544
|
+
await this.api.updateFunction(this.projectRef, name, {
|
|
3545
|
+
body: code,
|
|
3546
|
+
verify_jwt: false
|
|
3547
|
+
});
|
|
3548
|
+
} else {
|
|
3549
|
+
await this.api.createFunction(this.projectRef, {
|
|
3550
|
+
slug: name,
|
|
3551
|
+
name,
|
|
3552
|
+
body: code,
|
|
3553
|
+
verify_jwt: false
|
|
3554
|
+
});
|
|
3555
|
+
}
|
|
3556
|
+
}
|
|
3557
|
+
/**
|
|
3558
|
+
* Set secrets for Edge Functions
|
|
3559
|
+
*/
|
|
3560
|
+
async setSecrets(secrets) {
|
|
3561
|
+
await this.api.createSecrets(this.projectRef, secrets);
|
|
3562
|
+
}
|
|
3563
|
+
/**
|
|
3564
|
+
* Run SQL against the database
|
|
3565
|
+
*/
|
|
3566
|
+
async runSQL(sql3) {
|
|
3567
|
+
return await this.api.runQuery(this.projectRef, sql3);
|
|
3568
|
+
}
|
|
3569
|
+
/**
|
|
3570
|
+
* Setup pg_cron job to invoke worker function
|
|
3571
|
+
*/
|
|
3572
|
+
async setupPgCronJob() {
|
|
3573
|
+
const serviceRoleKey = await this.getServiceRoleKey();
|
|
3574
|
+
const escapedServiceRoleKey = serviceRoleKey.replace(/'/g, "''");
|
|
3575
|
+
const sql3 = `
|
|
3576
|
+
-- Enable extensions
|
|
3577
|
+
CREATE EXTENSION IF NOT EXISTS pg_cron;
|
|
3578
|
+
CREATE EXTENSION IF NOT EXISTS pg_net;
|
|
3579
|
+
CREATE EXTENSION IF NOT EXISTS pgmq;
|
|
3580
|
+
|
|
3581
|
+
-- Create pgmq queue for sync work (idempotent)
|
|
3582
|
+
SELECT pgmq.create('stripe_sync_work')
|
|
3583
|
+
WHERE NOT EXISTS (
|
|
3584
|
+
SELECT 1 FROM pgmq.list_queues() WHERE queue_name = 'stripe_sync_work'
|
|
3585
|
+
);
|
|
3586
|
+
|
|
3587
|
+
-- Store service role key in vault for pg_cron to use
|
|
3588
|
+
-- Delete existing secret if it exists, then create new one
|
|
3589
|
+
DELETE FROM vault.secrets WHERE name = 'stripe_sync_service_role_key';
|
|
3590
|
+
SELECT vault.create_secret('${escapedServiceRoleKey}', 'stripe_sync_service_role_key');
|
|
3591
|
+
|
|
3592
|
+
-- Delete existing jobs if they exist
|
|
3593
|
+
SELECT cron.unschedule('stripe-sync-worker') WHERE EXISTS (
|
|
3594
|
+
SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker'
|
|
3595
|
+
);
|
|
3596
|
+
SELECT cron.unschedule('stripe-sync-scheduler') WHERE EXISTS (
|
|
3597
|
+
SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-scheduler'
|
|
3598
|
+
);
|
|
3599
|
+
|
|
3600
|
+
-- Create job to invoke worker every 10 seconds
|
|
3601
|
+
-- Worker reads from pgmq, enqueues objects if empty, and processes sync work
|
|
3602
|
+
SELECT cron.schedule(
|
|
3603
|
+
'stripe-sync-worker',
|
|
3604
|
+
'10 seconds',
|
|
3605
|
+
$$
|
|
3606
|
+
SELECT net.http_post(
|
|
3607
|
+
url := 'https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/stripe-worker',
|
|
3608
|
+
headers := jsonb_build_object(
|
|
3609
|
+
'Authorization', 'Bearer ' || (SELECT decrypted_secret FROM vault.decrypted_secrets WHERE name = 'stripe_sync_service_role_key')
|
|
3610
|
+
)
|
|
3611
|
+
)
|
|
3612
|
+
$$
|
|
3613
|
+
);
|
|
3614
|
+
`;
|
|
3615
|
+
await this.runSQL(sql3);
|
|
3616
|
+
}
|
|
3617
|
+
/**
|
|
3618
|
+
* Get the webhook URL for this project
|
|
3619
|
+
*/
|
|
3620
|
+
getWebhookUrl() {
|
|
3621
|
+
return `https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/stripe-webhook`;
|
|
3622
|
+
}
|
|
3623
|
+
/**
|
|
3624
|
+
* Get the service role key for this project (needed to invoke Edge Functions)
|
|
3625
|
+
*/
|
|
3626
|
+
async getServiceRoleKey() {
|
|
3627
|
+
const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
|
|
3628
|
+
const serviceRoleKey = apiKeys?.find((k) => k.name === "service_role");
|
|
3629
|
+
if (!serviceRoleKey) {
|
|
3630
|
+
throw new Error("Could not find service_role API key");
|
|
3631
|
+
}
|
|
3632
|
+
return serviceRoleKey.api_key;
|
|
3633
|
+
}
|
|
3634
|
+
/**
|
|
3635
|
+
* Get the anon key for this project (needed for Realtime subscriptions)
|
|
3636
|
+
*/
|
|
3637
|
+
async getAnonKey() {
|
|
3638
|
+
const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
|
|
3639
|
+
const anonKey = apiKeys?.find((k) => k.name === "anon");
|
|
3640
|
+
if (!anonKey) {
|
|
3641
|
+
throw new Error("Could not find anon API key");
|
|
3642
|
+
}
|
|
3643
|
+
return anonKey.api_key;
|
|
3644
|
+
}
|
|
3645
|
+
/**
|
|
3646
|
+
* Get the project URL
|
|
3647
|
+
*/
|
|
3648
|
+
getProjectUrl() {
|
|
3649
|
+
return `https://${this.projectRef}.${this.projectBaseUrl}`;
|
|
3650
|
+
}
|
|
3651
|
+
/**
|
|
3652
|
+
* Invoke an Edge Function
|
|
3653
|
+
*/
|
|
3654
|
+
async invokeFunction(name, serviceRoleKey) {
|
|
3655
|
+
const url = `https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/${name}`;
|
|
3656
|
+
const response = await fetch(url, {
|
|
3657
|
+
method: "POST",
|
|
3658
|
+
headers: {
|
|
3659
|
+
Authorization: `Bearer ${serviceRoleKey}`,
|
|
3660
|
+
"Content-Type": "application/json"
|
|
3661
|
+
}
|
|
3662
|
+
});
|
|
3663
|
+
if (!response.ok) {
|
|
3664
|
+
const text = await response.text();
|
|
3665
|
+
return { success: false, error: `${response.status}: ${text}` };
|
|
3666
|
+
}
|
|
3667
|
+
const result = await response.json();
|
|
3668
|
+
if (result.success === false) {
|
|
3669
|
+
return { success: false, error: result.error };
|
|
3670
|
+
}
|
|
3671
|
+
return { success: true };
|
|
3672
|
+
}
|
|
3673
|
+
/**
|
|
3674
|
+
* Check if stripe-sync is installed in the database.
|
|
3675
|
+
*
|
|
3676
|
+
* Uses the Supabase Management API to run SQL queries.
|
|
3677
|
+
* Uses duck typing (schema + migrations table) combined with comment validation.
|
|
3678
|
+
* Throws error for legacy installations to prevent accidental corruption.
|
|
3679
|
+
*
|
|
3680
|
+
* @param schema The schema name to check (defaults to 'stripe')
|
|
3681
|
+
* @returns true if properly installed with comment marker, false if not installed
|
|
3682
|
+
* @throws Error if legacy installation detected (schema exists without comment)
|
|
3683
|
+
*/
|
|
3684
|
+
async isInstalled(schema = "stripe") {
|
|
3685
|
+
try {
|
|
3686
|
+
const schemaCheck = await this.runSQL(
|
|
3687
|
+
`SELECT EXISTS (
|
|
3688
|
+
SELECT 1 FROM information_schema.schemata
|
|
3689
|
+
WHERE schema_name = '${schema}'
|
|
3690
|
+
) as schema_exists`
|
|
3691
|
+
);
|
|
3692
|
+
const schemaExists = schemaCheck[0]?.rows?.[0]?.schema_exists === true;
|
|
3693
|
+
if (!schemaExists) {
|
|
3694
|
+
return false;
|
|
3695
|
+
}
|
|
3696
|
+
const migrationsCheck = await this.runSQL(
|
|
3697
|
+
`SELECT EXISTS (
|
|
3698
|
+
SELECT 1 FROM information_schema.tables
|
|
3699
|
+
WHERE table_schema = '${schema}' AND table_name IN ('migrations', '_migrations')
|
|
3700
|
+
) as table_exists`
|
|
3701
|
+
);
|
|
3702
|
+
const migrationsTableExists = migrationsCheck[0]?.rows?.[0]?.table_exists === true;
|
|
3703
|
+
if (!migrationsTableExists) {
|
|
3704
|
+
return false;
|
|
3705
|
+
}
|
|
3706
|
+
const commentCheck = await this.runSQL(
|
|
3707
|
+
`SELECT obj_description(oid, 'pg_namespace') as comment
|
|
3708
|
+
FROM pg_namespace
|
|
3709
|
+
WHERE nspname = '${schema}'`
|
|
3710
|
+
);
|
|
3711
|
+
const comment = commentCheck[0]?.rows?.[0]?.comment;
|
|
3712
|
+
if (!comment || !comment.includes(STRIPE_SCHEMA_COMMENT_PREFIX)) {
|
|
3713
|
+
throw new Error(
|
|
3714
|
+
`Legacy installation detected: Schema '${schema}' and migrations table exist, but missing stripe-sync comment marker. This may be a legacy installation or manually created schema. Please contact support or manually drop the schema before proceeding.`
|
|
3715
|
+
);
|
|
3716
|
+
}
|
|
3717
|
+
if (comment.includes(INSTALLATION_STARTED_SUFFIX)) {
|
|
3718
|
+
return false;
|
|
3719
|
+
}
|
|
3720
|
+
if (comment.includes(INSTALLATION_ERROR_SUFFIX)) {
|
|
3721
|
+
throw new Error(
|
|
3722
|
+
`Installation failed: Schema '${schema}' exists but installation encountered an error. Comment: ${comment}. Please uninstall and install again.`
|
|
3723
|
+
);
|
|
3724
|
+
}
|
|
3725
|
+
return true;
|
|
3726
|
+
} catch (error) {
|
|
3727
|
+
if (error instanceof Error && (error.message.includes("Legacy installation detected") || error.message.includes("Installation failed"))) {
|
|
3728
|
+
throw error;
|
|
3729
|
+
}
|
|
3730
|
+
return false;
|
|
3731
|
+
}
|
|
3732
|
+
}
|
|
3733
|
+
/**
|
|
3734
|
+
* Update installation progress comment on the stripe schema
|
|
3735
|
+
*/
|
|
3736
|
+
async updateInstallationComment(message) {
|
|
3737
|
+
const escapedMessage = message.replace(/'/g, "''");
|
|
3738
|
+
await this.runSQL(`COMMENT ON SCHEMA stripe IS '${escapedMessage}'`);
|
|
3739
|
+
}
|
|
3740
|
+
/**
|
|
3741
|
+
* Delete an Edge Function
|
|
3742
|
+
*/
|
|
3743
|
+
async deleteFunction(name) {
|
|
3744
|
+
try {
|
|
3745
|
+
await this.api.deleteFunction(this.projectRef, name);
|
|
3746
|
+
} catch (err) {
|
|
3747
|
+
console.warn(`Could not delete function ${name}:`, err);
|
|
3748
|
+
}
|
|
3749
|
+
}
|
|
3750
|
+
/**
|
|
3751
|
+
* Delete a secret
|
|
3752
|
+
*/
|
|
3753
|
+
async deleteSecret(name) {
|
|
3754
|
+
try {
|
|
3755
|
+
await this.api.deleteSecrets(this.projectRef, [name]);
|
|
3756
|
+
} catch (err) {
|
|
3757
|
+
console.warn(`Could not delete secret ${name}:`, err);
|
|
3758
|
+
}
|
|
3759
|
+
}
|
|
3760
|
+
/**
|
|
3761
|
+
* Uninstall stripe-sync from a Supabase project
|
|
3762
|
+
* Removes all Edge Functions, secrets, database resources, and Stripe webhooks
|
|
3763
|
+
*/
|
|
3764
|
+
async uninstall(stripeSecretKey) {
|
|
3765
|
+
const stripe = new import_stripe3.default(stripeSecretKey, { apiVersion: "2025-02-24.acacia" });
|
|
3766
|
+
try {
|
|
3767
|
+
try {
|
|
3768
|
+
const webhookResult = await this.runSQL(`
|
|
3769
|
+
SELECT id FROM stripe._managed_webhooks WHERE id IS NOT NULL
|
|
3770
|
+
`);
|
|
3771
|
+
const webhookIds = webhookResult[0]?.rows?.map((r) => r.id) || [];
|
|
3772
|
+
for (const webhookId of webhookIds) {
|
|
3773
|
+
try {
|
|
3774
|
+
await stripe.webhookEndpoints.del(webhookId);
|
|
3775
|
+
} catch (err) {
|
|
3776
|
+
console.warn(`Could not delete Stripe webhook ${webhookId}:`, err);
|
|
3777
|
+
}
|
|
3778
|
+
}
|
|
3779
|
+
} catch (err) {
|
|
3780
|
+
console.warn("Could not query/delete webhooks:", err);
|
|
3781
|
+
}
|
|
3782
|
+
await this.deleteFunction("stripe-setup");
|
|
3783
|
+
await this.deleteFunction("stripe-webhook");
|
|
3784
|
+
await this.deleteFunction("stripe-worker");
|
|
3785
|
+
await this.deleteSecret("STRIPE_SECRET_KEY");
|
|
3786
|
+
try {
|
|
3787
|
+
await this.runSQL(`
|
|
3788
|
+
SELECT cron.unschedule('stripe-sync-worker')
|
|
3789
|
+
WHERE EXISTS (
|
|
3790
|
+
SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker'
|
|
3791
|
+
)
|
|
3792
|
+
`);
|
|
3793
|
+
} catch (err) {
|
|
3794
|
+
console.warn("Could not unschedule pg_cron job:", err);
|
|
3795
|
+
}
|
|
3796
|
+
try {
|
|
3797
|
+
await this.runSQL(`
|
|
3798
|
+
DELETE FROM vault.secrets
|
|
3799
|
+
WHERE name = 'stripe_sync_service_role_key'
|
|
3800
|
+
`);
|
|
3801
|
+
} catch (err) {
|
|
3802
|
+
console.warn("Could not delete vault secret:", err);
|
|
3803
|
+
}
|
|
3804
|
+
await this.runSQL(`DROP SCHEMA IF EXISTS stripe CASCADE`);
|
|
3805
|
+
} catch (error) {
|
|
3806
|
+
throw new Error(`Uninstall failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3807
|
+
}
|
|
3808
|
+
}
|
|
3809
|
+
async install(stripeKey) {
|
|
3810
|
+
const trimmedStripeKey = stripeKey.trim();
|
|
3811
|
+
if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
|
|
3812
|
+
throw new Error('Stripe key should start with "sk_" or "rk_"');
|
|
3813
|
+
}
|
|
3814
|
+
try {
|
|
3815
|
+
await this.validateProject();
|
|
3816
|
+
await this.runSQL(`CREATE SCHEMA IF NOT EXISTS stripe`);
|
|
3817
|
+
await this.updateInstallationComment(
|
|
3818
|
+
`${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_STARTED_SUFFIX}`
|
|
3819
|
+
);
|
|
3820
|
+
await this.deployFunction("stripe-setup", setupFunctionCode);
|
|
3821
|
+
await this.deployFunction("stripe-webhook", webhookFunctionCode);
|
|
3822
|
+
await this.deployFunction("stripe-worker", workerFunctionCode);
|
|
3823
|
+
await this.setSecrets([{ name: "STRIPE_SECRET_KEY", value: trimmedStripeKey }]);
|
|
3824
|
+
const serviceRoleKey = await this.getServiceRoleKey();
|
|
3825
|
+
const setupResult = await this.invokeFunction("stripe-setup", serviceRoleKey);
|
|
3826
|
+
if (!setupResult.success) {
|
|
3827
|
+
throw new Error(`Setup failed: ${setupResult.error}`);
|
|
3828
|
+
}
|
|
3829
|
+
let pgCronEnabled = false;
|
|
3830
|
+
try {
|
|
3831
|
+
await this.setupPgCronJob();
|
|
3832
|
+
pgCronEnabled = true;
|
|
3833
|
+
} catch {
|
|
3834
|
+
console.warn("pg_cron setup failed - falling back to manual worker invocation");
|
|
3835
|
+
}
|
|
3836
|
+
if (!pgCronEnabled) {
|
|
3837
|
+
try {
|
|
3838
|
+
await this.invokeFunction("stripe-worker", serviceRoleKey);
|
|
3839
|
+
} catch (err) {
|
|
3840
|
+
console.warn("Failed to trigger initial worker invocation:", err);
|
|
3841
|
+
}
|
|
3842
|
+
}
|
|
3843
|
+
await this.updateInstallationComment(
|
|
3844
|
+
`${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_INSTALLED_SUFFIX}`
|
|
3845
|
+
);
|
|
3846
|
+
} catch (error) {
|
|
3847
|
+
await this.updateInstallationComment(
|
|
3848
|
+
`${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_ERROR_SUFFIX} - ${error instanceof Error ? error.message : String(error)}`
|
|
3849
|
+
);
|
|
3850
|
+
throw error;
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
};
|
|
3854
|
+
async function install(params) {
|
|
3855
|
+
const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
|
|
3856
|
+
const client = new SupabaseSetupClient({
|
|
3857
|
+
accessToken: supabaseAccessToken,
|
|
3858
|
+
projectRef: supabaseProjectRef,
|
|
3859
|
+
projectBaseUrl: params.baseProjectUrl,
|
|
3860
|
+
managementApiBaseUrl: params.baseManagementApiUrl
|
|
3861
|
+
});
|
|
3862
|
+
await client.install(stripeKey);
|
|
3863
|
+
}
|
|
3864
|
+
async function uninstall(params) {
|
|
3865
|
+
const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
|
|
3866
|
+
const trimmedStripeKey = stripeKey.trim();
|
|
3867
|
+
if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
|
|
3868
|
+
throw new Error('Stripe key should start with "sk_" or "rk_"');
|
|
3869
|
+
}
|
|
3870
|
+
const client = new SupabaseSetupClient({
|
|
3871
|
+
accessToken: supabaseAccessToken,
|
|
3872
|
+
projectRef: supabaseProjectRef
|
|
3873
|
+
});
|
|
3874
|
+
await client.uninstall(trimmedStripeKey);
|
|
3875
|
+
}
|
|
3876
|
+
|
|
3877
|
+
// src/cli/commands.ts
|
|
3878
|
+
var VALID_SYNC_OBJECTS = [
|
|
3879
|
+
"all",
|
|
3880
|
+
"customer",
|
|
3881
|
+
"customer_with_entitlements",
|
|
3882
|
+
"invoice",
|
|
3883
|
+
"price",
|
|
3884
|
+
"product",
|
|
3885
|
+
"subscription",
|
|
3886
|
+
"subscription_schedules",
|
|
3887
|
+
"setup_intent",
|
|
3888
|
+
"payment_method",
|
|
3889
|
+
"dispute",
|
|
3890
|
+
"charge",
|
|
3891
|
+
"payment_intent",
|
|
3892
|
+
"plan",
|
|
3893
|
+
"tax_id",
|
|
3894
|
+
"credit_note",
|
|
3895
|
+
"early_fraud_warning",
|
|
3896
|
+
"refund",
|
|
3897
|
+
"checkout_sessions"
|
|
3898
|
+
];
|
|
3899
|
+
async function backfillCommand(options, entityName) {
|
|
3900
|
+
let stripeSync = null;
|
|
3901
|
+
try {
|
|
3902
|
+
if (!VALID_SYNC_OBJECTS.includes(entityName)) {
|
|
3903
|
+
console.error(
|
|
3904
|
+
import_chalk3.default.red(
|
|
3905
|
+
`Error: Invalid entity name "${entityName}". Valid entities are: ${VALID_SYNC_OBJECTS.join(", ")}`
|
|
3906
|
+
)
|
|
3907
|
+
);
|
|
3908
|
+
process.exit(1);
|
|
3909
|
+
}
|
|
3910
|
+
import_dotenv2.default.config();
|
|
3911
|
+
let stripeApiKey = options.stripeKey || process.env.STRIPE_API_KEY || process.env.STRIPE_SECRET_KEY || "";
|
|
3912
|
+
let databaseUrl = options.databaseUrl || process.env.DATABASE_URL || "";
|
|
3913
|
+
if (!stripeApiKey || !databaseUrl) {
|
|
3914
|
+
const inquirer2 = (await import("inquirer")).default;
|
|
3915
|
+
const questions = [];
|
|
3916
|
+
if (!stripeApiKey) {
|
|
3917
|
+
questions.push({
|
|
3918
|
+
type: "password",
|
|
3919
|
+
name: "stripeApiKey",
|
|
3920
|
+
message: "Enter your Stripe API key:",
|
|
3921
|
+
mask: "*",
|
|
3922
|
+
validate: (input) => {
|
|
3923
|
+
if (!input || input.trim() === "") {
|
|
3924
|
+
return "Stripe API key is required";
|
|
3925
|
+
}
|
|
3926
|
+
if (!input.startsWith("sk_")) {
|
|
3927
|
+
return 'Stripe API key should start with "sk_"';
|
|
3928
|
+
}
|
|
3929
|
+
return true;
|
|
3930
|
+
}
|
|
3931
|
+
});
|
|
3932
|
+
}
|
|
3933
|
+
if (!databaseUrl) {
|
|
3934
|
+
questions.push({
|
|
3935
|
+
type: "password",
|
|
3936
|
+
name: "databaseUrl",
|
|
3937
|
+
message: "Enter your Postgres DATABASE_URL:",
|
|
3938
|
+
mask: "*",
|
|
3939
|
+
validate: (input) => {
|
|
3940
|
+
if (!input || input.trim() === "") {
|
|
3941
|
+
return "DATABASE_URL is required";
|
|
3942
|
+
}
|
|
3943
|
+
if (!input.startsWith("postgres://") && !input.startsWith("postgresql://")) {
|
|
3944
|
+
return 'DATABASE_URL should start with "postgres://" or "postgresql://"';
|
|
3945
|
+
}
|
|
3946
|
+
return true;
|
|
3947
|
+
}
|
|
3948
|
+
});
|
|
3949
|
+
}
|
|
3950
|
+
if (questions.length > 0) {
|
|
3951
|
+
console.log(import_chalk3.default.yellow("\nMissing required configuration. Please provide:"));
|
|
3952
|
+
const answers = await inquirer2.prompt(questions);
|
|
3953
|
+
if (answers.stripeApiKey) stripeApiKey = answers.stripeApiKey;
|
|
3954
|
+
if (answers.databaseUrl) databaseUrl = answers.databaseUrl;
|
|
3955
|
+
}
|
|
3956
|
+
}
|
|
3957
|
+
const config = {
|
|
3958
|
+
stripeApiKey,
|
|
3959
|
+
databaseUrl,
|
|
3960
|
+
ngrokAuthToken: ""
|
|
3961
|
+
// Not needed for backfill
|
|
3962
|
+
};
|
|
3963
|
+
console.log(import_chalk3.default.blue(`Backfilling ${entityName} from Stripe in 'stripe' schema...`));
|
|
3964
|
+
console.log(import_chalk3.default.gray(`Database: ${config.databaseUrl.replace(/:[^:@]+@/, ":****@")}`));
|
|
3965
|
+
try {
|
|
3966
|
+
await runMigrations({
|
|
3967
|
+
databaseUrl: config.databaseUrl
|
|
3968
|
+
});
|
|
3969
|
+
} catch (migrationError) {
|
|
3970
|
+
console.error(import_chalk3.default.red("Failed to run migrations:"));
|
|
3971
|
+
console.error(
|
|
3972
|
+
migrationError instanceof Error ? migrationError.message : String(migrationError)
|
|
3973
|
+
);
|
|
3974
|
+
throw migrationError;
|
|
3975
|
+
}
|
|
3976
|
+
const poolConfig = {
|
|
3977
|
+
max: 10,
|
|
3978
|
+
connectionString: config.databaseUrl,
|
|
3979
|
+
keepAlive: true
|
|
3980
|
+
};
|
|
3981
|
+
stripeSync = new StripeSync({
|
|
3982
|
+
databaseUrl: config.databaseUrl,
|
|
3983
|
+
stripeSecretKey: config.stripeApiKey,
|
|
3984
|
+
stripeApiVersion: process.env.STRIPE_API_VERSION || "2020-08-27",
|
|
3985
|
+
autoExpandLists: process.env.AUTO_EXPAND_LISTS === "true",
|
|
3986
|
+
backfillRelatedEntities: process.env.BACKFILL_RELATED_ENTITIES !== "false",
|
|
3987
|
+
poolConfig
|
|
3988
|
+
});
|
|
3989
|
+
const result = await stripeSync.processUntilDone({ object: entityName });
|
|
3990
|
+
const totalSynced = Object.values(result).reduce(
|
|
3991
|
+
(sum, syncResult) => sum + (syncResult?.synced || 0),
|
|
3992
|
+
0
|
|
3993
|
+
);
|
|
3994
|
+
console.log(import_chalk3.default.green(`\u2713 Backfill complete: ${totalSynced} ${entityName} objects synced`));
|
|
3995
|
+
await stripeSync.close();
|
|
3996
|
+
} catch (error) {
|
|
3997
|
+
if (error instanceof Error) {
|
|
3998
|
+
console.error(import_chalk3.default.red(error.message));
|
|
3999
|
+
}
|
|
4000
|
+
if (stripeSync) {
|
|
4001
|
+
try {
|
|
4002
|
+
await stripeSync.close();
|
|
4003
|
+
} catch {
|
|
4004
|
+
}
|
|
4005
|
+
}
|
|
4006
|
+
process.exit(1);
|
|
4007
|
+
}
|
|
4008
|
+
}
|
|
4009
|
+
async function migrateCommand(options) {
|
|
4010
|
+
try {
|
|
4011
|
+
import_dotenv2.default.config();
|
|
4012
|
+
let databaseUrl = options.databaseUrl || process.env.DATABASE_URL || "";
|
|
4013
|
+
if (!databaseUrl) {
|
|
4014
|
+
const inquirer2 = (await import("inquirer")).default;
|
|
4015
|
+
const answers = await inquirer2.prompt([
|
|
4016
|
+
{
|
|
4017
|
+
type: "password",
|
|
4018
|
+
name: "databaseUrl",
|
|
4019
|
+
message: "Enter your Postgres DATABASE_URL:",
|
|
4020
|
+
mask: "*",
|
|
4021
|
+
validate: (input) => {
|
|
4022
|
+
if (!input || input.trim() === "") {
|
|
4023
|
+
return "DATABASE_URL is required";
|
|
4024
|
+
}
|
|
4025
|
+
if (!input.startsWith("postgres://") && !input.startsWith("postgresql://")) {
|
|
4026
|
+
return 'DATABASE_URL should start with "postgres://" or "postgresql://"';
|
|
4027
|
+
}
|
|
4028
|
+
return true;
|
|
4029
|
+
}
|
|
4030
|
+
}
|
|
4031
|
+
]);
|
|
4032
|
+
databaseUrl = answers.databaseUrl;
|
|
4033
|
+
}
|
|
4034
|
+
console.log(import_chalk3.default.blue("Running database migrations in 'stripe' schema..."));
|
|
4035
|
+
console.log(import_chalk3.default.gray(`Database: ${databaseUrl.replace(/:[^:@]+@/, ":****@")}`));
|
|
4036
|
+
try {
|
|
4037
|
+
await runMigrations({
|
|
4038
|
+
databaseUrl
|
|
4039
|
+
});
|
|
4040
|
+
console.log(import_chalk3.default.green("\u2713 Migrations completed successfully"));
|
|
4041
|
+
} catch (migrationError) {
|
|
4042
|
+
console.warn(import_chalk3.default.yellow("Migrations failed."));
|
|
4043
|
+
if (migrationError instanceof Error) {
|
|
4044
|
+
const errorMsg = migrationError.message || migrationError.toString();
|
|
4045
|
+
console.warn("Migration error:", errorMsg);
|
|
4046
|
+
if (migrationError.stack) {
|
|
4047
|
+
console.warn(import_chalk3.default.gray(migrationError.stack));
|
|
4048
|
+
}
|
|
4049
|
+
} else {
|
|
4050
|
+
console.warn("Migration error:", String(migrationError));
|
|
4051
|
+
}
|
|
4052
|
+
throw migrationError;
|
|
4053
|
+
}
|
|
4054
|
+
} catch (error) {
|
|
4055
|
+
if (error instanceof Error) {
|
|
4056
|
+
console.error(import_chalk3.default.red(error.message));
|
|
4057
|
+
}
|
|
4058
|
+
process.exit(1);
|
|
4059
|
+
}
|
|
4060
|
+
}
|
|
4061
|
+
async function syncCommand(options) {
|
|
4062
|
+
let stripeSync = null;
|
|
4063
|
+
let tunnel = null;
|
|
4064
|
+
let server = null;
|
|
4065
|
+
let webhookId = null;
|
|
4066
|
+
const cleanup = async (signal) => {
|
|
4067
|
+
console.log(import_chalk3.default.blue(`
|
|
4068
|
+
|
|
4069
|
+
Cleaning up... (signal: ${signal || "manual"})`));
|
|
4070
|
+
const keepWebhooksOnShutdown = process.env.KEEP_WEBHOOKS_ON_SHUTDOWN === "true";
|
|
4071
|
+
if (webhookId && stripeSync && !keepWebhooksOnShutdown) {
|
|
4072
|
+
try {
|
|
4073
|
+
await stripeSync.deleteManagedWebhook(webhookId);
|
|
4074
|
+
console.log(import_chalk3.default.green("\u2713 Webhook cleanup complete"));
|
|
4075
|
+
} catch {
|
|
4076
|
+
console.log(import_chalk3.default.yellow("\u26A0 Could not delete webhook"));
|
|
4077
|
+
}
|
|
4078
|
+
}
|
|
4079
|
+
if (server) {
|
|
4080
|
+
try {
|
|
4081
|
+
await new Promise((resolve, reject) => {
|
|
4082
|
+
server.close((err) => {
|
|
4083
|
+
if (err) reject(err);
|
|
4084
|
+
else resolve();
|
|
4085
|
+
});
|
|
4086
|
+
});
|
|
4087
|
+
console.log(import_chalk3.default.green("\u2713 Server stopped"));
|
|
4088
|
+
} catch {
|
|
4089
|
+
console.log(import_chalk3.default.yellow("\u26A0 Server already stopped"));
|
|
4090
|
+
}
|
|
4091
|
+
}
|
|
4092
|
+
if (tunnel) {
|
|
4093
|
+
try {
|
|
4094
|
+
await tunnel.close();
|
|
4095
|
+
} catch {
|
|
4096
|
+
console.log(import_chalk3.default.yellow("\u26A0 Could not close tunnel"));
|
|
4097
|
+
}
|
|
4098
|
+
}
|
|
4099
|
+
if (stripeSync) {
|
|
4100
|
+
try {
|
|
4101
|
+
await stripeSync.close();
|
|
4102
|
+
console.log(import_chalk3.default.green("\u2713 Database pool closed"));
|
|
4103
|
+
} catch {
|
|
4104
|
+
console.log(import_chalk3.default.yellow("\u26A0 Could not close database pool"));
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
4107
|
+
process.exit(0);
|
|
4108
|
+
};
|
|
4109
|
+
process.on("SIGINT", () => cleanup("SIGINT"));
|
|
4110
|
+
process.on("SIGTERM", () => cleanup("SIGTERM"));
|
|
4111
|
+
try {
|
|
4112
|
+
const config = await loadConfig(options);
|
|
4113
|
+
console.log(import_chalk3.default.gray(`$ stripe-sync start ${config.databaseUrl}`));
|
|
4114
|
+
try {
|
|
4115
|
+
await runMigrations({
|
|
4116
|
+
databaseUrl: config.databaseUrl
|
|
4117
|
+
});
|
|
4118
|
+
} catch (migrationError) {
|
|
4119
|
+
console.error(import_chalk3.default.red("Failed to run migrations:"));
|
|
4120
|
+
console.error(
|
|
4121
|
+
migrationError instanceof Error ? migrationError.message : String(migrationError)
|
|
4122
|
+
);
|
|
4123
|
+
throw migrationError;
|
|
4124
|
+
}
|
|
4125
|
+
const poolConfig = {
|
|
4126
|
+
max: 10,
|
|
4127
|
+
connectionString: config.databaseUrl,
|
|
4128
|
+
keepAlive: true
|
|
4129
|
+
};
|
|
4130
|
+
stripeSync = new StripeSync({
|
|
4131
|
+
databaseUrl: config.databaseUrl,
|
|
4132
|
+
stripeSecretKey: config.stripeApiKey,
|
|
4133
|
+
stripeApiVersion: process.env.STRIPE_API_VERSION || "2020-08-27",
|
|
4134
|
+
autoExpandLists: process.env.AUTO_EXPAND_LISTS === "true",
|
|
4135
|
+
backfillRelatedEntities: process.env.BACKFILL_RELATED_ENTITIES !== "false",
|
|
4136
|
+
poolConfig
|
|
4137
|
+
});
|
|
4138
|
+
const port = 3e3;
|
|
4139
|
+
tunnel = await createTunnel(port, config.ngrokAuthToken);
|
|
4140
|
+
const webhookPath = process.env.WEBHOOK_PATH || "/stripe-webhooks";
|
|
4141
|
+
console.log(import_chalk3.default.blue("\nCreating Stripe webhook endpoint..."));
|
|
4142
|
+
const webhook = await stripeSync.findOrCreateManagedWebhook(`${tunnel.url}${webhookPath}`);
|
|
4143
|
+
webhookId = webhook.id;
|
|
4144
|
+
const eventCount = webhook.enabled_events?.length || 0;
|
|
4145
|
+
console.log(import_chalk3.default.green(`\u2713 Webhook created: ${webhook.id}`));
|
|
4146
|
+
console.log(import_chalk3.default.cyan(` URL: ${webhook.url}`));
|
|
4147
|
+
console.log(import_chalk3.default.cyan(` Events: ${eventCount} supported events`));
|
|
4148
|
+
const app = (0, import_express.default)();
|
|
4149
|
+
const webhookRoute = webhookPath;
|
|
4150
|
+
app.use(webhookRoute, import_express.default.raw({ type: "application/json" }));
|
|
4151
|
+
app.post(webhookRoute, async (req, res) => {
|
|
4152
|
+
const sig = req.headers["stripe-signature"];
|
|
4153
|
+
if (!sig || typeof sig !== "string") {
|
|
4154
|
+
console.error("[Webhook] Missing stripe-signature header");
|
|
4155
|
+
return res.status(400).send({ error: "Missing stripe-signature header" });
|
|
4156
|
+
}
|
|
4157
|
+
const rawBody = req.body;
|
|
4158
|
+
if (!rawBody || !Buffer.isBuffer(rawBody)) {
|
|
4159
|
+
console.error("[Webhook] Body is not a Buffer!");
|
|
4160
|
+
return res.status(400).send({ error: "Missing raw body for signature verification" });
|
|
4161
|
+
}
|
|
4162
|
+
try {
|
|
4163
|
+
await stripeSync.processWebhook(rawBody, sig);
|
|
4164
|
+
return res.status(200).send({ received: true });
|
|
4165
|
+
} catch (error) {
|
|
4166
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
4167
|
+
console.error("[Webhook] Processing error:", errorMessage);
|
|
4168
|
+
return res.status(400).send({ error: errorMessage });
|
|
4169
|
+
}
|
|
4170
|
+
});
|
|
4171
|
+
app.use(import_express.default.json());
|
|
4172
|
+
app.use(import_express.default.urlencoded({ extended: false }));
|
|
4173
|
+
app.get("/health", async (req, res) => {
|
|
4174
|
+
return res.status(200).json({ status: "ok" });
|
|
4175
|
+
});
|
|
4176
|
+
console.log(import_chalk3.default.blue(`
|
|
4177
|
+
Starting server on port ${port}...`));
|
|
4178
|
+
await new Promise((resolve, reject) => {
|
|
4179
|
+
server = app.listen(port, "0.0.0.0", () => {
|
|
4180
|
+
resolve();
|
|
4181
|
+
});
|
|
4182
|
+
server.on("error", reject);
|
|
4183
|
+
});
|
|
4184
|
+
console.log(import_chalk3.default.green(`\u2713 Server started on port ${port}`));
|
|
4185
|
+
if (process.env.SKIP_BACKFILL !== "true") {
|
|
4186
|
+
console.log(import_chalk3.default.blue("\nStarting initial sync of all Stripe data..."));
|
|
4187
|
+
const syncResult = await stripeSync.processUntilDone();
|
|
4188
|
+
const totalSynced = Object.values(syncResult).reduce(
|
|
4189
|
+
(sum, result) => sum + (result?.synced || 0),
|
|
4190
|
+
0
|
|
4191
|
+
);
|
|
4192
|
+
console.log(import_chalk3.default.green(`\u2713 Sync complete: ${totalSynced} objects synced`));
|
|
4193
|
+
} else {
|
|
4194
|
+
console.log(import_chalk3.default.yellow("\n\u23ED\uFE0F Skipping initial sync (SKIP_BACKFILL=true)"));
|
|
4195
|
+
}
|
|
4196
|
+
console.log(
|
|
4197
|
+
import_chalk3.default.cyan("\n\u25CF Streaming live changes...") + import_chalk3.default.gray(" [press Ctrl-C to abort]")
|
|
4198
|
+
);
|
|
4199
|
+
await new Promise(() => {
|
|
4200
|
+
});
|
|
4201
|
+
} catch (error) {
|
|
4202
|
+
if (error instanceof Error) {
|
|
4203
|
+
console.error(import_chalk3.default.red(error.message));
|
|
4204
|
+
}
|
|
4205
|
+
await cleanup();
|
|
4206
|
+
process.exit(1);
|
|
4207
|
+
}
|
|
4208
|
+
}
|
|
4209
|
+
async function installCommand(options) {
|
|
4210
|
+
try {
|
|
4211
|
+
import_dotenv2.default.config();
|
|
4212
|
+
let accessToken = options.supabaseAccessToken || process.env.SUPABASE_ACCESS_TOKEN || "";
|
|
4213
|
+
let projectRef = options.supabaseProjectRef || process.env.SUPABASE_PROJECT_REF || "";
|
|
4214
|
+
let stripeKey = options.stripeKey || process.env.STRIPE_API_KEY || process.env.STRIPE_SECRET_KEY || "";
|
|
4215
|
+
if (!accessToken || !projectRef || !stripeKey) {
|
|
4216
|
+
const inquirer2 = (await import("inquirer")).default;
|
|
4217
|
+
const questions = [];
|
|
4218
|
+
if (!accessToken) {
|
|
4219
|
+
questions.push({
|
|
4220
|
+
type: "password",
|
|
4221
|
+
name: "accessToken",
|
|
4222
|
+
message: "Enter your Supabase access token (from supabase.com/dashboard/account/tokens):",
|
|
4223
|
+
mask: "*",
|
|
4224
|
+
validate: (input) => input.trim() !== "" || "Access token is required"
|
|
4225
|
+
});
|
|
4226
|
+
}
|
|
4227
|
+
if (!projectRef) {
|
|
4228
|
+
questions.push({
|
|
4229
|
+
type: "input",
|
|
4230
|
+
name: "projectRef",
|
|
4231
|
+
message: "Enter your Supabase project ref (e.g., abcdefghijklmnop):",
|
|
4232
|
+
validate: (input) => input.trim() !== "" || "Project ref is required"
|
|
4233
|
+
});
|
|
4234
|
+
}
|
|
4235
|
+
if (!stripeKey) {
|
|
4236
|
+
questions.push({
|
|
4237
|
+
type: "password",
|
|
4238
|
+
name: "stripeKey",
|
|
4239
|
+
message: "Enter your Stripe secret key:",
|
|
4240
|
+
mask: "*",
|
|
4241
|
+
validate: (input) => {
|
|
4242
|
+
if (!input.trim()) return "Stripe key is required";
|
|
4243
|
+
if (!input.startsWith("sk_")) return 'Stripe key should start with "sk_"';
|
|
4244
|
+
return true;
|
|
4245
|
+
}
|
|
4246
|
+
});
|
|
4247
|
+
}
|
|
4248
|
+
if (questions.length > 0) {
|
|
4249
|
+
console.log(import_chalk3.default.yellow("\nMissing required configuration. Please provide:"));
|
|
4250
|
+
const answers = await inquirer2.prompt(questions);
|
|
4251
|
+
if (answers.accessToken) accessToken = answers.accessToken;
|
|
4252
|
+
if (answers.projectRef) projectRef = answers.projectRef;
|
|
4253
|
+
if (answers.stripeKey) stripeKey = answers.stripeKey;
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
console.log(import_chalk3.default.blue("\n\u{1F680} Installing Stripe Sync to Supabase Edge Functions...\n"));
|
|
4257
|
+
console.log(import_chalk3.default.gray("Validating project access..."));
|
|
4258
|
+
await install({
|
|
4259
|
+
supabaseAccessToken: accessToken,
|
|
4260
|
+
supabaseProjectRef: projectRef,
|
|
4261
|
+
stripeKey
|
|
4262
|
+
});
|
|
4263
|
+
console.log(import_chalk3.default.cyan("\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"));
|
|
4264
|
+
console.log(import_chalk3.default.cyan.bold(" Installation Complete!"));
|
|
4265
|
+
console.log(import_chalk3.default.cyan("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n"));
|
|
4266
|
+
console.log(import_chalk3.default.gray("\n Your Stripe data will stay in sync to your Supabase database."));
|
|
4267
|
+
console.log(
|
|
4268
|
+
import_chalk3.default.gray(' View your data in the Supabase dashboard under the "stripe" schema.\n')
|
|
4269
|
+
);
|
|
4270
|
+
} catch (error) {
|
|
4271
|
+
if (error instanceof Error) {
|
|
4272
|
+
console.error(import_chalk3.default.red(`
|
|
4273
|
+
\u2717 Installation failed: ${error.message}`));
|
|
4274
|
+
}
|
|
4275
|
+
process.exit(1);
|
|
4276
|
+
}
|
|
4277
|
+
}
|
|
4278
|
+
async function uninstallCommand(options) {
|
|
4279
|
+
try {
|
|
4280
|
+
import_dotenv2.default.config();
|
|
4281
|
+
let accessToken = options.supabaseAccessToken || process.env.SUPABASE_ACCESS_TOKEN || "";
|
|
4282
|
+
let projectRef = options.supabaseProjectRef || process.env.SUPABASE_PROJECT_REF || "";
|
|
4283
|
+
let stripeKey = options.stripeKey || process.env.STRIPE_API_KEY || process.env.STRIPE_SECRET_KEY || "";
|
|
4284
|
+
if (!accessToken || !projectRef || !stripeKey) {
|
|
4285
|
+
const inquirer2 = (await import("inquirer")).default;
|
|
4286
|
+
const questions = [];
|
|
4287
|
+
if (!accessToken) {
|
|
4288
|
+
questions.push({
|
|
4289
|
+
type: "password",
|
|
4290
|
+
name: "accessToken",
|
|
4291
|
+
message: "Enter your Supabase access token (from supabase.com/dashboard/account/tokens):",
|
|
4292
|
+
mask: "*",
|
|
4293
|
+
validate: (input) => input.trim() !== "" || "Access token is required"
|
|
4294
|
+
});
|
|
4295
|
+
}
|
|
4296
|
+
if (!projectRef) {
|
|
4297
|
+
questions.push({
|
|
4298
|
+
type: "input",
|
|
4299
|
+
name: "projectRef",
|
|
4300
|
+
message: "Enter your Supabase project ref (e.g., abcdefghijklmnop):",
|
|
4301
|
+
validate: (input) => input.trim() !== "" || "Project ref is required"
|
|
4302
|
+
});
|
|
4303
|
+
}
|
|
4304
|
+
if (!stripeKey) {
|
|
4305
|
+
questions.push({
|
|
4306
|
+
type: "password",
|
|
4307
|
+
name: "stripeKey",
|
|
4308
|
+
message: "Enter your Stripe secret key:",
|
|
4309
|
+
mask: "*",
|
|
4310
|
+
validate: (input) => {
|
|
4311
|
+
if (!input.trim()) return "Stripe key is required";
|
|
4312
|
+
if (!input.startsWith("sk_")) return 'Stripe key should start with "sk_"';
|
|
4313
|
+
return true;
|
|
4314
|
+
}
|
|
4315
|
+
});
|
|
4316
|
+
}
|
|
4317
|
+
if (questions.length > 0) {
|
|
4318
|
+
console.log(import_chalk3.default.yellow("\nMissing required configuration. Please provide:"));
|
|
4319
|
+
const answers = await inquirer2.prompt(questions);
|
|
4320
|
+
if (answers.accessToken) accessToken = answers.accessToken;
|
|
4321
|
+
if (answers.projectRef) projectRef = answers.projectRef;
|
|
4322
|
+
if (answers.stripeKey) stripeKey = answers.stripeKey;
|
|
4323
|
+
}
|
|
4324
|
+
}
|
|
4325
|
+
console.log(import_chalk3.default.blue("\n\u{1F5D1}\uFE0F Uninstalling Stripe Sync from Supabase...\n"));
|
|
4326
|
+
console.log(import_chalk3.default.yellow("\u26A0\uFE0F Warning: This will delete all Stripe data from your database!\n"));
|
|
4327
|
+
console.log(import_chalk3.default.gray("Removing all resources..."));
|
|
4328
|
+
await uninstall({
|
|
4329
|
+
supabaseAccessToken: accessToken,
|
|
4330
|
+
supabaseProjectRef: projectRef,
|
|
4331
|
+
stripeKey
|
|
4332
|
+
});
|
|
4333
|
+
console.log(import_chalk3.default.cyan("\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"));
|
|
4334
|
+
console.log(import_chalk3.default.cyan.bold(" Uninstall Complete!"));
|
|
4335
|
+
console.log(import_chalk3.default.cyan("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n"));
|
|
4336
|
+
console.log(
|
|
4337
|
+
import_chalk3.default.gray("\n All Stripe sync resources have been removed from your Supabase project.")
|
|
4338
|
+
);
|
|
4339
|
+
console.log(import_chalk3.default.gray(" - Edge Functions deleted"));
|
|
4340
|
+
console.log(import_chalk3.default.gray(" - Stripe webhooks removed"));
|
|
4341
|
+
console.log(import_chalk3.default.gray(" - Database schema dropped\n"));
|
|
4342
|
+
} catch (error) {
|
|
4343
|
+
if (error instanceof Error) {
|
|
4344
|
+
console.error(import_chalk3.default.red(`
|
|
4345
|
+
\u2717 Uninstall failed: ${error.message}`));
|
|
4346
|
+
}
|
|
4347
|
+
process.exit(1);
|
|
4348
|
+
}
|
|
4349
|
+
}
|
|
4350
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
4351
|
+
0 && (module.exports = {
|
|
4352
|
+
backfillCommand,
|
|
4353
|
+
createTunnel,
|
|
4354
|
+
installCommand,
|
|
4355
|
+
loadConfig,
|
|
4356
|
+
migrateCommand,
|
|
4357
|
+
syncCommand,
|
|
4358
|
+
uninstallCommand
|
|
4359
|
+
});
|