@reopt-ai/brandapp-sdk 3.1.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 (104) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +39 -14
  3. package/dist/abort--nOBFN4M.js +50 -0
  4. package/dist/ai/index.d.ts +2 -314
  5. package/dist/ai/index.js +3 -7
  6. package/dist/ai-provider/index.d.ts +79 -163
  7. package/dist/ai-provider/index.js +752 -671
  8. package/dist/auth/index.d.ts +27 -27
  9. package/dist/auth/index.js +41 -33
  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 -133
  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 +105 -84
  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 -509
  37. package/dist/dev/index.js +2740 -2873
  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 -125
  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-DIAS8Rsl.d.ts → errors-CRCcErNC.d.ts} +55 -53
  48. package/dist/feedback/index.d.ts +2 -132
  49. package/dist/feedback/index.js +3 -5
  50. package/dist/files/index.d.ts +14 -14
  51. package/dist/files/index.js +41 -24
  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 -221
  56. package/dist/index.js +119 -70
  57. package/dist/logout/index.d.ts +109 -0
  58. package/dist/logout/index.js +264 -0
  59. package/dist/plans/index.d.ts +2 -236
  60. package/dist/plans/index.js +3 -5
  61. package/dist/push/index.d.ts +2 -79
  62. package/dist/push/index.js +3 -5
  63. package/dist/query-BvbCiGWb.js +35 -0
  64. package/dist/react/hooks.d.ts +97 -95
  65. package/dist/react/hooks.js +742 -356
  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 -5
  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 -47
  76. package/dist/webhooks/index.js +150 -127
  77. package/docs/api-reference.md +179 -2
  78. package/docs/dev-server.md +19 -18
  79. package/docs/errors.md +72 -15
  80. package/docs/logout.md +166 -0
  81. package/package.json +10 -5
  82. package/dist/chunk-2Q654O63.js +0 -350
  83. package/dist/chunk-F7BXBTZI.js +0 -54
  84. package/dist/chunk-IJOXTBIE.js +0 -599
  85. package/dist/chunk-JWXUVQRC.js +0 -157
  86. package/dist/chunk-L4DHB36G.js +0 -75
  87. package/dist/chunk-MRQY45U5.js +0 -465
  88. package/dist/chunk-N5JVE4WX.js +0 -449
  89. package/dist/chunk-O3PUWIDJ.js +0 -105
  90. package/dist/chunk-POLKEOYH.js +0 -63
  91. package/dist/chunk-R5CCGDUH.js +0 -49
  92. package/dist/chunk-RBHP7IZF.js +0 -96
  93. package/dist/chunk-REIKXSMY.js +0 -7
  94. package/dist/chunk-T7YTITRJ.js +0 -112
  95. package/dist/chunk-V73GORO3.js +0 -81
  96. package/dist/chunk-VRNBYSWU.js +0 -32
  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,703 +1,784 @@
