@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
@@ -0,0 +1,487 @@
1
+ //#region src/core/errors.ts
2
+ var ReoptSDKError = class extends Error {
3
+ status;
4
+ code;
5
+ context;
6
+ diagnostic;
7
+ constructor(message, status, code, context, diagnostic) {
8
+ const prefix = context?.method && context.url ? `[${context.method} ${context.url}] ` : "";
9
+ super(`${prefix}${message}`);
10
+ this.name = "ReoptSDKError";
11
+ this.status = status;
12
+ this.code = code;
13
+ this.context = context;
14
+ this.diagnostic = diagnostic;
15
+ }
16
+ };
17
+ var AuthError = class extends ReoptSDKError {
18
+ constructor(message = "Authentication failed", context) {
19
+ super(message, 401, "AUTH_ERROR", context, {
20
+ cause: "clientId 또는 clientSecret이 잘못되었거나 OAuth 클라이언트가 비활성화됨",
21
+ fix: "Studio → BrandApp → 설정 → OAuth 클라이언트에서 자격증명 확인",
22
+ doc: "docs/errors.md#auth_error"
23
+ });
24
+ this.name = "AuthError";
25
+ }
26
+ };
27
+ var RateLimitError = class extends ReoptSDKError {
28
+ constructor(message = "Rate limit exceeded", retryAfterMs, context) {
29
+ super(message, 429, "RATE_LIMIT", context, {
30
+ cause: "분당/시간당 요청 한도 초과",
31
+ fix: retryAfterMs ? `${Math.ceil(retryAfterMs / 1e3)}초 후 재시도하거나, BrandApp AI 설정에서 rateLimit 조정` : "요청 간격을 늘리거나 BrandApp AI 설정에서 rateLimit 조정",
32
+ doc: "docs/errors.md#rate_limit"
33
+ });
34
+ this.name = "RateLimitError";
35
+ }
36
+ };
37
+ var ServerError = class extends ReoptSDKError {
38
+ constructor(message = "Internal server error", context) {
39
+ super(message, 500, "SERVER_ERROR", context, {
40
+ cause: "서버 내부 오류",
41
+ fix: "잠시 후 재시도. 반복되면 서버 상태 확인",
42
+ doc: "docs/errors.md#server_error"
43
+ });
44
+ this.name = "ServerError";
45
+ }
46
+ };
47
+ /** AI 크레딧 잔액 부족 (HTTP 402). */
48
+ var CreditLimitError = class extends ReoptSDKError {
49
+ constructor(message = "Insufficient AI credits", context, code = "CREDIT_LIMIT") {
50
+ super(message, 402, code, context, {
51
+ cause: "BrandApp AI 크레딧 잔액 부족",
52
+ fix: "Studio → BrandApp → AI 크레딧 페이지에서 충전",
53
+ doc: "docs/errors.md#credit_limit"
54
+ });
55
+ this.name = "CreditLimitError";
56
+ }
57
+ };
58
+ /**
59
+ * 요청한 모델이 현재 plan tier에서 허용되지 않음 (HTTP 403, `MODEL_ACCESS_DENIED`).
60
+ * 일반 권한 실패(`ForbiddenError`)와 구분해 모델 선택/업그레이드 안내를 준다.
61
+ */
62
+ var ModelAccessError = class extends ReoptSDKError {
63
+ constructor(message = "Model not available for this plan tier", context) {
64
+ super(message, 403, "MODEL_ACCESS_DENIED", context, {
65
+ cause: "현재 plan tier 또는 BrandApp AI 설정에서 사용할 수 없는 모델",
66
+ fix: "sdk.ai.models()로 사용 가능 모델 확인, 또는 Studio → BrandApp → AI에서 모델 tier·plan 업그레이드",
67
+ doc: "docs/errors.md#model_access_denied"
68
+ });
69
+ this.name = "ModelAccessError";
70
+ }
71
+ };
72
+ /** 알 수 없는 모델 ID (HTTP 404, `MODEL_NOT_FOUND`). */
73
+ var ModelNotFoundError = class extends ReoptSDKError {
74
+ constructor(message = "Unknown model", context) {
75
+ super(message, 404, "MODEL_NOT_FOUND", context, {
76
+ cause: "요청한 model ID가 카탈로그에 없음 (오타 또는 폐기된 모델)",
77
+ fix: "sdk.ai.models()로 유효한 model ID를 조회",
78
+ doc: "docs/errors.md#model_not_found"
79
+ });
80
+ this.name = "ModelNotFoundError";
81
+ }
82
+ };
83
+ /** 콘텐츠 정책 위반으로 생성 거부 (HTTP 422, `CONTENT_FILTER`). */
84
+ var ContentFilterError = class extends ReoptSDKError {
85
+ constructor(message = "Content blocked by moderation policy", context) {
86
+ super(message, 422, "CONTENT_FILTER", context, {
87
+ cause: "프롬프트 또는 생성 결과가 콘텐츠 정책을 위반",
88
+ fix: "프롬프트를 수정해 정책 위반 소지를 제거",
89
+ doc: "docs/errors.md#content_filter"
90
+ });
91
+ this.name = "ContentFilterError";
92
+ }
93
+ };
94
+ var BadRequestError = class extends ReoptSDKError {
95
+ constructor(message = "Bad request", context, code = "BAD_REQUEST") {
96
+ super(message, 400, code, context, {
97
+ cause: "요청 파라미터가 잘못됨",
98
+ fix: "요청 본문과 쿼리 파라미터를 확인"
99
+ });
100
+ this.name = "BadRequestError";
101
+ }
102
+ };
103
+ var ForbiddenError = class extends ReoptSDKError {
104
+ constructor(message = "Forbidden", context, code = "FORBIDDEN") {
105
+ super(message, 403, code, context, {
106
+ cause: "해당 리소스에 대한 접근 권한이 없음",
107
+ fix: "OAuth 스코프, 워크스페이스 권한, 또는 authUserId를 확인"
108
+ });
109
+ this.name = "ForbiddenError";
110
+ }
111
+ };
112
+ var NotFoundError = class extends ReoptSDKError {
113
+ constructor(message = "Not found", context, code = "NOT_FOUND") {
114
+ super(message, 404, code, context, {
115
+ cause: "요청한 리소스가 존재하지 않음",
116
+ fix: "ID 또는 경로가 올바른지 확인. 삭제된 리소스일 수 있음"
117
+ });
118
+ this.name = "NotFoundError";
119
+ }
120
+ };
121
+ var ConflictError = class extends ReoptSDKError {
122
+ constructor(message = "Conflict", context, code = "CONFLICT") {
123
+ super(message, 409, code, context, {
124
+ cause: "현재 리소스 상태와 충돌 (중복 키, 동시 수정 등)",
125
+ fix: "기존 데이터를 다시 조회 후 재시도"
126
+ });
127
+ this.name = "ConflictError";
128
+ }
129
+ };
130
+ /** 한 brandapp user에 이미 같은 EAV entity의 record가 존재 (1:1 메타 위반). */
131
+ var AuthUserRecordExistsError = class extends ConflictError {
132
+ constructor(message = "Auth user already has a record for this entity", context) {
133
+ super(message, context, "AUTH_USER_RECORD_EXISTS");
134
+ this.name = "AuthUserRecordExistsError";
135
+ }
136
+ };
137
+ /** bulk create 입력에 같은 authUserId가 중복으로 등장 (1:1 메타 위반). */
138
+ var DuplicateAuthUserError = class extends ConflictError {
139
+ constructor(message = "Duplicate authUserId in bulk create", context) {
140
+ super(message, context, "DUPLICATE_AUTH_USER");
141
+ this.name = "DuplicateAuthUserError";
142
+ }
143
+ };
144
+ /** 참조한 brandappAuthUser가 이 brandapp에 존재하지 않음. status는 호출 경로에 따라 400 또는 422. */
145
+ var AuthUserNotFoundError = class extends ReoptSDKError {
146
+ constructor(message = "Auth user not found in this brandapp", status = 422, context) {
147
+ super(message, status, "AUTH_USER_NOT_FOUND", context, {
148
+ cause: "참조한 authUserId가 이 brandapp에 등록되지 않음",
149
+ fix: "BrandappAuthUser가 먼저 생성되었는지 확인. authUserId 오타 점검"
150
+ });
151
+ this.name = "AuthUserNotFoundError";
152
+ }
153
+ };
154
+ /**
155
+ * EAV 한도 초과 — entity/attribute/record 수가 plan 한도를 넘음.
156
+ * `code`로 어느 자원이 초과됐는지 분기:
157
+ * - `LIMIT_EXCEEDED_ENTITIES`
158
+ * - `LIMIT_EXCEEDED_ATTRIBUTES`
159
+ * - `LIMIT_EXCEEDED_RECORDS`
160
+ */
161
+ var LimitExceededError = class extends ReoptSDKError {
162
+ constructor(message, code, context) {
163
+ super(message, 422, code, context, {
164
+ cause: "EAV 자원 한도 초과 (plan 또는 시스템 limit)",
165
+ fix: "오래된 데이터 정리 후 재시도하거나, plan 업그레이드 검토"
166
+ });
167
+ this.name = "LimitExceededError";
168
+ }
169
+ };
170
+ /**
171
+ * 플랜 구독(checkout) 전에 동의해야 하는 필수 약관이 미동의 상태 (HTTP 422,
172
+ * `REQUIRED_TERMS`). `missingTermsIds`로 어떤 약관에 동의가 필요한지 알 수 있다 —
173
+ * `sdk.terms.list()` + `sdk.terms.consent()`로 동의를 수집한 뒤 checkout을 재시도한다.
174
+ *
175
+ * @example
176
+ * ```ts
177
+ * try {
178
+ * await sdk.plans.createCheckout({ planId, successUrl, cancelUrl }, token);
179
+ * } catch (e) {
180
+ * if (isRequiredTermsError(e)) {
181
+ * // e.missingTermsIds 에 해당하는 약관 동의 UI를 띄운다
182
+ * }
183
+ * }
184
+ * ```
185
+ */
186
+ var RequiredTermsError = class extends ReoptSDKError {
187
+ missingTermsIds;
188
+ constructor(message = "필수 약관 동의가 필요합니다", missingTermsIds = [], context) {
189
+ super(message, 422, "REQUIRED_TERMS", context, {
190
+ cause: "이 플랜 구독 전에 동의해야 하는 필수 약관이 남아 있음",
191
+ fix: "sdk.terms.list()로 약관을 조회하고 sdk.terms.consent()로 동의한 뒤 다시 결제를 시작",
192
+ doc: "docs/errors.md#required_terms"
193
+ });
194
+ this.name = "RequiredTermsError";
195
+ this.missingTermsIds = missingTermsIds;
196
+ }
197
+ };
198
+ /** Bundle-safe type guard for RequiredTermsError */
199
+ function isRequiredTermsError(error) {
200
+ return error instanceof Error && error.name === "RequiredTermsError" && "missingTermsIds" in error;
201
+ }
202
+ /**
203
+ * 필드 수준 검증 에러
204
+ *
205
+ * API가 필드별 에러를 반환하면 자동으로 파싱됩니다.
206
+ *
207
+ * @example
208
+ * ```ts
209
+ * try {
210
+ * await sdk.eav.records.create(entityId, { values: {} });
211
+ * } catch (e) {
212
+ * if (e instanceof ValidationError) {
213
+ * e.fieldErrors.forEach(fe =>
214
+ * console.log(`${fe.field}: ${fe.message}`)
215
+ * );
216
+ * // "name: 필수 필드입니다"
217
+ * // "email: 올바른 이메일 형식이 아닙니다"
218
+ * }
219
+ * }
220
+ * ```
221
+ */
222
+ var ValidationError = class extends ReoptSDKError {
223
+ fieldErrors;
224
+ constructor(message, fieldErrors, context) {
225
+ super(message, 422, "VALIDATION_ERROR", context);
226
+ this.name = "ValidationError";
227
+ this.fieldErrors = fieldErrors;
228
+ }
229
+ /** 특정 필드의 에러 메시지 반환 */
230
+ getFieldError(field) {
231
+ return this.fieldErrors.find((e) => e.field === field)?.message;
232
+ }
233
+ /** 필드 → 메시지 맵 반환 */
234
+ toFieldMap() {
235
+ const map = {};
236
+ for (const fe of this.fieldErrors) map[fe.field] = fe.message;
237
+ return map;
238
+ }
239
+ };
240
+ /** Bundle-safe type guard for ValidationError */
241
+ function isValidationError(error) {
242
+ return error instanceof Error && error.name === "ValidationError" && "fieldErrors" in error;
243
+ }
244
+ /**
245
+ * Bundle-safe type guard — works even when multiple SDK versions coexist.
246
+ *
247
+ * Duck-types on the SDK error shape (`status: number` + `code: string`) rather
248
+ * than `instanceof` to avoid cross-package class identity issues. (The base
249
+ * class name isn't checked because subclasses override `this.name` to
250
+ * `AuthError`/`ValidationError`/… — a single name comparison would miss them.)
251
+ * The type checks below keep a plain `Error` that happens to carry unrelated
252
+ * `status`/`code` fields from matching.
253
+ */
254
+ function isReoptSDKError(error) {
255
+ return error instanceof Error && typeof error.status === "number" && typeof error.code === "string";
256
+ }
257
+ /** Bundle-safe type guard for CreditLimitError */
258
+ function isCreditLimitError(error) {
259
+ return error instanceof Error && error.name === "CreditLimitError";
260
+ }
261
+ /** Bundle-safe type guard for ModelAccessError */
262
+ function isModelAccessError(error) {
263
+ return error instanceof Error && error.name === "ModelAccessError";
264
+ }
265
+ /**
266
+ * HTTP 상태 + 서버 에러 코드를 typed `ReoptSDKError`로 매핑하는 **단일 출처**.
267
+ *
268
+ * 비스트림 HTTP(`BaseHttpClient`), SSE 스트리밍(`ai/client.ts`), AI SDK provider
269
+ * (`ai-provider/provider-http.ts`)가 모두 이 함수를 거쳐 동일한 코드/진단을 갖는
270
+ * 에러를 생성한다. 그래서 `sdk.ai.*`와 `brandapp(...)`의 에러 형태가 통일된다.
271
+ *
272
+ * 반환만 하고 throw하지 않는다 — 호출처가 재시도 가능 여부(429/5xx)에 따라
273
+ * throw할지 `lastError`에 담을지 결정한다.
274
+ */
275
+ function mapHttpStatusToError(status, code, message, ctx, fieldErrors) {
276
+ switch (status) {
277
+ case 401: return new AuthError(message ?? "Authentication failed", ctx);
278
+ case 402: return new CreditLimitError(message ?? "Insufficient AI credits", ctx, code ?? "CREDIT_LIMIT");
279
+ case 400:
280
+ if (code === "AUTH_USER_NOT_FOUND") return new AuthUserNotFoundError(message ?? "Auth user not found in this brandapp", 400, ctx);
281
+ return new BadRequestError(message ?? "Bad request", ctx, code ?? "BAD_REQUEST");
282
+ case 403:
283
+ if (code === "MODEL_ACCESS_DENIED") return new ModelAccessError(message ?? "Model not available for this plan tier", ctx);
284
+ return new ForbiddenError(message ?? "Forbidden", ctx, code ?? "FORBIDDEN");
285
+ case 404:
286
+ if (code === "MODEL_NOT_FOUND") return new ModelNotFoundError(message ?? "Unknown model", ctx);
287
+ return new NotFoundError(message ?? "Not found", ctx, code ?? "NOT_FOUND");
288
+ case 409:
289
+ if (code === "AUTH_USER_RECORD_EXISTS") return new AuthUserRecordExistsError(message ?? "Auth user already has a record for this entity", ctx);
290
+ if (code === "DUPLICATE_AUTH_USER") return new DuplicateAuthUserError(message ?? "Duplicate authUserId in bulk create", ctx);
291
+ return new ConflictError(message ?? "Conflict", ctx, code ?? "CONFLICT");
292
+ case 422:
293
+ if (code === "REQUIRED_TERMS") return new RequiredTermsError(message ?? "필수 약관 동의가 필요합니다", (fieldErrors ?? []).map((f) => f.field), ctx);
294
+ if (fieldErrors && fieldErrors.length > 0) return new ValidationError(message ?? "Validation failed", fieldErrors, ctx);
295
+ if (code === "CONTENT_FILTER") return new ContentFilterError(message ?? "Content blocked by moderation policy", ctx);
296
+ if (code === "LIMIT_EXCEEDED_ENTITIES" || code === "LIMIT_EXCEEDED_ATTRIBUTES" || code === "LIMIT_EXCEEDED_RECORDS") return new LimitExceededError(message ?? "EAV limit exceeded", code, ctx);
297
+ if (code === "AUTH_USER_NOT_FOUND") return new AuthUserNotFoundError(message ?? "Auth user not found in this brandapp", 422, ctx);
298
+ return new ReoptSDKError(message ?? `Request failed with status ${status}`, 422, code ?? "REQUEST_ERROR", ctx);
299
+ case 429: return new RateLimitError(message ?? "Rate limit exceeded", void 0, ctx);
300
+ default:
301
+ if (status >= 500) return new ServerError(message ?? "Internal server error", ctx);
302
+ return new ReoptSDKError(message ?? `Unexpected status: ${status}`, status, code ?? "UNEXPECTED_ERROR", ctx);
303
+ }
304
+ }
305
+
306
+ //#endregion
307
+ //#region src/core/config.ts
308
+ const SDK_VERSION = "3.4.0";
309
+ /**
310
+ * Default API host for EAV / AI / Files / CMS / Terms. Consumers can override
311
+ * via `config.baseUrl` or the `REOPT_BASE_URL` env var.
312
+ *
313
+ * The canonical production host is `brandapp.reopt.ai` (the brandapp data API —
314
+ * distinct from `{alias}.reopt.ai` brandfront sites). The legacy `brand.reopt.ai`
315
+ * host stays served indefinitely as a backward-compat alias, so SDK builds
316
+ * published before this change keep working. ⚠️ Flip takes effect only on
317
+ * re-publish — republish after `brandapp.reopt.ai` is live on Vercel.
318
+ * (dev host stays `brand.reopt.de:3443` — bound to the local hosts file + cert.)
319
+ */
320
+ const REOPT_BASE_URLS = {
321
+ production: "https://brandapp.reopt.ai",
322
+ development: "https://brand.reopt.de:3443"
323
+ };
324
+ /**
325
+ * Better Auth handler (`/api/auth/*`) and CLI device-flow endpoints live on
326
+ * the dedicated id server, not the main API host. SDK helpers that hit OIDC
327
+ * (`getUserInfo`, OAuth discovery) must use these URLs.
328
+ *
329
+ * Override via `config.idBaseUrl` or the `REOPT_ID_BASE_URL` env var. If only
330
+ * the main host is overridden (`config.baseUrl` or `REOPT_BASE_URL`), the id
331
+ * host is auto-derived via {@link deriveIdFromBaseUrl} — e.g. setting
332
+ * `REOPT_BASE_URL=https://brand.reopt.de:3443` is enough; `id.reopt.de:3443` is
333
+ * inferred automatically.
334
+ */
335
+ const REOPT_ID_BASE_URLS = {
336
+ production: "https://id.reopt.ai",
337
+ development: "https://id.reopt.de:3443"
338
+ };
339
+ function validateConfig(config) {
340
+ if (!!!config.token?.trim()) {
341
+ if (!config.clientId?.trim()) throw new ConfigError("ReoptSDK: clientId is required (or pass a short-lived `token`). Set BRANDAPP_CLIENT_ID environment variable.", "BRANDAPP_CLIENT_ID");
342
+ if (!config.clientSecret?.trim()) throw new ConfigError("ReoptSDK: clientSecret is required (or pass a short-lived `token`). Set BRANDAPP_CLIENT_SECRET environment variable.", "BRANDAPP_CLIENT_SECRET");
343
+ }
344
+ if (!config.brandappId?.trim()) throw new ConfigError("ReoptSDK: brandappId is required. Set BRANDAPP_ID environment variable.", "BRANDAPP_ID");
345
+ if (/[\s/?#]/.test(config.brandappId)) throw new ConfigInvalidError("ReoptSDK: brandappId contains invalid characters (whitespace, '/', '?', or '#'). Use the BrandApp ID exactly as shown in Studio.", "BRANDAPP_ID");
346
+ assertValidUrl(config.baseUrl, "baseUrl", "REOPT_BASE_URL");
347
+ assertValidUrl(config.idBaseUrl, "idBaseUrl", "REOPT_ID_BASE_URL");
348
+ }
349
+ /**
350
+ * True in any browser-shipped runtime — the main window thread AND Web/Service
351
+ * Workers. A worker global has no `window` (only `self`/`WorkerGlobalScope` +
352
+ * `importScripts`), so a plain `typeof window` check would miss it and let a
353
+ * clientSecret slip into publicly-served worker JS. Node/edge server runtimes
354
+ * have none of these and correctly return false.
355
+ */
356
+ function isBrowserLikeRuntime() {
357
+ if (typeof window !== "undefined") return true;
358
+ const g = globalThis;
359
+ if (g.WorkerGlobalScope && g.self instanceof g.WorkerGlobalScope) return true;
360
+ return typeof g.importScripts === "function";
361
+ }
362
+ /**
363
+ * Refuse to use a `clientSecret` in a browser/client-side context (보안 리뷰 F-3).
364
+ *
365
+ * The client secret is a long-lived **admin** credential — it grants `scope=['*']`
366
+ * and can mint scoped tokens. Embedding it in a client bundle (e.g. a
367
+ * `NEXT_PUBLIC_*` env var) or instantiating the SDK in a client component leaks
368
+ * full app access via the JS bundle *and* every outbound request header.
369
+ *
370
+ * Secure patterns:
371
+ * - **Server**: construct the SDK with `clientId` + `clientSecret`.
372
+ * - **Client**: mint a short-lived, scoped token on your server
373
+ * (`POST /api/v1/brandapp/{id}/token/mint`) and pass it as `{ token }` —
374
+ * no `clientSecret`. A token-only config is allowed in the browser.
375
+ *
376
+ * Called by the public entry points (`createReoptSDK`, `createBrandappProvider`);
377
+ * the Better Auth `createReoptAdapter`/`createReoptOAuth` keep their own
378
+ * server-only guards.
379
+ */
380
+ function assertBrowserSafe(config) {
381
+ if (isBrowserLikeRuntime() && config.clientSecret) throw new ReoptSDKError("[@reopt-ai/brandapp-sdk] clientSecret must not be used in the browser. It is a long-lived admin credential — exposing it client-side leaks full app access. Construct the SDK on the server with clientId/clientSecret, or for client-side use mint a short-lived token on your server (POST /api/v1/brandapp/{id}/token/mint) and pass it as `{ token }`.", 0, "CONFIG_BROWSER_SECRET", void 0, {
382
+ cause: "브라우저에서 clientSecret 사용 — 자격증명 유출 위험",
383
+ fix: "서버에서 단기 토큰을 발급해 `{ token }`으로 전달 (clientSecret 미포함)",
384
+ doc: "docs/environment.md"
385
+ });
386
+ }
387
+ function assertValidUrl(value, field, envVar) {
388
+ if (value == null) return;
389
+ try {
390
+ new URL(value);
391
+ } catch {
392
+ throw new ConfigInvalidError(`ReoptSDK: ${field} is not a valid URL: "${value}". Use an absolute URL like "https://brandapp.reopt.ai".`, envVar);
393
+ }
394
+ }
395
+ var ConfigError = class extends ReoptSDKError {
396
+ constructor(message, envVar) {
397
+ super(message, 0, "CONFIG_MISSING", void 0, {
398
+ cause: `${envVar} 환경변수가 설정되지 않음`,
399
+ fix: `.env 파일에 ${envVar}=... 추가. 값은 Studio → BrandApp → 설정 → OAuth 클라이언트에서 확인`,
400
+ envVar,
401
+ doc: "docs/errors.md#config_missing"
402
+ });
403
+ }
404
+ };
405
+ var ConfigInvalidError = class extends ReoptSDKError {
406
+ constructor(message, envVar) {
407
+ super(message, 0, "CONFIG_INVALID", void 0, {
408
+ cause: `${envVar} 값의 형식이 올바르지 않음`,
409
+ fix: "Studio → BrandApp → 설정에서 값을 다시 복사하거나, URL은 절대 경로(https://...)로 지정",
410
+ envVar,
411
+ doc: "docs/errors.md#config_invalid"
412
+ });
413
+ }
414
+ };
415
+ /**
416
+ * Read an env var safely — returns undefined in browser-like contexts where
417
+ * `process` is not defined. Trailing slashes are trimmed for consistency with
418
+ * the `config.baseUrl` handling below.
419
+ */
420
+ function readEnvUrl(name) {
421
+ if (typeof process === "undefined") return void 0;
422
+ const raw = process.env?.[name];
423
+ if (!raw) return void 0;
424
+ return raw.replace(/\/$/, "");
425
+ }
426
+ /**
427
+ * Resolve the main API base URL for the given SDK config. Priority:
428
+ *
429
+ * 1. `config.baseUrl` — explicit override
430
+ * 2. `REOPT_BASE_URL` env var — set this once and skip threading
431
+ * `baseUrl` through every `createReoptSDK()` call
432
+ * 3. default by `isProduction` / `NODE_ENV` (production →
433
+ * `brandapp.reopt.ai`, otherwise → `brand.reopt.de:3443`)
434
+ */
435
+ function resolveBaseUrl(config) {
436
+ if (config.baseUrl) return config.baseUrl.replace(/\/$/, "");
437
+ const envBaseUrl = readEnvUrl("REOPT_BASE_URL");
438
+ if (envBaseUrl) return envBaseUrl;
439
+ return config.isProduction ?? (typeof process !== "undefined" && process.env?.NODE_ENV === "production") ? REOPT_BASE_URLS.production : REOPT_BASE_URLS.development;
440
+ }
441
+ /**
442
+ * Resolve the id (auth) base URL for the given SDK config. Priority:
443
+ *
444
+ * 1. `config.idBaseUrl` — explicit override
445
+ * 2. `REOPT_ID_BASE_URL` env var — explicit override via env
446
+ * 3. derived from `config.baseUrl` when set (e.g. `www.reopt.ai` →
447
+ * `id.reopt.ai`)
448
+ * 4. derived from `REOPT_BASE_URL` env var when set — single env override
449
+ * covers both API and auth hosts
450
+ * 5. default by `isProduction` / `NODE_ENV`
451
+ *
452
+ * Use this whenever the SDK calls `/api/auth/*` (OIDC userinfo, Better Auth
453
+ * discovery, session) — those endpoints only exist on `id.reopt.ai`.
454
+ */
455
+ function resolveIdBaseUrl(config) {
456
+ if (config.idBaseUrl) return config.idBaseUrl.replace(/\/$/, "");
457
+ const envIdBaseUrl = readEnvUrl("REOPT_ID_BASE_URL");
458
+ if (envIdBaseUrl) return envIdBaseUrl;
459
+ if (config.baseUrl) return deriveIdFromBaseUrl(config.baseUrl);
460
+ const envBaseUrl = readEnvUrl("REOPT_BASE_URL");
461
+ if (envBaseUrl) return deriveIdFromBaseUrl(envBaseUrl);
462
+ return config.isProduction ?? (typeof process !== "undefined" && process.env?.NODE_ENV === "production") ? REOPT_ID_BASE_URLS.production : REOPT_ID_BASE_URLS.development;
463
+ }
464
+ /**
465
+ * Best-effort host transform — any reopt.{ai,io,de} subdomain folds to the
466
+ * shared id host for that environment. Custom hosts fall back to prepending
467
+ * `id.` (with a leading `www.` stripped).
468
+ */
469
+ function deriveIdFromBaseUrl(baseUrl) {
470
+ const clean = baseUrl.replace(/\/$/, "");
471
+ try {
472
+ const url = new URL(clean);
473
+ const { hostname } = url;
474
+ if (hostname === "reopt.ai" || hostname.endsWith(".reopt.ai")) return REOPT_ID_BASE_URLS.production;
475
+ if (hostname === "reopt.io" || hostname.endsWith(".reopt.io")) return "https://id.reopt.io";
476
+ if (hostname === "reopt.de" || hostname.endsWith(".reopt.de")) return REOPT_ID_BASE_URLS.development;
477
+ if (hostname.startsWith("id.")) return url.origin;
478
+ url.hostname = `id.${hostname.replace(/^www\./, "")}`;
479
+ return url.origin;
480
+ } catch {
481
+ return clean;
482
+ }
483
+ }
484
+
485
+ //#endregion
486
+ export { mapHttpStatusToError as A, ServerError as C, isReoptSDKError as D, isModelAccessError as E, isRequiredTermsError as O, RequiredTermsError as S, isCreditLimitError as T, ModelAccessError as _, resolveIdBaseUrl as a, RateLimitError as b, AuthUserNotFoundError as c, ConflictError as d, ContentFilterError as f, LimitExceededError as g, ForbiddenError as h, resolveBaseUrl as i, isValidationError as k, AuthUserRecordExistsError as l, DuplicateAuthUserError as m, SDK_VERSION as n, validateConfig as o, CreditLimitError as p, assertBrowserSafe as r, AuthError as s, REOPT_BASE_URLS as t, BadRequestError as u, ModelNotFoundError as v, ValidationError as w, ReoptSDKError as x, NotFoundError as y };
487
+ //# sourceMappingURL=config-Cw0a3-C8.js.map