stripe-experiment-sync 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/lib.cjs CHANGED
@@ -77,20 +77,6 @@ async function loadConfig(options) {
77
77
  }
78
78
  });
79
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
80
  if (!config.databaseUrl) {
95
81
  questions.push({
96
82
  type: "password",
@@ -119,7 +105,7 @@ async function loadConfig(options) {
119
105
  // package.json
120
106
  var package_default = {
121
107
  name: "stripe-experiment-sync",
122
- version: "1.0.7",
108
+ version: "1.0.8-beta.1765856228",
123
109
  private: false,
124
110
  description: "Stripe Sync Engine to sync Stripe data to Postgres",
125
111
  type: "module",
@@ -1803,19 +1789,8 @@ var StripeSync = class {
1803
1789
  if (params?.runStartedAt) {
1804
1790
  runStartedAt = params.runStartedAt;
1805
1791
  } 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
- }
1792
+ const { runKey } = await this.joinOrCreateSyncRun(params?.triggeredBy ?? "processNext");
1793
+ runStartedAt = runKey.runStartedAt;
1819
1794
  }
1820
1795
  await this.postgresClient.createObjectRuns(accountId, runStartedAt, [resourceName]);
1821
1796
  const objRun = await this.postgresClient.getObjectRun(accountId, runStartedAt, resourceName);
@@ -1978,18 +1953,39 @@ var StripeSync = class {
1978
1953
  }
1979
1954
  return { synced: totalSynced };
1980
1955
  }
1981
- async processUntilDone(params) {
1982
- const { object } = params ?? { object: "all" };
1956
+ /**
1957
+ * Join existing sync run or create a new one.
1958
+ * Returns sync run key and list of supported objects to sync.
1959
+ *
1960
+ * Cooperative behavior: If a sync run already exists, joins it instead of failing.
1961
+ * This is used by workers and background processes that should cooperate.
1962
+ *
1963
+ * @param triggeredBy - What triggered this sync (for observability)
1964
+ * @returns Run key and list of objects to sync
1965
+ */
1966
+ async joinOrCreateSyncRun(triggeredBy = "worker") {
1983
1967
  await this.getCurrentAccount();
1984
1968
  const accountId = await this.getAccountId();
1985
- const runKey = await this.postgresClient.getOrCreateSyncRun(accountId, "processUntilDone");
1986
- if (!runKey) {
1969
+ const result = await this.postgresClient.getOrCreateSyncRun(accountId, triggeredBy);
1970
+ if (!result) {
1987
1971
  const activeRun = await this.postgresClient.getActiveSyncRun(accountId);
1988
1972
  if (!activeRun) {
1989
1973
  throw new Error("Failed to get or create sync run");
1990
1974
  }
1991
- return this.processUntilDoneWithRun(activeRun.runStartedAt, object, params);
1975
+ return {
1976
+ runKey: { accountId: activeRun.accountId, runStartedAt: activeRun.runStartedAt },
1977
+ objects: this.getSupportedSyncObjects()
1978
+ };
1992
1979
  }
1980
+ const { accountId: runAccountId, runStartedAt } = result;
1981
+ return {
1982
+ runKey: { accountId: runAccountId, runStartedAt },
1983
+ objects: this.getSupportedSyncObjects()
1984
+ };
1985
+ }
1986
+ async processUntilDone(params) {
1987
+ const { object } = params ?? { object: "all" };
1988
+ const { runKey } = await this.joinOrCreateSyncRun("processUntilDone");
1993
1989
  return this.processUntilDoneWithRun(runKey.runStartedAt, object, params);
1994
1990
  }
1995
1991
  /**
@@ -3448,6 +3444,167 @@ async function runMigrations(config) {
3448
3444
  }
3449
3445
  }
3450
3446
 
3447
+ // src/websocket-client.ts
3448
+ var import_ws = __toESM(require("ws"), 1);
3449
+ var CLI_VERSION = "1.33.0";
3450
+ var PONG_WAIT = 10 * 1e3;
3451
+ var PING_PERIOD = PONG_WAIT * 2 / 10;
3452
+ function getClientUserAgent() {
3453
+ return JSON.stringify({
3454
+ name: "stripe-cli",
3455
+ version: CLI_VERSION,
3456
+ publisher: "stripe",
3457
+ os: process.platform
3458
+ });
3459
+ }
3460
+ async function createCliSession(stripeApiKey) {
3461
+ const params = new URLSearchParams();
3462
+ params.append("device_name", "stripe-sync-engine");
3463
+ params.append("websocket_features[]", "webhooks");
3464
+ const response = await fetch("https://api.stripe.com/v1/stripecli/sessions", {
3465
+ method: "POST",
3466
+ headers: {
3467
+ Authorization: `Bearer ${stripeApiKey}`,
3468
+ "Content-Type": "application/x-www-form-urlencoded",
3469
+ "User-Agent": `Stripe/v1 stripe-cli/${CLI_VERSION}`,
3470
+ "X-Stripe-Client-User-Agent": getClientUserAgent()
3471
+ },
3472
+ body: params.toString()
3473
+ });
3474
+ if (!response.ok) {
3475
+ const error = await response.text();
3476
+ throw new Error(`Failed to create CLI session: ${error}`);
3477
+ }
3478
+ return await response.json();
3479
+ }
3480
+ async function createStripeWebSocketClient(options) {
3481
+ const { stripeApiKey, onEvent, onReady, onError, onClose } = options;
3482
+ const session = await createCliSession(stripeApiKey);
3483
+ let ws = null;
3484
+ let pingInterval = null;
3485
+ let connected = false;
3486
+ let shouldReconnect = true;
3487
+ function connect() {
3488
+ const wsUrl = `${session.websocket_url}?websocket_feature=${encodeURIComponent(session.websocket_authorized_feature)}`;
3489
+ ws = new import_ws.default(wsUrl, {
3490
+ headers: {
3491
+ "Accept-Encoding": "identity",
3492
+ "User-Agent": `Stripe/v1 stripe-cli/${CLI_VERSION}`,
3493
+ "X-Stripe-Client-User-Agent": getClientUserAgent(),
3494
+ "Websocket-Id": session.websocket_id
3495
+ }
3496
+ });
3497
+ ws.on("pong", () => {
3498
+ });
3499
+ ws.on("open", () => {
3500
+ connected = true;
3501
+ pingInterval = setInterval(() => {
3502
+ if (ws && ws.readyState === import_ws.default.OPEN) {
3503
+ ws.ping();
3504
+ }
3505
+ }, PING_PERIOD);
3506
+ if (onReady) {
3507
+ onReady(session.secret);
3508
+ }
3509
+ });
3510
+ ws.on("message", async (data) => {
3511
+ try {
3512
+ const message = JSON.parse(data.toString());
3513
+ const ack = {
3514
+ type: "event_ack",
3515
+ event_id: message.webhook_id,
3516
+ webhook_conversation_id: message.webhook_conversation_id,
3517
+ webhook_id: message.webhook_id
3518
+ };
3519
+ if (ws && ws.readyState === import_ws.default.OPEN) {
3520
+ ws.send(JSON.stringify(ack));
3521
+ }
3522
+ let response;
3523
+ try {
3524
+ const result = await onEvent(message);
3525
+ response = {
3526
+ type: "webhook_response",
3527
+ webhook_id: message.webhook_id,
3528
+ webhook_conversation_id: message.webhook_conversation_id,
3529
+ forward_url: "stripe-sync-engine",
3530
+ status: result?.status ?? 200,
3531
+ http_headers: {},
3532
+ body: JSON.stringify({
3533
+ event_type: result?.event_type,
3534
+ event_id: result?.event_id,
3535
+ database_url: result?.databaseUrl,
3536
+ error: result?.error
3537
+ }),
3538
+ request_headers: message.http_headers,
3539
+ request_body: message.event_payload,
3540
+ notification_id: message.webhook_id
3541
+ };
3542
+ } catch (err) {
3543
+ const errorMessage = err instanceof Error ? err.message : String(err);
3544
+ response = {
3545
+ type: "webhook_response",
3546
+ webhook_id: message.webhook_id,
3547
+ webhook_conversation_id: message.webhook_conversation_id,
3548
+ forward_url: "stripe-sync-engine",
3549
+ status: 500,
3550
+ http_headers: {},
3551
+ body: JSON.stringify({ error: errorMessage }),
3552
+ request_headers: message.http_headers,
3553
+ request_body: message.event_payload,
3554
+ notification_id: message.webhook_id
3555
+ };
3556
+ if (onError) {
3557
+ onError(err instanceof Error ? err : new Error(errorMessage));
3558
+ }
3559
+ }
3560
+ if (ws && ws.readyState === import_ws.default.OPEN) {
3561
+ ws.send(JSON.stringify(response));
3562
+ }
3563
+ } catch (err) {
3564
+ if (onError) {
3565
+ onError(err instanceof Error ? err : new Error(String(err)));
3566
+ }
3567
+ }
3568
+ });
3569
+ ws.on("error", (error) => {
3570
+ if (onError) {
3571
+ onError(error);
3572
+ }
3573
+ });
3574
+ ws.on("close", (code, reason) => {
3575
+ connected = false;
3576
+ if (pingInterval) {
3577
+ clearInterval(pingInterval);
3578
+ pingInterval = null;
3579
+ }
3580
+ if (onClose) {
3581
+ onClose(code, reason.toString());
3582
+ }
3583
+ if (shouldReconnect) {
3584
+ const delay = (session.reconnect_delay || 5) * 1e3;
3585
+ setTimeout(() => {
3586
+ connect();
3587
+ }, delay);
3588
+ }
3589
+ });
3590
+ }
3591
+ connect();
3592
+ return {
3593
+ close: () => {
3594
+ shouldReconnect = false;
3595
+ if (pingInterval) {
3596
+ clearInterval(pingInterval);
3597
+ pingInterval = null;
3598
+ }
3599
+ if (ws) {
3600
+ ws.close(1e3, "Connection Done");
3601
+ ws = null;
3602
+ }
3603
+ },
3604
+ isConnected: () => connected
3605
+ };
3606
+ }
3607
+
3451
3608
  // src/index.ts
3452
3609
  var VERSION = package_default.version;
3453
3610
 
@@ -3487,14 +3644,14 @@ Creating ngrok tunnel for port ${port}...`));
3487
3644
  // src/supabase/supabase.ts
3488
3645
  var import_supabase_management_js = require("supabase-management-js");
3489
3646
 
3490
- // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-setup.ts
3647
+ // raw-ts:/Users/lfdepombo/src/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-setup.ts
3491
3648
  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
3649
 
3493
- // raw-ts:/home/runner/work/stripe-sync-engine/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-webhook.ts
3650
+ // raw-ts:/Users/lfdepombo/src/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-webhook.ts
3494
3651
  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
3652
 
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";
3653
+ // raw-ts:/Users/lfdepombo/src/stripe-sync-engine/packages/sync-engine/src/supabase/edge-functions/stripe-worker.ts
3654
+ 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 // Create sync run to make enqueued work visible (status='pending')\n const { objects } = await stripeSync.joinOrCreateSyncRun('worker')\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
3655
 
3499
3656
  // src/supabase/edge-function-code.ts
3500
3657
  var setupFunctionCode = stripe_setup_default;
@@ -3806,40 +3963,43 @@ var SupabaseSetupClient = class {
3806
3963
  throw new Error(`Uninstall failed: ${error instanceof Error ? error.message : String(error)}`);
3807
3964
  }
3808
3965
  }
3809
- async install(stripeKey) {
3966
+ /**
3967
+ * Inject package version into Edge Function code
3968
+ */
3969
+ injectPackageVersion(code, version) {
3970
+ if (version === "latest") {
3971
+ return code;
3972
+ }
3973
+ return code.replace(
3974
+ /from ['"]npm:stripe-experiment-sync['"]/g,
3975
+ `from 'npm:stripe-experiment-sync@${version}'`
3976
+ );
3977
+ }
3978
+ async install(stripeKey, packageVersion) {
3810
3979
  const trimmedStripeKey = stripeKey.trim();
3811
3980
  if (!trimmedStripeKey.startsWith("sk_") && !trimmedStripeKey.startsWith("rk_")) {
3812
3981
  throw new Error('Stripe key should start with "sk_" or "rk_"');
3813
3982
  }
3983
+ const version = packageVersion || "latest";
3814
3984
  try {
3815
3985
  await this.validateProject();
3816
3986
  await this.runSQL(`CREATE SCHEMA IF NOT EXISTS stripe`);
3817
3987
  await this.updateInstallationComment(
3818
3988
  `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_STARTED_SUFFIX}`
3819
3989
  );
3820
- await this.deployFunction("stripe-setup", setupFunctionCode);
3821
- await this.deployFunction("stripe-webhook", webhookFunctionCode);
3822
- await this.deployFunction("stripe-worker", workerFunctionCode);
3990
+ const versionedSetup = this.injectPackageVersion(setupFunctionCode, version);
3991
+ const versionedWebhook = this.injectPackageVersion(webhookFunctionCode, version);
3992
+ const versionedWorker = this.injectPackageVersion(workerFunctionCode, version);
3993
+ await this.deployFunction("stripe-setup", versionedSetup);
3994
+ await this.deployFunction("stripe-webhook", versionedWebhook);
3995
+ await this.deployFunction("stripe-worker", versionedWorker);
3823
3996
  await this.setSecrets([{ name: "STRIPE_SECRET_KEY", value: trimmedStripeKey }]);
3824
3997
  const serviceRoleKey = await this.getServiceRoleKey();
3825
3998
  const setupResult = await this.invokeFunction("stripe-setup", serviceRoleKey);
3826
3999
  if (!setupResult.success) {
3827
4000
  throw new Error(`Setup failed: ${setupResult.error}`);
3828
4001
  }
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
- }
4002
+ await this.setupPgCronJob();
3843
4003
  await this.updateInstallationComment(
3844
4004
  `${STRIPE_SCHEMA_COMMENT_PREFIX} v${package_default.version} ${INSTALLATION_INSTALLED_SUFFIX}`
3845
4005
  );
@@ -3852,14 +4012,14 @@ var SupabaseSetupClient = class {
3852
4012
  }
3853
4013
  };
3854
4014
  async function install(params) {
3855
- const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
4015
+ const { supabaseAccessToken, supabaseProjectRef, stripeKey, packageVersion } = params;
3856
4016
  const client = new SupabaseSetupClient({
3857
4017
  accessToken: supabaseAccessToken,
3858
4018
  projectRef: supabaseProjectRef,
3859
4019
  projectBaseUrl: params.baseProjectUrl,
3860
4020
  managementApiBaseUrl: params.baseManagementApiUrl
3861
4021
  });
3862
- await client.install(stripeKey);
4022
+ await client.install(stripeKey, packageVersion);
3863
4023
  }
3864
4024
  async function uninstall(params) {
3865
4025
  const { supabaseAccessToken, supabaseProjectRef, stripeKey } = params;
@@ -4063,10 +4223,19 @@ async function syncCommand(options) {
4063
4223
  let tunnel = null;
4064
4224
  let server = null;
4065
4225
  let webhookId = null;
4226
+ let wsClient = null;
4066
4227
  const cleanup = async (signal) => {
4067
4228
  console.log(import_chalk3.default.blue(`
4068
4229
 
4069
4230
  Cleaning up... (signal: ${signal || "manual"})`));
4231
+ if (wsClient) {
4232
+ try {
4233
+ wsClient.close();
4234
+ console.log(import_chalk3.default.green("\u2713 WebSocket closed"));
4235
+ } catch {
4236
+ console.log(import_chalk3.default.yellow("\u26A0 Could not close WebSocket"));
4237
+ }
4238
+ }
4070
4239
  const keepWebhooksOnShutdown = process.env.KEEP_WEBHOOKS_ON_SHUTDOWN === "true";
4071
4240
  if (webhookId && stripeSync && !keepWebhooksOnShutdown) {
4072
4241
  try {
@@ -4110,7 +4279,12 @@ Cleaning up... (signal: ${signal || "manual"})`));
4110
4279
  process.on("SIGTERM", () => cleanup("SIGTERM"));
4111
4280
  try {
4112
4281
  const config = await loadConfig(options);
4113
- console.log(import_chalk3.default.gray(`$ stripe-sync start ${config.databaseUrl}`));
4282
+ const useWebSocketMode = !config.ngrokAuthToken;
4283
+ const modeLabel = useWebSocketMode ? "WebSocket" : "Webhook (ngrok)";
4284
+ console.log(import_chalk3.default.blue(`
4285
+ Mode: ${modeLabel}`));
4286
+ const maskedDbUrl = config.databaseUrl.replace(/:[^:@]+@/, ":****@");
4287
+ console.log(import_chalk3.default.gray(`Database: ${maskedDbUrl}`));
4114
4288
  try {
4115
4289
  await runMigrations({
4116
4290
  databaseUrl: config.databaseUrl
@@ -4135,53 +4309,90 @@ Cleaning up... (signal: ${signal || "manual"})`));
4135
4309
  backfillRelatedEntities: process.env.BACKFILL_RELATED_ENTITIES !== "false",
4136
4310
  poolConfig
4137
4311
  });
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(`
4312
+ const databaseUrlWithoutPassword = config.databaseUrl.replace(/:[^:@]+@/, ":****@");
4313
+ if (useWebSocketMode) {
4314
+ console.log(import_chalk3.default.blue("\nConnecting to Stripe WebSocket..."));
4315
+ wsClient = await createStripeWebSocketClient({
4316
+ stripeApiKey: config.stripeApiKey,
4317
+ onEvent: async (event) => {
4318
+ try {
4319
+ const payload = JSON.parse(event.event_payload);
4320
+ console.log(import_chalk3.default.cyan(`\u2190 ${payload.type}`) + import_chalk3.default.gray(` (${payload.id})`));
4321
+ if (stripeSync) {
4322
+ await stripeSync.processEvent(payload);
4323
+ return {
4324
+ status: 200,
4325
+ event_type: payload.type,
4326
+ event_id: payload.id,
4327
+ databaseUrl: databaseUrlWithoutPassword
4328
+ };
4329
+ }
4330
+ } catch (err) {
4331
+ console.error(import_chalk3.default.red("Error processing event:"), err);
4332
+ return {
4333
+ status: 500,
4334
+ databaseUrl: databaseUrlWithoutPassword,
4335
+ error: err instanceof Error ? err.message : String(err)
4336
+ };
4337
+ }
4338
+ },
4339
+ onReady: (secret) => {
4340
+ console.log(import_chalk3.default.green("\u2713 Connected to Stripe WebSocket"));
4341
+ const maskedSecret = secret.length > 14 ? `${secret.slice(0, 10)}...${secret.slice(-4)}` : "****";
4342
+ console.log(import_chalk3.default.gray(` Webhook secret: ${maskedSecret}`));
4343
+ },
4344
+ onError: (error) => {
4345
+ console.error(import_chalk3.default.red("WebSocket error:"), error.message);
4346
+ },
4347
+ onClose: (code, reason) => {
4348
+ console.log(import_chalk3.default.yellow(`WebSocket closed: ${code} - ${reason}`));
4349
+ }
4350
+ });
4351
+ } else {
4352
+ const port = 3e3;
4353
+ tunnel = await createTunnel(port, config.ngrokAuthToken);
4354
+ const webhookPath = process.env.WEBHOOK_PATH || "/stripe-webhooks";
4355
+ console.log(import_chalk3.default.blue("\nCreating Stripe webhook endpoint..."));
4356
+ const webhook = await stripeSync.findOrCreateManagedWebhook(`${tunnel.url}${webhookPath}`);
4357
+ webhookId = webhook.id;
4358
+ const eventCount = webhook.enabled_events?.length || 0;
4359
+ console.log(import_chalk3.default.green(`\u2713 Webhook created: ${webhook.id}`));
4360
+ console.log(import_chalk3.default.cyan(` URL: ${webhook.url}`));
4361
+ console.log(import_chalk3.default.cyan(` Events: ${eventCount} supported events`));
4362
+ const app = (0, import_express.default)();
4363
+ const webhookRoute = webhookPath;
4364
+ app.use(webhookRoute, import_express.default.raw({ type: "application/json" }));
4365
+ app.post(webhookRoute, async (req, res) => {
4366
+ const sig = req.headers["stripe-signature"];
4367
+ if (!sig || typeof sig !== "string") {
4368
+ console.error("[Webhook] Missing stripe-signature header");
4369
+ return res.status(400).send({ error: "Missing stripe-signature header" });
4370
+ }
4371
+ const rawBody = req.body;
4372
+ if (!rawBody || !Buffer.isBuffer(rawBody)) {
4373
+ console.error("[Webhook] Body is not a Buffer!");
4374
+ return res.status(400).send({ error: "Missing raw body for signature verification" });
4375
+ }
4376
+ try {
4377
+ await stripeSync.processWebhook(rawBody, sig);
4378
+ return res.status(200).send({ received: true });
4379
+ } catch (error) {
4380
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
4381
+ console.error("[Webhook] Processing error:", errorMessage);
4382
+ return res.status(400).send({ error: errorMessage });
4383
+ }
4384
+ });
4385
+ app.use(import_express.default.json());
4386
+ app.use(import_express.default.urlencoded({ extended: false }));
4387
+ app.get("/health", async (req, res) => res.status(200).json({ status: "ok" }));
4388
+ console.log(import_chalk3.default.blue(`
4177
4389
  Starting server on port ${port}...`));
4178
- await new Promise((resolve, reject) => {
4179
- server = app.listen(port, "0.0.0.0", () => {
4180
- resolve();
4390
+ await new Promise((resolve, reject) => {
4391
+ server = app.listen(port, "0.0.0.0", () => resolve());
4392
+ server.on("error", reject);
4181
4393
  });
4182
- server.on("error", reject);
4183
- });
4184
- console.log(import_chalk3.default.green(`\u2713 Server started on port ${port}`));
4394
+ console.log(import_chalk3.default.green(`\u2713 Server started on port ${port}`));
4395
+ }
4185
4396
  if (process.env.SKIP_BACKFILL !== "true") {
4186
4397
  console.log(import_chalk3.default.blue("\nStarting initial sync of all Stripe data..."));
4187
4398
  const syncResult = await stripeSync.processUntilDone();
@@ -4258,7 +4469,8 @@ async function installCommand(options) {
4258
4469
  await install({
4259
4470
  supabaseAccessToken: accessToken,
4260
4471
  supabaseProjectRef: projectRef,
4261
- stripeKey
4472
+ stripeKey,
4473
+ packageVersion: options.packageVersion
4262
4474
  });
4263
4475
  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
4476
  console.log(import_chalk3.default.cyan.bold(" Installation Complete!"));
@@ -1,6 +1,6 @@
1
1
  interface Config {
2
2
  stripeApiKey: string;
3
- ngrokAuthToken: string;
3
+ ngrokAuthToken?: string;
4
4
  databaseUrl: string;
5
5
  }
6
6
  interface CliOptions {
@@ -18,6 +18,7 @@ interface DeployOptions {
18
18
  supabaseAccessToken?: string;
19
19
  supabaseProjectRef?: string;
20
20
  stripeKey?: string;
21
+ packageVersion?: string;
21
22
  }
22
23
 
23
24
  /**
@@ -30,11 +31,9 @@ declare function backfillCommand(options: CliOptions, entityName: string): Promi
30
31
  declare function migrateCommand(options: CliOptions): Promise<void>;
31
32
  /**
32
33
  * Main sync command - syncs Stripe data to PostgreSQL using webhooks for real-time updates.
33
- * 1. Runs database migrations
34
- * 2. Creates StripeSync instance
35
- * 3. Creates ngrok tunnel and Stripe webhook endpoint
36
- * 4. Runs initial backfill of all Stripe data
37
- * 5. Keeps running to process live webhook events (Ctrl+C to stop)
34
+ * Supports two modes:
35
+ * - WebSocket mode (default): Direct connection to Stripe via WebSocket, no ngrok needed
36
+ * - Webhook mode: Uses ngrok tunnel + Express server (when NGROK_AUTH_TOKEN is provided)
38
37
  */
39
38
  declare function syncCommand(options: CliOptions): Promise<void>;
40
39
  /**
package/dist/cli/lib.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  interface Config {
2
2
  stripeApiKey: string;
3
- ngrokAuthToken: string;
3
+ ngrokAuthToken?: string;
4
4
  databaseUrl: string;
5
5
  }
6
6
  interface CliOptions {
@@ -18,6 +18,7 @@ interface DeployOptions {
18
18
  supabaseAccessToken?: string;
19
19
  supabaseProjectRef?: string;
20
20
  stripeKey?: string;
21
+ packageVersion?: string;
21
22
  }
22
23
 
23
24
  /**
@@ -30,11 +31,9 @@ declare function backfillCommand(options: CliOptions, entityName: string): Promi
30
31
  declare function migrateCommand(options: CliOptions): Promise<void>;
31
32
  /**
32
33
  * Main sync command - syncs Stripe data to PostgreSQL using webhooks for real-time updates.
33
- * 1. Runs database migrations
34
- * 2. Creates StripeSync instance
35
- * 3. Creates ngrok tunnel and Stripe webhook endpoint
36
- * 4. Runs initial backfill of all Stripe data
37
- * 5. Keeps running to process live webhook events (Ctrl+C to stop)
34
+ * Supports two modes:
35
+ * - WebSocket mode (default): Direct connection to Stripe via WebSocket, no ngrok needed
36
+ * - Webhook mode: Uses ngrok tunnel + Express server (when NGROK_AUTH_TOKEN is provided)
38
37
  */
39
38
  declare function syncCommand(options: CliOptions): Promise<void>;
40
39
  /**
package/dist/cli/lib.js CHANGED
@@ -6,10 +6,10 @@ import {
6
6
  migrateCommand,
7
7
  syncCommand,
8
8
  uninstallCommand
9
- } from "../chunk-3P5TZKWU.js";
10
- import "../chunk-7JWRDXNB.js";
11
- import "../chunk-SX3HLE4H.js";
12
- import "../chunk-YXQZXR7S.js";
9
+ } from "../chunk-YH6KRZDQ.js";
10
+ import "../chunk-J7BH3XD6.js";
11
+ import "../chunk-X2OQQCC2.js";
12
+ import "../chunk-CKWVW2JK.js";
13
13
  export {
14
14
  backfillCommand,
15
15
  createTunnel,