1
- import { createSSELineProcessor } from '../chunk-L4DHB36G.js';
2
- import { createManagedAbort } from '../chunk-F7BXBTZI.js';
3
- import { assertBrowserSafe, validateConfig, resolveBaseUrl, createAuthHeader, SDK_VERSION, mapHttpStatusToError } from '../chunk-MRQY45U5.js';
4
- import { NoSuchModelError, APICallError } from '@ai-sdk/provider';
1
+ import { A as mapHttpStatusToError, i as resolveBaseUrl, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-Cw0a3-C8.js";
2
+ import { t as createManagedAbort } from "../abort--nOBFN4M.js";
3
+ import { t as createAuthHeader } from "../encoding-Bwfm3iaE.js";
4
+ import { t as createSSELineProcessor } from "../sse-parser-FMjxM7sY.js";
5
+ import { APICallError, NoSuchModelError } from "@ai-sdk/provider";
5
6
 
7
+ //#region src/ai-provider/provider-http.ts
8
+ /**
9
+ * Shared HTTP utilities for BrandApp AI provider models.
10
+ *
11
+ * Used by BrandappLanguageModel and BrandappImageModel to avoid duplication.
12
+ */
13
+ /** Per-request id for X-Request-Id / Idempotency-Key + error correlation. */
6
14
  function newRequestId(sdkVersion) {
7
- return globalThis.crypto?.randomUUID?.() ?? `sdk-${sdkVersion}-${Date.now()}`;
15
+ return globalThis.crypto?.randomUUID?.() ?? `sdk-${sdkVersion}-${Date.now()}`;
8
16
  }
17
+ /**
18
+ * Call-invariant base headers (auth + content-type + SDK version). Compute
19
+ * once per model and reuse via {@link mergeProviderHeaders} — these don't
20
+ * change between requests.
21
+ */
9
22
  function buildBaseProviderHeaders(config) {
10
- return {
11
- Authorization: config.authHeader,
12
- "Content-Type": "application/json",
13
- "X-SDK-Version": `brandapp-sdk/${config.sdkVersion}`
14
- };
23
+ return {
24
+ Authorization: config.authHeader,
25
+ "Content-Type": "application/json",
26
+ "X-SDK-Version": `brandapp-sdk/${config.sdkVersion}`
27
+ };
15
28
  }
29
+ /** Merge per-call headers onto a base, dropping `undefined` values. */
16
30
  function mergeProviderHeaders(base, extraHeaders) {
17
- if (!extraHeaders) return { ...base };
18
- const headers = { ...base };
19
- for (const [key, value] of Object.entries(extraHeaders)) {
20
- if (value !== void 0) {
21
- headers[key] = value;
22
- }
23
- }
24
- return headers;
31
+ if (!extraHeaders) return { ...base };
32
+ const headers = { ...base };
33
+ for (const [key, value] of Object.entries(extraHeaders)) if (value !== void 0) headers[key] = value;
34
+ return headers;
25
35
  }
36
+ /**
37
+ * Convenience: base + per-call merge in one call. Kept for the image model,
38
+ * which builds a fresh header set per request.
39
+ */
26
40
  function buildProviderHeaders(config, extraHeaders) {
27
- return mergeProviderHeaders(buildBaseProviderHeaders(config), extraHeaders);
41
+ return mergeProviderHeaders(buildBaseProviderHeaders(config), extraHeaders);
28
42
  }
43
+ /**
44
+ * fetch with a hard deadline that covers the **entire** transfer — headers AND
45
+ * body. A plain fetch + timeout that clears once headers arrive leaves the body
46
+ * read (`.json()`/`.arrayBuffer()`) unbounded, so a server that sends headers
47
+ * then stalls the body hangs forever. We buffer the body inside the timeout
48
+ * window (the abort signal aborts a stalled read) and hand back a `Response`
49
+ * over the buffered bytes, so callers keep calling `.json()`/`.arrayBuffer()`
50
+ * unchanged — now non-blocking. Non-streaming reads only (both AI-provider
51
+ * callers consume the full body).
52
+ */
29
53
  async function fetchWithTimeout(config, fetchFn, url, init) {
30
- const controller = new AbortController();
31
- const existingSignal = init.signal;
32
- const onAbort = () => controller.abort(existingSignal.reason);
33
- if (existingSignal) {
34
- existingSignal.addEventListener("abort", onAbort);
35
- }
36
- const timeoutId = setTimeout(
37
- () => controller.abort(new Error("Request timed out")),
38
- config.timeout
39
- );
40
- try {
41
- return await fetchFn(url, {
42
- ...init,
43
- signal: controller.signal
44
- });
45
- } finally {
46
- clearTimeout(timeoutId);
47
- existingSignal?.removeEventListener("abort", onAbort);
48
- }
54
+ const controller = new AbortController();
55
+ const existingSignal = init.signal;
56
+ const onAbort = () => controller.abort(existingSignal.reason);
57
+ if (existingSignal) existingSignal.addEventListener("abort", onAbort);
58
+ const timeoutId = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Request timed out")), config.timeout);
59
+ try {
60
+ const response = await fetchFn(url, {
61
+ ...init,
62
+ signal: controller.signal
63
+ });
64
+ const buffer = response.body !== null ? await response.arrayBuffer() : null;
65
+ const headers = new Headers(response.headers);
66
+ headers.delete("content-encoding");
67
+ headers.delete("content-length");
68
+ return new Response(buffer, {
69
+ status: response.status,
70
+ statusText: response.statusText,
71
+ headers
72
+ });
73
+ } finally {
74
+ clearTimeout(timeoutId);
75
+ existingSignal?.removeEventListener("abort", onAbort);
76
+ }
49
77
  }
78
+ /**
79
+ * 비-OK 응답을 AI SDK의 `APICallError`로 throw한다.
80
+ *
81
+ * - `APICallError`라서 AI SDK의 내장 재시도(`isRetryable`)·에러 분류가 동작한다.
82
+ * - `cause`에 typed `ReoptSDKError`, `data`에 `{ code, diagnostic }`를 실어
83
+ * `sdk.ai.*` 경로와 **동일한 코드/진단**을 노출한다(공유 mapper 사용).
84
+ * 소비처: `err.data?.code`, `err.data?.diagnostic`, `err.cause`(ReoptSDKError).
85
+ */
50
86
  async function throwProviderApiError(response, url, requestBodyValues, requestId) {
51
- const body = await response.json().catch(() => ({}));
52
- const code = body.error?.code;
53
- const message = body.error?.message ?? `HTTP ${response.status}`;
54
- const reoptError = mapHttpStatusToError(response.status, code, message, {
55
- method: "POST",
56
- url,
57
- requestId
58
- });
59
- throw new APICallError({
60
- message: reoptError.message,
61
- url,
62
- requestBodyValues,
63
- statusCode: response.status,
64
- responseHeaders: extractResponseHeaders(response),
65
- responseBody: JSON.stringify(body),
66
- isRetryable: response.status === 429 || response.status >= 500,
67
- data: {
68
- code: reoptError.code,
69
- diagnostic: reoptError.diagnostic,
70
- reoptError
71
- },
72
- cause: reoptError
73
- });
87
+ const body = await response.json().catch(() => ({}));
88
+ const code = body.error?.code;
89
+ const message = body.error?.message ?? `HTTP ${response.status}`;
90
+ const reoptError = mapHttpStatusToError(response.status, code, message, {
91
+ method: "POST",
92
+ url,
93
+ requestId
94
+ });
95
+ throw new APICallError({
96
+ message: reoptError.message,
97
+ url,
98
+ requestBodyValues,
99
+ statusCode: response.status,
100
+ responseHeaders: extractResponseHeaders(response),
101
+ responseBody: JSON.stringify(body),
102
+ isRetryable: response.status === 429 || response.status >= 500,
103
+ data: {
104
+ code: reoptError.code,
105
+ diagnostic: reoptError.diagnostic,
106
+ reoptError
107
+ },
108
+ cause: reoptError
109
+ });
74
110
  }
75
111
  function extractResponseHeaders(response) {
76
- const headers = {};
77
- response.headers.forEach((value, key) => {
78
- headers[key] = value;
79
- });
80
- return headers;
112
+ const headers = {};
113
+ response.headers.forEach((value, key) => {
114
+ headers[key] = value;
115
+ });
116
+ return headers;
81
117
  }
82
118
 
83
- // src/ai-provider/brandapp-image-model.ts
119
+ //#endregion
120
+ //#region src/ai-provider/brandapp-image-model.ts
84
121
  var BrandappImageModel = class {
85
- specificationVersion = "v3";
86
- provider = "brandapp";
87
- modelId;
88
- // BrandApp API emits exactly one image per request. AI SDK honors this by
89
- // calling `doGenerate({ n: 1 })` repeatedly when the caller asks for n>1.
90
- // The `Promise.all(n)` fan-out in `doGenerate` covers direct callers who
91
- // skip the AI SDK layer and pass `n>1` themselves.
92
- maxImagesPerCall = 1;
93
- config;
94
- constructor(modelId, config) {
95
- this.modelId = modelId;
96
- this.config = config;
97
- }
98
- // -----------------------------------------------------------------------
99
- // doGenerate — 이미지 생성
100
- // -----------------------------------------------------------------------
101
- async doGenerate(options) {
102
- const warnings = this.collectWarnings(options);
103
- const brandappOptions = options.providerOptions?.brandapp;
104
- const body = {
105
- prompt: options.prompt,
106
- model: this.modelId,
107
- // providerOptions.brandapp.aspectRatio → top-level aspectRatio → "1:1".
108
- aspectRatio: brandappOptions?.aspectRatio ?? options.aspectRatio ?? "1:1",
109
- customerId: brandappOptions?.customerId ?? this.config.customerId
110
- };
111
- if (brandappOptions?.negativePrompt) {
112
- body.negativePrompt = brandappOptions.negativePrompt;
113
- }
114
- if (brandappOptions?.style) {
115
- body.style = brandappOptions.style;
116
- }
117
- const fetchFn = this.config.fetch ?? globalThis.fetch;
118
- const count = Math.max(1, options.n);
119
- const url = `${this.config.baseUrl}/images/generate`;
120
- const generateOne = async () => {
121
- const requestId = newRequestId(this.config.sdkVersion);
122
- const response = await fetchWithTimeout(this.config, fetchFn, url, {
123
- method: "POST",
124
- headers: mergeProviderHeaders(
125
- buildProviderHeaders(this.config, options.headers),
126
- {
127
- "X-Request-Id": requestId,
128
- "Idempotency-Key": requestId
129
- }
130
- ),
131
- body: JSON.stringify(body),
132
- signal: options.abortSignal
133
- });
134
- if (!response.ok) {
135
- await throwProviderApiError(response, url, body, requestId);
136
- }
137
- const json = await response.json();
138
- const { data } = json;
139
- const imageResponse = await fetchWithTimeout(
140
- this.config,
141
- fetchFn,
142
- data.url,
143
- {
144
- method: "GET",
145
- signal: options.abortSignal
146
- }
147
- );
148
- const imageBuffer = await imageResponse.arrayBuffer();
149
- const base64 = arrayBufferToBase64(new Uint8Array(imageBuffer));
150
- return {
151
- base64,
152
- meta: {
153
- id: data.id,
154
- url: data.url,
155
- size: data.size,
156
- contentType: data.contentType,
157
- creditCost: data.usage.creditCost,
158
- creditsRemaining: data.creditsRemaining
159
- },
160
- responseHeaders: extractResponseHeaders(response)
161
- };
162
- };
163
- const results = await Promise.all(
164
- Array.from({ length: count }, () => generateOne())
165
- );
166
- const images = results.map((r) => r.base64);
167
- const perImageMetadata = results.map((r) => r.meta);
168
- const lastResponseHeaders = results[results.length - 1]?.responseHeaders;
169
- return {
170
- images,
171
- warnings,
172
- providerMetadata: {
173
- brandapp: {
174
- images: perImageMetadata
175
- }
176
- },
177
- response: {
178
- timestamp: /* @__PURE__ */ new Date(),
179
- modelId: this.modelId,
180
- headers: lastResponseHeaders
181
- }
182
- };
183
- }
184
- // -----------------------------------------------------------------------
185
- // 경고 수집 — 미지원 기능 보고
186
- // -----------------------------------------------------------------------
187
- collectWarnings(options) {
188
- const warnings = [];
189
- if (options.size != null) {
190
- warnings.push({
191
- type: "unsupported",
192
- feature: "size",
193
- details: "BrandApp AI API uses aspectRatio instead of size. Use aspectRatio parameter."
194
- });
195
- }
196
- if (options.seed != null) {
197
- warnings.push({
198
- type: "unsupported",
199
- feature: "seed",
200
- details: "BrandApp AI API does not support seed parameter"
201
- });
202
- }
203
- if (options.files?.length) {
204
- warnings.push({
205
- type: "unsupported",
206
- feature: "files",
207
- details: "BrandApp AI API does not support image editing or variation generation"
208
- });
209
- }
210
- if (options.mask != null) {
211
- warnings.push({
212
- type: "unsupported",
213
- feature: "mask",
214
- details: "BrandApp AI API does not support inpainting masks"
215
- });
216
- }
217
- return warnings;
218
- }
122
+ specificationVersion = "v3";
123
+ provider = "brandapp";
124
+ modelId;
125
+ maxImagesPerCall = 1;
126
+ config;
127
+ constructor(modelId, config) {
128
+ this.modelId = modelId;
129
+ this.config = config;
130
+ }
131
+ async doGenerate(options) {
132
+ const warnings = this.collectWarnings(options);
133
+ const brandappOptions = options.providerOptions?.brandapp;
134
+ const body = {
135
+ prompt: options.prompt,
136
+ model: this.modelId,
137
+ aspectRatio: brandappOptions?.aspectRatio ?? options.aspectRatio ?? "1:1",
138
+ customerId: brandappOptions?.customerId ?? this.config.customerId
139
+ };
140
+ if (brandappOptions?.negativePrompt) body.negativePrompt = brandappOptions.negativePrompt;
141
+ if (brandappOptions?.style) body.style = brandappOptions.style;
142
+ const fetchFn = this.config.fetch ?? globalThis.fetch;
143
+ const count = Math.max(1, options.n);
144
+ const url = `${this.config.baseUrl}/images/generate`;
145
+ const generateOne = async () => {
146
+ const requestId = newRequestId(this.config.sdkVersion);
147
+ const response = await fetchWithTimeout(this.config, fetchFn, url, {
148
+ method: "POST",
149
+ headers: mergeProviderHeaders(buildProviderHeaders(this.config, options.headers), {
150
+ "X-Request-Id": requestId,
151
+ "Idempotency-Key": requestId
152
+ }),
153
+ body: JSON.stringify(body),
154
+ signal: options.abortSignal
155
+ });
156
+ if (!response.ok) await throwProviderApiError(response, url, body, requestId);
157
+ const { data } = await response.json();
158
+ const imageResponse = await fetchWithTimeout(this.config, fetchFn, data.url, {
159
+ method: "GET",
160
+ signal: options.abortSignal
161
+ });
162
+ if (!imageResponse.ok) await throwProviderApiError(imageResponse, data.url, body, requestId);
163
+ const imageBuffer = await imageResponse.arrayBuffer();
164
+ return {
165
+ base64: arrayBufferToBase64(new Uint8Array(imageBuffer)),
166
+ meta: {
167
+ id: data.id,
168
+ url: data.url,
169
+ size: data.size,
170
+ contentType: data.contentType,
171
+ creditCost: data.usage.creditCost,
172
+ creditsRemaining: data.creditsRemaining
173
+ },
174
+ responseHeaders: extractResponseHeaders(response)
175
+ };
176
+ };
177
+ const results = await Promise.all(Array.from({ length: count }, () => generateOne()));
178
+ const images = results.map((r) => r.base64);
179
+ const perImageMetadata = results.map((r) => r.meta);
180
+ const lastResponseHeaders = results[results.length - 1]?.responseHeaders;
181
+ return {
182
+ images,
183
+ warnings,
184
+ providerMetadata: { brandapp: { images: perImageMetadata } },
185
+ response: {
186
+ timestamp: /* @__PURE__ */ new Date(),
187
+ modelId: this.modelId,
188
+ headers: lastResponseHeaders
189
+ }
190
+ };
191
+ }
192
+ collectWarnings(options) {
193
+ const warnings = [];
194
+ if (options.size != null) warnings.push({
195
+ type: "unsupported",
196
+ feature: "size",
197
+ details: "BrandApp AI API uses aspectRatio instead of size. Use aspectRatio parameter."
198
+ });
199
+ if (options.seed != null) warnings.push({
200
+ type: "unsupported",
201
+ feature: "seed",
202
+ details: "BrandApp AI API does not support seed parameter"
203
+ });
204
+ if (options.files?.length) warnings.push({
205
+ type: "unsupported",
206
+ feature: "files",
207
+ details: "BrandApp AI API does not support image editing or variation generation"
208
+ });
209
+ if (options.mask != null) warnings.push({
210
+ type: "unsupported",
211
+ feature: "mask",
212
+ details: "BrandApp AI API does not support inpainting masks"
213
+ });
214
+ return warnings;
215
+ }
219
216
  };
220
217
  function arrayBufferToBase64(bytes) {
221
- const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
222
- return btoa(binString);
218
+ const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
219
+ return btoa(binString);
223
220
  }
224
221
 
225
- // src/ai-provider/convert-prompt.ts
222
+ //#endregion
223
+ //#region src/ai-provider/convert-prompt.ts
224
+ /**
225
+ * AI SDK 프롬프트 → BrandApp API 메시지 배열 (+ 손실 변환 보고).
226
+ *
227
+ * BrandApp API는 텍스트 전용이라 비-text part는 손실된다. 무엇이 손실됐는지를
228
+ * `droppedParts`로 돌려줘 호출자(language model)가 `warnings`로 **소리내어** 알리게
229
+ * 한다(과거엔 file/image 입력이 조용히 사라졌다).
230
+ *
231
+ * - system: content 문자열 그대로
232
+ * - user: text part만 추출하여 결합 / file part는 드롭("file" 보고)
233
+ * - assistant: text + tool-call을 텍스트로 표현("tool-call" 보고)
234
+ * - tool: tool-result를 user 메시지 텍스트로 변환("tool-result" 보고)
235
+ */
226
236
  function convertPromptToBrandappMessages(prompt) {
227
- const messages = [];
228
- const dropped = /* @__PURE__ */ new Set();
229
- for (const message of prompt) {
230
- switch (message.role) {
231
- case "system": {
232
- messages.push({ role: "system", content: message.content });
233
- break;
234
- }
235
- case "user": {
236
- const textParts = [];
237
- for (const part of message.content) {
238
- if (part.type === "text") {
239
- textParts.push(part.text);
240
- } else {
241
- dropped.add("file");
242
- }
243
- }
244
- if (textParts.length > 0) {
245
- messages.push({ role: "user", content: textParts.join("\n") });
246
- }
247
- break;
248
- }
249
- case "assistant": {
250
- const textParts = message.content.filter(
251
- (part) => part.type === "text"
252
- ).map((part) => part.text);
253
- const toolCallParts = message.content.filter(
254
- (part) => part.type === "tool-call"
255
- ).map(
256
- (part) => `[Tool Call: ${part.toolName}(${typeof part.input === "string" ? part.input : JSON.stringify(part.input)})]`
257
- );
258
- if (toolCallParts.length > 0) dropped.add("tool-call");
259
- const allText = [...textParts, ...toolCallParts].join("\n");
260
- if (allText.length > 0) {
261
- messages.push({ role: "assistant", content: allText });
262
- }
263
- break;
264
- }
265
- case "tool": {
266
- const resultParts = message.content.filter(
267
- (part) => part.type === "tool-result"
268
- ).map((part) => {
269
- const output = typeof part.output === "string" ? part.output : JSON.stringify(part.output);
270
- return `[Tool Result: ${part.toolName}] ${output}`;
271
- });
272
- if (resultParts.length > 0) {
273
- dropped.add("tool-result");
274
- messages.push({ role: "user", content: resultParts.join("\n") });
275
- }
276
- break;
277
- }
278
- }
279
- }
280
- return { messages, droppedParts: [...dropped] };
237
+ const messages = [];
238
+ const dropped = /* @__PURE__ */ new Set();
239
+ for (const message of prompt) switch (message.role) {
240
+ case "system":
241
+ messages.push({
242
+ role: "system",
243
+ content: message.content
244
+ });
245
+ break;
246
+ case "user": {
247
+ const textParts = [];
248
+ for (const part of message.content) if (part.type === "text") textParts.push(part.text);
249
+ else dropped.add("file");
250
+ if (textParts.length > 0) messages.push({
251
+ role: "user",
252
+ content: textParts.join("\n")
253
+ });
254
+ break;
255
+ }
256
+ case "assistant": {
257
+ const textParts = message.content.filter((part) => part.type === "text").map((part) => part.text);
258
+ const toolCallParts = message.content.filter((part) => part.type === "tool-call").map((part) => `[Tool Call: ${part.toolName}(${typeof part.input === "string" ? part.input : JSON.stringify(part.input)})]`);
259
+ if (toolCallParts.length > 0) dropped.add("tool-call");
260
+ const allText = [...textParts, ...toolCallParts].join("\n");
261
+ if (allText.length > 0) messages.push({
262
+ role: "assistant",
263
+ content: allText
264
+ });
265
+ break;
266
+ }
267
+ case "tool": {
268
+ const resultParts = message.content.filter((part) => part.type === "tool-result").map((part) => {
269
+ const output = typeof part.output === "string" ? part.output : JSON.stringify(part.output);
270
+ return `[Tool Result: ${part.toolName}] ${output}`;
271
+ });
272
+ if (resultParts.length > 0) {
273
+ dropped.add("tool-result");
274
+ messages.push({
275
+ role: "user",
276
+ content: resultParts.join("\n")
277
+ });
278
+ }
279
+ break;
280
+ }
281
+ }
282
+ return {
283
+ messages,
284
+ droppedParts: [...dropped]
285
+ };
281
286
  }
282
287
 
283
- // src/ai-provider/brandapp-language-model.ts
288
+ //#endregion
289
+ //#region src/ai-provider/brandapp-language-model.ts
284
290
  var BrandappLanguageModel = class {
285
- specificationVersion = "v3";
286
- provider = "brandapp";
287
- modelId;
288
- supportedUrls = {};
289
- config;
290
- /** Call-invariant headers, frozen once per model instead of per request. */
291
- baseHeaders;
292
- constructor(modelId, config) {
293
- this.modelId = modelId;
294
- this.config = config;
295
- this.baseHeaders = buildBaseProviderHeaders(config);
296
- }
297
- // -----------------------------------------------------------------------
298
- // doGenerate — Non-streaming
299
- // -----------------------------------------------------------------------
300
- async doGenerate(options) {
301
- const { messages, droppedParts } = convertPromptToBrandappMessages(
302
- options.prompt
303
- );
304
- const warnings = this.collectWarnings(options, droppedParts);
305
- const body = this.buildRequestBody(options, false, messages);
306
- const fetchFn = this.config.fetch ?? globalThis.fetch;
307
- const url = `${this.config.baseUrl}/chat/completions`;
308
- const requestId = newRequestId(this.config.sdkVersion);
309
- const response = await fetchWithTimeout(this.config, fetchFn, url, {
310
- method: "POST",
311
- headers: mergeProviderHeaders(this.baseHeaders, {
312
- ...options.headers,
313
- "X-Request-Id": requestId,
314
- "Idempotency-Key": requestId
315
- }),
316
- body: JSON.stringify(body),
317
- signal: options.abortSignal
318
- });
319
- if (!response.ok) {
320
- await throwProviderApiError(response, url, body, requestId);
321
- }
322
- const json = await response.json();
323
- const { data } = json;
324
- const responseHeaders = extractResponseHeaders(response);
325
- return {
326
- content: [{ type: "text", text: data.message.content }],
327
- // 서버가 finishReason을 보고하면 그대로, 미보고 시 정상 종료(stop)로 폴백.
328
- // raw 키는 LanguageModelV3FinishReason에서 필수 — 명시 제공.
329
- finishReason: data.finishReason ? { unified: data.finishReason.unified, raw: data.finishReason.raw } : { unified: "stop", raw: "stop" },
330
- usage: {
331
- inputTokens: {
332
- total: data.usage.promptTokens,
333
- noCache: void 0,
334
- cacheRead: void 0,
335
- cacheWrite: void 0
336
- },
337
- outputTokens: {
338
- total: data.usage.completionTokens,
339
- text: void 0,
340
- reasoning: void 0
341
- }
342
- },
343
- providerMetadata: {
344
- brandapp: {
345
- creditCost: data.usage.creditCost,
346
- creditsRemaining: data.creditsRemaining,
347
- responseId: data.id
348
- }
349
- },
350
- request: { body },
351
- response: {
352
- headers: responseHeaders,
353
- body: json,
354
- modelId: data.model
355
- },
356
- warnings
357
- };
358
- }
359
- // -----------------------------------------------------------------------
360
- // doStream — SSE Streaming
361
- // -----------------------------------------------------------------------
362
- async doStream(options) {
363
- const { messages, droppedParts } = convertPromptToBrandappMessages(
364
- options.prompt
365
- );
366
- const warnings = this.collectWarnings(options, droppedParts);
367
- const body = this.buildRequestBody(options, true, messages);
368
- const fetchFn = this.config.fetch ?? globalThis.fetch;
369
- const url = `${this.config.baseUrl}/chat/completions`;
370
- const requestId = newRequestId(this.config.sdkVersion);
371
- const managed = createManagedAbort({
372
- timeoutMs: this.config.timeout,
373
- external: options.abortSignal,
374
- idle: true
375
- });
376
- let response;
377
- try {
378
- response = await fetchFn(url, {
379
- method: "POST",
380
- headers: mergeProviderHeaders(this.baseHeaders, {
381
- ...options.headers,
382
- Accept: "text/event-stream",
383
- "X-Request-Id": requestId,
384
- "Idempotency-Key": requestId
385
- }),
386
- body: JSON.stringify(body),
387
- signal: managed.signal
388
- });
389
- } catch (e) {
390
- managed.cleanup();
391
- throw e;
392
- }
393
- if (!response.ok) {
394
- managed.cleanup();
395
- await throwProviderApiError(response, url, body, requestId);
396
- }
397
- const responseHeaders = extractResponseHeaders(response);
398
- if (!response.body) {
399
- managed.cleanup();
400
- throw new Error(
401
- "BrandApp AI API returned no response body for streaming"
402
- );
403
- }
404
- const stream = this.createStreamPartTransform(
405
- response.body,
406
- warnings,
407
- managed,
408
- options.includeRawChunks
409
- );
410
- return {
411
- stream,
412
- request: { body },
413
- response: { headers: responseHeaders }
414
- };
415
- }
416
- // -----------------------------------------------------------------------
417
- // 요청 빌드
418
- // -----------------------------------------------------------------------
419
- buildRequestBody(options, stream, messages) {
420
- const brandappOptions = options.providerOptions?.brandapp;
421
- return {
422
- model: this.modelId,
423
- messages,
424
- maxTokens: options.maxOutputTokens,
425
- temperature: options.temperature,
426
- stream,
427
- customerId: brandappOptions?.customerId ?? this.config.customerId
428
- };
429
- }
430
- // -----------------------------------------------------------------------
431
- // 경고 수집 — 미지원 기능 보고
432
- // -----------------------------------------------------------------------
433
- collectWarnings(options, droppedParts = []) {
434
- const warnings = [];
435
- for (const part of droppedParts) {
436
- warnings.push({
437
- type: "unsupported",
438
- feature: part === "file" ? "image/file input" : part,
439
- details: part === "file" ? "BrandApp AI API\uB294 \uD14D\uC2A4\uD2B8 \uC804\uC6A9\uC785\uB2C8\uB2E4 \u2014 \uC774\uBBF8\uC9C0/\uD30C\uC77C \uC785\uB825\uC740 \uBB34\uC2DC\uB429\uB2C8\uB2E4." : `BrandApp AI API does not support ${part} parts natively; converted to text (lossy).`
440
- });
441
- }
442
- if (options.topP != null) {
443
- warnings.push({
444
- type: "unsupported",
445
- feature: "topP",
446
- details: "BrandApp AI API does not support topP parameter"
447
- });
448
- }
449
- if (options.topK != null) {
450
- warnings.push({
451
- type: "unsupported",
452
- feature: "topK",
453
- details: "BrandApp AI API does not support topK parameter"
454
- });
455
- }
456
- if (options.frequencyPenalty != null) {
457
- warnings.push({
458
- type: "unsupported",
459
- feature: "frequencyPenalty",
460
- details: "BrandApp AI API does not support frequencyPenalty parameter"
461
- });
462
- }
463
- if (options.presencePenalty != null) {
464
- warnings.push({
465
- type: "unsupported",
466
- feature: "presencePenalty",
467
- details: "BrandApp AI API does not support presencePenalty parameter"
468
- });
469
- }
470
- if (options.stopSequences?.length) {
471
- warnings.push({
472
- type: "unsupported",
473
- feature: "stopSequences",
474
- details: "BrandApp AI API does not support stopSequences parameter"
475
- });
476
- }
477
- if (options.responseFormat?.type === "json") {
478
- warnings.push({
479
- type: "unsupported",
480
- feature: "responseFormat",
481
- details: "BrandApp AI API does not support JSON response format directly. Use prompt engineering instead."
482
- });
483
- }
484
- if (options.tools?.length) {
485
- warnings.push({
486
- type: "unsupported",
487
- feature: "tools",
488
- details: "BrandApp AI API does not support tool calling. Tools will be ignored."
489
- });
490
- }
491
- if (options.seed != null) {
492
- warnings.push({
493
- type: "unsupported",
494
- feature: "seed",
495
- details: "BrandApp AI API does not support seed parameter"
496
- });
497
- }
498
- return warnings;
499
- }
500
- // -----------------------------------------------------------------------
501
- // SSE 스트림 파싱 → ReadableStream<LanguageModelV3StreamPart>
502
- // -----------------------------------------------------------------------
503
- createStreamPartTransform(body, warnings, managed, includeRawChunks) {
504
- const decoder = new TextDecoder();
505
- const modelId = this.modelId;
506
- let emittedStreamStart = false;
507
- let emittedTextStart = false;
508
- let emittedTextEnd = false;
509
- let emittedFinish = false;
510
- const textId = "text-0";
511
- function processSSEEvent({ event, data }, controller) {
512
- if (includeRawChunks) {
513
- controller.enqueue({ type: "raw", rawValue: { event, data } });
514
- }
515
- switch (event) {
516
- case "text-delta": {
517
- if (!emittedTextStart) {
518
- controller.enqueue({ type: "text-start", id: textId });
519
- emittedTextStart = true;
520
- }
521
- controller.enqueue({ type: "text-delta", id: textId, delta: data });
522
- break;
523
- }
524
- case "done": {
525
- if (emittedTextStart && !emittedTextEnd) {
526
- controller.enqueue({ type: "text-end", id: textId });
527
- emittedTextEnd = true;
528
- }
529
- try {
530
- const meta = JSON.parse(data);
531
- controller.enqueue({
532
- type: "finish",
533
- usage: {
534
- inputTokens: {
535
- total: meta.usage.promptTokens,
536
- noCache: void 0,
537
- cacheRead: void 0,
538
- cacheWrite: void 0
539
- },
540
- outputTokens: {
541
- total: meta.usage.completionTokens,
542
- text: void 0,
543
- reasoning: void 0
544
- }
545
- },
546
- finishReason: meta.finishReason ? {
547
- unified: meta.finishReason.unified,
548
- raw: meta.finishReason.raw
549
- } : { unified: "stop", raw: "stop" },
550
- providerMetadata: {
551
- brandapp: {
552
- creditCost: meta.usage.creditCost,
553
- creditsRemaining: meta.creditsRemaining
554
- }
555
- }
556
- });
557
- } catch {
558
- controller.enqueue({
559
- type: "finish",
560
- usage: {
561
- inputTokens: {
562
- total: void 0,
563
- noCache: void 0,
564
- cacheRead: void 0,
565
- cacheWrite: void 0
566
- },
567
- outputTokens: {
568
- total: void 0,
569
- text: void 0,
570
- reasoning: void 0
571
- }
572
- },
573
- finishReason: { unified: "stop", raw: "stop" }
574
- });
575
- }
576
- emittedFinish = true;
577
- break;
578
- }
579
- case "error": {
580
- try {
581
- const err = JSON.parse(data);
582
- const mapped = typeof err.status === "number" ? mapHttpStatusToError(err.status, err.code, err.message) : new Error(err.message ?? "Stream error");
583
- controller.enqueue({ type: "error", error: mapped });
584
- } catch {
585
- controller.enqueue({ type: "error", error: new Error(data) });
586
- }
587
- break;
588
- }
589
- }
590
- }
591
- let processor;
592
- return body.pipeThrough(
593
- new TransformStream({
594
- transform(chunk, controller) {
595
- managed.kick();
596
- if (!emittedStreamStart) {
597
- controller.enqueue({ type: "stream-start", warnings });
598
- controller.enqueue({
599
- type: "response-metadata",
600
- timestamp: /* @__PURE__ */ new Date(),
601
- modelId
602
- });
603
- emittedStreamStart = true;
604
- }
605
- if (!processor) {
606
- processor = createSSELineProcessor((sseEvent) => {
607
- processSSEEvent(sseEvent, controller);
608
- });
609
- }
610
- processor.feed(decoder.decode(chunk, { stream: true }));
611
- },
612
- flush(controller) {
613
- managed.cleanup();
614
- if (!emittedStreamStart) {
615
- controller.enqueue({ type: "stream-start", warnings });
616
- }
617
- if (emittedTextStart && !emittedTextEnd) {
618
- controller.enqueue({ type: "text-end", id: textId });
619
- }
620
- if (!emittedFinish) {
621
- controller.enqueue({
622
- type: "finish",
623
- usage: {
624
- inputTokens: {
625
- total: void 0,
626
- noCache: void 0,
627
- cacheRead: void 0,
628
- cacheWrite: void 0
629
- },
630
- outputTokens: {
631
- total: void 0,
632
- text: void 0,
633
- reasoning: void 0
634
- }
635
- },
636
- finishReason: { unified: "error", raw: "incomplete_stream" }
637
- });
638
- }
639
- }
640
- })
641
- );
642
- }
291
+ specificationVersion = "v3";
292
+ provider = "brandapp";
293
+ modelId;
294
+ supportedUrls = {};
295
+ config;
296
+ /** Call-invariant headers, frozen once per model instead of per request. */
297
+ baseHeaders;
298
+ constructor(modelId, config) {
299
+ this.modelId = modelId;
300
+ this.config = config;
301
+ this.baseHeaders = buildBaseProviderHeaders(config);
302
+ }
303
+ async doGenerate(options) {
304
+ const { messages, droppedParts } = convertPromptToBrandappMessages(options.prompt);
305
+ const warnings = this.collectWarnings(options, droppedParts);
306
+ const body = this.buildRequestBody(options, false, messages);
307
+ const fetchFn = this.config.fetch ?? globalThis.fetch;
308
+ const url = `${this.config.baseUrl}/chat/completions`;
309
+ const requestId = newRequestId(this.config.sdkVersion);
310
+ const response = await fetchWithTimeout(this.config, fetchFn, url, {
311
+ method: "POST",
312
+ headers: mergeProviderHeaders(this.baseHeaders, {
313
+ ...options.headers,
314
+ "X-Request-Id": requestId,
315
+ "Idempotency-Key": requestId
316
+ }),
317
+ body: JSON.stringify(body),
318
+ signal: options.abortSignal
319
+ });
320
+ if (!response.ok) await throwProviderApiError(response, url, body, requestId);
321
+ const json = await response.json();
322
+ const { data } = json;
323
+ const responseHeaders = extractResponseHeaders(response);
324
+ return {
325
+ content: [{
326
+ type: "text",
327
+ text: data.message.content
328
+ }],
329
+ finishReason: data.finishReason ? {
330
+ unified: data.finishReason.unified,
331
+ raw: data.finishReason.raw
332
+ } : {
333
+ unified: "stop",
334
+ raw: "stop"
335
+ },
336
+ usage: {
337
+ inputTokens: {
338
+ total: data.usage.promptTokens,
339
+ noCache: void 0,
340
+ cacheRead: void 0,
341
+ cacheWrite: void 0
342
+ },
343
+ outputTokens: {
344
+ total: data.usage.completionTokens,
345
+ text: void 0,
346
+ reasoning: void 0
347
+ }
348
+ },
349
+ providerMetadata: { brandapp: {
350
+ creditCost: data.usage.creditCost,
351
+ creditsRemaining: data.creditsRemaining,
352
+ responseId: data.id
353
+ } },
354
+ request: { body },
355
+ response: {
356
+ headers: responseHeaders,
357
+ body: json,
358
+ modelId: data.model
359
+ },
360
+ warnings
361
+ };
362
+ }
363
+ async doStream(options) {
364
+ const { messages, droppedParts } = convertPromptToBrandappMessages(options.prompt);
365
+ const warnings = this.collectWarnings(options, droppedParts);
366
+ const body = this.buildRequestBody(options, true, messages);
367
+ const fetchFn = this.config.fetch ?? globalThis.fetch;
368
+ const url = `${this.config.baseUrl}/chat/completions`;
369
+ const requestId = newRequestId(this.config.sdkVersion);
370
+ const managed = createManagedAbort({
371
+ timeoutMs: this.config.timeout,
372
+ external: options.abortSignal,
373
+ idle: true
374
+ });
375
+ let response;
376
+ try {
377
+ response = await fetchFn(url, {
378
+ method: "POST",
379
+ headers: mergeProviderHeaders(this.baseHeaders, {
380
+ ...options.headers,
381
+ Accept: "text/event-stream",
382
+ "X-Request-Id": requestId,
383
+ "Idempotency-Key": requestId
384
+ }),
385
+ body: JSON.stringify(body),
386
+ signal: managed.signal
387
+ });
388
+ } catch (e) {
389
+ managed.cleanup();
390
+ throw e;
391
+ }
392
+ if (!response.ok) {
393
+ managed.cleanup();
394
+ await throwProviderApiError(response, url, body, requestId);
395
+ }
396
+ const responseHeaders = extractResponseHeaders(response);
397
+ if (!response.body) {
398
+ managed.cleanup();
399
+ throw new Error("BrandApp AI API returned no response body for streaming");
400
+ }
401
+ return {
402
+ stream: this.createStreamPartTransform(response.body, warnings, managed, options.includeRawChunks),
403
+ request: { body },
404
+ response: { headers: responseHeaders }
405
+ };
406
+ }
407
+ buildRequestBody(options, stream, messages) {
408
+ const brandappOptions = options.providerOptions?.brandapp;
409
+ return {
410
+ model: this.modelId,
411
+ messages,
412
+ maxTokens: options.maxOutputTokens,
413
+ temperature: options.temperature,
414
+ stream,
415
+ customerId: brandappOptions?.customerId ?? this.config.customerId
416
+ };
417
+ }
418
+ collectWarnings(options, droppedParts = []) {
419
+ const warnings = [];
420
+ for (const part of droppedParts) warnings.push({
421
+ type: "unsupported",
422
+ feature: part === "file" ? "image/file input" : part,
423
+ details: part === "file" ? "BrandApp AI API는 텍스트 전용입니다 — 이미지/파일 입력은 무시됩니다." : `BrandApp AI API does not support ${part} parts natively; converted to text (lossy).`
424
+ });
425
+ if (options.topP != null) warnings.push({
426
+ type: "unsupported",
427
+ feature: "topP",
428
+ details: "BrandApp AI API does not support topP parameter"
429
+ });
430
+ if (options.topK != null) warnings.push({
431
+ type: "unsupported",
432
+ feature: "topK",
433
+ details: "BrandApp AI API does not support topK parameter"
434
+ });
435
+ if (options.frequencyPenalty != null) warnings.push({
436
+ type: "unsupported",
437
+ feature: "frequencyPenalty",
438
+ details: "BrandApp AI API does not support frequencyPenalty parameter"
439
+ });
440
+ if (options.presencePenalty != null) warnings.push({
441
+ type: "unsupported",
442
+ feature: "presencePenalty",
443
+ details: "BrandApp AI API does not support presencePenalty parameter"
444
+ });
445
+ if (options.stopSequences?.length) warnings.push({
446
+ type: "unsupported",
447
+ feature: "stopSequences",
448
+ details: "BrandApp AI API does not support stopSequences parameter"
449
+ });
450
+ if (options.responseFormat?.type === "json") warnings.push({
451
+ type: "unsupported",
452
+ feature: "responseFormat",
453
+ details: "BrandApp AI API does not support JSON response format directly. Use prompt engineering instead."
454
+ });
455
+ if (options.tools?.length) warnings.push({
456
+ type: "unsupported",
457
+ feature: "tools",
458
+ details: "BrandApp AI API does not support tool calling. Tools will be ignored."
459
+ });
460
+ if (options.seed != null) warnings.push({
461
+ type: "unsupported",
462
+ feature: "seed",
463
+ details: "BrandApp AI API does not support seed parameter"
464
+ });
465
+ return warnings;
466
+ }
467
+ createStreamPartTransform(body, warnings, managed, includeRawChunks) {
468
+ const decoder = new TextDecoder();
469
+ const modelId = this.modelId;
470
+ let emittedStreamStart = false;
471
+ let emittedTextStart = false;
472
+ let emittedTextEnd = false;
473
+ let emittedFinish = false;
474
+ const textId = "text-0";
475
+ function processSSEEvent({ event, data }, controller) {
476
+ if (includeRawChunks) controller.enqueue({
477
+ type: "raw",
478
+ rawValue: {
479
+ event,
480
+ data
481
+ }
482
+ });
483
+ switch (event) {
484
+ case "text-delta":
485
+ if (!emittedTextStart) {
486
+ controller.enqueue({
487
+ type: "text-start",
488
+ id: textId
489
+ });
490
+ emittedTextStart = true;
491
+ }
492
+ controller.enqueue({
493
+ type: "text-delta",
494
+ id: textId,
495
+ delta: data
496
+ });
497
+ break;
498
+ case "done":
499
+ if (emittedTextStart && !emittedTextEnd) {
500
+ controller.enqueue({
501
+ type: "text-end",
502
+ id: textId
503
+ });
504
+ emittedTextEnd = true;
505
+ }
506
+ try {
507
+ const meta = JSON.parse(data);
508
+ controller.enqueue({
509
+ type: "finish",
510
+ usage: {
511
+ inputTokens: {
512
+ total: meta.usage.promptTokens,
513
+ noCache: void 0,
514
+ cacheRead: void 0,
515
+ cacheWrite: void 0
516
+ },
517
+ outputTokens: {
518
+ total: meta.usage.completionTokens,
519
+ text: void 0,
520
+ reasoning: void 0
521
+ }
522
+ },
523
+ finishReason: meta.finishReason ? {
524
+ unified: meta.finishReason.unified,
525
+ raw: meta.finishReason.raw
526
+ } : {
527
+ unified: "stop",
528
+ raw: "stop"
529
+ },
530
+ providerMetadata: { brandapp: {
531
+ creditCost: meta.usage.creditCost,
532
+ creditsRemaining: meta.creditsRemaining
533
+ } }
534
+ });
535
+ } catch {
536
+ controller.enqueue({
537
+ type: "finish",
538
+ usage: {
539
+ inputTokens: {
540
+ total: void 0,
541
+ noCache: void 0,
542
+ cacheRead: void 0,
543
+ cacheWrite: void 0
544
+ },
545
+ outputTokens: {
546
+ total: void 0,
547
+ text: void 0,
548
+ reasoning: void 0
549
+ }
550
+ },
551
+ finishReason: {
552
+ unified: "stop",
553
+ raw: "stop"
554
+ }
555
+ });
556
+ }
557
+ emittedFinish = true;
558
+ break;
559
+ case "error":
560
+ try {
561
+ const err = JSON.parse(data);
562
+ const mapped = typeof err.status === "number" ? mapHttpStatusToError(err.status, err.code, err.message) : new Error(err.message ?? "Stream error");
563
+ controller.enqueue({
564
+ type: "error",
565
+ error: mapped
566
+ });
567
+ } catch {
568
+ controller.enqueue({
569
+ type: "error",
570
+ error: new Error(data)
571
+ });
572
+ }
573
+ break;
574
+ }
575
+ }
576
+ let processor;
577
+ return body.pipeThrough(new TransformStream({
578
+ transform(chunk, controller) {
579
+ managed.kick();
580
+ if (!emittedStreamStart) {
581
+ controller.enqueue({
582
+ type: "stream-start",
583
+ warnings
584
+ });
585
+ controller.enqueue({
586
+ type: "response-metadata",
587
+ timestamp: /* @__PURE__ */ new Date(),
588
+ modelId
589
+ });
590
+ emittedStreamStart = true;
591
+ }
592
+ if (!processor) processor = createSSELineProcessor((sseEvent) => {
593
+ processSSEEvent(sseEvent, controller);
594
+ });
595
+ processor.feed(decoder.decode(chunk, { stream: true }));
596
+ },
597
+ flush(controller) {
598
+ managed.cleanup();
599
+ if (!emittedStreamStart) controller.enqueue({
600
+ type: "stream-start",
601
+ warnings
602
+ });
603
+ if (emittedTextStart && !emittedTextEnd) controller.enqueue({
604
+ type: "text-end",
605
+ id: textId
606
+ });
607
+ if (!emittedFinish) controller.enqueue({
608
+ type: "finish",
609
+ usage: {
610
+ inputTokens: {
611
+ total: void 0,
612
+ noCache: void 0,
613
+ cacheRead: void 0,
614
+ cacheWrite: void 0
615
+ },
616
+ outputTokens: {
617
+ total: void 0,
618
+ text: void 0,
619
+ reasoning: void 0
620
+ }
621
+ },
622
+ finishReason: {
623
+ unified: "error",
624
+ raw: "incomplete_stream"
625
+ }
626
+ });
627
+ }
628
+ }));
629
+ }
643
630
  };
644
631
 
645
- // src/ai-provider/index.ts
632
+ //#endregion
633
+ //#region src/ai-provider/index.ts
634
+ /**
635
+ * BrandApp AI SDK Provider
636
+ *
637
+ * Vercel AI SDK와 호환되는 커스텀 프로바이더를 생성합니다.
638
+ *
639
+ * **지원**: `generateText()`, `streamText()` (텍스트 생성), `generateImage()`
640
+ * (이미지 생성), `providerMetadata.brandapp`(크레딧/사용량), `providerOptions.brandapp`.
641
+ *
642
+ * **미지원** (호출 시 `warnings`로 알리고 해당 부분은 무시됨): tool/function calling,
643
+ * 구조화 출력(`generateObject`/`responseFormat: json`), 비전·파일 입력, `topP`/`topK`/
644
+ * `frequencyPenalty`/`presencePenalty`/`stopSequences`/`seed`. BrandApp AI API는 멀티
645
+ * 테넌트 안전을 위해 텍스트·이미지 표면만 노출한다. 임베딩/음성/전사 모델은 없다
646
+ * (`NoSuchModelError`).
647
+ *
648
+ * @example
649
+ * ```ts
650
+ * import { createBrandappProvider } from "@reopt-ai/brandapp-sdk/ai-provider";
651
+ * import { generateText, streamText } from "ai";
652
+ *
653
+ * const brandapp = createBrandappProvider({
654
+ * clientId: process.env.BRANDAPP_CLIENT_ID!,
655
+ * clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
656
+ * brandappId: process.env.BRANDAPP_ID!,
657
+ * });
658
+ *
659
+ * // Non-streaming
660
+ * const { text } = await generateText({
661
+ * model: brandapp("anthropic/claude-haiku-4.5"),
662
+ * prompt: "안녕하세요",
663
+ * });
664
+ *
665
+ * // Streaming
666
+ * const result = streamText({
667
+ * model: brandapp("zai/glm-4.7-flash"),
668
+ * prompt: "Hello, world!",
669
+ * });
670
+ *
671
+ * for await (const chunk of result.textStream) {
672
+ * process.stdout.write(chunk);
673
+ * }
674
+ *
675
+ * // BrandApp 전용 메타데이터 접근
676
+ * const { text, providerMetadata } = await generateText({
677
+ * model: brandapp("anthropic/claude-haiku-4.5"),
678
+ * prompt: "Hello",
679
+ * });
680
+ * console.log(providerMetadata?.brandapp?.creditCost);
681
+ * console.log(providerMetadata?.brandapp?.creditsRemaining);
682
+ *
683
+ * // customerId를 providerOptions로 전달
684
+ * const { text } = await generateText({
685
+ * model: brandapp("anthropic/claude-haiku-4.5"),
686
+ * prompt: "Hello",
687
+ * providerOptions: {
688
+ * brandapp: { customerId: "customer-uuid" },
689
+ * },
690
+ * });
691
+ *
692
+ * // Image generation
693
+ * const { images } = await generateImage({
694
+ * model: brandapp.imageModel("google/gemini-2.5-flash-image"),
695
+ * prompt: "A cat sitting on a windowsill",
696
+ * });
697
+ * ```
698
+ */
699
+ /**
700
+ * BrandApp AI SDK 프로바이더를 생성합니다.
701
+ *
702
+ * 반환된 함수는 모델 ID를 받아 LanguageModelV3 인스턴스를 반환합니다.
703
+ * AI SDK의 generateText(), streamText() 등에서 model 파라미터로 사용합니다.
704
+ *
705
+ * @example
706
+ * ```ts
707
+ * const brandapp = createBrandappProvider({ clientId, clientSecret, brandappId });
708
+ *
709
+ * // 함수 호출로 모델 인스턴스 생성
710
+ * const model = brandapp("anthropic/claude-haiku-4.5");
711
+ *
712
+ * // AI SDK 함수에 전달
713
+ * const { text } = await generateText({ model, prompt: "Hello" });
714
+ * ```
715
+ */
646
716
  function createBrandappProvider(config) {
647
- assertBrowserSafe(config);
648
- const sdkConfig = {
649
- clientId: config.clientId,
650
- clientSecret: config.clientSecret,
651
- brandappId: config.brandappId,
652
- token: config.token,
653
- isProduction: config.isProduction,
654
- baseUrl: config.baseUrl
655
- };
656
- validateConfig(sdkConfig);
657
- const baseUrl = resolveBaseUrl(sdkConfig) + `/api/v1/brandapp/${config.brandappId}/ai`;
658
- const modelConfig = {
659
- baseUrl,
660
- authHeader: createAuthHeader(sdkConfig),
661
- timeout: config.timeout ?? 6e4,
662
- sdkVersion: SDK_VERSION,
663
- customerId: config.customerId,
664
- fetch: config.fetch
665
- };
666
- const languageModelCache = /* @__PURE__ */ new Map();
667
- const imageModelCache = /* @__PURE__ */ new Map();
668
- function provider(modelId) {
669
- let model = languageModelCache.get(modelId);
670
- if (!model) {
671
- model = new BrandappLanguageModel(modelId, modelConfig);
672
- languageModelCache.set(modelId, model);
673
- }
674
- return model;
675
- }
676
- provider.specificationVersion = "v3";
677
- provider.languageModel = provider;
678
- provider.imageModel = (modelId) => {
679
- let model = imageModelCache.get(modelId);
680
- if (!model) {
681
- model = new BrandappImageModel(modelId, modelConfig);
682
- imageModelCache.set(modelId, model);
683
- }
684
- return model;
685
- };
686
- provider.embeddingModel = (modelId) => {
687
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
688
- };
689
- provider.textEmbeddingModel = (modelId) => {
690
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
691
- };
692
- provider.transcriptionModel = (modelId) => {
693
- throw new NoSuchModelError({ modelId, modelType: "transcriptionModel" });
694
- };
695
- provider.speechModel = (modelId) => {
696
- throw new NoSuchModelError({ modelId, modelType: "speechModel" });
697
- };
698
- return provider;
717
+ assertBrowserSafe(config);
718
+ const sdkConfig = {
719
+ clientId: config.clientId,
720
+ clientSecret: config.clientSecret,
721
+ brandappId: config.brandappId,
722
+ token: config.token,
723
+ isProduction: config.isProduction,
724
+ baseUrl: config.baseUrl
725
+ };
726
+ validateConfig(sdkConfig);
727
+ const modelConfig = {
728
+ baseUrl: resolveBaseUrl(sdkConfig) + `/api/v1/brandapp/${config.brandappId}/ai`,
729
+ authHeader: createAuthHeader(sdkConfig),
730
+ timeout: config.timeout ?? 6e4,
731
+ sdkVersion: SDK_VERSION,
732
+ customerId: config.customerId,
733
+ fetch: config.fetch
734
+ };
735
+ const languageModelCache = /* @__PURE__ */ new Map();
736
+ const imageModelCache = /* @__PURE__ */ new Map();
737
+ function provider(modelId) {
738
+ let model = languageModelCache.get(modelId);
739
+ if (!model) {
740
+ model = new BrandappLanguageModel(modelId, modelConfig);
741
+ languageModelCache.set(modelId, model);
742
+ }
743
+ return model;
744
+ }
745
+ provider.specificationVersion = "v3";
746
+ provider.languageModel = provider;
747
+ provider.imageModel = (modelId) => {
748
+ let model = imageModelCache.get(modelId);
749
+ if (!model) {
750
+ model = new BrandappImageModel(modelId, modelConfig);
751
+ imageModelCache.set(modelId, model);
752
+ }
753
+ return model;
754
+ };
755
+ provider.embeddingModel = (modelId) => {
756
+ throw new NoSuchModelError({
757
+ modelId,
758
+ modelType: "embeddingModel"
759
+ });
760
+ };
761
+ provider.textEmbeddingModel = (modelId) => {
762
+ throw new NoSuchModelError({
763
+ modelId,
764
+ modelType: "embeddingModel"
765
+ });
766
+ };
767
+ provider.transcriptionModel = (modelId) => {
768
+ throw new NoSuchModelError({
769
+ modelId,
770
+ modelType: "transcriptionModel"
771
+ });
772
+ };
773
+ provider.speechModel = (modelId) => {
774
+ throw new NoSuchModelError({
775
+ modelId,
776
+ modelType: "speechModel"
777
+ });
778
+ };
779
+ return provider;
699
780
  }
700
781
 
782
+ //#endregion
701
783
  export { BrandappImageModel, BrandappLanguageModel, createBrandappProvider };
702
- //# sourceMappingURL=index.js.map
703
784
  //# sourceMappingURL=index.js.map