@reopt-ai/brandapp-sdk 3.3.0 → 3.5.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 (104) hide show
  1. package/CHANGELOG.md +115 -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-61ldOHMz.js +503 -0
  15. package/dist/client-7PCoxVhZ.js +28 -0
  16. package/dist/client-B7rZQ8Zi.d.ts +272 -0
  17. package/dist/client-BGGd_cpV.d.ts +103 -0
  18. package/dist/client-BoIuyx4S.js +273 -0
  19. package/dist/client-BruP5_nU.d.ts +147 -0
  20. package/dist/client-BxtZt405.js +305 -0
  21. package/dist/client-ByN3EQdk.js +83 -0
  22. package/dist/client-CAghoGD_.js +53 -0
  23. package/dist/client-C_pHsPlj.js +81 -0
  24. package/dist/client-D0eBxh8j.d.ts +284 -0
  25. package/dist/client-D6gs61w8.d.ts +53 -0
  26. package/dist/client-DDw5yz_h.d.ts +53 -0
  27. package/dist/client-Dxg8_DIH.d.ts +71 -0
  28. package/dist/client-aMR4CRB8.d.ts +211 -0
  29. package/dist/client-lk6wBu_0.d.ts +48 -0
  30. package/dist/client-wEVKLdly.js +55 -0
  31. package/dist/client-zF1RG2uA.js +86 -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-aml9oQpX.js +487 -0
  36. package/dist/dev/index.d.ts +2 -528
  37. package/dist/dev/index.js +3047 -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-BZc2mngq.js +386 -0
  53. package/dist/index-1j_738qk.d.ts +470 -0
  54. package/dist/index-CeOLGdyL.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-xWqtfkvR.js +35 -0
  64. package/dist/react/hooks.d.ts +157 -100
  65. package/dist/react/hooks.js +862 -406
  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 +121 -8
  78. package/docs/errors.md +19 -0
  79. package/docs/files.md +165 -7
  80. package/package.json +7 -6
  81. package/dist/chunk-2LSCQHAU.js +0 -21
  82. package/dist/chunk-4U4ZPPL4.js +0 -599
  83. package/dist/chunk-55KHY5GH.js +0 -96
  84. package/dist/chunk-C5VTRZWX.js +0 -458
  85. package/dist/chunk-F7BXBTZI.js +0 -54
  86. package/dist/chunk-FJUCWXX3.js +0 -350
  87. package/dist/chunk-H33OTQEN.js +0 -112
  88. package/dist/chunk-L4DHB36G.js +0 -75
  89. package/dist/chunk-OG7R3UAR.js +0 -105
  90. package/dist/chunk-PF24XU54.js +0 -32
  91. package/dist/chunk-QN3QD67K.js +0 -49
  92. package/dist/chunk-REIKXSMY.js +0 -7
  93. package/dist/chunk-UGBBXCZE.js +0 -157
  94. package/dist/chunk-UVT2E6KD.js +0 -81
  95. package/dist/chunk-YPLT3RFL.js +0 -63
  96. package/dist/chunk-YTKSAWV2.js +0 -463
  97. package/dist/client-BkcO-0C2.d.ts +0 -216
  98. package/dist/client-CN5_tNOC.d.ts +0 -147
  99. package/dist/client-DttyeM_h.d.ts +0 -102
  100. package/dist/config-CtxyJsDR.d.ts +0 -397
  101. package/dist/typed-client-BxOVIiMU.d.ts +0 -40
  102. package/dist/types-6E3ZLL9X.d.ts +0 -24
  103. package/dist/types-DskYLVb8.d.ts +0 -104
  104. 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
