@koreaaitel/sdk 0.0.0-stage → 0.62.2

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +943 -2
  3. package/dist/agent/index.cjs +5512 -0
  4. package/dist/agent/index.cjs.map +1 -0
  5. package/dist/agent/index.d.cts +1574 -0
  6. package/dist/agent/index.d.ts +1574 -0
  7. package/dist/agent/index.js +5402 -0
  8. package/dist/agent/index.js.map +1 -0
  9. package/dist/agent/livekit/index.cjs +675 -0
  10. package/dist/agent/livekit/index.cjs.map +1 -0
  11. package/dist/agent/livekit/index.d.cts +165 -0
  12. package/dist/agent/livekit/index.d.ts +165 -0
  13. package/dist/agent/livekit/index.js +669 -0
  14. package/dist/agent/livekit/index.js.map +1 -0
  15. package/dist/chunk-35XJNMFU.js +10 -0
  16. package/dist/chunk-35XJNMFU.js.map +1 -0
  17. package/dist/chunk-B3QB5WPI.cjs +202 -0
  18. package/dist/chunk-B3QB5WPI.cjs.map +1 -0
  19. package/dist/chunk-I7N2GTBL.js +6 -0
  20. package/dist/chunk-I7N2GTBL.js.map +1 -0
  21. package/dist/chunk-LLPMUDNE.cjs +16 -0
  22. package/dist/chunk-LLPMUDNE.cjs.map +1 -0
  23. package/dist/chunk-PDE4I4MV.cjs +1134 -0
  24. package/dist/chunk-PDE4I4MV.cjs.map +1 -0
  25. package/dist/chunk-T4ZQXFTN.js +181 -0
  26. package/dist/chunk-T4ZQXFTN.js.map +1 -0
  27. package/dist/chunk-TCIIGMEU.cjs +8 -0
  28. package/dist/chunk-TCIIGMEU.cjs.map +1 -0
  29. package/dist/chunk-ZFBHUDJB.js +1103 -0
  30. package/dist/chunk-ZFBHUDJB.js.map +1 -0
  31. package/dist/client-CrTIZPmY.d.cts +3074 -0
  32. package/dist/client-DJApW4Uf.d.ts +3074 -0
  33. package/dist/error-D1uHhe6r.d.cts +205 -0
  34. package/dist/error-D1uHhe6r.d.ts +205 -0
  35. package/dist/index.cjs +1741 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +22 -0
  38. package/dist/index.d.ts +22 -0
  39. package/dist/index.js +1638 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/media-profile-DZCqLJKa.d.cts +492 -0
  42. package/dist/media-profile-DZCqLJKa.d.ts +492 -0
  43. package/dist/solapi/index.cjs +684 -0
  44. package/dist/solapi/index.cjs.map +1 -0
  45. package/dist/solapi/index.d.cts +282 -0
  46. package/dist/solapi/index.d.ts +282 -0
  47. package/dist/solapi/index.js +673 -0
  48. package/dist/solapi/index.js.map +1 -0
  49. package/package.json +121 -4
