@reopt-ai/brandapp-sdk 3.3.0 → 3.4.0

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.
Files changed (102) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +10 -1
  3. package/dist/abort--nOBFN4M.js +50 -0
  4. package/dist/ai/index.d.ts +2 -314
  5. package/dist/ai/index.js +3 -8
  6. package/dist/ai-provider/index.d.ts +79 -163
  7. package/dist/ai-provider/index.js +752 -685
  8. package/dist/auth/index.d.ts +27 -27
  9. package/dist/auth/index.js +41 -34
  10. package/dist/better-auth/client.d.ts +6 -5
  11. package/dist/better-auth/client.js +28 -5
  12. package/dist/better-auth/index.d.ts +19 -17
  13. package/dist/better-auth/index.js +180 -144
  14. package/dist/client-B1q5P8rv.js +83 -0
  15. package/dist/client-B9QHVhdM.js +77 -0
  16. package/dist/client-BGGd_cpV.d.ts +103 -0
  17. package/dist/client-BJcy1V1a.js +140 -0
  18. package/dist/client-Beivhucf.js +55 -0
  19. package/dist/client-BruP5_nU.d.ts +147 -0
  20. package/dist/client-D-yNxNfk.js +28 -0
  21. package/dist/client-D0eBxh8j.d.ts +284 -0
  22. package/dist/client-D3RHHUUW.d.ts +207 -0
  23. package/dist/client-D6gs61w8.d.ts +53 -0
  24. package/dist/client-DBnK7ooQ.js +86 -0
  25. package/dist/client-DDw5yz_h.d.ts +53 -0
  26. package/dist/client-DPmoKuR9.js +305 -0
  27. package/dist/client-DsdakibF.js +503 -0
  28. package/dist/client-Dxg8_DIH.d.ts +71 -0
  29. package/dist/client-EbhUIhHq.js +53 -0
  30. package/dist/client-lk6wBu_0.d.ts +48 -0
  31. package/dist/client-p49ol9pg.d.ts +124 -0
  32. package/dist/cms/index.d.ts +52 -108
  33. package/dist/cms/index.js +103 -86
  34. package/dist/config-CRytOPPl.d.ts +394 -0
  35. package/dist/config-Cw0a3-C8.js +487 -0
  36. package/dist/dev/index.d.ts +2 -528
  37. package/dist/dev/index.js +2731 -2967
  38. package/dist/eav/coerce.d.ts +3 -1
  39. package/dist/eav/coerce.js +72 -46
  40. package/dist/eav/index.d.ts +72 -100
  41. package/dist/eav/index.js +158 -126
  42. package/dist/eav/migrate.d.ts +112 -109
  43. package/dist/eav/migrate.js +230 -196
  44. package/dist/eav/schema.d.ts +111 -150
  45. package/dist/eav/schema.js +624 -603
  46. package/dist/encoding-Bwfm3iaE.js +21 -0
  47. package/dist/{errors-BjDFIyA6.d.ts → errors-CRCcErNC.d.ts} +55 -53
  48. package/dist/feedback/index.d.ts +2 -132
  49. package/dist/feedback/index.js +3 -6
  50. package/dist/files/index.d.ts +14 -14
  51. package/dist/files/index.js +41 -25
  52. package/dist/http-client-QKUvvirs.js +386 -0
  53. package/dist/index-DrVaKfhs.d.ts +456 -0
  54. package/dist/index-Z6OGcurJ.d.ts +169 -0
  55. package/dist/index.d.ts +6 -230
  56. package/dist/index.js +119 -71
  57. package/dist/logout/index.d.ts +56 -53
  58. package/dist/logout/index.js +232 -289
  59. package/dist/plans/index.d.ts +2 -236
  60. package/dist/plans/index.js +3 -6
  61. package/dist/push/index.d.ts +2 -79
  62. package/dist/push/index.js +3 -6
  63. package/dist/query-BvbCiGWb.js +35 -0
  64. package/dist/react/hooks.d.ts +97 -99
  65. package/dist/react/hooks.js +742 -404
  66. package/dist/sse-parser-FMjxM7sY.js +86 -0
  67. package/dist/terms/index.d.ts +3 -79
  68. package/dist/terms/index.js +3 -6
  69. package/dist/testing/index.d.ts +52 -104
  70. package/dist/testing/index.js +94 -72
  71. package/dist/types-B-SMkH6s.d.ts +26 -0
  72. package/dist/types-BXDcoJHG.d.ts +131 -0
  73. package/dist/types-BrghN2rJ.d.ts +105 -0
  74. package/dist/types-DjDRszNj.js +11 -0
  75. package/dist/webhooks/index.d.ts +77 -50
  76. package/dist/webhooks/index.js +150 -127
  77. package/docs/api-reference.md +87 -6
  78. package/package.json +6 -5
  79. package/dist/chunk-2LSCQHAU.js +0 -21
  80. package/dist/chunk-4U4ZPPL4.js +0 -599
  81. package/dist/chunk-55KHY5GH.js +0 -96
  82. package/dist/chunk-C5VTRZWX.js +0 -458
  83. package/dist/chunk-F7BXBTZI.js +0 -54
  84. package/dist/chunk-FJUCWXX3.js +0 -350
  85. package/dist/chunk-H33OTQEN.js +0 -112
  86. package/dist/chunk-L4DHB36G.js +0 -75
  87. package/dist/chunk-OG7R3UAR.js +0 -105
  88. package/dist/chunk-PF24XU54.js +0 -32
  89. package/dist/chunk-QN3QD67K.js +0 -49
  90. package/dist/chunk-REIKXSMY.js +0 -7
  91. package/dist/chunk-UGBBXCZE.js +0 -157
  92. package/dist/chunk-UVT2E6KD.js +0 -81
  93. package/dist/chunk-YPLT3RFL.js +0 -63
  94. package/dist/chunk-YTKSAWV2.js +0 -463
  95. package/dist/client-BkcO-0C2.d.ts +0 -216
  96. package/dist/client-CN5_tNOC.d.ts +0 -147
  97. package/dist/client-DttyeM_h.d.ts +0 -102
  98. package/dist/config-CtxyJsDR.d.ts +0 -397
  99. package/dist/typed-client-BxOVIiMU.d.ts +0 -40
  100. package/dist/types-6E3ZLL9X.d.ts +0 -24
  101. package/dist/types-DskYLVb8.d.ts +0 -104
  102. package/dist/types-ckmDDW3N.d.ts +0 -129
