@reopt-ai/brandapp-sdk 4.4.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -0
  3. package/dist/ai/index.js +1 -1
  4. package/dist/ai-provider/index.js +1 -1
  5. package/dist/analytics/index.js +1 -1
  6. package/dist/auth/index.js +1 -1
  7. package/dist/better-auth/index.js +2 -2
  8. package/dist/{client-afAv7Ebi.js → client-BlKXDOUb.js} +4 -4
  9. package/dist/{client-EG1p7FL0.js → client-BnRfa5hI.js} +2 -2
  10. package/dist/{client-D_6WdWsc.js → client-CU9KBiDi.js} +3 -3
  11. package/dist/{client-DuATTvcr.js → client-Cg_gl0Gk.js} +2 -2
  12. package/dist/{client-s2uJ3OML.js → client-D9QA4f3H.js} +2 -2
  13. package/dist/{client-C4sDbXto.js → client-DLvWSpaz.js} +4 -4
  14. package/dist/{client-CuM8MNS5.js → client-NQ0p6XSB.js} +2 -2
  15. package/dist/{client-DsM84EZZ.js → client-d0EwZNc4.js} +3 -3
  16. package/dist/{client-mD6o-qVl.js → client-ijQDMf1X.js} +2 -2
  17. package/dist/{client-DYkDNPyN.js → client-p-tpQ1xj.js} +2 -2
  18. package/dist/cms/index.js +1 -1
  19. package/dist/{config-C_OFYAgP.js → config-DCFgtfSu.js} +2 -2
  20. package/dist/eav/index.js +2 -2
  21. package/dist/feedback/index.js +1 -1
  22. package/dist/files/index.js +1 -1
  23. package/dist/{http-client-BUbFBOvG.js → http-client-CHXNS9TI.js} +2 -2
  24. package/dist/index.js +12 -12
  25. package/dist/logout/index.js +1 -1
  26. package/dist/plans/index.js +1 -1
  27. package/dist/push/index.js +1 -1
  28. package/dist/{query-BkdTSuB5.js → query-ZVC28Rp8.js} +2 -2
  29. package/dist/terms/index.js +1 -1
  30. package/dist/webhooks/index.d.ts +25 -2
  31. package/dist/workspace/index.d.ts +602 -0
  32. package/dist/workspace/index.js +688 -0
  33. package/docs/api-reference.md +5 -1
  34. package/docs/workspace.md +141 -0
  35. package/package.json +10 -2