@@ -203,7 +203,8 @@ export async function GET(request: Request) {
203
203
  const { data: files, meta } = await sdk.files.list({
204
204
  page?: number; // Default: 1
205
205
  limit?: number; // Default: 20
206
- contentType?: string; // e.g. "image/*"
206
+ contentType?: string; // e.g. "image/png" 또는 와일드카드 "image/*"
207
+ folderId?: string | null; // 미지정=전체, null=루트만, id=해당 폴더 직속
207
208
  sortBy?: "createdAt" | "name" | "size";
208
209
  sortOrder?: "asc" | "desc";
209
210
  });
@@ -211,19 +212,50 @@ const { data: files, meta } = await sdk.files.list({
211
212
 
212
213
  // Get single file
213
214
  const file = await sdk.files.get(fileId);
214
- // Returns: { id, name, url, size, contentType, pathname, createdAt, updatedAt }
215
+ // Returns: { id, name, url, size, contentType, pathname, folderId, createdAt, updatedAt }
215
216
 
216
217
  // Upload file (multipart FormData)
217
218
  const uploaded = await sdk.files.upload(file, {
218
219
  name?: string; // Override filename
219
220
  contentType?: string; // Override MIME type
221
+ folderId?: string; // 업로드할 폴더 (미지정 = 루트)
220
222
  });
221
223
  // Accepts: Blob | Uint8Array | File
222
224
  // Returns: FileInfo
223
225
 
226
+ // Rename / move file
227
+ const updated = await sdk.files.update(fileId, {
228
+ name?: string; // 표시명 변경 (pathname은 불변)
229
+ folderId?: string | null; // 폴더 이동 (null = 루트로)
230
+ });
231
+ // Returns: FileInfo
232
+
233
+ // Read text content (미리보기용 — text/*, application/json 등만. 그 외 415, 1MB 초과 413)
234
+ const text = await sdk.files.readContent(fileId);
235
+ // Returns: string
236
+
237
+ // Storage usage (사용량 미터 — usedBytes/limitBytes는 워크스페이스 단위, 402 STORAGE_LIMIT 판정과 동일 소스)
238
+ const usage = await sdk.files.usage();
239
+ // Returns: { usedBytes: number, limitBytes: number | null, fileCount: number }
240
+
224
241
  // Delete file
225
242
  await sdk.files.delete(fileId);
226
243
  // Returns: void
244
+
245
+ // ---- Folders (3.5+) ----
246
+
247
+ // List direct child folders (미지정 = 루트)
248
+ const folders = await sdk.files.listFolders({ parentId?: string | null });
249
+ // Returns: FolderInfo[] — { id, name, parentId, childCount, fileCount, createdAt, updatedAt }
250
+
251
+ // Create folder
252
+ const folder = await sdk.files.createFolder({ name: "docs", parentId?: string | null });
253
+
254
+ // Rename / move folder (자기 자신·자손으로의 이동은 400)
255
+ await sdk.files.updateFolder(folderId, { name?: string, parentId?: string | null });
256
+
257
+ // Delete folder (비어있어야 함 — 아니면 409 FOLDER_NOT_EMPTY)
258
+ await sdk.files.deleteFolder(folderId);
227
259
  ```
228
260
 
229
261
  ### Image URL helpers (1.8+)
@@ -501,6 +533,7 @@ import {
501
533
  type Plan,
502
534
  type CheckoutSession,
503
535
  type CurrentPlan,
536
+ type CancelSubscriptionResult,
504
537
  } from "@reopt-ai/brandapp-sdk/plans";
505
538
 
506
539
  // Catalog — Basic Auth (or pass an accessToken to use Bearer)
@@ -529,14 +562,68 @@ if (session.status === "completed") {
529
562
  /* granted */
530
563
  }
531
564
 
532
- // Cancel the current sandbox subscription (access kept until period end):
533
- await sdk.plans.cancel(accessToken);
565
+ // Cancel the current subscription — sandbox and live (Paddle/Toss/IAP) alike.
566
+ // Access is kept until the paid period ends.
567
+ const canceled: CancelSubscriptionResult = await sdk.plans.cancel(accessToken);
568
+ canceled.status; // "canceled"
569
+ canceled.provider; // "sandbox" | "paddle" | "toss" | "apple" | "google" (3.4+)
570
+ canceled.accessUntil; // ISO-8601, or null when the plan has no expiry (3.4+)
571
+ canceled.providerCanceled; // false → local subscription is definitely over (no
572
+ // further billing) but the payment provider still shows a
573
+ // remnant that an operator should check (3.4+)
534
574
  ```
535
575
 
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.
576
+ > The three fields added in 3.4 are optional — an older platform deployment
577
+ > simply omits them. Apple/Google (IAP) subscriptions are canceled in the store,
578
+ > so no remote call is made and `providerCanceled` stays `false`.
579
+
580
+ > Live **Paddle** checkout runs through the same `createCheckout` since 3.4 —
581
+ > `checkoutUrl` is then a Paddle-hosted payment page (zero-price plans keep the
582
+ > sandbox session flow). Live **Toss** stays in the first-party brandfront flow:
583
+ > `createCheckout` returns HTTP 409 `LIVE_MODE_UNSUPPORTED` for a priced plan.
584
+ > usage-model meters are read-only metadata.
585
+
586
+ ## Feedback Client (`sdk.feedback`) — two-way thread (3.4+)
587
+
588
+ ```typescript
589
+ import type {
590
+ Feedback,
591
+ FeedbackDetail,
592
+ FeedbackReply,
593
+ } from "@reopt-ai/brandapp-sdk/feedback";
594
+
595
+ // Server-side collection with app credentials
596
+ await sdk.feedback.create({ content: "배송이 늦어요", rating: 2, customerId });
597
+ const { feedbacks, meta } = await sdk.feedback.list({ status: "reopened" });
598
+ const detail: FeedbackDetail = await sdk.feedback.get(feedbacks[0].id);
599
+
600
+ // ── Signed-in user surface (OAuth access token) ──
601
+ await sdk.feedback.me.create({ content: "좋아요!", rating: 5 }, accessToken);
602
+ const mine = await sdk.feedback.me.list(accessToken);
603
+ const thread = await sdk.feedback.me.get(mine.feedbacks[0].id, accessToken);
604
+
605
+ // The thread mixes both directions in chronological order:
606
+ thread.replies.forEach((reply: FeedbackReply) => {
607
+ reply.author; // "staff" | "customer"
608
+ reply.helpful; // customer's rating of a staff reply (null = not rated)
609
+ });
610
+
611
+ // Rate a staff answer, then follow up — the feedback flips to "reopened"
612
+ // and the workspace is notified.
613
+ const staffReply = thread.replies.find((r) => r.author === "staff")!;
614
+ await sdk.feedback.me.rateReply(thread.id, staffReply.id, false, accessToken);
615
+ const sent = await sdk.feedback.me.reply(
616
+ thread.id,
617
+ "아직 해결이 안 됐어요",
618
+ accessToken,
619
+ );
620
+ sent.feedbackStatus; // "reopened"
621
+ ```
622
+
623
+ > `replyCount` counts **staff replies only**, so `replyCount > 0` keeps meaning
624
+ > "the workspace has answered" even after the customer follows up. Rating alone
625
+ > never reopens a feedback — send a `reply` when the customer still needs
626
+ > something. Ratings are accepted on staff replies only; `null` clears one.
540
627
 
541
628
  ## Webhooks
542
629
 
@@ -563,8 +650,29 @@ export const POST = createWebhookHandler({
563
650
  // Event types (match the platform sender):
564
651
  // "contactCreated" | "contactUpdated" | "contactDeleted"
565
652
  // | "workflowRunCompleted" | "workflowRunFailed"
653
+ // | "subscriptionActivated" | "subscriptionRenewed" // 3.4+
654
+ // | "subscriptionCanceled" | "subscriptionPaymentFailed" // 3.4+
566
655
  // Payload: { id, type, entityType, entityId, createdAt, data }
567
656
 
657
+ // Subscription lifecycle (3.4+) — data is `SubscriptionWebhookData`:
658
+ import type { SubscriptionWebhookData } from "@reopt-ai/brandapp-sdk/webhooks";
659
+
660
+ export const POST = createWebhookHandler({
661
+ secret,
662
+ handlers: {
663
+ subscriptionActivated: async ({ data }) => {
664
+ const sub = data as SubscriptionWebhookData;
665
+ if (sub.brandappId !== process.env.BRANDAPP_ID) return; // see note below
666
+ await grantEntitlement(sub.brandappCustomerId, sub.planId, sub.accessUntil);
667
+ },
668
+ subscriptionRenewed: async ({ data }) => extendAccess(data),
669
+ subscriptionPaymentFailed: async ({ data }) => startDunning(data),
670
+ subscriptionCanceled: async ({ data }) => keepAccessUntil(data), // not immediate
671
+ },
672
+ });
673
+ // SubscriptionWebhookData: { brandappId, brandappCustomerId, customerId,
674
+ // planId, planName, provider, accessUntil }
675
+
568
676
  // Manual signature verification — timestamp first; signs "{timestamp}.{body}",
569
677
  // accepts the sha256=-prefixed header value the platform sends.
570
678
  const timestamp = request.headers.get("x-reopt-timestamp")!;
@@ -572,6 +680,11 @@ const signature = request.headers.get("x-reopt-signature")!;
572
680
  const ok = await verifySignature(timestamp, rawBody, signature, secret);
573
681
  ```
574
682
 
683
+ > Webhooks are registered **per workspace**, so if a workspace runs several
684
+ > Brandapps every subscription event reaches the same endpoint — always filter
685
+ > on `data.brandappId`. `subscriptionCanceled` does not mean "cut access now":
686
+ > honour `accessUntil` (null = no expiry).
687
+
575
688
  ## React Hooks
576
689
 
577
690
  ```typescript
package/docs/errors.md CHANGED
@@ -45,6 +45,25 @@ treating a transient JWKS outage as a permanently bad token). See
45
45
  > `"RateLimitError"`, `"CreditLimitError"`) so log aggregation / Sentry grouping
46
46
  > can distinguish them. `instanceof`, `.code`, and `.status` work as before.
47
47
 
48
+ ### Files-specific (3.5+)
49
+
50
+ `sdk.files.*` 도메인 코드. 409는 `ConflictError`로, 413/415는 base
51
+ `ReoptSDKError`로 도착한다 — `.code`/`.status`로 분기하면 된다. ⚠️ 402는 클래스
52
+ 매핑이 status 단위라 저장공간 초과도 **`CreditLimitError` 클래스**로 도착한다
53
+ (이름과 달리 AI 크레딧이 아님) — `.code === "STORAGE_LIMIT"`으로 구분할 것.
54
+
55
+ | Code | Status | Class | When |
56
+ | -------------------------- | ------ | ------------------ | ------------------------------------------------------------------------ |
57
+ | `STORAGE_LIMIT` | 402 | `CreditLimitError` | 업로드 — 플랜 저장공간 한도 초과 (`sdk.files.usage()`로 사전 확인 가능) |
58
+ | `FILE_IN_USE` | 409 | `ConflictError` | 파일 삭제 — 브랜드프론트·이메일 등에서 사용 중 (메시지에 사용처 포함) |
59
+ | `FOLDER_NOT_EMPTY` | 409 | `ConflictError` | 폴더 삭제 — 파일/하위 폴더가 남아 있음 (메시지에 남은 개수 포함) |
60
+ | `CONFLICT` | 409 | `ConflictError` | 폴더 생성/이동 — 같은 위치에 동명 폴더 존재 |
61
+ | `CONTENT_TOO_LARGE` | 413 | `ReoptSDKError` | `readContent` — 1MB 초과 파일 |
62
+ | `UNSUPPORTED_CONTENT_TYPE` | 415 | `ReoptSDKError` | `readContent` — 텍스트 계열(`text/*`, `application/json` 등)이 아닌 파일 |
63
+
64
+ `STORAGE_LIMIT`·`FILE_IN_USE`·`FOLDER_NOT_EMPTY`의 메시지는 사람이 읽을 수 있는
65
+ 형태라 UI에 그대로 표면화해도 된다.
66
+
48
67
  ### EAV-specific (1.9+)
49
68
 
50
69
  These extend the general classes above so existing `instanceof ConflictError` /