@@ -1,142 +1,165 @@
1
- // src/webhooks/index.ts
2
- var DEFAULT_WEBHOOK_TOLERANCE_MS = 5 * 60 * 1e3;
3
- var DEFAULT_IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1e3;
1
+ //#region src/webhooks/index.ts
2
+ /**
3
+ * Default replay-protection window (5 minutes). Webhooks whose
4
+ * `x-reopt-timestamp` is older than this are rejected with HTTP 410. Set
5
+ * `toleranceMs: 0` to disable.
6
+ */
7
+ const DEFAULT_WEBHOOK_TOLERANCE_MS = 300 * 1e3;
8
+ /** Default idempotency cache window — events processed within this window are
9
+ * deduplicated by `payload.id`. */
10
+ const DEFAULT_IDEMPOTENCY_TTL_MS = 1440 * 60 * 1e3;
11
+ /**
12
+ * In-memory idempotency store with a soft cap to avoid unbounded growth.
13
+ * Suitable for single-instance dev/preview deployments. For production with
14
+ * multiple replicas, supply a Redis/Postgres-backed store instead.
15
+ */
4
16
  function createMemoryIdempotencyStore(options) {
5
- const maxEntries = options?.maxEntries ?? 1e4;
6
- const seen = /* @__PURE__ */ new Map();
7
- const sweep = (now) => {
8
- for (const [id, exp] of seen) {
9
- if (exp <= now) seen.delete(id);
10
- }
11
- if (seen.size > maxEntries) {
12
- const drop = seen.size - maxEntries;
13
- let i = 0;
14
- for (const id of seen.keys()) {
15
- if (i++ >= drop) break;
16
- seen.delete(id);
17
- }
18
- }
19
- };
20
- return {
21
- has(id) {
22
- const now = Date.now();
23
- const exp = seen.get(id);
24
- if (exp == null) return false;
25
- if (exp <= now) {
26
- seen.delete(id);
27
- return false;
28
- }
29
- return true;
30
- },
31
- markProcessed(id, ttlMs) {
32
- const now = Date.now();
33
- sweep(now);
34
- seen.set(id, now + Math.max(ttlMs, 0));
35
- }
36
- };
17
+ const maxEntries = options?.maxEntries ?? 1e4;
18
+ const seen = /* @__PURE__ */ new Map();
19
+ const sweep = (now) => {
20
+ for (const [id, exp] of seen) if (exp <= now) seen.delete(id);
21
+ if (seen.size > maxEntries) {
22
+ const drop = seen.size - maxEntries;
23
+ let i = 0;
24
+ for (const id of seen.keys()) {
25
+ if (i++ >= drop) break;
26
+ seen.delete(id);
27
+ }
28
+ }
29
+ };
30
+ return {
31
+ has(id) {
32
+ const now = Date.now();
33
+ const exp = seen.get(id);
34
+ if (exp == null) return false;
35
+ if (exp <= now) {
36
+ seen.delete(id);
37
+ return false;
38
+ }
39
+ return true;
40
+ },
41
+ markProcessed(id, ttlMs) {
42
+ const now = Date.now();
43
+ sweep(now);
44
+ seen.set(id, now + Math.max(ttlMs, 0));
45
+ }
46
+ };
37
47
  }
