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