@reopt-ai/brandapp-sdk 3.0.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 (76) hide show
  1. package/CHANGELOG.md +574 -0
  2. package/LICENSE +21 -0
  3. package/README.md +468 -0
  4. package/dist/ai/index.d.ts +314 -0
  5. package/dist/ai/index.js +7 -0
  6. package/dist/ai-provider/index.d.ts +196 -0
  7. package/dist/ai-provider/index.js +703 -0
  8. package/dist/auth/index.d.ts +76 -0
  9. package/dist/auth/index.js +40 -0
  10. package/dist/better-auth/client.d.ts +29 -0
  11. package/dist/better-auth/client.js +10 -0
  12. package/dist/better-auth/index.d.ts +82 -0
  13. package/dist/better-auth/index.js +145 -0
  14. package/dist/chunk-6FLYVNZI.js +32 -0
  15. package/dist/chunk-6KPKZ7ZB.js +49 -0
  16. package/dist/chunk-DI6QJPTQ.js +449 -0
  17. package/dist/chunk-E457LO5A.js +599 -0
  18. package/dist/chunk-F7BXBTZI.js +54 -0
  19. package/dist/chunk-J5Y2GSJF.js +443 -0
  20. package/dist/chunk-K3YVJE6E.js +96 -0
  21. package/dist/chunk-KU2LN5SE.js +350 -0
  22. package/dist/chunk-L4DHB36G.js +75 -0
  23. package/dist/chunk-PJZB4VP7.js +63 -0
  24. package/dist/chunk-REIKXSMY.js +7 -0
  25. package/dist/chunk-T2WXHAAC.js +54 -0
  26. package/dist/chunk-TUKIYH4Q.js +112 -0
  27. package/dist/chunk-WSEROZVO.js +81 -0
  28. package/dist/chunk-YRGLBM6V.js +157 -0
  29. package/dist/client-BkcO-0C2.d.ts +216 -0
  30. package/dist/client-CN5_tNOC.d.ts +147 -0
  31. package/dist/client-DttyeM_h.d.ts +102 -0
  32. package/dist/cms/index.d.ts +137 -0
  33. package/dist/cms/index.js +101 -0
  34. package/dist/config-CtxyJsDR.d.ts +397 -0
  35. package/dist/dev/index.d.ts +509 -0
  36. package/dist/dev/index.js +3071 -0
  37. package/dist/eav/coerce.d.ts +42 -0
  38. package/dist/eav/coerce.js +65 -0
  39. package/dist/eav/index.d.ts +214 -0
  40. package/dist/eav/index.js +147 -0
  41. package/dist/eav/migrate.d.ts +236 -0
  42. package/dist/eav/migrate.js +219 -0
  43. package/dist/eav/schema.d.ts +260 -0
  44. package/dist/eav/schema.js +656 -0
  45. package/dist/errors-5hd5ZR-M.d.ts +158 -0
  46. package/dist/feedback/index.d.ts +132 -0
  47. package/dist/feedback/index.js +5 -0
  48. package/dist/files/index.d.ts +54 -0
  49. package/dist/files/index.js +31 -0
  50. package/dist/index.d.ts +221 -0
  51. package/dist/index.js +84 -0
  52. package/dist/plans/index.d.ts +140 -0
  53. package/dist/plans/index.js +5 -0
  54. package/dist/push/index.d.ts +79 -0
  55. package/dist/push/index.js +5 -0
  56. package/dist/react/hooks.d.ts +376 -0
  57. package/dist/react/hooks.js +421 -0
  58. package/dist/terms/index.d.ts +79 -0
  59. package/dist/terms/index.js +5 -0
  60. package/dist/testing/index.d.ts +154 -0
  61. package/dist/testing/index.js +81 -0
  62. package/dist/typed-client-BxOVIiMU.d.ts +40 -0
  63. package/dist/types-6E3ZLL9X.d.ts +24 -0
  64. package/dist/types-DskYLVb8.d.ts +104 -0
  65. package/dist/types-ckmDDW3N.d.ts +129 -0
  66. package/dist/webhooks/index.d.ts +140 -0
  67. package/dist/webhooks/index.js +142 -0
  68. package/docs/api-reference.md +557 -0
  69. package/docs/cms.md +318 -0
  70. package/docs/dev-server.md +164 -0
  71. package/docs/environment.md +211 -0
  72. package/docs/errors.md +290 -0
  73. package/docs/files.md +272 -0
  74. package/docs/migration.md +315 -0
  75. package/docs/testing.md +163 -0
  76. package/package.json +173 -0
@@ -0,0 +1,703 @@
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-J5Y2GSJF.js';
4
+ import { NoSuchModelError, APICallError } from '@ai-sdk/provider';
5
+
6
+ function newRequestId(sdkVersion) {
7
+ return globalThis.crypto?.randomUUID?.() ?? `sdk-${sdkVersion}-${Date.now()}`;
8
+ }
9
+ function buildBaseProviderHeaders(config) {
10
+ return {
11
+ Authorization: config.authHeader,
12
+ "Content-Type": "application/json",
13
+ "X-SDK-Version": `brandapp-sdk/${config.sdkVersion}`
14
+ };
15
+ }
16
+ 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;
25
+ }
26
+ function buildProviderHeaders(config, extraHeaders) {
27
+ return mergeProviderHeaders(buildBaseProviderHeaders(config), extraHeaders);
28
+ }
29
+ 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
+ }
49
+ }
50
+ 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
+ });
74
+ }
75
+ function extractResponseHeaders(response) {
76
+ const headers = {};
77
+ response.headers.forEach((value, key) => {
78
+ headers[key] = value;
79
+ });
80
+ return headers;
81
+ }
82
+
83
+ // src/ai-provider/brandapp-image-model.ts
84
+ 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
+ }
219
+ };
220
+ function arrayBufferToBase64(bytes) {
221
+ const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
222
+ return btoa(binString);
223
+ }
224
+
225
+ // src/ai-provider/convert-prompt.ts
226
+ 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] };
281
+ }
282
+
283
+ // src/ai-provider/brandapp-language-model.ts
284
+ 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
+ }
643
+ };
644
+
645
+ // src/ai-provider/index.ts
646
+ 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;
699
+ }
700
+
701
+ export { BrandappImageModel, BrandappLanguageModel, createBrandappProvider };
702
+ //# sourceMappingURL=index.js.map
703
+ //# sourceMappingURL=index.js.map