48
+ /**
49
+ * Create a webhook handler for Web-standard `Request` → `Response` runtimes
50
+ * (Next.js App Router route handlers, Edge runtime, Hono, …).
51
+ *
52
+ * Usage:
53
+ * ```ts
54
+ * // app/api/webhooks/reopt/route.ts
55
+ * import { createWebhookHandler } from "@reopt-ai/brandapp-sdk/webhooks";
56
+ *
57
+ * export const POST = createWebhookHandler({
58
+ * secret: process.env.BRANDAPP_WEBHOOK_SECRET!,
59
+ * handlers: {
60
+ * contactCreated: async (payload) => { ... },
61
+ * workflowRunCompleted: async (payload) => { ... },
62
+ * },
63
+ * });
64
+ * ```
65
+ */
38
66
  function createWebhookHandler(config) {
39
- const toleranceMs = config.toleranceMs ?? DEFAULT_WEBHOOK_TOLERANCE_MS;
40
- const idempotencyStore = config.idempotency === true ? createMemoryIdempotencyStore() : config.idempotency && typeof config.idempotency === "object" ? config.idempotency : null;
41
- const idempotencyTtl = config.idempotencyTtlMs ?? DEFAULT_IDEMPOTENCY_TTL_MS;
42
- return async (request) => {
43
- const signature = request.headers.get("x-reopt-signature");
44
- const timestamp = request.headers.get("x-reopt-timestamp");
45
- const body = await request.text();
46
- if (!signature || !timestamp || !await verifySignature(timestamp, body, signature, config.secret)) {
47
- return jsonResponse({ error: "Invalid signature" }, 401);
48
- }
49
- let payload;
50
- try {
51
- payload = JSON.parse(body);
52
- } catch {
53
- return jsonResponse({ error: "Invalid JSON" }, 400);
54
- }
55
- if (toleranceMs > 0) {
56
- const ts = Number(timestamp);
57
- if (!Number.isFinite(ts)) {
58
- return jsonResponse({ error: "Invalid timestamp" }, 400);
59
- }
60
- if (Math.abs(Date.now() - ts) > toleranceMs) {
61
- return jsonResponse(
62
- { error: "Webhook timestamp outside tolerance" },
63
- 410
64
- );
65
- }
66
- }
67
- const attempt = parseAttemptHeader(
68
- request.headers.get("x-reopt-delivery-attempt")
69
- );
70
- if (idempotencyStore && payload.id) {
71
- if (await idempotencyStore.has(payload.id)) {
72
- return jsonResponse({ received: true, deduplicated: true }, 200);
73
- }
74
- }
75
- const handler = config.handlers[payload.type];
76
- if (handler) {
77
- try {
78
- await handler(payload);
79
- } catch (error) {
80
- await config.onError?.(
81
- error instanceof Error ? error : new Error(String(error)),
82
- payload,
83
- { attempt }
84
- );
85
- return jsonResponse({ error: "Handler error" }, 500);
86
- }
87
- }
88
- if (idempotencyStore && payload.id) {
89
- await idempotencyStore.markProcessed(payload.id, idempotencyTtl);
90
- }
91
- return jsonResponse({ received: true }, 200);
92
- };
67
+ const toleranceMs = config.toleranceMs ?? 3e5;
68
+ const idempotencyStore = config.idempotency === true ? createMemoryIdempotencyStore() : config.idempotency && typeof config.idempotency === "object" ? config.idempotency : null;
69
+ const idempotencyTtl = config.idempotencyTtlMs ?? 864e5;
70
+ return async (request) => {
71
+ const signature = request.headers.get("x-reopt-signature");
72
+ const timestamp = request.headers.get("x-reopt-timestamp");
73
+ const body = await request.text();
74
+ if (!signature || !timestamp || !await verifySignature(timestamp, body, signature, config.secret)) return jsonResponse({ error: "Invalid signature" }, 401);
75
+ let payload;
76
+ try {
77
+ payload = JSON.parse(body);
78
+ } catch {
79
+ return jsonResponse({ error: "Invalid JSON" }, 400);
80
+ }
81
+ if (toleranceMs > 0) {
82
+ const ts = Number(timestamp);
83
+ if (!Number.isFinite(ts)) return jsonResponse({ error: "Invalid timestamp" }, 400);
84
+ if (Math.abs(Date.now() - ts) > toleranceMs) return jsonResponse({ error: "Webhook timestamp outside tolerance" }, 410);
85
+ }
86
+ const attempt = parseAttemptHeader(request.headers.get("x-reopt-delivery-attempt"));
87
+ if (idempotencyStore && payload.id) {
88
+ if (await idempotencyStore.has(payload.id)) return jsonResponse({
89
+ received: true,
90
+ deduplicated: true
91
+ }, 200);
92
+ }
93
+ const handler = config.handlers[payload.type];
94
+ if (handler) try {
95
+ await handler(payload);
96
+ } catch (error) {
97
+ await config.onError?.(error instanceof Error ? error : new Error(String(error)), payload, { attempt });
98
+ return jsonResponse({ error: "Handler error" }, 500);
99
+ }
100
+ if (idempotencyStore && payload.id) await idempotencyStore.markProcessed(payload.id, idempotencyTtl);
101
+ return jsonResponse({ received: true }, 200);
102
+ };
93
103
  }
