stripe-experiment-sync 1.0.2 → 1.0.6

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.
@@ -0,0 +1,509 @@
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/supabase/index.ts
31
+ var supabase_exports = {};
32
+ __export(supabase_exports, {
33
+ INSTALLATION_ERROR_SUFFIX: () => INSTALLATION_ERROR_SUFFIX,
34
+ INSTALLATION_INSTALLED_SUFFIX: () => INSTALLATION_INSTALLED_SUFFIX,
35
+ INSTALLATION_STARTED_SUFFIX: () => INSTALLATION_STARTED_SUFFIX,
36
+ STRIPE_SCHEMA_COMMENT_PREFIX: () => STRIPE_SCHEMA_COMMENT_PREFIX,
37
+ SupabaseDeployClient: () => SupabaseSetupClient,
38
+ SupabaseSetupClient: () => SupabaseSetupClient,
39
+ install: () => install,
40
+ setupFunctionCode: () => setupFunctionCode,
41
+ uninstall: () => uninstall,
42
+ webhookFunctionCode: () => webhookFunctionCode,
43
+ workerFunctionCode: () => workerFunctionCode
44
+ });
45
+ module.exports = __toCommonJS(supabase_exports);
46
+
47
+ // src/supabase/supabase.ts
48
+ var import_supabase_management_js = require("supabase-management-js");
49
+
50
+ // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-setup.ts
51
+ 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";
52
+
53
+ // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-webhook.ts
54
+ 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";
55
+
56
+ // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-worker.ts
57
+ 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";
58
+
59
+ // src/supabase/edge-function-code.ts
60
+ var setupFunctionCode = stripe_setup_default;
61
+ var webhookFunctionCode = stripe_webhook_default;
62
+ var workerFunctionCode = stripe_worker_default;
63
+
64
+ // package.json
65
+ var package_default = {
66
+ name: "stripe-experiment-sync",
67
+ version: "1.0.6",
68
+ private: false,
69
+ description: "Stripe Sync Engine to sync Stripe data to Postgres",
70
+ type: "module",
71
+ main: "./dist/index.cjs",
72
+ bin: "./dist/cli/index.cjs",
73
+ exports: {
74
+ ".": {
75
+ types: "./dist/index.d.ts",
76
+ import: "./dist/index.js",
77
+ require: "./dist/index.cjs"
78
+ },
79
+ "./supabase": {
80
+ types: "./dist/supabase/index.d.ts",
81
+ import: "./dist/supabase/index.js",
82
+ require: "./dist/supabase/index.cjs"
83
+ }
84
+ },
85
+ scripts: {
86
+ clean: "rimraf dist",
87
+ prebuild: "npm run clean",
88
+ build: "tsup src/index.ts src/supabase/index.ts --format esm,cjs --dts --shims && cp -r src/database/migrations dist/migrations",
89
+ lint: "eslint src --ext .ts",
90
+ test: "vitest"
91
+ },
92
+ files: [
93
+ "dist"
94
+ ],
95
+ dependencies: {
96
+ pg: "^8.16.3",
97
+ "pg-node-migrations": "0.0.8",
98
+ "supabase-management-js": "^0.1.6",
99
+ ws: "^8.18.0",
100
+ yesql: "^7.0.0"
101
+ },
102
+ peerDependencies: {
103
+ stripe: "> 11"
104
+ },
105
+ devDependencies: {
106
+ "@types/node": "^24.10.1",
107
+ "@types/pg": "^8.15.5",
108
+ "@types/ws": "^8.5.13",
109
+ "@types/yesql": "^4.1.4",
110
+ "@vitest/ui": "^4.0.9",
111
+ vitest: "^3.2.4"
112
+ },
113
+ repository: {
114
+ type: "git",
115
+ url: "https://github.com/tx-stripe/stripe-sync-engine.git"
116
+ },
117
+ homepage: "https://github.com/tx-stripe/stripe-sync-engine#readme",
118
+ bugs: {
119
+ url: "https://github.com/tx-stripe/stripe-sync-engine/issues"
120
+ },
121
+ keywords: [
122
+ "stripe",
123
+ "postgres",
124
+ "sync",
125
+ "webhooks",
126
+ "supabase",
127
+ "billing",
128
+ "database",
129
+ "typescript"
130
+ ],
131
+ author: "Supabase <https://supabase.com/>"
132
+ };
133
+
134
+ // src/supabase/supabase.ts
135
+ var import_stripe = __toESM(require("stripe"), 1);
136
+ var STRIPE_SCHEMA_COMMENT_PREFIX = "stripe-sync";
137
+ var INSTALLATION_STARTED_SUFFIX = "installation:started";
138
+ var INSTALLATION_ERROR_SUFFIX = "installation:error";
139
+ var INSTALLATION_INSTALLED_SUFFIX = "installed";
140
+ var SupabaseSetupClient = class {
141
+ api;
142
+ projectRef;
143
+ projectBaseUrl;
144
+ constructor(options) {
145
+ this.api = new import_supabase_management_js.SupabaseManagementAPI({
146
+ accessToken: options.accessToken,
147
+ baseUrl: options.managementApiBaseUrl
148
+ });
149
+ this.projectRef = options.projectRef;
150
+ this.projectBaseUrl = options.projectBaseUrl || process.env.SUPABASE_BASE_URL || "supabase.co";
151
+ }
152
+ /**
153
+ * Validate that the project exists and we have access
154
+ */
155
+ async validateProject() {
156
+ const projects = await this.api.getProjects();
157
+ const project = projects?.find((p) => p.id === this.projectRef);
158
+ if (!project) {
159
+ throw new Error(`Project ${this.projectRef} not found or you don't have access`);
160
+ }
161
+ return {
162
+ id: project.id,
163
+ name: project.name,
164
+ region: project.region
165
+ };
166
+ }
167
+ /**
168
+ * Deploy an Edge Function
169
+ */
170
+ async deployFunction(name, code) {
171
+ const functions = await this.api.listFunctions(this.projectRef);
172
+ const exists = functions?.some((f) => f.slug === name);
173
+ if (exists) {
174
+ await this.api.updateFunction(this.projectRef, name, {
175
+ body: code,
176
+ verify_jwt: false
177
+ });
178
+ } else {
179
+ await this.api.createFunction(this.projectRef, {
180
+ slug: name,
181
+ name,
182
+ body: code,
183
+ verify_jwt: false
184
+ });
185
+ }
186
+ }
187
+ /**
188
+ * Set secrets for Edge Functions
189
+ */
190
+ async setSecrets(secrets) {
191
+ await this.api.createSecrets(this.projectRef, secrets);
192
+ }
193
+ /**
194
+ * Run SQL against the database
195
+ */
196
+ async runSQL(sql) {
197
+ return await this.api.runQuery(this.projectRef, sql);
198
+ }
199
+ /**
200
+ * Setup pg_cron job to invoke worker function
201
+ */
202
+ async setupPgCronJob() {
203
+ const serviceRoleKey = await this.getServiceRoleKey();
204
+ const escapedServiceRoleKey = serviceRoleKey.replace(/'/g, "''");
205
+ const sql = `
206
+ -- Enable extensions
207
+ CREATE EXTENSION IF NOT EXISTS pg_cron;
208
+ CREATE EXTENSION IF NOT EXISTS pg_net;
209
+ CREATE EXTENSION IF NOT EXISTS pgmq;
210
+
211
+ -- Create pgmq queue for sync work (idempotent)
212
+ SELECT pgmq.create('stripe_sync_work')
213
+ WHERE NOT EXISTS (
214
+ SELECT 1 FROM pgmq.list_queues() WHERE queue_name = 'stripe_sync_work'
215
+ );
216
+
217
+ -- Store service role key in vault for pg_cron to use
218
+ -- Delete existing secret if it exists, then create new one
219
+ DELETE FROM vault.secrets WHERE name = 'stripe_sync_service_role_key';
220
+ SELECT vault.create_secret('${escapedServiceRoleKey}', 'stripe_sync_service_role_key');
221
+
222
+ -- Delete existing jobs if they exist
223
+ SELECT cron.unschedule('stripe-sync-worker') WHERE EXISTS (
224
+ SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker'
225
+ );
226
+ SELECT cron.unschedule('stripe-sync-scheduler') WHERE EXISTS (
227
+ SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-scheduler'
228
+ );
229
+
230
+ -- Create job to invoke worker every 10 seconds
231
+ -- Worker reads from pgmq, enqueues objects if empty, and processes sync work
232
+ SELECT cron.schedule(
233
+ 'stripe-sync-worker',
234
+ '10 seconds',
235
+ $$
236
+ SELECT net.http_post(
237
+ url := 'https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/stripe-worker',
238
+ headers := jsonb_build_object(
239
+ 'Authorization', 'Bearer ' || (SELECT decrypted_secret FROM vault.decrypted_secrets WHERE name = 'stripe_sync_service_role_key')
240
+ )
241
+ )
242
+ $$
243
+ );
244
+ `;
245
+ await this.runSQL(sql);
246
+ }
247
+ /**
248
+ * Get the webhook URL for this project
249
+ */
250
+ getWebhookUrl() {
251
+ return `https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/stripe-webhook`;
252
+ }
253
+ /**
254
+ * Get the service role key for this project (needed to invoke Edge Functions)
255
+ */
256
+ async getServiceRoleKey() {
257
+ const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
258
+ const serviceRoleKey = apiKeys?.find((k) => k.name === "service_role");
259
+ if (!serviceRoleKey) {
260
+ throw new Error("Could not find service_role API key");
261
+ }
262
+ return serviceRoleKey.api_key;
263
+ }
264
+ /**
265
+ * Get the anon key for this project (needed for Realtime subscriptions)
266
+ */
267
+ async getAnonKey() {
268
+ const apiKeys = await this.api.getProjectApiKeys(this.projectRef);
269
+ const anonKey = apiKeys?.find((k) => k.name === "anon");
270
+ if (!anonKey) {
271
+ throw new Error("Could not find anon API key");
272
+ }
273
+ return anonKey.api_key;
274
+ }
275
+ /**
276
+ * Get the project URL
277
+ */
278
+ getProjectUrl() {
279
+ return `https://${this.projectRef}.${this.projectBaseUrl}`;
280
+ }
281
+ /**
282
+ * Invoke an Edge Function
283
+ */
284
+ async invokeFunction(name, serviceRoleKey) {
285
+ const url = `https://${this.projectRef}.${this.projectBaseUrl}/functions/v1/${name}`;
286
+ const response = await fetch(url, {
287
+ method: "POST",
288
+ headers: {
289
+ Authorization: `Bearer ${serviceRoleKey}`,
290
+ "Content-Type": "application/json"
291
+ }
292
+ });
293
+ if (!response.ok) {
294
+ const text = await response.text();
295
+ return { success: false, error: `${response.status}: ${text}` };
296
+ }
297
+ const result = await response.json();
298
+ if (result.success === false) {
299
+ return { success: false, error: result.error };
300
+ }
301
+ return { success: true };
302
+ }
303
+ /**
304
+ * Check if stripe-sync is installed in the database.
305
+ *
306
+ * Uses the Supabase Management API to run SQL queries.
307
+ * Uses duck typing (schema + migrations table) combined with comment validation.
308
+ * Throws error for legacy installations to prevent accidental corruption.
309
+ *
310
+ * @param schema The schema name to check (defaults to 'stripe')
311
+ * @returns true if properly installed with comment marker, false if not installed
312
+ * @throws Error if legacy installation detected (schema exists without comment)
313
+ */
314
+ async isInstalled(schema = "stripe") {
315
+ try {
316
+ const schemaCheck = await this.runSQL(
317
+ `SELECT EXISTS (
318
+ SELECT 1 FROM information_schema.schemata
319
+ WHERE schema_name = '${schema}'
320
+ ) as schema_exists`
321
+ );
322
+ const schemaExists = schemaCheck[0]?.rows?.[0]?.schema_exists === true;
323
+ if (!schemaExists) {
324
+ return false;
325
+ }
326
+ const migrationsCheck = await this.runSQL(
327
+ `SELECT EXISTS (
328
+ SELECT 1 FROM information_schema.tables
329
+ WHERE table_schema = '${schema}' AND table_name IN ('migrations', '_migrations')
330
+ ) as table_exists`
331
+ );
332
+ const migrationsTableExists = migrationsCheck[0]?.rows?.[0]?.table_exists === true;
333
+ if (!migrationsTableExists) {
334
+ return false;
335
+ }
336
+ const commentCheck = await this.runSQL(
337
+ `SELECT obj_description(oid, 'pg_namespace') as comment
338
+ FROM pg_namespace
339
+ WHERE nspname = '${schema}'`
340
+ );
341
+ const comment = commentCheck[0]?.rows?.[0]?.comment;
342
+ if (!comment || !comment.includes(STRIPE_SCHEMA_COMMENT_PREFIX)) {
343
+ throw new Error(
344
+ `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.`
345
+ );
346
+ }
347
+ if (comment.includes(INSTALLATION_STARTED_SUFFIX)) {
348
+ return false;
349
+ }
350
+ if (comment.includes(INSTALLATION_ERROR_SUFFIX)) {
351
+ throw new Error(
352
+ `Installation failed: Schema '${schema}' exists but installation encountered an error. Comment: ${comment}. Please uninstall and install again.`
353
+ );
354
+ }
355
+ return true;
356
+ } catch (error) {
357
+ if (error instanceof Error && (error.message.includes("Legacy installation detected") || error.message.includes("Installation failed"))) {
358
+ throw error;
359
+ }
360
+ return false;
361
+ }
362
+ }
363
+ /**
364
+ * Update installation progress comment on the stripe schema
365
+ */
366
+ async updateInstallationComment(message) {
367
+ const escapedMessage = message.replace(/'/g, "''");
368
+ await this.runSQL(`COMMENT ON SCHEMA stripe IS '${escapedMessage}'`);
369
+ }
370
+ /**
371
+ * Delete an Edge Function
372
+ */
373
+ async deleteFunction(name) {
374
+ try {
375
+ await this.api.deleteFunction(this.projectRef, name);
376
+ } catch (err) {
377
+ console.warn(`Could not delete function ${name}:`, err);
378
+ }
379
+ }
380
+ /**
381
+ * Delete a secret
382
+ */
383
+ async deleteSecret(name) {
384
+ try {
385
+ await this.api.deleteSecrets(this.projectRef, [name]);
386
+ } catch (err) {
387
+ console.warn(`Could not delete secret ${name}:`, err);
388
+ }
389
+ }
390
+ /**
391
+ * Uninstall stripe-sync from a Supabase project
392
+ * Removes all Edge Functions, secrets, database resources, and Stripe webhooks
393
+ */
394
+ async uninstall(stripeSecretKey) {
395
+ const stripe = new import_stripe.default(stripeSecretKey, { apiVersion: "2025-05-28.basil" });
396
+ try {
397
+ try {
398
+ const webhookResult = await this.runSQL(`
399
+ SELECT id FROM stripe._managed_webhooks WHERE id IS NOT NULL
400
+ `);
401
+ const webhookIds = webhookResult[0]?.rows?.map((r) => r.id) || [];
402
+ for (const webhookId of webhookIds) {
403
+ try {
404
+ await stripe.webhookEndpoints.del(webhookId);
405
+ } catch (err) {
406
+ console.warn(`Could not delete Stripe webhook ${webhookId}:`, err);
407
+ }
408
+ }
409
+ } catch (err) {
410
+ console.warn("Could not query/delete webhooks:", err);
411
+ }
412
+ await this.deleteFunction("stripe-setup");
413
+ await this.deleteFunction("stripe-webhook");
414
+ await this.deleteFunction("stripe-worker");
415
+ await this.deleteSecret("STRIPE_SECRET_KEY");
416
+ try {
417
+ await this.runSQL(`
418
+ SELECT cron.unschedule('stripe-sync-worker')
419
+ WHERE EXISTS (
420
+ SELECT 1 FROM cron.job WHERE jobname = 'stripe-sync-worker'
421
+ )
422
+ `);
423
+ } catch (err) {
424
+ console.warn("Could not unschedule pg_cron job:", err);
425
+ }
426
+ try {
427
+ await this.runSQL(`
428
+ DELETE FROM vault.secrets
429
+ WHERE name = 'stripe_sync_service_role_key'
430
+ `);
431
+ } catch (err) {
432
+ console.warn("Could not delete vault secret:", err);
433
+ }
434
+ await this.runSQL(`DROP SCHEMA IF EXISTS stripe CASCADE`);
435
+ } catch (error) {
436
+ throw new Error(`Uninstall failed: ${error instanceof Error ? error.message : String(error)}`);
437
+ }
438
+ }
439
+ async install(stripeKey) {
440
+ const trimmedStripeKey = stripeKey.trim();
441
+ if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
442
+ throw new Error('Stripe key should start with "sk_" or "rk_"');
443
+ }
444
+ try {
445
+ await this.validateProject();
446
+ await this.runSQL(`CREATE SCHEMA IF NOT EXISTS stripe`);
447
+ await this.updateInstallationComment(
448
+ `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_STARTED_SUFFIX}`
449
+ );
450
+ await this.deployFunction("stripe-setup", setupFunctionCode);
451
+ await this.deployFunction("stripe-webhook", webhookFunctionCode);
452
+ await this.deployFunction("stripe-worker", workerFunctionCode);
453
+ await this.setSecrets([{ name: "STRIPE_SECRET_KEY", value: trimmedStripeKey }]);
454
+ const serviceRoleKey = await this.getServiceRoleKey();
455
+ const setupResult = await this.invokeFunction("stripe-setup", serviceRoleKey);
456
+ if (!setupResult.success) {
457
+ throw new Error(`Setup failed: ${setupResult.error}`);
458
+ }
459
+ try {
460
+ await this.setupPgCronJob();
461
+ } catch {
462
+ }
463
+ await this.updateInstallationComment(
464
+ `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_INSTALLED_SUFFIX}`
465
+ );
466
+ } catch (error) {
467
+ await this.updateInstallationComment(
468
+ `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_ERROR_SUFFIX} - ${error instanceof Error ? error.message : String(error)}`
469
+ );
470
+ throw error;
471
+ }
472
+ }
473
+ };
474
+ async function install(params) {
475
+ const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
476
+ const client = new SupabaseSetupClient({
477
+ accessToken: supabaseAccessToken,
478
+ projectRef: supabaseProjectRef,
479
+ projectBaseUrl: params.baseProjectUrl,
480
+ managementApiBaseUrl: params.baseManagementApiUrl
481
+ });
482
+ await client.install(stripeKey);
483
+ }
484
+ async function uninstall(params) {
485
+ const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
486
+ const trimmedStripeKey = stripeKey.trim();
487
+ if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
488
+ throw new Error('Stripe key should start with "sk_" or "rk_"');
489
+ }
490
+ const client = new SupabaseSetupClient({
491
+ accessToken: supabaseAccessToken,
492
+ projectRef: supabaseProjectRef
493
+ });
494
+ await client.uninstall(trimmedStripeKey);
495
+ }
496
+ // Annotate the CommonJS export names for ESM import in node:
497
+ 0 && (module.exports = {
498
+ INSTALLATION_ERROR_SUFFIX,
499
+ INSTALLATION_INSTALLED_SUFFIX,
500
+ INSTALLATION_STARTED_SUFFIX,
501
+ STRIPE_SCHEMA_COMMENT_PREFIX,
502
+ SupabaseDeployClient,
503
+ SupabaseSetupClient,
504
+ install,
505
+ setupFunctionCode,
506
+ uninstall,
507
+ webhookFunctionCode,
508
+ workerFunctionCode
509
+ });
@@ -0,0 +1,115 @@
1
+ declare const STRIPE_SCHEMA_COMMENT_PREFIX = "stripe-sync";
2
+ declare const INSTALLATION_STARTED_SUFFIX = "installation:started";
3
+ declare const INSTALLATION_ERROR_SUFFIX = "installation:error";
4
+ declare const INSTALLATION_INSTALLED_SUFFIX = "installed";
5
+ interface DeployClientOptions {
6
+ accessToken: string;
7
+ projectRef: string;
8
+ projectBaseUrl?: string;
9
+ managementApiBaseUrl?: string;
10
+ }
11
+ interface ProjectInfo {
12
+ id: string;
13
+ name: string;
14
+ region: string;
15
+ }
16
+ declare class SupabaseSetupClient {
17
+ private api;
18
+ private projectRef;
19
+ private projectBaseUrl;
20
+ constructor(options: DeployClientOptions);
21
+ /**
22
+ * Validate that the project exists and we have access
23
+ */
24
+ validateProject(): Promise<ProjectInfo>;
25
+ /**
26
+ * Deploy an Edge Function
27
+ */
28
+ deployFunction(name: string, code: string): Promise<void>;
29
+ /**
30
+ * Set secrets for Edge Functions
31
+ */
32
+ setSecrets(secrets: {
33
+ name: string;
34
+ value: string;
35
+ }[]): Promise<void>;
36
+ /**
37
+ * Run SQL against the database
38
+ */
39
+ runSQL(sql: string): Promise<unknown>;
40
+ /**
41
+ * Setup pg_cron job to invoke worker function
42
+ */
43
+ setupPgCronJob(): Promise<void>;
44
+ /**
45
+ * Get the webhook URL for this project
46
+ */
47
+ getWebhookUrl(): string;
48
+ /**
49
+ * Get the service role key for this project (needed to invoke Edge Functions)
50
+ */
51
+ getServiceRoleKey(): Promise<string>;
52
+ /**
53
+ * Get the anon key for this project (needed for Realtime subscriptions)
54
+ */
55
+ getAnonKey(): Promise<string>;
56
+ /**
57
+ * Get the project URL
58
+ */
59
+ getProjectUrl(): string;
60
+ /**
61
+ * Invoke an Edge Function
62
+ */
63
+ invokeFunction(name: string, serviceRoleKey: string): Promise<{
64
+ success: boolean;
65
+ error?: string;
66
+ }>;
67
+ /**
68
+ * Check if stripe-sync is installed in the database.
69
+ *
70
+ * Uses the Supabase Management API to run SQL queries.
71
+ * Uses duck typing (schema + migrations table) combined with comment validation.
72
+ * Throws error for legacy installations to prevent accidental corruption.
73
+ *
74
+ * @param schema The schema name to check (defaults to 'stripe')
75
+ * @returns true if properly installed with comment marker, false if not installed
76
+ * @throws Error if legacy installation detected (schema exists without comment)
77
+ */
78
+ isInstalled(schema?: string): Promise<boolean>;
79
+ /**
80
+ * Update installation progress comment on the stripe schema
81
+ */
82
+ updateInstallationComment(message: string): Promise<void>;
83
+ /**
84
+ * Delete an Edge Function
85
+ */
86
+ deleteFunction(name: string): Promise<void>;
87
+ /**
88
+ * Delete a secret
89
+ */
90
+ deleteSecret(name: string): Promise<void>;
91
+ /**
92
+ * Uninstall stripe-sync from a Supabase project
93
+ * Removes all Edge Functions, secrets, database resources, and Stripe webhooks
94
+ */
95
+ uninstall(stripeSecretKey: string): Promise<void>;
96
+ install(stripeKey: string): Promise<void>;
97
+ }
98
+ declare function install(params: {
99
+ supabaseAccessToken: string;
100
+ supabaseProjectRef: string;
101
+ stripeKey: string;
102
+ baseProjectUrl?: string;
103
+ baseManagementApiUrl?: string;
104
+ }): Promise<void>;
105
+ declare function uninstall(params: {
106
+ supabaseAccessToken: string;
107
+ supabaseProjectRef: string;
108
+ stripeKey: string;
109
+ }): Promise<void>;
110
+
111
+ declare const setupFunctionCode: string;
112
+ declare const webhookFunctionCode: string;
113
+ declare const workerFunctionCode: string;
114
+
115
+ export { type DeployClientOptions, INSTALLATION_ERROR_SUFFIX, INSTALLATION_INSTALLED_SUFFIX, INSTALLATION_STARTED_SUFFIX, type ProjectInfo, STRIPE_SCHEMA_COMMENT_PREFIX, SupabaseSetupClient as SupabaseDeployClient, SupabaseSetupClient, install, setupFunctionCode, uninstall, webhookFunctionCode, workerFunctionCode };