@kodelyth/line 2026.5.39 → 2026.5.42

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 (120) hide show
  1. package/api.ts +11 -0
  2. package/channel-plugin-api.ts +1 -0
  3. package/contract-api.ts +5 -0
  4. package/dist/accounts-CD4A1FE7.js +105 -0
  5. package/dist/api.js +11 -0
  6. package/dist/basic-cards-BISytiSa.js +307 -0
  7. package/dist/card-command-dQBX3fVN.js +240 -0
  8. package/dist/channel-DV5h44-j.js +649 -0
  9. package/dist/channel-plugin-api.js +2 -0
  10. package/dist/channel.runtime-Cc-v3szZ.js +4 -0
  11. package/dist/contract-api.js +2 -0
  12. package/dist/index.js +45 -0
  13. package/dist/markdown-to-line-CC3BU6CC.js +810 -0
  14. package/dist/monitor-Ci8Hg8ay.js +1485 -0
  15. package/dist/monitor.runtime-t6-QvlDB.js +2 -0
  16. package/dist/outbound.runtime-D1CxEvcL.js +2 -0
  17. package/dist/probe-BPSs_A_8.js +30 -0
  18. package/dist/probe.runtime-7u2o9QN5.js +2 -0
  19. package/dist/reply-payload-transform-CDuBzoT4.js +855 -0
  20. package/dist/runtime-api.js +291 -0
  21. package/dist/schedule-cards-D-yZMHDE.js +359 -0
  22. package/dist/secret-contract-api.js +5 -0
  23. package/dist/setup-api.js +2 -0
  24. package/dist/setup-entry.js +11 -0
  25. package/dist/setup-surface-CHfQ6Z4i.js +282 -0
  26. package/index.ts +53 -0
  27. package/klaw.plugin.json +2 -329
  28. package/package.json +4 -4
  29. package/runtime-api.ts +179 -0
  30. package/secret-contract-api.ts +4 -0
  31. package/setup-api.ts +2 -0
  32. package/setup-entry.ts +9 -0
  33. package/src/account-helpers.ts +16 -0
  34. package/src/accounts.test.ts +288 -0
  35. package/src/accounts.ts +187 -0
  36. package/src/actions.ts +61 -0
  37. package/src/auto-reply-delivery.test.ts +253 -0
  38. package/src/auto-reply-delivery.ts +200 -0
  39. package/src/bindings.ts +65 -0
  40. package/src/bot-access.ts +30 -0
  41. package/src/bot-handlers.test.ts +1094 -0
  42. package/src/bot-handlers.ts +620 -0
  43. package/src/bot-message-context.test.ts +420 -0
  44. package/src/bot-message-context.ts +586 -0
  45. package/src/bot.ts +66 -0
  46. package/src/card-command.ts +347 -0
  47. package/src/channel-access-token.ts +14 -0
  48. package/src/channel-api.ts +17 -0
  49. package/src/channel-setup-status.contract.test.ts +70 -0
  50. package/src/channel-shared.ts +48 -0
  51. package/src/channel.logout.test.ts +145 -0
  52. package/src/channel.runtime.ts +3 -0
  53. package/src/channel.sendPayload.test.ts +659 -0
  54. package/src/channel.setup.ts +11 -0
  55. package/src/channel.status.test.ts +63 -0
  56. package/src/channel.ts +155 -0
  57. package/src/config-adapter.ts +29 -0
  58. package/src/config-schema.test.ts +53 -0
  59. package/src/config-schema.ts +81 -0
  60. package/src/download.test.ts +164 -0
  61. package/src/download.ts +34 -0
  62. package/src/flex-templates/basic-cards.ts +395 -0
  63. package/src/flex-templates/common.ts +20 -0
  64. package/src/flex-templates/media-control-cards.ts +555 -0
  65. package/src/flex-templates/message.ts +13 -0
  66. package/src/flex-templates/schedule-cards.ts +467 -0
  67. package/src/flex-templates/types.ts +22 -0
  68. package/src/flex-templates.ts +32 -0
  69. package/src/gateway.ts +129 -0
  70. package/src/group-keys.test.ts +123 -0
  71. package/src/group-keys.ts +65 -0
  72. package/src/group-policy.ts +22 -0
  73. package/src/markdown-to-line.test.ts +348 -0
  74. package/src/markdown-to-line.ts +416 -0
  75. package/src/message-cards.test.ts +204 -0
  76. package/src/monitor-durable.test.ts +57 -0
  77. package/src/monitor-durable.ts +37 -0
  78. package/src/monitor.lifecycle.test.ts +499 -0
  79. package/src/monitor.runtime.ts +1 -0
  80. package/src/monitor.ts +507 -0
  81. package/src/outbound-media.test.ts +194 -0
  82. package/src/outbound-media.ts +120 -0
  83. package/src/outbound.runtime.ts +12 -0
  84. package/src/outbound.ts +427 -0
  85. package/src/probe.contract.test.ts +9 -0
  86. package/src/probe.runtime.ts +1 -0
  87. package/src/probe.ts +34 -0
  88. package/src/quick-reply-fallback.ts +10 -0
  89. package/src/reply-chunks.test.ts +180 -0
  90. package/src/reply-chunks.ts +110 -0
  91. package/src/reply-payload-transform.test.ts +392 -0
  92. package/src/reply-payload-transform.ts +317 -0
  93. package/src/rich-menu.test.ts +315 -0
  94. package/src/rich-menu.ts +326 -0
  95. package/src/runtime.ts +32 -0
  96. package/src/send-receipt.ts +32 -0
  97. package/src/send.test.ts +453 -0
  98. package/src/send.ts +531 -0
  99. package/src/setup-core.ts +149 -0
  100. package/src/setup-runtime-api.ts +9 -0
  101. package/src/setup-surface.test.ts +481 -0
  102. package/src/setup-surface.ts +229 -0
  103. package/src/signature.test.ts +34 -0
  104. package/src/signature.ts +24 -0
  105. package/src/status.ts +37 -0
  106. package/src/template-messages.ts +333 -0
  107. package/src/types.ts +130 -0
  108. package/src/webhook-node.test.ts +598 -0
  109. package/src/webhook-node.ts +155 -0
  110. package/src/webhook-utils.ts +10 -0
  111. package/src/webhook.ts +135 -0
  112. package/tsconfig.json +16 -0
  113. package/api.js +0 -7
  114. package/channel-plugin-api.js +0 -7
  115. package/contract-api.js +0 -7
  116. package/index.js +0 -7
  117. package/runtime-api.js +0 -7
  118. package/secret-contract-api.js +0 -7
  119. package/setup-api.js +0 -7
  120. package/setup-entry.js +0 -7