94
104
  function jsonResponse(body, status) {
95
- return new Response(JSON.stringify(body), {
96
- status,
97
- headers: { "Content-Type": "application/json" }
98
- });
105
+ return new Response(JSON.stringify(body), {
106
+ status,
107
+ headers: { "Content-Type": "application/json" }
108
+ });
99
109
  }
100
110
  function parseAttemptHeader(value) {
101
- if (!value) return 1;
102
- const n = Number(value);
103
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : 1;
111
+ if (!value) return 1;
112
+ const n = Number(value);
113
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 1;
104
114
  }
115
+ /** Strip the `sha256=` prefix the platform sender prepends to the hex digest. */
105
116
  function stripSignaturePrefix(signature) {
106
- return signature.startsWith("sha256=") ? signature.slice("sha256=".length) : signature;
117
+ return signature.startsWith("sha256=") ? signature.slice(7) : signature;
107
118
  }
119
+ /**
120
+ * Verify a Reopt webhook signature.
121
+ *
122
+ * Recomputes `HMAC-SHA256(secret, "{timestamp}.{body}")` and compares it against
123
+ * the hex digest carried in the `x-reopt-signature` header (the `sha256=` prefix
124
+ * is accepted and stripped). Uses a double-HMAC constant-time comparison so it
125
+ * is safe against timing side-channels and works in Node, Edge, and Browser
126
+ * runtimes.
127
+ *
128
+ * This matches the platform sender's `buildWebhookSignature`
129
+ * (`packages/server-core/events/workspace-webhook-delivery.ts`).
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { verifySignature } from "@reopt-ai/brandapp-sdk/webhooks";
134
+ *
135
+ * const timestamp = request.headers.get("x-reopt-timestamp")!;
136
+ * const signature = request.headers.get("x-reopt-signature")!;
137
+ * const body = await request.text();
138
+ * const ok = await verifySignature(timestamp, body, signature, secret);
139
+ * ```
140
+ */
108
141
  async function verifySignature(timestamp, body, signature, secret) {
109
- try {
110
- const encoder = new TextEncoder();
111
- const key = await crypto.subtle.importKey(
112
- "raw",
113
- encoder.encode(secret),
114
- { name: "HMAC", hash: "SHA-256" },
115
- false,
116
- ["sign"]
117
- );
118
- const sig = await crypto.subtle.sign(
119
- "HMAC",
120
- key,
121
- encoder.encode(`${timestamp}.${body}`)
122
- );
123
- const expected = Array.from(new Uint8Array(sig)).map((b2) => b2.toString(16).padStart(2, "0")).join("");
124
- const provided = stripSignaturePrefix(signature);
125
- const [hmacA, hmacB] = await Promise.all([
126
- crypto.subtle.sign("HMAC", key, encoder.encode(provided)),
127
- crypto.subtle.sign("HMAC", key, encoder.encode(expected))
128
- ]);
129
- const a = new Uint8Array(hmacA);
130
- const b = new Uint8Array(hmacB);
131
- if (a.length !== b.length) return false;
132
- let diff = 0;
133
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
134
- return diff === 0;
135
- } catch {
136
- return false;
137
- }
142
+ try {
143
+ const encoder = new TextEncoder();
144
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
145
+ name: "HMAC",
146
+ hash: "SHA-256"
147
+ }, false, ["sign"]);
148
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${body}`));
149
+ const expected = Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
150
+ const provided = stripSignaturePrefix(signature);
151
+ const [hmacA, hmacB] = await Promise.all([crypto.subtle.sign("HMAC", key, encoder.encode(provided)), crypto.subtle.sign("HMAC", key, encoder.encode(expected))]);
152
+ const a = new Uint8Array(hmacA);
153
+ const b = new Uint8Array(hmacB);
154
+ if (a.length !== b.length) return false;
155
+ let diff = 0;
156
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
157
+ return diff === 0;
158
+ } catch {
159
+ return false;
160
+ }
138
161
  }
139
162
 
163
+ //#endregion
140
164
  export { DEFAULT_IDEMPOTENCY_TTL_MS, DEFAULT_WEBHOOK_TOLERANCE_MS, createMemoryIdempotencyStore, createWebhookHandler, verifySignature };
141
- //# sourceMappingURL=index.js.map
142
165
  //# sourceMappingURL=index.js.map
@@ -501,6 +501,7 @@ import {
501
501
  type Plan,
502
502
  type CheckoutSession,
503
503
  type CurrentPlan,
504
+ type CancelSubscriptionResult,
504
505
  } from "@reopt-ai/brandapp-sdk/plans";
505
506
 
506
507
  // Catalog — Basic Auth (or pass an accessToken to use Bearer)
@@ -529,14 +530,68 @@ if (session.status === "completed") {
529
530
  /* granted */
530
531
  }
531
532
 
532
- // Cancel the current sandbox subscription (access kept until period end):
533
- await sdk.plans.cancel(accessToken);
533
+ // Cancel the current subscription — sandbox and live (Paddle/Toss/IAP) alike.
534
+ // Access is kept until the paid period ends.
535
+ const canceled: CancelSubscriptionResult = await sdk.plans.cancel(accessToken);
536
+ canceled.status; // "canceled"
537
+ canceled.provider; // "sandbox" | "paddle" | "toss" | "apple" | "google" (3.4+)
538
+ canceled.accessUntil; // ISO-8601, or null when the plan has no expiry (3.4+)
539
+ canceled.providerCanceled; // false → local subscription is definitely over (no
540
+ // further billing) but the payment provider still shows a
541
+ // remnant that an operator should check (3.4+)
534
542
  ```