@@ -0,0 +1,684 @@
1
+ 'use strict';
2
+
3
+ var chunkB3QB5WPI_cjs = require('../chunk-B3QB5WPI.cjs');
4
+
5
+ // src/solapi/_concurrency.ts
6
+ var DEFAULT_CONCURRENCY = 10;
7
+ async function mapWithConcurrency(items, limit, run) {
8
+ const results = new Array(items.length);
9
+ let cursor = 0;
10
+ const worker = async () => {
11
+ for (let index = cursor++; index < items.length; index = cursor++) {
12
+ results[index] = await run(items[index]);
13
+ }
14
+ };
15
+ const workers = Math.min(Math.max(1, limit), items.length);
16
+ await Promise.all(Array.from({ length: workers }, worker));
17
+ return results;
18
+ }
19
+
20
+ // src/solapi/_message-type.ts
21
+ var SMS_MAX_EUCKR_BYTES = 90;
22
+ function euckrByteLength(text) {
23
+ let bytes = 0;
24
+ for (const ch of text) bytes += ch.codePointAt(0) < 128 ? 1 : 2;
25
+ return bytes;
26
+ }
27
+ var normalizePhone = (value) => value.replace(/-/g, "");
28
+ var upperType = (message) => message.type === void 0 ? "" : String(message.type).toUpperCase();
29
+ function clawopsType(message) {
30
+ const type = upperType(message);
31
+ if (type === "SMS") return "sms";
32
+ if (type === "LMS") return "lms";
33
+ if (message.subject !== void 0 && message.subject !== null && message.subject !== "") {
34
+ return "lms";
35
+ }
36
+ return euckrByteLength(message.text ?? "") > SMS_MAX_EUCKR_BYTES ? "lms" : "sms";
37
+ }
38
+
39
+ // src/solapi/fallback-text.ts
40
+ var VARIABLE_KEY = /^#\{.+\}$/;
41
+ var LEFTOVER = /#\{[^}]*\}/g;
42
+ var asKey = (key) => VARIABLE_KEY.test(key) ? key : `#{${key}}`;
43
+ function render(content, variables = {}) {
44
+ let out = content;
45
+ for (const [key, value] of Object.entries(variables)) {
46
+ out = out.split(asKey(key)).join(value);
47
+ }
48
+ return out;
49
+ }
50
+ var leftovers = (text) => text.match(LEFTOVER) ?? [];
51
+ function templateRef(kakaoOptions) {
52
+ if (kakaoOptions === null || typeof kakaoOptions !== "object") return {};
53
+ const options = kakaoOptions;
54
+ const templateId = typeof options.templateId === "string" ? options.templateId : void 0;
55
+ let variables;
56
+ const raw = options.variables;
57
+ if (raw !== null && typeof raw === "object") {
58
+ const entries = Object.entries(raw).filter(
59
+ (entry) => typeof entry[1] === "string"
60
+ );
61
+ if (entries.length > 0) variables = Object.fromEntries(entries);
62
+ }
63
+ return { templateId, variables };
64
+ }
65
+ var DEFAULT_FALLBACK_FIELD = "clawopsFallbackText";
66
+ async function resolveFallbackText(message, solapi, options = {}) {
67
+ const field = options.field ?? DEFAULT_FALLBACK_FIELD;
68
+ const explicit = message.customFields?.[field];
69
+ if (explicit !== void 0) return finish(explicit, "customFields");
70
+ const { templateId, variables } = templateRef(message.kakaoOptions);
71
+ if (templateId !== void 0) {
72
+ const cache = options.cache;
73
+ let pending = cache?.get(templateId);
74
+ if (pending === void 0) {
75
+ pending = solapi.getKakaoAlimtalkTemplate(templateId).then((template) => template.content);
76
+ cache?.set(templateId, pending);
77
+ pending.catch(() => cache?.delete(templateId));
78
+ }
79
+ const content = await pending;
80
+ if (content === void 0) {
81
+ return { ok: false, reason: "no_template_content", source: "template" };
82
+ }
83
+ return finish(render(content, variables), "template");
84
+ }
85
+ if (message.text === void 0 || message.text === null) {
86
+ return { ok: false, reason: "no_text", source: "text" };
87
+ }
88
+ return finish(message.text, "text");
89
+ }
90
+ function finish(text, source) {
91
+ const unresolved = leftovers(text);
92
+ return unresolved.length > 0 ? { ok: false, reason: "unresolved_variables", unresolved, source } : { ok: true, text, source };
93
+ }
94
+
95
+ // src/solapi/_fallback.ts
96
+ async function deliverFallback(request, solapi, context) {
97
+ let resolved;
98
+ try {
99
+ resolved = await resolveFallbackText(request.source, solapi, {
100
+ field: context.field,
101
+ cache: context.cache
102
+ });
103
+ } catch {
104
+ resolved = { ok: false, reason: "no_template_content", source: "template" };
105
+ }
106
+ if (!resolved.ok) return { status: "blocked", reason: resolved };
107
+ const subject = request.source.subject ?? void 0;
108
+ try {
109
+ const created = await context.clawops.messages.create({
110
+ to: normalizePhone(request.to),
111
+ from: normalizePhone(request.from),
112
+ body: resolved.text,
113
+ type: clawopsType({ text: resolved.text, subject }),
114
+ subject,
115
+ idempotencyKey: request.idempotencyKey
116
+ });
117
+ return {
118
+ status: "sent",
119
+ source: resolved.source,
120
+ text: resolved.text,
121
+ messageId: created.messageId
122
+ };
123
+ } catch (error) {
124
+ return { status: "send_failed", source: resolved.source, text: resolved.text, error };
125
+ }
126
+ }
127
+
128
+ // src/solapi/sweep.ts
129
+ var FALLBACK_MARKER_FIELD = "clawopsFallback";
130
+ var FALLBACK_MARKER_VALUE = "1";
131
+ var RECOMMENDED_EXCLUDED_CODES = [
132
+ // 수신거부 — 문자로 대체하면 거부한 사람에게 보내는 것이 된다
133
+ "3061",
134
+ // 스팸·발신번호 변작 차단 — 막힌 발송을 문자로 우회하는 셈이 된다
135
+ "3054",
136
+ "3055",
137
+ "3059",
138
+ "3112",
139
+ "3113",
140
+ // 설정 오류 — 전건이 실패한다. 문자가 덮으면 알림톡이 깨진 걸 몇 달간 모르고,
141
+ // 단가도 알림톡에서 문자로 조용히 올라간다
142
+ "3013",
143
+ "3101",
144
+ "3103",
145
+ "3105",
146
+ "3106",
147
+ "3109",
148
+ "3117",
149
+ // 발송 가능 시간이 아님 — 문자로 대체하면 야간 발송이 된다
150
+ "3108"
151
+ ];
152
+ var DEFAULT_SWEEP_TYPES = ["ATA"];
153
+ var DELIVERY_FAILURE = /^3\d{3}$/;
154
+ var IN_FLIGHT_CODE = "3000";
155
+ var DEFAULT_LOOKBACK_MS = 60 * 60 * 1e3;
156
+ var PAGE_SIZE = 200;
157
+ var MAX_PAGES = 50;
158
+ var firstRecipient = (to) => Array.isArray(to) ? to[0] : to;
159
+ var timeOf = (row) => row.dateUpdated ?? row.dateCreated;
160
+ async function sweepFailedAlimtalk(options) {
161
+ const targets = options.on ? new Set(options.on) : null;
162
+ const excluded = new Set(options.except ?? []);
163
+ const boundary = new Set(options.cursor?.seen ?? []);
164
+ const templateCache = options.templateCache ?? /* @__PURE__ */ new Map();
165
+ const window = options.lookbackMs ?? DEFAULT_LOOKBACK_MS;
166
+ const startDate = options.cursor ? new Date(options.cursor.updatedAt) : new Date(Date.now() - window);
167
+ const endDate = new Date(Math.min(Date.now(), startDate.getTime() + window));
168
+ const candidates = [];
169
+ const ineligible = [];
170
+ let scanned = 0;
171
+ let maxTime = startDate.getTime();
172
+ let atMax = new Set(boundary);
173
+ let truncated = false;
174
+ for (const type of options.types ?? DEFAULT_SWEEP_TYPES) {
175
+ let startKey;
176
+ for (let page = 0; page < MAX_PAGES; page += 1) {
177
+ const response = await options.solapi.getMessages({
178
+ type,
179
+ dateType: "UPDATED",
180
+ startDate,
181
+ endDate,
182
+ limit: PAGE_SIZE,
183
+ startKey
184
+ });
185
+ const rows = Object.values(response.messageList ?? {});
186
+ if (rows.length === 0) break;
187
+ scanned += rows.length;
188
+ for (const row of rows) {
189
+ const at = timeOf(row);
190
+ const id = row.messageId;
191
+ if (at && id) {
192
+ const time = new Date(at).getTime();
193
+ if (time > maxTime) {
194
+ maxTime = time;
195
+ atMax = /* @__PURE__ */ new Set([id]);
196
+ } else if (time === maxTime) {
197
+ atMax.add(id);
198
+ }
199
+ }
200
+ if (!id || boundary.has(id)) continue;
201
+ if (options.skip?.(id)) continue;
202
+ if (row.customFields?.[FALLBACK_MARKER_FIELD] !== FALLBACK_MARKER_VALUE) continue;
203
+ const code = String(row.statusCode ?? "");
204
+ if (code === IN_FLIGHT_CODE || !DELIVERY_FAILURE.test(code)) continue;
205
+ if (targets !== null && !targets.has(code) || excluded.has(code)) {
206
+ ineligible.push(row);
207
+ continue;
208
+ }
209
+ candidates.push(row);
210
+ }
211
+ startKey = response.nextKey ?? void 0;
212
+ if (!startKey) break;
213
+ if (page === MAX_PAGES - 1) truncated = true;
214
+ }
215
+ }
216
+ const deliveries = await mapWithConcurrency(
217
+ candidates,
218
+ options.concurrency ?? DEFAULT_CONCURRENCY,
219
+ async (row) => {
220
+ const to = firstRecipient(row.to);
221
+ if (to === void 0) return void 0;
222
+ return deliverFallback(
223
+ { source: row, to, from: options.from, idempotencyKey: `solapi:${row.messageId}` },
224
+ options.solapi,
225
+ { clawops: options.clawops, field: options.fallbackField, cache: templateCache }
226
+ );
227
+ }
228
+ );
229
+ const processed = [];
230
+ let blocked = 0;
231
+ for (const row of ineligible) {
232
+ blocked += 1;
233
+ options.onBlocked?.({
234
+ messageId: row.messageId ?? "",
235
+ to: firstRecipient(row.to) ?? "",
236
+ statusCode: String(row.statusCode ?? ""),
237
+ ok: false,
238
+ reason: "code_not_eligible"
239
+ });
240
+ }
241
+ deliveries.forEach((delivery, index) => {
242
+ const row = candidates[index];
243
+ const messageId = row.messageId ?? "";
244
+ const to = firstRecipient(row.to) ?? "";
245
+ const statusCode = String(row.statusCode ?? "");
246
+ if (delivery === void 0) return;
247
+ if (delivery.status !== "sent") {
248
+ blocked += 1;
249
+ options.onBlocked?.(
250
+ delivery.status === "blocked" ? { messageId, to, statusCode, ...delivery.reason } : (
251
+ // 문구는 만들었는데 ClawOps 가 거절했다. 다음 스윕이 다시 시도하고,
252
+ // 멱등키가 같아 중복 발송은 되지 않는다
253
+ { messageId, to, statusCode, ok: false, reason: "send_rejected" }
254
+ )
255
+ );
256
+ return;
257
+ }
258
+ processed.push(messageId);
259
+ options.onFallback?.({
260
+ messageId,
261
+ to,
262
+ statusCode,
263
+ source: delivery.source,
264
+ text: delivery.text
265
+ });
266
+ });
267
+ const cursor = truncated ? options.cursor ?? { updatedAt: startDate.toISOString(), seen: [] } : { updatedAt: new Date(maxTime).toISOString(), seen: [...atMax] };
268
+ return { cursor, scanned, sent: processed.length, blocked, truncated, processed };
269
+ }
270
+
271
+ // src/solapi/index.ts
272
+ var ZERO_CASH = { requested: 0, replacement: 0, refund: 0, sum: 0 };
273
+ var CHARGE_KEYS = [
274
+ "sms",
275
+ "lms",
276
+ "mms",
277
+ "ata",
278
+ "cta",
279
+ "cti",
280
+ "nsa",
281
+ "rcs_sms",
282
+ "rcs_lms",
283
+ "rcs_mms",
284
+ "rcs_tpl"
285
+ ];
286
+ var NO_CHARGE = Object.fromEntries(
287
+ CHARGE_KEYS.map((k) => [k, {}])
288
+ );
289
+ var NO_PROFIT = Object.fromEntries(CHARGE_KEYS.map((k) => [k, 0]));
290
+ var OURS = /* @__PURE__ */ new Set(["SMS", "LMS", "MMS"]);
291
+ var VENDOR_OPTION_FIELDS = [
292
+ "kakaoOptions",
293
+ "rcsOptions",
294
+ "naverOptions",
295
+ "voiceOptions",
296
+ "faxOptions"
297
+ ];
298
+ var hasVendorOptions = (message) => VENDOR_OPTION_FIELDS.some((field) => message[field] != null);
299
+ var recipientsOf = (to) => Array.isArray(to) ? to : [to];
300
+ var CLAWOPS_FAILURE_STATUS_CODE = "CLAWOPS";
301
+ function normalizeFallback(config) {
302
+ if (config === void 0 || config === true) return { enabled: true };
303
+ if (config === false || !config.enabled) return void 0;
304
+ return config;
305
+ }
306
+ function isMessageNotReceived(error) {
307
+ return typeof error === "object" && error !== null && "failedMessageList" in error && Array.isArray(error.failedMessageList);
308
+ }
309
+ function assertConfigSupported(config) {
310
+ if (!config) return;
311
+ const unsupported = [];
312
+ if (config.scheduledDate !== void 0) unsupported.push("scheduledDate");
313
+ if (config.allowDuplicates === false) unsupported.push("allowDuplicates: false");
314
+ if (unsupported.length > 0) {
315
+ throw new chunkB3QB5WPI_cjs.SolapiBridgeError(
316
+ `ClawOps \uB85C \uBCF4\uB0B4\uB294 \uBA54\uC2DC\uC9C0\uC5D0\uB294 ${unsupported.join(", ")} \uB97C \uC801\uC6A9\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD574\uB2F9 \uC124\uC815\uC774 \uD544\uC694\uD55C \uBC1C\uC1A1\uC740 \uC194\uB77C\uD53C\uB85C \uBCF4\uB0B4\uAC70\uB098 \uD638\uCD9C\uC744 \uBD84\uB9AC\uD558\uC2ED\uC2DC\uC624.`
317
+ );
318
+ }
319
+ }
320
+ function makeGroupInfo(base, counts) {
321
+ if (base) {
322
+ return {
323
+ ...base,
324
+ count: {
325
+ ...base.count,
326
+ total: base.count.total + counts.ok + counts.failed,
327
+ registeredSuccess: base.count.registeredSuccess + counts.ok,
328
+ registeredFailed: base.count.registeredFailed + counts.failed,
329
+ sentReplacement: base.count.sentReplacement + counts.replacement
330
+ }
331
+ };
332
+ }
333
+ const registered = {
334
+ total: counts.ok + counts.failed,
335
+ registeredSuccess: counts.ok,
336
+ registeredFailed: counts.failed
337
+ };
338
+ const now = (/* @__PURE__ */ new Date()).toISOString();
339
+ return {
340
+ count: {
341
+ ...registered,
342
+ sentTotal: 0,
343
+ sentFailed: 0,
344
+ sentSuccess: 0,
345
+ sentPending: 0,
346
+ sentReplacement: counts.replacement,
347
+ refund: 0
348
+ },
349
+ countForCharge: NO_CHARGE,
350
+ balance: ZERO_CASH,
351
+ point: ZERO_CASH,
352
+ app: { profit: NO_PROFIT, appId: null },
353
+ log: [],
354
+ status: "PENDING",
355
+ allowDuplicates: false,
356
+ isRefunded: false,
357
+ accountId: "",
358
+ masterAccountId: null,
359
+ apiVersion: "4",
360
+ // 솔라피 그룹이 아니므로 getGroupMessages 로 조회되지 않는다. 접두사로 구분한다
361
+ groupId: `CLAWOPS-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`,
362
+ price: {},
363
+ dateCreated: now,
364
+ dateUpdated: now,
365
+ scheduledDate: null,
366
+ dateSent: null,
367
+ dateCompleted: null
368
+ };
369
+ }
370
+ function partition(list) {
371
+ const forSolapi = [];
372
+ const forClawOps = [];
373
+ for (const message of list) {
374
+ const type = upperType(message);
375
+ if (type !== "" && !OURS.has(type) || hasVendorOptions(message)) {
376
+ forSolapi.push(message);
377
+ continue;
378
+ }
379
+ if (message.imageId !== void 0) {
380
+ throw new chunkB3QB5WPI_cjs.SolapiBridgeError(
381
+ "imageId \uB294 \uC194\uB77C\uD53C\uC5D0 \uC5C5\uB85C\uB4DC\uB41C \uD30C\uC77C ID \uB77C ClawOps \uB85C \uC804\uB2EC\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uC774\uBBF8\uC9C0 \uCCA8\uBD80\uAC00 \uD544\uC694\uD558\uBA74 ClawOps \uC758 mediaUrl \uB85C \uC9C1\uC811 \uBC1C\uC1A1\uD558\uC2ED\uC2DC\uC624."
382
+ );
383
+ }
384
+ for (const to of recipientsOf(message.to)) forClawOps.push({ to, message });
385
+ }
386
+ return { forSolapi, forClawOps };
387
+ }
388
+ function fallbackFrom(message) {
389
+ const kakaoOptions = message?.kakaoOptions;
390
+ if (!kakaoOptions || kakaoOptions.disableSms === true) return void 0;
391
+ return message?.from;
392
+ }
393
+ function clawopsFailure(to, from, error) {
394
+ return {
395
+ to: normalizePhone(to),
396
+ from: normalizePhone(from),
397
+ type: "SMS",
398
+ statusMessage: error instanceof Error ? error.message : String(error),
399
+ country: "82",
400
+ messageId: "",
401
+ statusCode: CLAWOPS_FAILURE_STATUS_CODE,
402
+ accountId: ""
403
+ };
404
+ }
405
+ function buildPlans(messages, fallbackEnabled) {
406
+ return messages.map((message) => {
407
+ const kakaoOptions = message.kakaoOptions;
408
+ if (!kakaoOptions || !fallbackEnabled || kakaoOptions.bms) {
409
+ return { outgoing: message, source: message };
410
+ }
411
+ const fields = message.customFields ?? {};
412
+ const canMark = FALLBACK_MARKER_FIELD in fields || Object.keys(fields).length < 10;
413
+ if (!canMark) return { outgoing: message, source: message };
414
+ const { from: _from, ...rest } = message;
415
+ let customFields = message.customFields;
416
+ if (fallbackFrom(message) !== void 0) {
417
+ customFields = { ...fields, [FALLBACK_MARKER_FIELD]: FALLBACK_MARKER_VALUE };
418
+ }
419
+ return {
420
+ outgoing: {
421
+ ...rest,
422
+ ...customFields ? { customFields } : {},
423
+ kakaoOptions: { ...kakaoOptions, disableSms: true }
424
+ },
425
+ source: message
426
+ };
427
+ });
428
+ }
429
+ function matchFailures(plans, failures) {
430
+ const byRecipient = /* @__PURE__ */ new Map();
431
+ plans.forEach((plan, index) => {
432
+ for (const to of recipientsOf(plan.outgoing.to)) {
433
+ const key = normalizePhone(to);
434
+ const bucket = byRecipient.get(key);
435
+ if (bucket) bucket.push(index);
436
+ else byRecipient.set(key, [index]);
437
+ }
438
+ });
439
+ return failures.map((failure) => {
440
+ const index = byRecipient.get(normalizePhone(failure.to))?.shift();
441
+ return { failure, plan: index === void 0 ? void 0 : plans[index] };
442
+ });
443
+ }
444
+ function makeSend(options, fallbackConfig, templateCache) {
445
+ const fallbackEnabled = fallbackConfig !== void 0;
446
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
447
+ const viaClawOps = async (to, message, statusMessage = "\uC815\uC0C1 \uC811\uC218") => {
448
+ const from = normalizePhone(message.from ?? options.from);
449
+ const type = clawopsType(message);
450
+ try {
451
+ const created = await options.clawops.messages.create({
452
+ to: normalizePhone(to),
453
+ from,
454
+ body: message.text ?? "",
455
+ type,
456
+ subject: message.subject
457
+ });
458
+ return {
459
+ ok: true,
460
+ sent: { messageId: created.messageId, statusCode: "2000", statusMessage }
461
+ };
462
+ } catch (error) {
463
+ return {
464
+ ok: false,
465
+ failed: {
466
+ to: normalizePhone(to),
467
+ from,
468
+ type: type.toUpperCase(),
469
+ statusMessage: error instanceof Error ? error.message : String(error),
470
+ country: "82",
471
+ messageId: "",
472
+ statusCode: CLAWOPS_FAILURE_STATUS_CODE,
473
+ accountId: ""
474
+ }
475
+ };
476
+ }
477
+ };
478
+ const runFallbacks = async (plans, failures, solapi) => {
479
+ const jobs = matchFailures(plans, failures);
480
+ const deliveries = await mapWithConcurrency(jobs, concurrency, async (job) => {
481
+ const from = fallbackFrom(job.plan?.source);
482
+ if (from === void 0) return void 0;
483
+ return deliverFallback({ source: job.plan.source, to: job.failure.to, from }, solapi, {
484
+ clawops: options.clawops,
485
+ field: fallbackConfig?.field,
486
+ cache: templateCache
487
+ });
488
+ });
489
+ const sent = [];
490
+ const failed = [];
491
+ let replacement = 0;
492
+ let failedCount = 0;
493
+ deliveries.forEach((delivery, index) => {
494
+ const { failure } = jobs[index];
495
+ if (delivery === void 0) {
496
+ failed.push(failure);
497
+ return;
498
+ }
499
+ if (delivery.status === "blocked") {
500
+ fallbackConfig?.onBlocked?.({ to: failure.to, ...delivery.reason });
501
+ failed.push(failure);
502
+ return;
503
+ }
504
+ if (delivery.status === "send_failed") {
505
+ failed.push(clawopsFailure(failure.to, options.from, delivery.error));
506
+ failedCount += 1;
507
+ return;
508
+ }
509
+ sent.push({
510
+ messageId: delivery.messageId,
511
+ statusCode: "2000",
512
+ statusMessage: "\uC815\uC0C1 \uC811\uC218(\uB300\uCCB4\uBC1C\uC1A1)"
513
+ });
514
+ replacement += 1;
515
+ fallbackConfig?.onFallback?.({
516
+ to: failure.to,
517
+ source: delivery.source,
518
+ text: delivery.text
519
+ });
520
+ });
521
+ return { sent, failed, replacement, failedCount };
522
+ };
523
+ return async (messages, config) => {
524
+ const list = Array.isArray(messages) ? messages : [messages];
525
+ const { forSolapi, forClawOps } = partition(list);
526
+ const sent = [];
527
+ const failed = [];
528
+ let replacement = 0;
529
+ let ourOk = 0;
530
+ let ourFailed = 0;
531
+ const willFallback = fallbackEnabled && forSolapi.some((message) => fallbackFrom(message) !== void 0);
532
+ if (forClawOps.length > 0 || willFallback) assertConfigSupported(config);
533
+ if (forClawOps.length > 0) {
534
+ for (const outcome of await mapWithConcurrency(
535
+ forClawOps,
536
+ concurrency,
537
+ (item) => viaClawOps(item.to, item.message)
538
+ )) {
539
+ if (outcome.ok) {
540
+ sent.push(outcome.sent);
541
+ ourOk += 1;
542
+ } else {
543
+ failed.push(outcome.failed);
544
+ ourFailed += 1;
545
+ }
546
+ }
547
+ }
548
+ let base = null;
549
+ if (forSolapi.length > 0) {
550
+ const solapi = options.solapi;
551
+ if (!solapi) {
552
+ throw new chunkB3QB5WPI_cjs.SolapiBridgeError(
553
+ "\uC54C\uB9BC\uD1A1\xB7RCS \uB97C \uBCF4\uB0B4\uB824\uBA74 solapi \uC778\uC2A4\uD134\uC2A4\uB97C \uB118\uACA8\uC57C \uD569\uB2C8\uB2E4. new ClawOpsMessageService({ solapi: new SolapiMessageService(key, secret), \u2026 })"
554
+ );
555
+ }
556
+ const plans = buildPlans(forSolapi, fallbackEnabled);
557
+ let solapiFailed = [];
558
+ try {
559
+ const response = await solapi.send(
560
+ plans.map((plan) => plan.outgoing),
561
+ config
562
+ );
563
+ base = response.groupInfo;
564
+ sent.push(...response.messageList ?? []);
565
+ solapiFailed = response.failedMessageList;
566
+ } catch (error) {
567
+ if (!isMessageNotReceived(error)) throw error;
568
+ solapiFailed = error.failedMessageList;
569
+ }
570
+ if (solapiFailed.length > 0) {
571
+ if (!fallbackEnabled) {
572
+ failed.push(...solapiFailed);
573
+ } else {
574
+ const result = await runFallbacks(plans, solapiFailed, solapi);
575
+ sent.push(...result.sent);
576
+ failed.push(...result.failed);
577
+ replacement += result.replacement;
578
+ ourFailed += result.failedCount;
579
+ }
580
+ }
581
+ }
582
+ return {
583
+ groupInfo: makeGroupInfo(base, { ok: ourOk, failed: ourFailed, replacement }),
584
+ messageList: sent,
585
+ failedMessageList: failed
586
+ };
587
+ };
588
+ }
589
+ var NON_METHOD_KEYS = /* @__PURE__ */ new Set(["then", "toJSON", "inspect"]);
590
+ var DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1e3;
591
+ var PROCESSED_LIMIT = 1e4;
592
+ function startSweepLoop(options, sweep, solapi, templateCache) {
593
+ const processed = /* @__PURE__ */ new Set();
594
+ let cursor = sweep.initialCursor;
595
+ let running = false;
596
+ const tick = async () => {
597
+ if (running) return;
598
+ running = true;
599
+ try {
600
+ const result = await sweepFailedAlimtalk({
601
+ clawops: options.clawops,
602
+ solapi,
603
+ from: options.from,
604
+ cursor,
605
+ lookbackMs: sweep.lookbackMs,
606
+ on: sweep.on,
607
+ except: sweep.except,
608
+ types: sweep.types,
609
+ fallbackField: sweep.field,
610
+ concurrency: options.concurrency,
611
+ templateCache,
612
+ skip: (messageId) => processed.has(messageId),
613
+ onFallback: sweep.onFallback,
614
+ onBlocked: sweep.onBlocked
615
+ });
616
+ cursor = result.cursor;
617
+ for (const messageId of result.processed) processed.add(messageId);
618
+ if (processed.size > PROCESSED_LIMIT) {
619
+ for (const messageId of [...processed].slice(0, processed.size - PROCESSED_LIMIT / 2)) {
620
+ processed.delete(messageId);
621
+ }
622
+ }
623
+ if (result.scanned > 0) sweep.onCursor?.(result.cursor);
624
+ } catch (error) {
625
+ sweep.onError?.(error);
626
+ } finally {
627
+ running = false;
628
+ }
629
+ };
630
+ const timer = setInterval(() => void tick(), sweep.intervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
631
+ timer.unref?.();
632
+ }
633
+ function create(options) {
634
+ const fallbackConfig = normalizeFallback(options.fallback);
635
+ const templateCache = /* @__PURE__ */ new Map();
636
+ const send = makeSend(options, fallbackConfig, templateCache);
637
+ if (fallbackConfig?.mode === "sweep") {
638
+ if (!options.solapi) {
639
+ throw new chunkB3QB5WPI_cjs.SolapiBridgeError(
640
+ "mode: 'sweep' \uC740 \uC194\uB77C\uD53C \uB9AC\uD3EC\uD2B8\uB97C \uD6D1\uB294 \uAE30\uB2A5\uC774\uB77C solapi \uC778\uC2A4\uD134\uC2A4\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uBB38\uC790\uB9CC \uBCF4\uB0B8\uB2E4\uBA74 \uC774 \uC124\uC815\uC740 \uD560 \uC77C\uC774 \uC5C6\uC2B5\uB2C8\uB2E4."
641
+ );
642
+ }
643
+ startSweepLoop(options, fallbackConfig, options.solapi, templateCache);
644
+ }
645
+ const solapi = options.solapi;
646
+ const handler = solapi ? {
647
+ get(instance, property) {
648
+ if (property === "send") return send;
649
+ const value = Reflect.get(instance, property, instance);
650
+ return typeof value === "function" ? value.bind(instance) : value;
651
+ }
652
+ } : {
653
+ get(_instance, property) {
654
+ if (property === "send") return send;
655
+ if (typeof property === "symbol" || NON_METHOD_KEYS.has(property)) return void 0;
656
+ if (property in Object.prototype) {
657
+ return Reflect.get(Object.prototype, property);
658
+ }
659
+ return () => {
660
+ throw new chunkB3QB5WPI_cjs.SolapiBridgeError(
661
+ `${String(property)}() \uB294 \uC194\uB77C\uD53C \uAE30\uB2A5\uC785\uB2C8\uB2E4. solapi \uC778\uC2A4\uD134\uC2A4\uB97C \uB118\uACA8\uC8FC\uC138\uC694.`
662
+ );
663
+ };
664
+ }
665
+ };
666
+ return new Proxy(solapi ?? {}, handler);
667
+ }
668
+ var ClawOpsMessageService = function(options) {
669
+ return create(options);
670
+ };
671
+
672
+ Object.defineProperty(exports, "SolapiBridgeError", {
673
+ enumerable: true,
674
+ get: function () { return chunkB3QB5WPI_cjs.SolapiBridgeError; }
675
+ });
676
+ exports.CLAWOPS_FAILURE_STATUS_CODE = CLAWOPS_FAILURE_STATUS_CODE;
677
+ exports.ClawOpsMessageService = ClawOpsMessageService;
678
+ exports.DEFAULT_FALLBACK_FIELD = DEFAULT_FALLBACK_FIELD;
679
+ exports.FALLBACK_MARKER_FIELD = FALLBACK_MARKER_FIELD;
680
+ exports.RECOMMENDED_EXCLUDED_CODES = RECOMMENDED_EXCLUDED_CODES;
681
+ exports.resolveFallbackText = resolveFallbackText;
682
+ exports.sweepFailedAlimtalk = sweepFailedAlimtalk;
683
+ //# sourceMappingURL=index.cjs.map
684
+ //# sourceMappingURL=index.cjs.map