@@ -0,0 +1,688 @@
1
+ import { n as SDK_VERSION } from "../config-DCFgtfSu.js";
2
+ import { z } from "zod";
3
+
4
+ //#region src/workspace/schemas.ts
5
+ /**
6
+ * 플랫폼 API(RFC-0029) 와이어 계약 — zod 한 벌.
7
+ *
8
+ * 서버(`apps/web/server/hono/routes/platform-schemas.ts`)와 같은 모양이다. 패키지 경계 때문에
9
+ * 파일은 둘이지만 서버 테스트(`platform-sdk-parity.test.ts`)가 이 스키마로 서버 응답을 파싱해
10
+ * 파리티를 고정한다. 소비자(reopt-data 등)는 tRPC 입력·웹훅 검증에 그대로 쓴다.
11
+ *
12
+ * 🔑 `.default()`를 쓰지 않는다 — 생략(`undefined`)이 "건드리지 않는다"를 뜻하는 필드가 있다.
13
+ * 🔑 타입은 손으로 적고 스키마에 `z.ZodType<T>`를 단다 — 이 패키지는 `isolatedDeclarations`라
14
+ * 추론된 export가 빌드를 깬다(TS9010).
15
+ */
16
+ const PLATFORM_TASK_PRIORITIES = [
17
+ "low",
18
+ "medium",
19
+ "high",
20
+ "urgent"
21
+ ];
22
+ const PLATFORM_TASK_OUTCOMES = ["completed", "canceled"];
23
+ const PLATFORM_WEBHOOK_TRIGGERS = ["workTaskStageChanged"];
24
+ /** 소스 쪽 식별자 — 경로 세그먼트라 슬래시·공백 금지, ≤255 */
25
+ const platformExternalIdSchema = z.string().trim().min(1).max(255).regex(/^[^/\s]+$/, "externalId must not contain slashes or whitespace");
26
+ const versionSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
27
+ const exactlyOneOf = (value) => value.stageId === void 0 !== (value.outcome === void 0);
28
+ const platformTaskStageSchema = z.object({
29
+ outcome: z.enum(PLATFORM_TASK_OUTCOMES).nullable().optional(),
30
+ stageId: z.uuid().optional()
31
+ }).strict().refine(exactlyOneOf, "stage needs exactly one of outcome or stageId");
32
+ const platformTaskUpsertInputSchema = z.object({
33
+ version: versionSchema,
34
+ title: z.string().trim().min(1).max(255),
35
+ description: z.string().trim().max(8e3).nullable().optional(),
36
+ priority: z.enum(PLATFORM_TASK_PRIORITIES).optional(),
37
+ dueDate: z.iso.datetime({ offset: true }).nullable().optional(),
38
+ brandId: z.uuid().optional(),
39
+ pipelineId: z.uuid().optional(),
40
+ url: z.url().max(2e3).nullable().optional(),
41
+ label: z.string().trim().min(1).max(64).nullable().optional(),
42
+ stage: platformTaskStageSchema.optional()
43
+ }).strict();
44
+ const platformTaskStageInputSchema = z.object({
45
+ version: versionSchema,
46
+ outcome: z.enum(PLATFORM_TASK_OUTCOMES).nullable().optional(),
47
+ stageId: z.uuid().optional()
48
+ }).strict().refine(exactlyOneOf, "exactly one of outcome or stageId is required");
49
+ const platformWebhookUpsertInputSchema = z.object({
50
+ url: z.url().max(2e3),
51
+ triggers: z.array(z.enum(PLATFORM_WEBHOOK_TRIGGERS)).min(1),
52
+ secret: z.string().min(16).max(1024).optional(),
53
+ managedBy: z.literal("code").nullable().optional()
54
+ }).strict();
55
+ const outcomeSchema = z.enum(PLATFORM_TASK_OUTCOMES).nullable();
56
+ const platformTaskSchema = z.object({
57
+ id: z.string(),
58
+ workspaceId: z.string(),
59
+ brandId: z.string().nullable(),
60
+ title: z.string(),
61
+ description: z.string().nullable(),
62
+ priority: z.enum(PLATFORM_TASK_PRIORITIES),
63
+ dueDate: z.string().nullable(),
64
+ pipeline: z.object({
65
+ id: z.string(),
66
+ name: z.string()
67
+ }).nullable(),
68
+ stage: z.object({
69
+ id: z.string(),
70
+ key: z.string(),
71
+ label: z.string(),
72
+ outcome: outcomeSchema
73
+ }).nullable(),
74
+ externalRef: z.object({
75
+ source: z.string(),
76
+ externalId: z.string(),
77
+ url: z.string().nullable(),
78
+ label: z.string().nullable(),
79
+ version: z.number()
80
+ }),
81
+ url: z.string(),
82
+ createdAt: z.string(),
83
+ updatedAt: z.string()
84
+ });
85
+ const platformWriteMetaSchema = z.object({
86
+ created: z.boolean(),
87
+ applied: z.boolean()
88
+ });
89
+ const platformPipelineSchema = z.object({
90
+ id: z.string(),
91
+ name: z.string(),
92
+ isDefault: z.boolean(),
93
+ stages: z.array(z.object({
94
+ id: z.string(),
95
+ key: z.string(),
96
+ label: z.string(),
97
+ order: z.number(),
98
+ isEntry: z.boolean(),
99
+ outcome: outcomeSchema
100
+ }))
101
+ });
102
+ const platformMeSchema = z.object({
103
+ clientId: z.string(),
104
+ clientName: z.string(),
105
+ source: z.string(),
106
+ workspaceId: z.string(),
107
+ brandappId: z.string(),
108
+ defaultBrandId: z.string(),
109
+ scopes: z.array(z.string())
110
+ });
111
+ const platformWebhookSchema = z.object({
112
+ id: z.string(),
113
+ url: z.string(),
114
+ triggers: z.array(z.string()),
115
+ hasSecret: z.boolean()
116
+ });
117
+ const platformErrorSchema = z.object({ error: z.object({
118
+ code: z.string(),
119
+ message: z.string(),
120
+ retryable: z.boolean(),
121
+ fields: z.array(z.object({
122
+ field: z.string(),
123
+ message: z.string()
124
+ })).optional()
125
+ }) });
126
+ const platformWorkTaskStageChangedEventSchema = z.object({
127
+ id: z.string(),
128
+ title: z.string(),
129
+ pipelineId: z.string().nullable(),
130
+ fromStageLabel: z.string().nullable(),
131
+ toStageId: z.string(),
132
+ toStageLabel: z.string(),
133
+ toStageOutcome: outcomeSchema,
134
+ origin: z.string(),
135
+ version: z.number(),
136
+ externalRefs: z.array(z.object({
137
+ source: z.string(),
138
+ externalId: z.string(),
139
+ label: z.string().nullable()
140
+ }))
141
+ });
142
+ const PLATFORM_ADMIN_SCOPE = "workspace:admin";
143
+ const PLATFORM_MANAGED_BY_VALUES = ["code"];
144
+ /** 단계 색 어휘 — `packages/studio-ui/composites/stage-colors.ts` STAGE_COLORS와 같은 집합(apps/web 파리티 테스트가 고정) */
145
+ const PLATFORM_STAGE_COLORS = [
146
+ "slate",
147
+ "gray",
148
+ "red",
149
+ "rose",
150
+ "orange",
151
+ "amber",
152
+ "yellow",
153
+ "lime",
154
+ "green",
155
+ "emerald",
156
+ "teal",
157
+ "cyan",
158
+ "sky",
159
+ "blue",
160
+ "indigo",
161
+ "violet",
162
+ "purple",
163
+ "pink"
164
+ ];
165
+ /** `/^[a-z0-9][a-z0-9-]{0,59}$/` — 선언 파일의 키이자 URL 경로 세그먼트 */
166
+ const platformResourceKeySchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,59}$/, "key must be lowercase letters, digits or '-' (≤60, must start with a letter or digit)");
167
+ const stageColorSchema = z.enum(PLATFORM_STAGE_COLORS);
168
+ const platformPipelineStageInputSchema = z.object({
169
+ key: platformResourceKeySchema,
170
+ label: z.string().trim().min(1).max(80),
171
+ color: stageColorSchema.optional(),
172
+ isEntry: z.boolean().optional(),
173
+ outcome: z.enum(PLATFORM_TASK_OUTCOMES).nullable().optional()
174
+ }).strict();
175
+ const platformPipelineUpsertInputSchema = z.object({
176
+ name: z.string().trim().min(1).max(120),
177
+ description: z.string().trim().max(500).nullable().optional(),
178
+ isDefault: z.boolean().optional(),
179
+ stages: z.array(platformPipelineStageInputSchema).min(1).max(50),
180
+ allowDestructive: z.boolean().optional()
181
+ }).strict().refine((value) => new Set(value.stages.map((stage) => stage.key)).size === value.stages.length, "stage keys must be unique within a pipeline").refine((value) => value.stages.filter((stage) => stage.isEntry === true).length === 1, "exactly one stage must have isEntry: true");
182
+ const platformPipelineImportInputSchema = z.object({ pipelineId: z.uuid() }).strict();
183
+ const managedBySchema = z.enum(PLATFORM_MANAGED_BY_VALUES).nullable();
184
+ const platformPipelineResourceSchema = z.object({
185
+ id: z.string(),
186
+ key: z.string().nullable(),
187
+ name: z.string(),
188
+ description: z.string().nullable(),
189
+ isDefault: z.boolean(),
190
+ isArchived: z.boolean(),
191
+ order: z.number(),
192
+ managedBy: managedBySchema,
193
+ taskCount: z.number(),
194
+ stages: z.array(z.object({
195
+ id: z.string(),
196
+ key: z.string(),
197
+ label: z.string(),
198
+ color: z.string(),
199
+ order: z.number(),
200
+ isEntry: z.boolean(),
201
+ outcome: outcomeSchema,
202
+ taskCount: z.number()
203
+ }))
204
+ });
205
+ const platformWebhookResourceSchema = z.object({
206
+ id: z.string(),
207
+ url: z.string(),
208
+ triggers: z.array(z.string()),
209
+ hasSecret: z.boolean(),
210
+ managedBy: managedBySchema
211
+ });
212
+ const platformResourcesSchema = z.object({
213
+ workspaceId: z.string(),
214
+ pipelines: z.array(platformPipelineResourceSchema),
215
+ webhooks: z.array(platformWebhookResourceSchema)
216
+ });
217
+ const platformLockAcquiredSchema = z.object({
218
+ acquired: z.literal(true),
219
+ expiresAt: z.string()
220
+ });
221
+ const platformLockReleasedSchema = z.object({ released: z.boolean() });
222
+ const PLATFORM_DOMAIN_STATUSES = [
223
+ "active",
224
+ "inactive",
225
+ "pending",
226
+ "suspended"
227
+ ];
228
+ const PLATFORM_BRANDAPP_STATUSES = [
229
+ "draft",
230
+ "active",
231
+ "suspended",
232
+ "archived"
233
+ ];
234
+ const PLATFORM_TOKEN_ENDPOINT_AUTH_METHODS = [
235
+ "client_secret_post",
236
+ "client_secret_basic",
237
+ "none"
238
+ ];
239
+ const PLATFORM_OAUTH_GRANT_TYPES = [
240
+ "authorization_code",
241
+ "refresh_token",
242
+ "client_credentials"
243
+ ];
244
+ const PLATFORM_OAUTH_APPLICATION_TYPES = ["web", "native"];
245
+ const domainStatusSchema = z.enum(PLATFORM_DOMAIN_STATUSES);
246
+ const hostnameSchema = z.string().trim().min(1).max(255).regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/, "domain must be a bare hostname");
247
+ const platformBrandUpsertInputSchema = z.object({
248
+ name: z.string().trim().min(1).max(255),
249
+ logo: z.url().max(2048).nullable().optional(),
250
+ description: z.string().trim().max(280).nullable().optional(),
251
+ isSystemBrand: z.boolean().optional(),
252
+ domain: hostnameSchema.optional()
253
+ }).strict();
254
+ const platformBrandImportInputSchema = z.object({ brandId: z.uuid() }).strict();
255
+ const platformBrandResourceSchema = z.object({
256
+ id: z.string(),
257
+ key: z.string().nullable(),
258
+ name: z.string(),
259
+ logo: z.string().nullable(),
260
+ description: z.string().nullable(),
261
+ isSystemBrand: z.boolean(),
262
+ managedBy: managedBySchema,
263
+ domains: z.array(z.object({
264
+ id: z.string(),
265
+ domain: z.string(),
266
+ isPrimary: z.boolean(),
267
+ status: domainStatusSchema
268
+ })),
269
+ brandappSlug: z.string().nullable()
270
+ });
271
+ const platformBrandappUpsertInputSchema = z.object({
272
+ name: z.string().trim().min(1).max(100),
273
+ brand: platformResourceKeySchema,
274
+ description: z.string().trim().max(500).nullable().optional(),
275
+ logo: z.url().max(2048).nullable().optional(),
276
+ aiEnabled: z.boolean().optional(),
277
+ isSystemBrandapp: z.boolean().optional(),
278
+ settings: z.record(z.string(), z.unknown()).optional()
279
+ }).strict();
280
+ const platformBrandappResourceSchema = z.object({
281
+ id: z.string(),
282
+ slug: z.string(),
283
+ name: z.string(),
284
+ description: z.string().nullable(),
285
+ logo: z.string().nullable(),
286
+ status: z.string(),
287
+ aiEnabled: z.boolean(),
288
+ isSystemBrandapp: z.boolean(),
289
+ brandId: z.string(),
290
+ brandKey: z.string().nullable(),
291
+ domainId: z.string().nullable(),
292
+ settings: z.record(z.string(), z.unknown()).nullable(),
293
+ managedBy: managedBySchema
294
+ });
295
+ const platformOAuthClientUpsertInputSchema = z.object({
296
+ brandapp: platformResourceKeySchema,
297
+ name: z.string().trim().min(1).max(255).optional(),
298
+ scopes: z.array(z.string().trim().min(1).max(64)).min(1).max(32),
299
+ grantTypes: z.array(z.enum(PLATFORM_OAUTH_GRANT_TYPES)).min(1),
300
+ redirectUris: z.array(z.url().max(500)).max(32).optional(),
301
+ postLogoutRedirectUris: z.array(z.url().max(500)).max(32).optional(),
302
+ tokenEndpointAuthMethod: z.enum(PLATFORM_TOKEN_ENDPOINT_AUTH_METHODS).optional(),
303
+ requirePKCE: z.boolean().optional(),
304
+ skipConsent: z.boolean().optional(),
305
+ enableEndSession: z.boolean().optional(),
306
+ applicationType: z.enum(PLATFORM_OAUTH_APPLICATION_TYPES).optional(),
307
+ disabled: z.boolean().optional()
308
+ }).strict().refine((value) => !value.grantTypes.includes("authorization_code") || (value.redirectUris?.length ?? 0) > 0, "authorization_code requires at least one redirectUri");
309
+ const platformOAuthClientImportInputSchema = z.object({ clientId: z.string().min(8).max(255) }).strict();
310
+ const platformOAuthClientResourceSchema = z.object({
311
+ id: z.string(),
312
+ key: z.string().nullable(),
313
+ clientId: z.string(),
314
+ name: z.string().nullable(),
315
+ brandappSlug: z.string().nullable(),
316
+ disabled: z.boolean(),
317
+ scopes: z.array(z.string()),
318
+ clientCredentialsScopes: z.array(z.string()),
319
+ grantTypes: z.array(z.string()),
320
+ redirectUris: z.array(z.string()),
321
+ postLogoutRedirectUris: z.array(z.string()),
322
+ tokenEndpointAuthMethod: z.string().nullable(),
323
+ requirePKCE: z.boolean(),
324
+ skipConsent: z.boolean(),
325
+ enableEndSession: z.boolean(),
326
+ applicationType: z.string().nullable(),
327
+ hasSecret: z.boolean(),
328
+ managedBy: managedBySchema,
329
+ clientSecret: z.string().optional()
330
+ });
331
+ const eavAttributeResourceSchema = z.object({
332
+ id: z.string(),
333
+ name: z.string(),
334
+ label: z.string(),
335
+ dataType: z.string(),
336
+ isRequired: z.boolean(),
337
+ isUnique: z.boolean(),
338
+ defaultValue: z.string().nullable(),
339
+ validation: z.unknown(),
340
+ options: z.unknown(),
341
+ sortOrder: z.number()
342
+ });
343
+ const platformEavEntityResourceSchema = z.object({
344
+ id: z.string(),
345
+ name: z.string(),
346
+ description: z.string().nullable(),
347
+ icon: z.string().nullable(),
348
+ linkedTo: z.string(),
349
+ attributes: z.array(eavAttributeResourceSchema),
350
+ recordCount: z.number()
351
+ });
352
+ const platformEavBrandappResourcesSchema = z.object({
353
+ brandappId: z.string(),
354
+ brandappSlug: z.string(),
355
+ entities: z.array(platformEavEntityResourceSchema)
356
+ });
357
+ const eavName = z.string().trim().min(1).max(100);
358
+ const platformEavSchemaOperationSchema = z.discriminatedUnion("kind", [
359
+ z.object({
360
+ kind: z.literal("addEntity"),
361
+ name: eavName,
362
+ def: z.object({
363
+ description: z.string().max(500).nullable().optional(),
364
+ icon: z.string().max(10).nullable().optional(),
365
+ linkedTo: z.enum(["brandapp", "brandappAuthUser"]).optional()
366
+ }).optional()
367
+ }).strict(),
368
+ z.object({
369
+ kind: z.literal("updateEntity"),
370
+ name: eavName,
371
+ changes: z.object({
372
+ description: z.string().max(500).nullable().optional(),
373
+ icon: z.string().max(10).nullable().optional()
374
+ }).strict()
375
+ }).strict(),
376
+ z.object({
377
+ kind: z.literal("removeEntity"),
378
+ name: eavName
379
+ }).strict(),
380
+ z.object({
381
+ kind: z.literal("addAttribute"),
382
+ entity: eavName,
383
+ name: eavName,
384
+ def: z.record(z.string(), z.unknown())
385
+ }).strict(),
386
+ z.object({
387
+ kind: z.literal("updateAttribute"),
388
+ entity: eavName,
389
+ name: eavName,
390
+ changes: z.record(z.string(), z.unknown())
391
+ }).strict(),
392
+ z.object({
393
+ kind: z.literal("removeAttribute"),
394
+ entity: eavName,
395
+ name: eavName
396
+ }).strict(),
397
+ z.object({
398
+ kind: z.literal("renameAttribute"),
399
+ entity: eavName,
400
+ oldName: eavName,
401
+ newName: eavName
402
+ }).strict()
403
+ ]);
404
+ const platformEavSchemaApplyInputSchema = z.object({
405
+ brandapp: platformResourceKeySchema.optional(),
406
+ operations: z.array(platformEavSchemaOperationSchema).max(1e3),
407
+ allowDestructive: z.boolean().optional()
408
+ }).strict();
409
+ const platformEavSchemaApplyResultSchema = z.object({
410
+ applied: z.number(),
411
+ entities: z.array(platformEavEntityResourceSchema)
412
+ });
413
+ const platformResourcesV2Schema = z.object({
414
+ workspaceId: z.string(),
415
+ pipelines: z.array(platformPipelineResourceSchema),
416
+ webhooks: z.array(platformWebhookResourceSchema),
417
+ brands: z.array(platformBrandResourceSchema),
418
+ brandapps: z.array(platformBrandappResourceSchema),
419
+ oauthClients: z.array(platformOAuthClientResourceSchema),
420
+ eav: z.array(platformEavBrandappResourcesSchema)
421
+ });
422
+
423
+ //#endregion
424
+ //#region src/workspace/client.ts
425
+ /**
426
+ * 플랫폼 API(RFC-0029) 클라이언트 — **서버 전용**.
427
+ *
428
+ * `client_credentials`로 `platform.reopt.ai` audience 토큰을 받아(캐시·만료 60초 전 재발급·401 시 1회
429
+ * 재발급) `/v1/*`를 부른다. 브라우저에서 만들면 던진다 — clientSecret이 곧 워크스페이스 쓰기 권한이다.
430
+ *
431
+ * 기본 origin은 환경에서 파생하고(`isProduction` 또는 `REOPT_PLATFORM_URL`/`REOPT_ID_BASE_URL` env),
432
+ * 자체서명 dev 인증서는 `fetch` 주입(undici Agent 등)으로 요청 단위로 푼다 — 프로세스 전역
433
+ * `NODE_TLS_REJECT_UNAUTHORIZED`는 쓰지 않는다.
434
+ */
435
+ const REOPT_PLATFORM_URLS = {
436
+ production: "https://platform.reopt.ai",
437
+ development: "https://platform.reopt.de:3443"
438
+ };
439
+ const REOPT_PLATFORM_ID_URLS = {
440
+ production: "https://id.reopt.ai",
441
+ development: "https://id.reopt.de:3443"
442
+ };
443
+ const DEFAULT_PLATFORM_SCOPES = ["works:read", "works:write"];
444
+ var PlatformApiError = class PlatformApiError extends Error {
445
+ status;
446
+ code;
447
+ retryable;
448
+ fields;
449
+ requestId;
450
+ constructor(input) {
451
+ super(`[platform ${input.status} ${input.code}] ${input.message}`);
452
+ this.name = "PlatformApiError";
453
+ this.status = input.status;
454
+ this.code = input.code;
455
+ this.retryable = input.retryable;
456
+ this.fields = input.fields;
457
+ this.requestId = input.requestId;
458
+ Object.setPrototypeOf(this, PlatformApiError.prototype);
459
+ }
460
+ };
461
+ const REFRESH_SKEW_MS = 6e4;
462
+ function readEnv(name) {
463
+ const value = (globalThis.process?.env)?.[name];
464
+ return value && value.length > 0 ? value : void 0;
465
+ }
466
+ function trimSlash(value) {
467
+ return value.endsWith("/") ? value.slice(0, -1) : value;
468
+ }
469
+ function assertServerRuntime() {
470
+ if (typeof window !== "undefined" && typeof document !== "undefined") throw new Error("@reopt-ai/brandapp-sdk/workspace is server-only — clientSecret grants workspace write access and must never reach the browser.");
471
+ }
472
+ function resolvePlatformUrls(config) {
473
+ const production = config.isProduction ?? readEnv("NODE_ENV") === "production";
474
+ return {
475
+ platformUrl: trimSlash(config.platformUrl ?? readEnv("REOPT_PLATFORM_URL") ?? (production ? REOPT_PLATFORM_URLS.production : REOPT_PLATFORM_URLS.development)),
476
+ idBaseUrl: trimSlash(config.idBaseUrl ?? readEnv("REOPT_ID_BASE_URL") ?? (production ? REOPT_PLATFORM_ID_URLS.production : REOPT_PLATFORM_ID_URLS.development))
477
+ };
478
+ }
479
+ function createPlatformClient(config) {
480
+ assertServerRuntime();
481
+ if (!config.clientId || !config.clientSecret) throw new Error("createPlatformClient: clientId and clientSecret are required");
482
+ const { platformUrl, idBaseUrl } = resolvePlatformUrls(config);
483
+ const scopes = config.scopes ?? DEFAULT_PLATFORM_SCOPES;
484
+ const fetchImpl = config.fetch ?? globalThis.fetch;
485
+ const timeoutMs = config.timeoutMs ?? 1e4;
486
+ const nextRequestId = config.requestId ?? (() => crypto.randomUUID());
487
+ let token = null;
488
+ let inflight = null;
489
+ async function fetchToken() {
490
+ const body = new URLSearchParams({
491
+ grant_type: "client_credentials",
492
+ client_id: config.clientId,
493
+ client_secret: config.clientSecret,
494
+ scope: scopes.join(" "),
495
+ resource: platformUrl
496
+ });
497
+ const res = await fetchImpl(`${idBaseUrl}/api/auth/oauth2/token`, {
498
+ method: "POST",
499
+ headers: {
500
+ "content-type": "application/x-www-form-urlencoded",
501
+ accept: "application/json",
502
+ "x-sdk-version": SDK_VERSION
503
+ },
504
+ body,
505
+ signal: AbortSignal.timeout(timeoutMs)
506
+ });
507
+ const json = await res.json().catch(() => null);
508
+ if (!res.ok || !json?.access_token) throw new PlatformApiError({
509
+ status: res.status,
510
+ code: json?.error ?? "TOKEN_ERROR",
511
+ message: json?.error_description ?? "Failed to obtain platform access token",
512
+ retryable: res.status >= 500 || res.status === 429
513
+ });
514
+ const ttlMs = (json.expires_in ?? 3600) * 1e3;
515
+ return {
516
+ accessToken: json.access_token,
517
+ expiresAt: Date.now() + ttlMs
518
+ };
519
+ }
520
+ async function getToken(force = false) {
521
+ if (!force && token && token.expiresAt - REFRESH_SKEW_MS > Date.now()) return token.accessToken;
522
+ if (!inflight) inflight = fetchToken().finally(() => {
523
+ inflight = null;
524
+ });
525
+ token = await inflight;
526
+ return token.accessToken;
527
+ }
528
+ async function request(method, path, options) {
529
+ const accessToken = await getToken(options.retried === true);
530
+ const requestId = nextRequestId();
531
+ const res = await fetchImpl(`${platformUrl}${path}`, {
532
+ method,
533
+ headers: {
534
+ authorization: `Bearer ${accessToken}`,
535
+ accept: "application/json",
536
+ "x-request-id": requestId,
537
+ "x-sdk-version": SDK_VERSION,
538
+ ...options.body !== void 0 ? { "content-type": "application/json" } : {}
539
+ },
540
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
541
+ signal: AbortSignal.timeout(timeoutMs)
542
+ });
543
+ if (res.status === 401 && !options.retried) {
544
+ token = null;
545
+ return request(method, path, {
546
+ ...options,
547
+ retried: true
548
+ });
549
+ }
550
+ const text = await res.text();
551
+ const json = text ? JSON.parse(text) : null;
552
+ if (!res.ok) {
553
+ const parsed = platformErrorSchema.safeParse(json);
554
+ const error = parsed.success ? parsed.data.error : null;
555
+ throw new PlatformApiError({
556
+ status: res.status,
557
+ code: error?.code ?? "HTTP_ERROR",
558
+ message: error?.message ?? `Platform API responded ${res.status}`,
559
+ retryable: error?.retryable ?? (res.status >= 500 || res.status === 429),
560
+ fields: error?.fields,
561
+ requestId: res.headers.get("x-request-id") ?? requestId
562
+ });
563
+ }
564
+ return options.parse(json);
565
+ }
566
+ const parseWrite = (value) => {
567
+ const envelope = value;
568
+ return {
569
+ data: platformTaskSchema.parse(envelope.data),
570
+ meta: platformWriteMetaSchema.parse(envelope.meta)
571
+ };
572
+ };
573
+ const parseData = (parse) => (value) => parse(value.data);
574
+ const parseWriteWith = (schema) => (value) => {
575
+ const envelope = value;
576
+ return {
577
+ data: schema.parse(envelope.data),
578
+ meta: platformWriteMetaSchema.parse(envelope.meta)
579
+ };
580
+ };
581
+ return {
582
+ /** 진단 — 이 자격이 어느 워크스페이스·source에 묶였는가 */
583
+ me: () => request("GET", "/v1/me", { parse: parseData((v) => platformMeSchema.parse(v)) }),
584
+ works: {
585
+ listPipelines: () => request("GET", "/v1/works/pipelines", { parse: parseData((v) => platformPipelineSchema.array().parse(v)) }),
586
+ upsertTask: (externalId, input) => request("PUT", `/v1/works/tasks/${encodeURIComponent(externalId)}`, {
587
+ body: input,
588
+ parse: parseWrite
589
+ }),
590
+ getTask: (externalId) => request("GET", `/v1/works/tasks/${encodeURIComponent(externalId)}`, { parse: parseData((v) => platformTaskSchema.parse(v)) }),
591
+ setTaskStage: (externalId, input) => request("PATCH", `/v1/works/tasks/${encodeURIComponent(externalId)}/stage`, {
592
+ body: input,
593
+ parse: parseWrite
594
+ }),
595
+ upsertPipeline: (key, input) => request("PUT", `/v1/works/pipelines/${encodeURIComponent(key)}`, {
596
+ body: input,
597
+ parse: (value) => {
598
+ const envelope = value;
599
+ return {
600
+ data: platformPipelineResourceSchema.parse(envelope.data),
601
+ meta: platformWriteMetaSchema.parse(envelope.meta)
602
+ };
603
+ }
604
+ }),
605
+ deletePipeline: (key, options) => request("DELETE", `/v1/works/pipelines/${encodeURIComponent(key)}${options?.allowDestructive ? "?allowDestructive=true" : ""}`, { parse: parseData((v) => v) }),
606
+ importPipeline: (key, input) => request("POST", `/v1/works/pipelines/${encodeURIComponent(key)}/import`, {
607
+ body: input,
608
+ parse: parseData((v) => platformPipelineResourceSchema.parse(v))
609
+ })
610
+ },
611
+ resources: { list: () => request("GET", "/v1/resources", { parse: parseData((v) => platformResourcesV2Schema.parse(v)) }) },
612
+ brands: {
613
+ upsert: (key, input) => request("PUT", `/v1/brands/${encodeURIComponent(key)}`, {
614
+ body: input,
615
+ parse: parseWriteWith(platformBrandResourceSchema)
616
+ }),
617
+ import: (key, input) => request("POST", `/v1/brands/${encodeURIComponent(key)}/import`, {
618
+ body: input,
619
+ parse: parseData((v) => platformBrandResourceSchema.parse(v))
620
+ })
621
+ },
622
+ brandapps: {
623
+ upsert: (slug, input) => request("PUT", `/v1/brandapps/${encodeURIComponent(slug)}`, {
624
+ body: input,
625
+ parse: parseWriteWith(platformBrandappResourceSchema)
626
+ }),
627
+ import: (slug) => request("POST", `/v1/brandapps/${encodeURIComponent(slug)}/import`, {
628
+ body: {},
629
+ parse: parseData((v) => platformBrandappResourceSchema.parse(v))
630
+ })
631
+ },
632
+ oauthClients: {
633
+ upsert: (key, input) => request("PUT", `/v1/oauth-clients/${encodeURIComponent(key)}`, {
634
+ body: input,
635
+ parse: parseWriteWith(platformOAuthClientResourceSchema)
636
+ }),
637
+ rotateSecret: (key) => request("POST", `/v1/oauth-clients/${encodeURIComponent(key)}/rotate-secret`, {
638
+ body: {},
639
+ parse: parseData((v) => platformOAuthClientResourceSchema.parse(v))
640
+ }),
641
+ delete: (key, options) => request("DELETE", `/v1/oauth-clients/${encodeURIComponent(key)}${options?.allowDestructive ? "?allowDestructive=true" : ""}`, { parse: parseData((v) => v) }),
642
+ import: (key, input) => request("POST", `/v1/oauth-clients/${encodeURIComponent(key)}/import`, {
643
+ body: input,
644
+ parse: parseData((v) => platformOAuthClientResourceSchema.parse(v))
645
+ })
646
+ },
647
+ eav: { applySchema: (input) => request("POST", "/v1/eav/schema/apply", {
648
+ body: input,
649
+ parse: parseData((v) => platformEavSchemaApplyResultSchema.parse(v))
650
+ }) },
651
+ lock: {
652
+ acquire: (holderId) => request("POST", "/v1/lock", {
653
+ body: { holderId },
654
+ parse: parseData((v) => platformLockAcquiredSchema.parse(v))
655
+ }),
656
+ release: (holderId) => request("DELETE", "/v1/lock", {
657
+ body: { holderId },
658
+ parse: parseData((v) => platformLockReleasedSchema.parse(v))
659
+ })
660
+ },
661
+ webhooks: {
662
+ list: () => request("GET", "/v1/webhooks", { parse: parseData((v) => platformWebhookSchema.array().parse(v)) }),
663
+ upsert: (input) => request("PUT", "/v1/webhooks", {
664
+ body: input,
665
+ parse: (value) => {
666
+ const envelope = value;
667
+ return {
668
+ data: platformWebhookSchema.parse(envelope.data),
669
+ meta: platformWriteMetaSchema.parse(envelope.meta)
670
+ };
671
+ }
672
+ }),
673
+ delete: (id) => request("DELETE", `/v1/webhooks/${encodeURIComponent(id)}`, { parse: parseData((v) => v) })
674
+ },
675
+ /** 테스트·진단용 — 캐시된 토큰을 버린다 */
676
+ invalidateToken: () => {
677
+ token = null;
678
+ },
679
+ urls: {
680
+ platformUrl,
681
+ idBaseUrl
682
+ }
683
+ };
684
+ }
685
+
686
+ //#endregion
687
+ export { DEFAULT_PLATFORM_SCOPES, PLATFORM_ADMIN_SCOPE, PLATFORM_BRANDAPP_STATUSES, PLATFORM_DOMAIN_STATUSES, PLATFORM_MANAGED_BY_VALUES, PLATFORM_OAUTH_APPLICATION_TYPES, PLATFORM_OAUTH_GRANT_TYPES, PLATFORM_STAGE_COLORS, PLATFORM_TASK_OUTCOMES, PLATFORM_TASK_PRIORITIES, PLATFORM_TOKEN_ENDPOINT_AUTH_METHODS, PLATFORM_WEBHOOK_TRIGGERS, PlatformApiError, REOPT_PLATFORM_ID_URLS, REOPT_PLATFORM_URLS, createPlatformClient, platformBrandImportInputSchema, platformBrandResourceSchema, platformBrandUpsertInputSchema, platformBrandappResourceSchema, platformBrandappUpsertInputSchema, platformEavBrandappResourcesSchema, platformEavEntityResourceSchema, platformEavSchemaApplyInputSchema, platformEavSchemaApplyResultSchema, platformEavSchemaOperationSchema, platformErrorSchema, platformExternalIdSchema, platformLockAcquiredSchema, platformLockReleasedSchema, platformMeSchema, platformOAuthClientImportInputSchema, platformOAuthClientResourceSchema, platformOAuthClientUpsertInputSchema, platformPipelineImportInputSchema, platformPipelineResourceSchema, platformPipelineSchema, platformPipelineStageInputSchema, platformPipelineUpsertInputSchema, platformResourceKeySchema, platformResourcesSchema, platformResourcesV2Schema, platformTaskSchema, platformTaskStageInputSchema, platformTaskStageSchema, platformTaskUpsertInputSchema, platformWebhookResourceSchema, platformWebhookSchema, platformWebhookUpsertInputSchema, platformWorkTaskStageChangedEventSchema, platformWriteMetaSchema, resolvePlatformUrls };
688
+ //# sourceMappingURL=index.js.map