535
543
 
536
- > Live Toss/Paddle checkout is not driven through the SDK yet — `createCheckout`
537
- > returns HTTP 409 `LIVE_MODE_UNSUPPORTED` when the Brandapp is set to live
538
- > payments (use the first-party brandfront flow). usage-model meters are
539
- > read-only metadata.
544
+ > The three fields added in 3.4 are optional — an older platform deployment
545
+ > simply omits them. Apple/Google (IAP) subscriptions are canceled in the store,
546
+ > so no remote call is made and `providerCanceled` stays `false`.
547
+
548
+ > Live **Paddle** checkout runs through the same `createCheckout` since 3.4 —
549
+ > `checkoutUrl` is then a Paddle-hosted payment page (zero-price plans keep the
550
+ > sandbox session flow). Live **Toss** stays in the first-party brandfront flow:
551
+ > `createCheckout` returns HTTP 409 `LIVE_MODE_UNSUPPORTED` for a priced plan.
552
+ > usage-model meters are read-only metadata.
553
+
554
+ ## Feedback Client (`sdk.feedback`) — two-way thread (3.4+)
555
+
556
+ ```typescript
557
+ import type {
558
+ Feedback,
559
+ FeedbackDetail,
560
+ FeedbackReply,
561
+ } from "@reopt-ai/brandapp-sdk/feedback";
562
+
563
+ // Server-side collection with app credentials
564
+ await sdk.feedback.create({ content: "배송이 늦어요", rating: 2, customerId });
565
+ const { feedbacks, meta } = await sdk.feedback.list({ status: "reopened" });
566
+ const detail: FeedbackDetail = await sdk.feedback.get(feedbacks[0].id);
567
+
568
+ // ── Signed-in user surface (OAuth access token) ──
569
+ await sdk.feedback.me.create({ content: "좋아요!", rating: 5 }, accessToken);
570
+ const mine = await sdk.feedback.me.list(accessToken);
571
+ const thread = await sdk.feedback.me.get(mine.feedbacks[0].id, accessToken);
572
+
573
+ // The thread mixes both directions in chronological order:
574
+ thread.replies.forEach((reply: FeedbackReply) => {
575
+ reply.author; // "staff" | "customer"
576
+ reply.helpful; // customer's rating of a staff reply (null = not rated)
577
+ });
578
+
579
+ // Rate a staff answer, then follow up — the feedback flips to "reopened"
580
+ // and the workspace is notified.
581
+ const staffReply = thread.replies.find((r) => r.author === "staff")!;
582
+ await sdk.feedback.me.rateReply(thread.id, staffReply.id, false, accessToken);
583
+ const sent = await sdk.feedback.me.reply(
584
+ thread.id,
585
+ "아직 해결이 안 됐어요",
586
+ accessToken,
587
+ );
588
+ sent.feedbackStatus; // "reopened"
589
+ ```
590
+
591
+ > `replyCount` counts **staff replies only**, so `replyCount > 0` keeps meaning
592
+ > "the workspace has answered" even after the customer follows up. Rating alone
593
+ > never reopens a feedback — send a `reply` when the customer still needs
594
+ > something. Ratings are accepted on staff replies only; `null` clears one.
540
595
 
