@openclaw/line 2026.11.12 → 2026.12.1-beta.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.
@@ -0,0 +1,664 @@
1
+ import { S as normalizeLineMessagingTarget, a as runLinePushWithRetries, p as applyLineQuoteToken, r as findLineHttpError, s as resolveLineChannelAccessToken, x as buildLineMediaMessage, y as withoutLineQuoteTokens } from "./channel-D8h0qJMW.mjs";
2
+ import { r as resolveLineAccount } from "./accounts-Dm_NoU7R.mjs";
3
+ import { _ as fitsLineFlexBubble, c as cardBox, l as cardText, p as normalizeLineMessage, r as createReceiptCard, v as toFlexMessage } from "./schedule-cards-D2zI0jRv.mjs";
4
+ import { i as createQuickReplyItems, n as createFlexMessage, r as createLocationMessage } from "./template-messages-5ZlXYNrb.mjs";
5
+ import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
6
+ import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
7
+ import { chunkTextRanges, markdownToIRWithMeta, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
8
+ import { createStaleWhileRevalidateCache } from "openclaw/plugin-sdk/collection-runtime";
9
+ import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
10
+ import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
11
+ import { HTTPFetchError, messagingApi } from "@line/bot-sdk";
12
+ import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
13
+ import { fetchWithRuntimeDispatcherOrMockedGlobal } from "openclaw/plugin-sdk/runtime-fetch";
14
+ import { randomUUID } from "node:crypto";
15
+ import lineBotSdkPackage from "@line/bot-sdk/package.json" with { type: "json" };
16
+ import { recordChannelActivity } from "openclaw/plugin-sdk/channel-activity-runtime";
17
+ import { captureEffectAuthority } from "openclaw/plugin-sdk/fetch-runtime";
18
+ import { redactToolPayloadText } from "openclaw/plugin-sdk/logging-core";
19
+ import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
20
+ import { createDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
21
+ // extensions/line/src/markdown-to-line.ts
22
+ /** Prose uses LINE's Markdown chunker. A projected table needs contiguous, lossless slices. */
23
+ function chunkLineText(segment, limit, chunkMarkdown) {
24
+ if (!segment.parts) return chunkMarkdown(segment.text, limit).map((text) => ({ text }));
25
+ const chunks = [];
26
+ let text = "";
27
+ let firstTable = Infinity;
28
+ let lastTable = 0;
29
+ const flush = () => {
30
+ const start = Math.min(text.length - text.trimStart().length, firstTable);
31
+ const end = Math.max(text.trimEnd().length, lastTable);
32
+ const pushText = text.slice(start, end);
33
+ if (pushText) chunks.push(pushText === text.trim() ? { text } : {
34
+ text,
35
+ pushText
36
+ });
37
+ text = "";
38
+ firstTable = Infinity;
39
+ lastTable = 0;
40
+ };
41
+ for (const part of segment.parts) {
42
+ const pieces = part.table ? chunkTextRanges(part.text, {
43
+ limit,
44
+ mode: "preferred"
45
+ }).map(({ start, end }) => part.text.slice(start, end)) : chunkMarkdown(part.text, limit);
46
+ for (const [index, piece] of pieces.entries()) {
47
+ if (!part.table && index > 0 || limit > 0 && text.length + piece.length > limit) flush();
48
+ if (part.table) {
49
+ firstTable = Math.min(firstTable, text.length);
50
+ lastTable = text.length + piece.length;
51
+ }
52
+ text += piece;
53
+ }
54
+ }
55
+ flush();
56
+ return chunks;
57
+ }
58
+ const LINE_MARKDOWN_OPTIONS = {
59
+ assistantTranscriptRoleHeaders: true,
60
+ autolink: false,
61
+ blockquotePrefix: "",
62
+ headingStyle: "none",
63
+ horizontalRuleText: "",
64
+ linkify: false,
65
+ preserveSourceBlockSpacing: true
66
+ };
67
+ const TRANSCRIPT_ROLE_PREFIX = "[assistant-authored transcript] ";
68
+ const LINE_FLEX_CODE_CARD_MAX_CHARS = 2e3;
69
+ function parseLineMarkdown(text, tableMode = "block") {
70
+ return markdownToIRWithMeta(text, {
71
+ ...LINE_MARKDOWN_OPTIONS,
72
+ tableMode
73
+ });
74
+ }
75
+ function rangesOverlap(left, right) {
76
+ return left.start < right.end && right.start < left.end;
77
+ }
78
+ /** A link shows its href after the label unless the label already is that address. */
79
+ function linkAddsHref(rawLabel, href) {
80
+ const label = rawLabel.trim();
81
+ return Boolean(href && label && label !== href && `mailto:${label}` !== href);
82
+ }
83
+ function trimOutsideInlineCode(text, ir, codeSpans) {
84
+ const first = codeSpans[0];
85
+ const last = codeSpans.at(-1);
86
+ if (!first || !last) return text.trim();
87
+ const before = ir.text.slice(0, first.start).replace(/<\/?u>/gi, "");
88
+ const after = ir.text.slice(last.end).replace(/<\/?u>/gi, "");
89
+ const start = Math.min(before.length, text.length - text.trimStart().length);
90
+ const end = text.length - Math.min(after.length, text.length - text.trimEnd().length);
91
+ return text.slice(start, end);
92
+ }
93
+ function projectPlainText(ir, omitted = [], additionalInsertions = [], onSegment) {
94
+ const insertions = [...additionalInsertions];
95
+ for (const link of ir.links) {
96
+ if (omitted.some((range) => rangesOverlap(range, link))) continue;
97
+ const href = link.href.trim();
98
+ if (linkAddsHref(ir.text.slice(link.start, link.end), href)) insertions.push({
99
+ position: link.end,
100
+ text: ` (${href})`
101
+ });
102
+ }
103
+ for (const annotation of ir.annotations ?? []) if (annotation.type === "assistant_transcript_role" && !omitted.some((range) => rangesOverlap(range, annotation))) insertions.push({
104
+ position: annotation.start,
105
+ text: TRANSCRIPT_ROLE_PREFIX
106
+ });
107
+ const inlineCodeSpans = ir.styles.filter((span) => span.style === "code" && !omitted.some((range) => rangesOverlap(range, span)));
108
+ for (const span of inlineCodeSpans) {
109
+ const code = ir.text.slice(span.start, span.end);
110
+ if (stripMarkdown(code, { assistantTranscriptRoleHeaders: true }).startsWith(TRANSCRIPT_ROLE_PREFIX)) insertions.push({
111
+ position: span.start,
112
+ text: TRANSCRIPT_ROLE_PREFIX
113
+ });
114
+ }
115
+ insertions.sort((left, right) => left.position - right.position);
116
+ const underlineTags = [...ir.text.matchAll(/<\/?u>/gi)].map((match) => ({
117
+ start: match.index,
118
+ end: match.index + match[0].length
119
+ })).filter((tag) => !inlineCodeSpans.some((span) => rangesOverlap(tag, span)) && !omitted.some((span) => rangesOverlap(tag, span)));
120
+ const removed = [...omitted, ...underlineTags].toSorted((left, right) => left.start - right.start);
121
+ let output = "";
122
+ let parts = [];
123
+ const flushText = () => {
124
+ const tail = parts.length ? output.trimEnd() : output.trim();
125
+ if (parts.length && tail) parts.push({ text: tail });
126
+ const text = parts.length ? parts.map((part) => part.text).join("") : tail;
127
+ if (text) onSegment?.({
128
+ type: "text",
129
+ text,
130
+ ...parts.some((part) => part.table) ? { parts } : {}
131
+ });
132
+ output = "";
133
+ parts = [];
134
+ };
135
+ let cursor = 0;
136
+ let insertionIndex = 0;
137
+ const appendRange = (end) => {
138
+ while (insertionIndex < insertions.length) {
139
+ const insertion = insertions[insertionIndex];
140
+ if (!insertion || insertion.position > end) break;
141
+ if (insertion.position >= cursor) {
142
+ output += ir.text.slice(cursor, insertion.position);
143
+ if ("text" in insertion) output += insertion.text;
144
+ else if ("tableText" in insertion) {
145
+ output += "\n\n";
146
+ const preceding = parts.length ? output : output.trimStart();
147
+ if (preceding) parts.push({ text: preceding });
148
+ if (insertion.tableText) parts.push({
149
+ text: insertion.tableText,
150
+ table: insertion.preserveTableSpaces
151
+ });
152
+ output = "\n\n";
153
+ } else if (onSegment) {
154
+ flushText();
155
+ onSegment({
156
+ type: "flex",
157
+ message: insertion.message
158
+ });
159
+ }
160
+ cursor = insertion.position;
161
+ }
162
+ insertionIndex += 1;
163
+ }
164
+ output += ir.text.slice(cursor, end);
165
+ cursor = end;
166
+ };
167
+ for (const range of removed) {
168
+ appendRange(range.start);
169
+ cursor = Math.max(cursor, range.end);
170
+ while (insertionIndex < insertions.length && (insertions[insertionIndex]?.position ?? cursor) < cursor) insertionIndex += 1;
171
+ }
172
+ appendRange(ir.text.length);
173
+ if (onSegment) {
174
+ flushText();
175
+ return "";
176
+ }
177
+ return trimOutsideInlineCode(output, ir, inlineCodeSpans);
178
+ }
179
+ function renderTableCell(cell) {
180
+ if (!cell.text) return {
181
+ text: "-",
182
+ hasMarkup: false
183
+ };
184
+ const codeSpans = cell.styles.filter((span) => span.style === "code");
185
+ const tags = [...cell.text.matchAll(/<\/?u>/gi)].map((match) => ({
186
+ start: match.index,
187
+ end: match.index + match[0].length,
188
+ closing: match[0][1] === "/"
189
+ })).filter((tag) => !codeSpans.some((span) => rangesOverlap(tag, span)));
190
+ const boundaries = /* @__PURE__ */ new Set([0, cell.text.length]);
191
+ for (const style of cell.styles) {
192
+ boundaries.add(style.start);
193
+ boundaries.add(style.end);
194
+ }
195
+ for (const link of cell.links) boundaries.add(link.end);
196
+ for (const tag of tags) {
197
+ boundaries.add(tag.start);
198
+ boundaries.add(tag.end);
199
+ }
200
+ const sortedBoundaries = [...boundaries].toSorted((left, right) => left - right);
201
+ const spans = [];
202
+ let underlineDepth = 0;
203
+ let hasMarkup = false;
204
+ const appendSpan = (span) => {
205
+ const previous = spans.at(-1);
206
+ if (previous && previous.weight === span.weight && previous.style === span.style && previous.decoration === span.decoration) previous.text = `${previous.text ?? ""}${span.text ?? ""}`;
207
+ else spans.push(span);
208
+ };
209
+ for (let index = 0; index < sortedBoundaries.length - 1; index += 1) {
210
+ const start = sortedBoundaries[index];
211
+ const end = sortedBoundaries[index + 1];
212
+ if (start === void 0 || end === void 0) continue;
213
+ const tag = tags.find((candidate) => candidate.start === start);
214
+ if (tag) {
215
+ underlineDepth += tag.closing ? -1 : 1;
216
+ hasMarkup = true;
217
+ continue;
218
+ }
219
+ const text = cell.text.slice(start, end);
220
+ if (text) {
221
+ const active = new Set(cell.styles.filter((style) => style.start <= start && style.end >= end).map((style) => style.style));
222
+ const weight = active.has("bold") ? "bold" : void 0;
223
+ const style = active.has("italic") ? "italic" : void 0;
224
+ const decoration = active.has("strikethrough") ? "line-through" : underlineDepth > 0 ? "underline" : void 0;
225
+ hasMarkup ||= weight !== void 0 || style !== void 0 || decoration !== void 0;
226
+ appendSpan({
227
+ type: "span",
228
+ text,
229
+ weight,
230
+ style,
231
+ decoration
232
+ });
233
+ }
234
+ for (const link of cell.links.filter((candidate) => candidate.end === end)) {
235
+ const href = link.href.trim();
236
+ if (linkAddsHref(cell.text.slice(link.start, link.end), href)) {
237
+ appendSpan({
238
+ type: "span",
239
+ text: ` (${href})`
240
+ });
241
+ hasMarkup = true;
242
+ }
243
+ }
244
+ }
245
+ return {
246
+ text: trimOutsideInlineCode(spans.map((span) => span.text ?? "").join(""), cell, codeSpans) || "-",
247
+ ...hasMarkup ? { contents: spans } : {},
248
+ hasMarkup
249
+ };
250
+ }
251
+ function convertTableToFlexBubble(table) {
252
+ const requiresPlainCells = table.rowCells.length > 10;
253
+ if (requiresPlainCells && (table.headers.length !== 2 || table.rowCells.length > 12)) return;
254
+ let hasInlineMarkup = false;
255
+ const renderCells = (cells) => {
256
+ const rendered = [];
257
+ for (const cell of cells) {
258
+ const prepared = renderTableCell(cell);
259
+ if (requiresPlainCells && prepared.hasMarkup) return;
260
+ hasInlineMarkup ||= prepared.hasMarkup;
261
+ rendered.push(prepared);
262
+ }
263
+ return rendered;
264
+ };
265
+ const headerCells = renderCells(table.headerCells);
266
+ if (!headerCells) return;
267
+ const rowCells = [];
268
+ for (const row of table.rowCells) {
269
+ const cells = renderCells(row);
270
+ if (!cells) return;
271
+ rowCells.push(cells);
272
+ }
273
+ if (table.headers.length === 2 && !hasInlineMarkup) return createReceiptCard({
274
+ title: headerCells.map((cell) => cell.text).join(" / "),
275
+ items: rowCells.map((row) => ({
276
+ name: row[0]?.text ?? "-",
277
+ value: row[1]?.text ?? "-"
278
+ }))
279
+ });
280
+ const renderRow = (cells, textStyle, rowStyle) => cardBox("horizontal", cells.map((cell) => cardText(cell.text, {
281
+ contents: cell.contents,
282
+ ...textStyle,
283
+ size: "sm",
284
+ flex: 1,
285
+ wrap: true
286
+ })), rowStyle);
287
+ const headerRow = renderRow(headerCells, {
288
+ weight: "bold",
289
+ color: "#333333"
290
+ }, { paddingBottom: "sm" });
291
+ const dataRows = rowCells.map((row, rowIndex) => renderRow(table.headers.map((_, colIndex) => row[colIndex] ?? {
292
+ text: "-",
293
+ hasMarkup: false
294
+ }), { color: "#666666" }, { margin: rowIndex === 0 ? "md" : "sm" }));
295
+ return {
296
+ type: "bubble",
297
+ body: cardBox("vertical", [
298
+ headerRow,
299
+ {
300
+ type: "separator",
301
+ margin: "sm"
302
+ },
303
+ ...dataRows
304
+ ], { paddingAll: "lg" })
305
+ };
306
+ }
307
+ /** Parse once, route existing block surfaces to Flex, and project the remainder as plain text. */
308
+ function processLineMessage(text) {
309
+ const { ir, tables } = parseLineMarkdown(text);
310
+ const codeSpans = ir.styles.filter((span) => span.style === "code_block");
311
+ const plainTextInsertions = [];
312
+ for (const table of tables) {
313
+ const bubble = convertTableToFlexBubble(table);
314
+ if (!bubble || !fitsLineFlexBubble(bubble)) {
315
+ const hasPaddedCode = (cell) => cell.styles.some(({ style, start, end }) => style === "code" && /^\s|\s$/u.test(cell.text.slice(start, end)));
316
+ const markdownCell = (cell) => projectPlainText(cell).replace(/[\\|`*_[\]~<>&]/gu, "\\$&").replace(/\r?\n/gu, " ").replace(/^\s+|(?<=\S)\s+$/gu, (edge) => "`" + (/[^ ]/u.test(edge) ? ` ${edge} ` : edge) + "`");
317
+ const markdownRow = (cells) => `| ${cells.map(markdownCell).join(" | ")} |`;
318
+ const markdown = [
319
+ markdownRow(table.headerCells),
320
+ `| ${table.headerCells.map(() => "---").join(" | ")} |`,
321
+ ...table.rowCells.map(markdownRow)
322
+ ].join("\n");
323
+ plainTextInsertions.push({
324
+ position: table.placeholderOffset,
325
+ tableText: projectPlainText(parseLineMarkdown(markdown, "bullets").ir),
326
+ preserveTableSpaces: table.headerCells.some(hasPaddedCode) || table.rowCells.some((row) => row.some(hasPaddedCode))
327
+ });
328
+ continue;
329
+ }
330
+ const message = toFlexMessage("Table", bubble);
331
+ plainTextInsertions.push({
332
+ position: table.placeholderOffset,
333
+ message
334
+ });
335
+ }
336
+ for (const span of codeSpans) {
337
+ const block = {
338
+ ...span.language ? { language: span.language } : {},
339
+ code: ir.text.slice(span.start, span.end).trimEnd()
340
+ };
341
+ if (!block.code.trim()) continue;
342
+ if (block.code.length > LINE_FLEX_CODE_CARD_MAX_CHARS) {
343
+ plainTextInsertions.push({
344
+ position: span.start,
345
+ text: `\n\n${block.code}\n\n`
346
+ });
347
+ continue;
348
+ }
349
+ const titleText = block.language ? `Code (${block.language})` : "Code";
350
+ plainTextInsertions.push({
351
+ position: span.start,
352
+ message: toFlexMessage("Code", {
353
+ type: "bubble",
354
+ body: cardBox("vertical", [cardText(titleText, {
355
+ weight: "bold",
356
+ size: "sm",
357
+ color: "#666666"
358
+ }), cardBox("vertical", [cardText(block.code, {
359
+ size: "xs",
360
+ color: "#333333",
361
+ wrap: true
362
+ })], {
363
+ backgroundColor: "#F5F5F5",
364
+ paddingAll: "md",
365
+ cornerRadius: "md",
366
+ margin: "sm"
367
+ })], { paddingAll: "lg" })
368
+ })
369
+ });
370
+ }
371
+ const segments = [];
372
+ projectPlainText(ir, codeSpans, plainTextInsertions, (segment) => segments.push(segment));
373
+ return segments;
374
+ }
375
+ // extensions/line/src/outbound-message-log.ts
376
+ const RECENT_SENT_LIMIT = 500;
377
+ const recentSentByAccount = /* @__PURE__ */ new Map();
378
+ function recentSentFor(accountId) {
379
+ const existing = recentSentByAccount.get(accountId);
380
+ if (existing) return existing;
381
+ const created = createDedupeCache({
382
+ ttlMs: 0,
383
+ maxSize: RECENT_SENT_LIMIT
384
+ });
385
+ recentSentByAccount.set(accountId, created);
386
+ return created;
387
+ }
388
+ function recordLineSentMessages(accountId, messageIds) {
389
+ if (messageIds.length === 0) return;
390
+ const recentSent = recentSentFor(accountId);
391
+ for (const messageId of messageIds) recentSent.check(messageId);
392
+ }
393
+ function quotesLineBotMessage(accountId, quotedMessageId) {
394
+ return recentSentByAccount.get(accountId)?.peek(quotedMessageId) ?? false;
395
+ }
396
+ // extensions/line/src/send.ts
397
+ const PROFILE_CACHE_TTL_MS = 3e5;
398
+ const PROFILE_CACHE_MAX_ENTRIES = 1e3;
399
+ const profileCache = createStaleWhileRevalidateCache({
400
+ maxEntries: PROFILE_CACHE_MAX_ENTRIES,
401
+ ttlMs: PROFILE_CACHE_TTL_MS
402
+ });
403
+ const groupNameCache = createStaleWhileRevalidateCache({
404
+ maxEntries: PROFILE_CACHE_MAX_ENTRIES,
405
+ ttlMs: PROFILE_CACHE_TTL_MS
406
+ });
407
+ const LINE_PROVIDER_RESPONSE_MAX_BYTES = 16384;
408
+ function resolveLineProviderMessageIds(response, operation) {
409
+ const sentMessages = Array.isArray(response?.sentMessages) ? response.sentMessages : [];
410
+ const messageIds = sentMessages.flatMap((entry) => {
411
+ const id = entry && typeof entry === "object" ? entry.id : void 0;
412
+ const messageId = typeof id === "string" ? id.trim() : "";
413
+ return messageId ? [messageId] : [];
414
+ });
415
+ const messageId = messageIds[0];
416
+ if (!messageId || messageIds.length !== sentMessages.length) throw createChannelPartialDeliveryError(/* @__PURE__ */ new Error(`LINE ${operation} response did not include a sent message id`), {
417
+ messageIds,
418
+ visibleReplySent: true
419
+ });
420
+ return {
421
+ messageId,
422
+ messageIds
423
+ };
424
+ }
425
+ function normalizeTarget(to) {
426
+ const normalized = normalizeLineMessagingTarget(to);
427
+ if (!normalized) throw new Error("Recipient is required for LINE sends");
428
+ if (normalized.length >= 33 && !/^[CUR]/.test(normalized)) throw new Error(`Recipient is not a valid LINE id (case-sensitive; expected leading capital C/U/R): ${truncateUtf16Safe(normalized, 4)}…`);
429
+ return normalized;
430
+ }
431
+ function resolveLineMessagingAccount(opts) {
432
+ const cfg = requireRuntimeConfig(opts.cfg, "LINE send");
433
+ const account = resolveLineAccount({
434
+ cfg,
435
+ accountId: opts.accountId
436
+ });
437
+ return {
438
+ account,
439
+ token: resolveLineChannelAccessToken(opts.channelAccessToken, account)
440
+ };
441
+ }
442
+ async function sendLineProviderMessages(operation, token, request, retryKey, authorize, assertDirectAdapterHandoff) {
443
+ try {
444
+ return await postLineProviderMessages(operation, token, request, retryKey, authorize, assertDirectAdapterHandoff);
445
+ } catch (error) {
446
+ const unquoted = findLineHttpError(error)?.status === 400 ? withoutLineQuoteTokens(request.messages) : void 0;
447
+ if (!unquoted) throw error;
448
+ return await postLineProviderMessages(operation, token, {
449
+ ...request,
450
+ messages: unquoted
451
+ }, retryKey, authorize, assertDirectAdapterHandoff);
452
+ }
453
+ }
454
+ async function postLineProviderMessages(operation, token, request, retryKey, authorize, assertDirectAdapterHandoff) {
455
+ const effect = captureEffectAuthority();
456
+ const requestBody = JSON.stringify(request);
457
+ if (authorize) {
458
+ const authorized = authorize();
459
+ if (!(typeof authorized === "boolean" ? authorized : await authorized)) throw new Error("LINE send authorization denied");
460
+ }
461
+ const response = await effect.initiate(() => {
462
+ assertDirectAdapterHandoff?.();
463
+ return fetchWithRuntimeDispatcherOrMockedGlobal(`https://api.line.me/v2/bot/message/${operation}`, {
464
+ method: "POST",
465
+ headers: {
466
+ "Content-Type": "application/json",
467
+ Authorization: `Bearer ${token}`,
468
+ "User-Agent": `@line/bot-sdk/${lineBotSdkPackage.version}`,
469
+ ...retryKey ? { "X-Line-Retry-Key": retryKey } : {}
470
+ },
471
+ body: requestBody
472
+ });
473
+ });
474
+ const acceptedRetryConflict = retryKey !== void 0 && response.status === 409;
475
+ if (!response.ok && !acceptedRetryConflict) {
476
+ const body = await readResponseTextLimited(response, LINE_PROVIDER_RESPONSE_MAX_BYTES).catch(() => "");
477
+ const redactedBody = redactToolPayloadText(body);
478
+ throw new HTTPFetchError(`${response.status} - ${response.statusText}`, {
479
+ status: response.status,
480
+ statusText: response.statusText,
481
+ headers: response.headers,
482
+ body: redactedBody
483
+ });
484
+ }
485
+ try {
486
+ return await readProviderJsonResponse(response, `LINE ${operation} response`, { maxBytes: LINE_PROVIDER_RESPONSE_MAX_BYTES });
487
+ } catch (error) {
488
+ throw createChannelPartialDeliveryError(error, {
489
+ messageIds: [],
490
+ visibleReplySent: true
491
+ });
492
+ }
493
+ }
494
+ function recordLineOutboundActivity(accountId, delivery) {
495
+ recordLineSentMessages(accountId, delivery.messageIds);
496
+ try {
497
+ recordChannelActivity({
498
+ channel: "line",
499
+ accountId,
500
+ direction: "outbound"
501
+ });
502
+ } catch (error) {
503
+ throw createChannelPartialDeliveryError(error, {
504
+ messageIds: delivery.messageIds,
505
+ ...delivery.receipt ? { receipt: delivery.receipt } : {},
506
+ visibleReplySent: true
507
+ });
508
+ }
509
+ }
510
+ function resolveLineReceiptKind(messages) {
511
+ const types = new Set(messages.map((message) => message.type));
512
+ if (types.has("audio")) return "voice";
513
+ if (types.has("image") || types.has("video")) return "media";
514
+ if (types.has("flex") || types.has("template") || types.has("location")) return "card";
515
+ if (types.has("text")) return "text";
516
+ return "unknown";
517
+ }
518
+ async function pushLineMessages(to, messages, opts) {
519
+ if (messages.length === 0) throw new Error("Message must be non-empty for LINE sends");
520
+ const { account, token } = resolveLineMessagingAccount(opts);
521
+ const chatId = normalizeTarget(to);
522
+ const normalizedMessages = applyLineQuoteToken(messages, opts.quoteToken).map(normalizeLineMessage);
523
+ const retryKey = randomUUID();
524
+ const { messageId, messageIds } = resolveLineProviderMessageIds(await runLinePushWithRetries(() => sendLineProviderMessages("push", token, {
525
+ to: chatId,
526
+ messages: normalizedMessages
527
+ }, retryKey, opts.authorize, opts.assertDirectAdapterHandoff), "line:push"), "push");
528
+ const result = {
529
+ messageId,
530
+ chatId,
531
+ receipt: createMessageReceiptFromOutboundResults({
532
+ results: messageIds.map((providerMessageId) => ({
533
+ channel: "line",
534
+ messageId: providerMessageId,
535
+ chatId,
536
+ conversationId: chatId,
537
+ meta: { messageCount: messages.length }
538
+ })),
539
+ ...chatId ? { threadId: chatId } : {},
540
+ kind: resolveLineReceiptKind(messages)
541
+ })
542
+ };
543
+ recordLineOutboundActivity(account.accountId, {
544
+ messageIds,
545
+ receipt: result.receipt
546
+ });
547
+ return result;
548
+ }
549
+ async function pushMessageLine(to, text, opts) {
550
+ const chatId = normalizeTarget(to);
551
+ const messages = [];
552
+ const mediaUrl = opts.mediaUrl?.trim();
553
+ if (mediaUrl) messages.push(await buildLineMediaMessage(mediaUrl, {
554
+ mediaKind: opts.mediaKind,
555
+ previewImageUrl: opts.previewImageUrl,
556
+ durationMs: opts.durationMs,
557
+ trackingId: opts.trackingId
558
+ }, chatId));
559
+ if (text?.trim()) messages.push({
560
+ type: "text",
561
+ text: text.trim()
562
+ });
563
+ return pushLineMessages(chatId, messages, opts);
564
+ }
565
+ async function replyMessageLine(replyToken, messages, opts) {
566
+ const { account, token } = resolveLineMessagingAccount(opts);
567
+ const { messageIds } = resolveLineProviderMessageIds(await sendLineProviderMessages("reply", token, {
568
+ replyToken,
569
+ messages: applyLineQuoteToken(messages, opts.quoteToken).map(normalizeLineMessage)
570
+ }, void 0, opts.authorize, opts.assertDirectAdapterHandoff), "reply");
571
+ recordLineOutboundActivity(account.accountId, { messageIds });
572
+ }
573
+ async function pushMessagesLine(to, messages, opts) {
574
+ return pushLineMessages(to, messages, opts);
575
+ }
576
+ async function pushLocationMessage(to, location, opts) {
577
+ return pushLineMessages(to, [createLocationMessage(location)], opts);
578
+ }
579
+ async function pushFlexMessage(to, altText, contents, opts) {
580
+ return pushLineMessages(to, [createFlexMessage(altText, contents)], opts);
581
+ }
582
+ async function pushTemplateMessage(to, template, opts) {
583
+ return pushLineMessages(to, [template], opts);
584
+ }
585
+ async function pushTextMessageWithQuickReplies(to, text, quickReplyLabels, opts) {
586
+ return pushLineMessages(to, [{
587
+ type: "text",
588
+ text,
589
+ quickReply: createQuickReplyItems(quickReplyLabels)
590
+ }], opts);
591
+ }
592
+ async function showLoadingAnimation(chatId, opts) {
593
+ const { token } = resolveLineMessagingAccount(opts);
594
+ const client = new messagingApi.MessagingApiClient({ channelAccessToken: token });
595
+ try {
596
+ await client.showLoadingAnimation({
597
+ chatId: normalizeTarget(chatId),
598
+ loadingSeconds: 20
599
+ });
600
+ } catch (err) {
601
+ logVerbose(`line: loading animation failed (non-fatal): ${String(err)}`);
602
+ }
603
+ }
604
+ function lineProfileCacheKey(accountId, userId, scope) {
605
+ const conversation = scope.groupId ? ["group", scope.groupId] : scope.roomId ? ["room", scope.roomId] : ["direct"];
606
+ return JSON.stringify([
607
+ accountId,
608
+ "profile",
609
+ ...conversation,
610
+ userId
611
+ ]);
612
+ }
613
+ function fetchLineMemberProfile(client, userId, scope) {
614
+ if (scope.groupId) return client.getGroupMemberProfile(scope.groupId, userId);
615
+ if (scope.roomId) return client.getRoomMemberProfile(scope.roomId, userId);
616
+ return client.getProfile(userId);
617
+ }
618
+ async function getUserProfile(userId, opts) {
619
+ try {
620
+ const { account, token } = resolveLineMessagingAccount(opts);
621
+ const cacheKey = lineProfileCacheKey(account.accountId, userId, opts);
622
+ const load = async () => {
623
+ try {
624
+ const profile = await fetchLineMemberProfile(new messagingApi.MessagingApiClient({ channelAccessToken: token }), userId, opts);
625
+ return {
626
+ displayName: profile.displayName,
627
+ pictureUrl: profile.pictureUrl
628
+ };
629
+ } catch (err) {
630
+ logVerbose(`line: failed to fetch profile for ${userId}: ${String(err)}`);
631
+ return null;
632
+ }
633
+ };
634
+ return (await profileCache.read(cacheKey, load, { allowStale: false })).value;
635
+ } catch (err) {
636
+ logVerbose(`line: failed to fetch profile for ${userId}: ${String(err)}`);
637
+ return null;
638
+ }
639
+ }
640
+ async function getUserDisplayName(userId, opts) {
641
+ return (await getUserProfile(userId, opts))?.displayName ?? userId;
642
+ }
643
+ async function getLineGroupName(groupId, opts) {
644
+ try {
645
+ const { account, token } = resolveLineMessagingAccount(opts);
646
+ const cacheKey = JSON.stringify([
647
+ account.accountId,
648
+ "group",
649
+ groupId
650
+ ]);
651
+ return (await groupNameCache.read(cacheKey, async () => {
652
+ try {
653
+ return (await new messagingApi.MessagingApiClient({ channelAccessToken: token }).getGroupSummary(groupId)).groupName.trim() || void 0;
654
+ } catch (err) {
655
+ logVerbose(`line: failed to fetch group summary for ${groupId}: ${String(err)}`);
656
+ return;
657
+ }
658
+ }, { allowStale: false })).value;
659
+ } catch (err) {
660
+ logVerbose(`line: failed to fetch group summary for ${groupId}: ${String(err)}`);
661
+ return;
662
+ }
663
+ }
664
+ export { pushLocationMessage as a, pushTemplateMessage as c, showLoadingAnimation as d, quotesLineBotMessage as f, pushFlexMessage as i, pushTextMessageWithQuickReplies as l, processLineMessage as m, getUserDisplayName as n, pushMessageLine as o, chunkLineText as p, getUserProfile as r, pushMessagesLine as s, getLineGroupName as t, replyMessageLine as u };