@@ -0,0 +1,481 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { createStartAccountContext } from "klaw/plugin-sdk/channel-test-helpers";
4
+ import {
5
+ createPluginSetupWizardConfigure,
6
+ createTestWizardPrompter,
7
+ runSetupWizardConfigure,
8
+ } from "klaw/plugin-sdk/plugin-test-runtime";
9
+ import type { WizardPrompter } from "klaw/plugin-sdk/plugin-test-runtime";
10
+ import { bundledPluginRoot } from "klaw/plugin-sdk/test-fixtures";
11
+ import ts from "typescript";
12
+ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
13
+ import type { KlawConfig, PluginRuntime, ResolvedLineAccount } from "../api.js";
14
+ import { linePlugin } from "./channel.js";
15
+ import { lineGatewayAdapter } from "./gateway.js";
16
+ import { probeLineBot } from "./probe.js";
17
+ import { clearLineRuntime, setLineRuntime } from "./runtime.js";
18
+ import { lineSetupWizard } from "./setup-surface.js";
19
+ import { lineStatusAdapter } from "./status.js";
20
+
21
+ const { getBotInfoMock, MessagingApiClientMock } = vi.hoisted(() => {
22
+ const getBotInfoMock = vi.fn();
23
+ const MessagingApiClientMock = vi.fn(function () {
24
+ return { getBotInfo: getBotInfoMock };
25
+ });
26
+ return { getBotInfoMock, MessagingApiClientMock };
27
+ });
28
+
29
+ vi.mock("@line/bot-sdk", () => ({
30
+ messagingApi: { MessagingApiClient: MessagingApiClientMock },
31
+ }));
32
+
33
+ afterAll(() => {
34
+ vi.doUnmock("@line/bot-sdk");
35
+ vi.resetModules();
36
+ });
37
+
38
+ const lineConfigure = createPluginSetupWizardConfigure(linePlugin);
39
+ const LINE_SRC_PREFIX = `../../${bundledPluginRoot("line")}/src/`;
40
+
41
+ function normalizeModuleSpecifier(specifier: string): string | null {
42
+ if (specifier.startsWith("./src/")) {
43
+ return specifier;
44
+ }
45
+ if (specifier.startsWith(LINE_SRC_PREFIX)) {
46
+ return `./src/${specifier.slice(LINE_SRC_PREFIX.length)}`;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function collectModuleExportNames(filePath: string): string[] {
52
+ const sourcePath = filePath.replace(/\.js$/, ".ts");
53
+ const sourceText = readFileSync(sourcePath, "utf8");
54
+ const sourceFile = ts.createSourceFile(sourcePath, sourceText, ts.ScriptTarget.Latest, true);
55
+ const names = new Set<string>();
56
+
57
+ for (const statement of sourceFile.statements) {
58
+ if (
59
+ ts.isExportDeclaration(statement) &&
60
+ statement.exportClause &&
61
+ ts.isNamedExports(statement.exportClause)
62
+ ) {
63
+ for (const element of statement.exportClause.elements) {
64
+ if (!element.isTypeOnly) {
65
+ names.add(element.name.text);
66
+ }
67
+ }
68
+ continue;
69
+ }
70
+
71
+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
72
+ const isExported = modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
73
+ if (!isExported) {
74
+ continue;
75
+ }
76
+
77
+ if (ts.isVariableStatement(statement)) {
78
+ for (const declaration of statement.declarationList.declarations) {
79
+ if (ts.isIdentifier(declaration.name)) {
80
+ names.add(declaration.name.text);
81
+ }
82
+ }
83
+ continue;
84
+ }
85
+
86
+ if (
87
+ ts.isFunctionDeclaration(statement) ||
88
+ ts.isClassDeclaration(statement) ||
89
+ ts.isEnumDeclaration(statement)
90
+ ) {
91
+ if (statement.name) {
92
+ names.add(statement.name.text);
93
+ }
94
+ }
95
+ }
96
+
97
+ return Array.from(names).toSorted();
98
+ }
99
+
100
+ function collectRuntimeApiPreExports(runtimeApiPath: string): string[] {
101
+ const runtimeApiSource = readFileSync(runtimeApiPath, "utf8");
102
+ const runtimeApiFile = ts.createSourceFile(
103
+ runtimeApiPath,
104
+ runtimeApiSource,
105
+ ts.ScriptTarget.Latest,
106
+ true,
107
+ );
108
+ const preExports = new Set<string>();
109
+ let pluginSdkLineRuntimeSeen = false;
110
+ const removedLineRuntimeSpecifier = ["klaw", "plugin-sdk", "line-runtime"].join("/");
111
+
112
+ for (const statement of runtimeApiFile.statements) {
113
+ if (!ts.isExportDeclaration(statement)) {
114
+ continue;
115
+ }
116
+ const moduleSpecifier =
117
+ statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)
118
+ ? statement.moduleSpecifier.text
119
+ : undefined;
120
+ if (!moduleSpecifier) {
121
+ continue;
122
+ }
123
+ if (moduleSpecifier === removedLineRuntimeSpecifier) {
124
+ pluginSdkLineRuntimeSeen = true;
125
+ break;
126
+ }
127
+ const normalized = normalizeModuleSpecifier(moduleSpecifier);
128
+ if (!normalized) {
129
+ continue;
130
+ }
131
+
132
+ if (!statement.exportClause) {
133
+ for (const name of collectModuleExportNames(
134
+ path.join(process.cwd(), "extensions", "line", normalized),
135
+ )) {
136
+ preExports.add(name);
137
+ }
138
+ continue;
139
+ }
140
+
141
+ if (!ts.isNamedExports(statement.exportClause)) {
142
+ continue;
143
+ }
144
+
145
+ for (const element of statement.exportClause.elements) {
146
+ if (!element.isTypeOnly) {
147
+ preExports.add(element.name.text);
148
+ }
149
+ }
150
+ }
151
+
152
+ if (!pluginSdkLineRuntimeSeen) {
153
+ return [];
154
+ }
155
+
156
+ return Array.from(preExports).toSorted();
157
+ }
158
+
159
+ describe("line setup wizard", () => {
160
+ it("configures token and secret for the default account", async () => {
161
+ const prompter = createTestWizardPrompter({
162
+ text: vi.fn(async ({ message }: { message: string }) => {
163
+ if (message === "Enter LINE channel access token") {
164
+ return "line-token";
165
+ }
166
+ if (message === "Enter LINE channel secret") {
167
+ return "line-secret";
168
+ }
169
+ throw new Error(`Unexpected prompt: ${message}`);
170
+ }) as WizardPrompter["text"],
171
+ });
172
+
173
+ const result = await runSetupWizardConfigure({
174
+ configure: lineConfigure,
175
+ cfg: {} as KlawConfig,
176
+ prompter,
177
+ options: {},
178
+ });
179
+
180
+ expect(result.accountId).toBe("default");
181
+ expect(result.cfg.channels?.line?.enabled).toBe(true);
182
+ expect(result.cfg.channels?.line?.channelAccessToken).toBe("line-token");
183
+ expect(result.cfg.channels?.line?.channelSecret).toBe("line-secret");
184
+ });
185
+
186
+ it("reads the named-account DM policy instead of the channel root", () => {
187
+ expect(
188
+ lineSetupWizard.dmPolicy?.getCurrent(
189
+ {
190
+ channels: {
191
+ line: {
192
+ dmPolicy: "disabled",
193
+ accounts: {
194
+ work: {
195
+ channelAccessToken: "token",
196
+ channelSecret: "secret",
197
+ dmPolicy: "allowlist",
198
+ },
199
+ },
200
+ },
201
+ },
202
+ } as KlawConfig,
203
+ "work",
204
+ ),
205
+ ).toBe("allowlist");
206
+ });
207
+
208
+ it("reports account-scoped config keys for named accounts", () => {
209
+ expect(lineSetupWizard.dmPolicy?.resolveConfigKeys?.({} as KlawConfig, "work")).toEqual({
210
+ policyKey: "channels.line.accounts.work.dmPolicy",
211
+ allowFromKey: "channels.line.accounts.work.allowFrom",
212
+ });
213
+ });
214
+
215
+ it("uses configured defaultAccount for omitted DM policy account context", () => {
216
+ const cfg = {
217
+ channels: {
218
+ line: {
219
+ defaultAccount: "work",
220
+ dmPolicy: "disabled",
221
+ allowFrom: ["Uroot"],
222
+ accounts: {
223
+ work: {
224
+ channelAccessToken: "token",
225
+ channelSecret: "secret",
226
+ dmPolicy: "allowlist",
227
+ },
228
+ },
229
+ },
230
+ },
231
+ } as KlawConfig;
232
+
233
+ expect(lineSetupWizard.dmPolicy?.getCurrent(cfg)).toBe("allowlist");
234
+ expect(lineSetupWizard.dmPolicy?.resolveConfigKeys?.(cfg)).toEqual({
235
+ policyKey: "channels.line.accounts.work.dmPolicy",
236
+ allowFromKey: "channels.line.accounts.work.allowFrom",
237
+ });
238
+
239
+ const next = lineSetupWizard.dmPolicy?.setPolicy(cfg, "open");
240
+ const workAccount = next?.channels?.line?.accounts?.work as
241
+ | {
242
+ dmPolicy?: string;
243
+ }
244
+ | undefined;
245
+ expect(next?.channels?.line?.dmPolicy).toBe("disabled");
246
+ expect(workAccount?.dmPolicy).toBe("open");
247
+ });
248
+
249
+ it('writes open policy state to the named account and preserves inherited allowFrom with "*"', () => {
250
+ const next = lineSetupWizard.dmPolicy?.setPolicy(
251
+ {
252
+ channels: {
253
+ line: {
254
+ allowFrom: ["Uroot"],
255
+ accounts: {
256
+ work: {
257
+ channelAccessToken: "token",
258
+ channelSecret: "secret",
259
+ },
260
+ },
261
+ },
262
+ },
263
+ } as KlawConfig,
264
+ "open",
265
+ "work",
266
+ );
267
+
268
+ const workAccount = next?.channels?.line?.accounts?.work as
269
+ | {
270
+ dmPolicy?: string;
271
+ allowFrom?: string[];
272
+ }
273
+ | undefined;
274
+ expect(next?.channels?.line?.dmPolicy).toBeUndefined();
275
+ expect(next?.channels?.line?.allowFrom).toEqual(["Uroot"]);
276
+ expect(workAccount?.dmPolicy).toBe("open");
277
+ expect(workAccount?.allowFrom).toEqual(["Uroot", "*"]);
278
+ });
279
+
280
+ it("uses configured defaultAccount for omitted setup configured state", async () => {
281
+ const configured = await lineSetupWizard.status.resolveConfigured({
282
+ cfg: {
283
+ channels: {
284
+ line: {
285
+ defaultAccount: "work",
286
+ channelAccessToken: "root-token",
287
+ channelSecret: "root-secret",
288
+ accounts: {
289
+ alerts: {
290
+ channelAccessToken: "alerts-token",
291
+ channelSecret: "alerts-secret",
292
+ },
293
+ work: {
294
+ channelAccessToken: "",
295
+ channelSecret: "",
296
+ },
297
+ },
298
+ },
299
+ },
300
+ } as KlawConfig,
301
+ });
302
+
303
+ expect(configured).toBe(false);
304
+ });
305
+ });
306
+
307
+ describe("probeLineBot", () => {
308
+ beforeEach(() => {
309
+ getBotInfoMock.mockReset();
310
+ MessagingApiClientMock.mockReset();
311
+ MessagingApiClientMock.mockImplementation(function () {
312
+ return { getBotInfo: getBotInfoMock };
313
+ });
314
+ });
315
+
316
+ afterEach(() => {
317
+ clearLineRuntime();
318
+ vi.useRealTimers();
319
+ getBotInfoMock.mockClear();
320
+ });
321
+
322
+ it("returns timeout when bot info stalls", async () => {
323
+ vi.useFakeTimers();
324
+ getBotInfoMock.mockImplementation(() => new Promise(() => {}));
325
+
326
+ const probePromise = probeLineBot("token", 10);
327
+ await vi.advanceTimersByTimeAsync(20);
328
+ const result = await probePromise;
329
+
330
+ expect(result.ok).toBe(false);
331
+ expect(result.error).toBe("timeout");
332
+ });
333
+
334
+ it("returns bot info when available", async () => {
335
+ getBotInfoMock.mockResolvedValue({
336
+ displayName: "Klaw",
337
+ userId: "U123",
338
+ basicId: "@klaw",
339
+ pictureUrl: "https://example.com/bot.png",
340
+ });
341
+
342
+ const result = await probeLineBot("token", 50);
343
+
344
+ expect(result.ok).toBe(true);
345
+ expect(result.bot?.userId).toBe("U123");
346
+ });
347
+ });
348
+
349
+ describe("linePlugin status.probeAccount", () => {
350
+ it("falls back to the direct probe helper when runtime is not initialized", async () => {
351
+ MessagingApiClientMock.mockReset();
352
+ MessagingApiClientMock.mockImplementation(function () {
353
+ return { getBotInfo: getBotInfoMock };
354
+ });
355
+ getBotInfoMock.mockResolvedValue({
356
+ displayName: "Klaw",
357
+ userId: "U123",
358
+ basicId: "@klaw",
359
+ pictureUrl: "https://example.com/bot.png",
360
+ });
361
+
362
+ const params = {
363
+ cfg: {} as KlawConfig,
364
+ account: {
365
+ accountId: "default",
366
+ enabled: true,
367
+ channelAccessToken: "token",
368
+ channelSecret: "secret",
369
+ tokenSource: "config",
370
+ } as ResolvedLineAccount,
371
+ timeoutMs: 50,
372
+ };
373
+
374
+ clearLineRuntime();
375
+
376
+ await expect(lineStatusAdapter.probeAccount!(params)).resolves.toEqual(
377
+ await probeLineBot("token", 50),
378
+ );
379
+ });
380
+ });
381
+
382
+ describe("line runtime api", () => {
383
+ it("keeps the LINE runtime barrel self-contained", () => {
384
+ const runtimeApiPath = path.join(process.cwd(), "extensions", "line", "runtime-api.ts");
385
+ expect(collectRuntimeApiPreExports(runtimeApiPath)).toStrictEqual([]);
386
+ expect(collectRuntimeApiPreExports(runtimeApiPath)).toStrictEqual([]);
387
+ });
388
+ });
389
+
390
+ function createRuntime() {
391
+ const monitorLineProvider = vi.fn(
392
+ async (_opts: { accountId?: string; channelAccessToken: string; channelSecret: string }) => ({
393
+ account: { accountId: "default" },
394
+ handleWebhook: async () => {},
395
+ stop: () => {},
396
+ }),
397
+ );
398
+
399
+ const runtime = {
400
+ channel: {
401
+ line: {
402
+ monitorLineProvider,
403
+ },
404
+ },
405
+ logging: {
406
+ shouldLogVerbose: () => false,
407
+ },
408
+ } as unknown as PluginRuntime;
409
+
410
+ return { runtime, monitorLineProvider };
411
+ }
412
+
413
+ function createAccount(params: { token: string; secret: string }): ResolvedLineAccount {
414
+ return {
415
+ accountId: "default",
416
+ enabled: true,
417
+ channelAccessToken: params.token,
418
+ channelSecret: params.secret,
419
+ tokenSource: "config",
420
+ config: {} as ResolvedLineAccount["config"],
421
+ };
422
+ }
423
+
424
+ function startLineAccount(params: { account: ResolvedLineAccount; abortSignal?: AbortSignal }) {
425
+ const { runtime, monitorLineProvider } = createRuntime();
426
+ setLineRuntime(runtime);
427
+ return {
428
+ monitorLineProvider,
429
+ task: lineGatewayAdapter.startAccount!(
430
+ createStartAccountContext({
431
+ account: params.account,
432
+ abortSignal: params.abortSignal,
433
+ }),
434
+ ),
435
+ };
436
+ }
437
+
438
+ describe("linePlugin gateway.startAccount", () => {
439
+ it("fails startup when channel secret is missing", async () => {
440
+ const { monitorLineProvider, task } = startLineAccount({
441
+ account: createAccount({ token: "token", secret: " " }),
442
+ });
443
+
444
+ await expect(task).rejects.toThrow(
445
+ 'LINE webhook mode requires a non-empty channel secret for account "default".',
446
+ );
447
+ expect(monitorLineProvider).not.toHaveBeenCalled();
448
+ });
449
+
450
+ it("fails startup when channel access token is missing", async () => {
451
+ const { monitorLineProvider, task } = startLineAccount({
452
+ account: createAccount({ token: " ", secret: "secret" }),
453
+ });
454
+
455
+ await expect(task).rejects.toThrow(
456
+ 'LINE webhook mode requires a non-empty channel access token for account "default".',
457
+ );
458
+ expect(monitorLineProvider).not.toHaveBeenCalled();
459
+ });
460
+
461
+ it("starts provider when token and secret are present", async () => {
462
+ const abort = new AbortController();
463
+ const { monitorLineProvider, task } = startLineAccount({
464
+ account: createAccount({ token: "token", secret: "secret" }),
465
+ abortSignal: abort.signal,
466
+ });
467
+
468
+ await vi.waitFor(() => {
469
+ expect(monitorLineProvider).toHaveBeenCalledTimes(1);
470
+ });
471
+ const startupParams = (monitorLineProvider.mock.calls as unknown[][])[0]?.[0] as
472
+ | { accountId?: string; channelAccessToken?: string; channelSecret?: string }
473
+ | undefined;
474
+ expect(startupParams?.channelAccessToken).toBe("token");
475
+ expect(startupParams?.channelSecret).toBe("secret");
476
+ expect(startupParams?.accountId).toBe("default");
477
+
478
+ abort.abort();
479
+ await task;
480
+ });
481
+ });
@@ -0,0 +1,229 @@
1
+ import {
2
+ createAllowFromSection,
3
+ createStandardChannelSetupStatus,
4
+ mergeAllowFromEntries,
5
+ createSetupTranslator,
6
+ } from "klaw/plugin-sdk/setup";
7
+ import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
8
+ import { resolveDefaultLineAccountId } from "./accounts.js";
9
+ import {
10
+ isLineConfigured,
11
+ listLineAccountIds,
12
+ parseLineAllowFromId,
13
+ patchLineAccountConfig,
14
+ } from "./setup-core.js";
15
+ import {
16
+ DEFAULT_ACCOUNT_ID,
17
+ formatDocsLink,
18
+ resolveLineAccount,
19
+ setSetupChannelEnabled,
20
+ splitSetupEntries,
21
+ type ChannelSetupDmPolicy,
22
+ type ChannelSetupWizard,
23
+ } from "./setup-runtime-api.js";
24
+
25
+ const t = createSetupTranslator();
26
+
27
+ const channel = "line" as const;
28
+
29
+ const LINE_SETUP_HELP_LINES = [
30
+ t("wizard.line.helpOpenConsole"),
31
+ t("wizard.line.helpCopyCredentials"),
32
+ t("wizard.line.helpEnableWebhook"),
33
+ t("wizard.line.helpWebhookUrl"),
34
+ t("wizard.channels.docs", { link: formatDocsLink("/channels/line", "channels/line") }),
35
+ ];
36
+
37
+ const LINE_ALLOW_FROM_HELP_LINES = [
38
+ t("wizard.line.allowlistIntro"),
39
+ t("wizard.line.idsCaseSensitive"),
40
+ t("wizard.line.examples"),
41
+ "- U1234567890abcdef1234567890abcdef",
42
+ "- line:user:U1234567890abcdef1234567890abcdef",
43
+ t("wizard.line.multipleEntries"),
44
+ t("wizard.channels.docs", { link: formatDocsLink("/channels/line", "channels/line") }),
45
+ ];
46
+
47
+ const lineDmPolicy: ChannelSetupDmPolicy = {
48
+ label: "LINE",
49
+ channel,
50
+ policyKey: "channels.line.dmPolicy",
51
+ allowFromKey: "channels.line.allowFrom",
52
+ resolveConfigKeys: (cfg, accountId) =>
53
+ (accountId ?? resolveDefaultLineAccountId(cfg)) !== DEFAULT_ACCOUNT_ID
54
+ ? {
55
+ policyKey: `channels.line.accounts.${accountId ?? resolveDefaultLineAccountId(cfg)}.dmPolicy`,
56
+ allowFromKey: `channels.line.accounts.${accountId ?? resolveDefaultLineAccountId(cfg)}.allowFrom`,
57
+ }
58
+ : {
59
+ policyKey: "channels.line.dmPolicy",
60
+ allowFromKey: "channels.line.allowFrom",
61
+ },
62
+ getCurrent: (cfg, accountId) =>
63
+ resolveLineAccount({ cfg, accountId: accountId ?? resolveDefaultLineAccountId(cfg) }).config
64
+ .dmPolicy ?? "pairing",
65
+ setPolicy: (cfg, policy, accountId) =>
66
+ patchLineAccountConfig({
67
+ cfg,
68
+ accountId: accountId ?? resolveDefaultLineAccountId(cfg),
69
+ enabled: true,
70
+ patch:
71
+ policy === "open"
72
+ ? {
73
+ dmPolicy: "open",
74
+ allowFrom: mergeAllowFromEntries(
75
+ resolveLineAccount({
76
+ cfg,
77
+ accountId: accountId ?? resolveDefaultLineAccountId(cfg),
78
+ }).config.allowFrom,
79
+ ["*"],
80
+ ),
81
+ }
82
+ : { dmPolicy: policy },
83
+ clearFields: policy === "pairing" || policy === "disabled" ? ["allowFrom"] : undefined,
84
+ }),
85
+ };
86
+
87
+ export const lineSetupWizard: ChannelSetupWizard = {
88
+ channel,
89
+ status: createStandardChannelSetupStatus({
90
+ channelLabel: "LINE",
91
+ configuredLabel: t("wizard.channels.statusConfigured"),
92
+ unconfiguredLabel: t("wizard.channels.statusNeedsTokenSecret"),
93
+ configuredHint: t("wizard.channels.statusConfigured"),
94
+ unconfiguredHint: t("wizard.channels.statusNeedsTokenSecret"),
95
+ configuredScore: 1,
96
+ unconfiguredScore: 0,
97
+ includeStatusLine: true,
98
+ resolveConfigured: ({ cfg, accountId }) =>
99
+ isLineConfigured(cfg, accountId ?? resolveDefaultLineAccountId(cfg)),
100
+ resolveExtraStatusLines: ({ cfg }) => [`Accounts: ${listLineAccountIds(cfg).length || 0}`],
101
+ }),
102
+ introNote: {
103
+ title: t("wizard.line.messagingApiTitle"),
104
+ lines: LINE_SETUP_HELP_LINES,
105
+ shouldShow: ({ cfg, accountId }) =>
106
+ !isLineConfigured(cfg, accountId ?? resolveDefaultLineAccountId(cfg)),
107
+ },
108
+ credentials: [
109
+ {
110
+ inputKey: "token",
111
+ providerHint: channel,
112
+ credentialLabel: t("wizard.line.channelAccessToken"),
113
+ preferredEnvVar: "LINE_CHANNEL_ACCESS_TOKEN",
114
+ helpTitle: t("wizard.line.messagingApiTitle"),
115
+ helpLines: LINE_SETUP_HELP_LINES,
116
+ envPrompt: t("wizard.line.tokenEnvPrompt"),
117
+ keepPrompt: t("wizard.line.tokenKeepPrompt"),
118
+ inputPrompt: t("wizard.line.tokenInputPrompt"),
119
+ allowEnv: ({ accountId }) => accountId === DEFAULT_ACCOUNT_ID,
120
+ inspect: ({ cfg, accountId }) => {
121
+ const resolved = resolveLineAccount({ cfg, accountId });
122
+ return {
123
+ accountConfigured: Boolean(
124
+ normalizeOptionalString(resolved.channelAccessToken) &&
125
+ normalizeOptionalString(resolved.channelSecret),
126
+ ),
127
+ hasConfiguredValue: Boolean(
128
+ normalizeOptionalString(resolved.config.channelAccessToken) ??
129
+ normalizeOptionalString(resolved.config.tokenFile),
130
+ ),
131
+ resolvedValue: normalizeOptionalString(resolved.channelAccessToken),
132
+ envValue:
133
+ accountId === DEFAULT_ACCOUNT_ID
134
+ ? normalizeOptionalString(process.env.LINE_CHANNEL_ACCESS_TOKEN)
135
+ : undefined,
136
+ };
137
+ },
138
+ applyUseEnv: ({ cfg, accountId }) =>
139
+ patchLineAccountConfig({
140
+ cfg,
141
+ accountId,
142
+ enabled: true,
143
+ clearFields: ["channelAccessToken", "tokenFile"],
144
+ patch: {},
145
+ }),
146
+ applySet: ({ cfg, accountId, resolvedValue }) =>
147
+ patchLineAccountConfig({
148
+ cfg,
149
+ accountId,
150
+ enabled: true,
151
+ clearFields: ["tokenFile"],
152
+ patch: { channelAccessToken: resolvedValue },
153
+ }),
154
+ },
155
+ {
156
+ inputKey: "password",
157
+ providerHint: "line-secret",
158
+ credentialLabel: t("wizard.line.channelSecret"),
159
+ preferredEnvVar: "LINE_CHANNEL_SECRET",
160
+ helpTitle: t("wizard.line.messagingApiTitle"),
161
+ helpLines: LINE_SETUP_HELP_LINES,
162
+ envPrompt: t("wizard.line.secretEnvPrompt"),
163
+ keepPrompt: t("wizard.line.secretKeepPrompt"),
164
+ inputPrompt: t("wizard.line.secretInputPrompt"),
165
+ allowEnv: ({ accountId }) => accountId === DEFAULT_ACCOUNT_ID,
166
+ inspect: ({ cfg, accountId }) => {
167
+ const resolved = resolveLineAccount({ cfg, accountId });
168
+ return {
169
+ accountConfigured: Boolean(
170
+ normalizeOptionalString(resolved.channelAccessToken) &&
171
+ normalizeOptionalString(resolved.channelSecret),
172
+ ),
173
+ hasConfiguredValue: Boolean(
174
+ normalizeOptionalString(resolved.config.channelSecret) ??
175
+ normalizeOptionalString(resolved.config.secretFile),
176
+ ),
177
+ resolvedValue: normalizeOptionalString(resolved.channelSecret),
178
+ envValue:
179
+ accountId === DEFAULT_ACCOUNT_ID
180
+ ? normalizeOptionalString(process.env.LINE_CHANNEL_SECRET)
181
+ : undefined,
182
+ };
183
+ },
184
+ applyUseEnv: ({ cfg, accountId }) =>
185
+ patchLineAccountConfig({
186
+ cfg,
187
+ accountId,
188
+ enabled: true,
189
+ clearFields: ["channelSecret", "secretFile"],
190
+ patch: {},
191
+ }),
192
+ applySet: ({ cfg, accountId, resolvedValue }) =>
193
+ patchLineAccountConfig({
194
+ cfg,
195
+ accountId,
196
+ enabled: true,
197
+ clearFields: ["secretFile"],
198
+ patch: { channelSecret: resolvedValue },
199
+ }),
200
+ },
201
+ ],
202
+ allowFrom: createAllowFromSection({
203
+ helpTitle: t("wizard.line.allowlistTitle"),
204
+ helpLines: LINE_ALLOW_FROM_HELP_LINES,
205
+ message: t("wizard.line.allowFromPrompt"),
206
+ placeholder: "U1234567890abcdef1234567890abcdef",
207
+ invalidWithoutCredentialNote: t("wizard.line.allowFromInvalid"),
208
+ parseInputs: splitSetupEntries,
209
+ parseId: parseLineAllowFromId,
210
+ apply: ({ cfg, accountId, allowFrom }) =>
211
+ patchLineAccountConfig({
212
+ cfg,
213
+ accountId,
214
+ enabled: true,
215
+ patch: { dmPolicy: "allowlist", allowFrom },
216
+ }),
217
+ }),
218
+ dmPolicy: lineDmPolicy,
219
+ completionNote: {
220
+ title: t("wizard.line.webhookTitle"),
221
+ lines: [
222
+ t("wizard.line.completionEnableWebhook"),
223
+ t("wizard.line.completionDefaultWebhook"),
224
+ t("wizard.line.completionWebhookPath"),
225
+ t("wizard.channels.docs", { link: formatDocsLink("/channels/line", "channels/line") }),
226
+ ],
227
+ },
228
+ disable: (cfg) => setSetupChannelEnabled(cfg, channel, false),
229
+ };