541
596
  ## Webhooks
542
597
 
@@ -563,8 +618,29 @@ export const POST = createWebhookHandler({
563
618
  // Event types (match the platform sender):
564
619
  // "contactCreated" | "contactUpdated" | "contactDeleted"
565
620
  // | "workflowRunCompleted" | "workflowRunFailed"
621
+ // | "subscriptionActivated" | "subscriptionRenewed" // 3.4+
622
+ // | "subscriptionCanceled" | "subscriptionPaymentFailed" // 3.4+
566
623
  // Payload: { id, type, entityType, entityId, createdAt, data }
567
624
 
625
+ // Subscription lifecycle (3.4+) — data is `SubscriptionWebhookData`:
626
+ import type { SubscriptionWebhookData } from "@reopt-ai/brandapp-sdk/webhooks";
627
+
628
+ export const POST = createWebhookHandler({
629
+ secret,
630
+ handlers: {
631
+ subscriptionActivated: async ({ data }) => {
632
+ const sub = data as SubscriptionWebhookData;
633
+ if (sub.brandappId !== process.env.BRANDAPP_ID) return; // see note below
634
+ await grantEntitlement(sub.brandappCustomerId, sub.planId, sub.accessUntil);
635
+ },
636
+ subscriptionRenewed: async ({ data }) => extendAccess(data),
637
+ subscriptionPaymentFailed: async ({ data }) => startDunning(data),
638
+ subscriptionCanceled: async ({ data }) => keepAccessUntil(data), // not immediate
639
+ },
640
+ });
641
+ // SubscriptionWebhookData: { brandappId, brandappCustomerId, customerId,
642
+ // planId, planName, provider, accessUntil }
643
+
568
644
  // Manual signature verification — timestamp first; signs "{timestamp}.{body}",
569
645
  // accepts the sha256=-prefixed header value the platform sends.
570
646
  const timestamp = request.headers.get("x-reopt-timestamp")!;
@@ -572,6 +648,11 @@ const signature = request.headers.get("x-reopt-signature")!;
572
648
  const ok = await verifySignature(timestamp, rawBody, signature, secret);
573
649
  ```
574
650
 
651
+ > Webhooks are registered **per workspace**, so if a workspace runs several
652
+ > Brandapps every subscription event reaches the same endpoint — always filter
653
+ > on `data.brandappId`. `subscriptionCanceled` does not mean "cut access now":
654
+ > honour `accessUntil` (null = no expiry).
655
+
575
656
  ## React Hooks
576
657
 
577
658
  ```typescript
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reopt-ai/brandapp-sdk",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "description": "Reopt Brandapp SDK — Better Auth adapter, OAuth login, and EAV client",
5
5
  "author": "Reopt",
6
6
  "license": "MIT",
@@ -139,11 +139,12 @@
139
139
  "@ai-sdk/provider": "4.0.0",
140
140
  "@reopt-ai/opt-editor": "1.1.2",
141
141
  "@testing-library/react": "^16.3.2",
142
+ "@types/node": "22.13.9",
142
143
  "better-auth": "^1.4.0",
143
144
  "happy-dom": "^20.8.9",
144
145
  "hono": "^4.7.0",
145
- "tsup": "^8.0.0",
146
- "typescript": "5.9.2",
146
+ "tsdown": "^0.22.14",
147
+ "typescript": "^7",
147
148
  "vitest": "^4.1.2",
148
149
  "@reopt/typescript-config": "0.0.0"
149
150
  },
@@ -167,8 +168,8 @@
167
168
  "node": ">=18"
168
169
  },
169
170
  "scripts": {
170
- "build": "tsup",
171
- "dev": "tsup --watch",
171
+ "build": "tsdown",
172
+ "dev": "tsdown --watch",
172
173
  "type-check": "tsc --noEmit",
173
174
  "test": "vitest run",
174
175
  "test:coverage": "vitest run --coverage",
@@ -1,21 +0,0 @@
1
- // src/core/encoding.ts
2
- function encodeBase64(str) {
3
- const bytes = new TextEncoder().encode(str);
4
- const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
5
- return btoa(binString);
6
- }
7
- function createBasicAuthHeader(clientId, clientSecret) {
8
- return `Basic ${encodeBase64(`${clientId}:${clientSecret}`)}`;
9
- }
10
- function createAuthHeader(config) {
11
- const token = config.token?.trim();
12
- if (token) return `Bearer ${token}`;
13
- return createBasicAuthHeader(
14
- config.clientId ?? "",
15
- config.clientSecret ?? ""
16
- );
17
- }
18
-
19
- export { createAuthHeader };
20
- //# sourceMappingURL=chunk-2LSCQHAU.js.map
21
- //# sourceMappingURL=chunk-2LSCQHAU.js.map