@zhin.js/adapter-line 2.0.1 → 2.0.3

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 (45) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +50 -19
  3. package/adapters/line.ts +26 -0
  4. package/agent/tools/get_group_members.ts +24 -0
  5. package/agent/tools/get_profile.ts +24 -0
  6. package/lib/endpoint.d.ts +45 -37
  7. package/lib/endpoint.js +114 -506
  8. package/lib/index.d.ts +4 -15
  9. package/lib/index.js +4 -83
  10. package/lib/line-agent-deps.d.ts +24 -0
  11. package/lib/line-agent-deps.js +33 -0
  12. package/lib/protocol.d.ts +151 -0
  13. package/lib/protocol.js +212 -0
  14. package/lib/webhook.d.ts +13 -0
  15. package/lib/webhook.js +50 -0
  16. package/package.json +48 -21
  17. package/plugin.ts +8 -0
  18. package/schema.json +22 -0
  19. package/src/endpoint.ts +148 -554
  20. package/src/index.ts +53 -100
  21. package/src/line-agent-deps.ts +47 -0
  22. package/src/protocol.ts +384 -0
  23. package/src/webhook.ts +79 -0
  24. package/lib/adapter.d.ts +0 -17
  25. package/lib/adapter.d.ts.map +0 -1
  26. package/lib/adapter.js +0 -22
  27. package/lib/adapter.js.map +0 -1
  28. package/lib/endpoint.d.ts.map +0 -1
  29. package/lib/endpoint.js.map +0 -1
  30. package/lib/index.d.ts.map +0 -1
  31. package/lib/index.js.map +0 -1
  32. package/lib/segment-mapper.d.ts +0 -2
  33. package/lib/segment-mapper.d.ts.map +0 -1
  34. package/lib/segment-mapper.js +0 -2
  35. package/lib/segment-mapper.js.map +0 -1
  36. package/lib/types.d.ts +0 -112
  37. package/lib/types.d.ts.map +0 -1
  38. package/lib/types.js +0 -5
  39. package/lib/types.js.map +0 -1
  40. package/plugin.yml +0 -3
  41. package/src/adapter.ts +0 -29
  42. package/src/segment-mapper.ts +0 -1
  43. package/src/types.ts +0 -130
  44. /package/{skills/line → agent}/PERMITS.md +0 -0
  45. /package/{skills/line/SKILL.md → agent/skills/line.md} +0 -0
package/lib/index.js CHANGED
@@ -1,83 +1,4 @@
1
- /**
2
- * LINE Messaging API 适配器入口:类型扩展、导出、注册
3
- */
4
- import { usePlugin } from 'zhin.js';
5
- import { LineAdapter } from './adapter.js';
6
- export * from './types.js';
7
- export { LineEndpoint } from './endpoint.js';
8
- export { LineAdapter } from './adapter.js';
9
- const plugin = usePlugin();
10
- const { provide, useContext } = plugin;
11
- useContext('router', (router) => {
12
- provide({
13
- name: 'line',
14
- description: 'LINE Messaging API Endpoint Adapter',
15
- mounted: async (p) => {
16
- const adapter = new LineAdapter(p, router);
17
- await adapter.start();
18
- return adapter;
19
- },
20
- dispose: async (adapter) => {
21
- await adapter.stop();
22
- },
23
- });
24
- });
25
- // L11: Register LINE-specific tools
26
- useContext('tool', 'line', (toolService, lineAdapter) => {
27
- const accessToken = lineAdapter.endpoints.values().next().value?.$config?.channelAccessToken;
28
- const apiBaseUrl = lineAdapter.endpoints.values().next().value?.$config?.apiBaseUrl || 'https://api.line.me';
29
- const disposers = [];
30
- disposers.push(toolService.addTool({
31
- name: 'line_get_profile',
32
- description: 'Get LINE user profile by userId',
33
- parameters: {
34
- type: 'object',
35
- properties: {
36
- userId: { type: 'string', description: 'LINE user ID (starts with U)' },
37
- },
38
- required: ['userId'],
39
- },
40
- execute: async ({ userId }) => {
41
- if (!userId.startsWith('U')) {
42
- throw new Error(`Invalid userId "${userId}": must start with U`);
43
- }
44
- const response = await fetch(`${apiBaseUrl}/v2/profile/${userId}`, {
45
- headers: { 'Authorization': `Bearer ${accessToken}` },
46
- });
47
- if (!response.ok) {
48
- const errorText = await response.text();
49
- throw new Error(`LINE Profile API error ${response.status}: ${errorText}`);
50
- }
51
- return await response.json();
52
- },
53
- }));
54
- disposers.push(toolService.addTool({
55
- name: 'line_get_group_members',
56
- description: 'Get LINE group member IDs',
57
- parameters: {
58
- type: 'object',
59
- properties: {
60
- groupId: { type: 'string', description: 'LINE group ID (starts with G)' },
61
- },
62
- required: ['groupId'],
63
- },
64
- execute: async ({ groupId }) => {
65
- if (!groupId.startsWith('G')) {
66
- throw new Error(`Invalid groupId "${groupId}": must start with G`);
67
- }
68
- const response = await fetch(`${apiBaseUrl}/v2/bot/group/${groupId}/members/ids`, {
69
- headers: { 'Authorization': `Bearer ${accessToken}` },
70
- });
71
- if (!response.ok) {
72
- const errorText = await response.text();
73
- throw new Error(`LINE Group Members API error ${response.status}: ${errorText}`);
74
- }
75
- return await response.json();
76
- },
77
- }));
78
- return () => {
79
- for (const disposer of disposers)
80
- disposer();
81
- };
82
- });
83
- //# sourceMappingURL=index.js.map
1
+ export { formatInboundContent, formatOutboundMessages, generateMessageId, isMessageEvent, isPostbackEvent, isValidLineRecipientId, normalizeWebhookPath, readTextBody, resolveChannel, resolveLineConfig, verifySignature, } from './protocol.js';
2
+ export { LineEndpoint, } from './endpoint.js';
3
+ export { registerLineWebhookRoutes, handleLineWebhookRequest, } from './webhook.js';
4
+ export { getLineAgentDeps, getLineApiConfig, registerLineAgentEndpoint, setLineAgentDeps, } from './line-agent-deps.js';
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Agent tool deps for line (get_profile / get_group_members).
3
+ * Endpoints register themselves on start; tools look up the active API config.
4
+ */
5
+ export interface LineAgentEndpoint {
6
+ getApiConfig(): {
7
+ accessToken: string;
8
+ apiBaseUrl: string;
9
+ };
10
+ }
11
+ export interface LineAgentDeps {
12
+ getApiConfig: () => {
13
+ accessToken: string;
14
+ apiBaseUrl: string;
15
+ };
16
+ }
17
+ export declare function registerLineAgentEndpoint(endpointId: string, endpoint: LineAgentEndpoint): () => void;
18
+ /** Optional override used by tests / transitional callers. Pass `null` to clear. */
19
+ export declare function setLineAgentDeps(deps: LineAgentDeps | null): void;
20
+ export declare function getLineAgentDeps(): LineAgentDeps;
21
+ export declare function getLineApiConfig(): {
22
+ accessToken: string;
23
+ apiBaseUrl: string;
24
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Agent tool deps for line (get_profile / get_group_members).
3
+ * Endpoints register themselves on start; tools look up the active API config.
4
+ */
5
+ const endpoints = new Map();
6
+ let override = null;
7
+ export function registerLineAgentEndpoint(endpointId, endpoint) {
8
+ endpoints.set(endpointId, endpoint);
9
+ return () => {
10
+ if (endpoints.get(endpointId) === endpoint) {
11
+ endpoints.delete(endpointId);
12
+ }
13
+ };
14
+ }
15
+ /** Optional override used by tests / transitional callers. Pass `null` to clear. */
16
+ export function setLineAgentDeps(deps) {
17
+ override = deps;
18
+ }
19
+ export function getLineAgentDeps() {
20
+ if (override)
21
+ return override;
22
+ return {
23
+ getApiConfig() {
24
+ const first = endpoints.values().next().value;
25
+ if (!first)
26
+ throw new Error('LINE channel access token not configured');
27
+ return first.getApiConfig();
28
+ },
29
+ };
30
+ }
31
+ export function getLineApiConfig() {
32
+ return getLineAgentDeps().getApiConfig();
33
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * LINE Messaging API protocol helpers — no legacy Adapter/Endpoint / segment-mapper.
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+ import type { IncomingMessage } from 'node:http';
6
+ /** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
7
+ export interface LineAdapterConfig {
8
+ readonly name?: string;
9
+ readonly channelSecret?: string;
10
+ readonly channelAccessToken?: string;
11
+ readonly webhookPath?: string;
12
+ readonly apiBaseUrl?: string;
13
+ /** Transitional: legacy root `endpoints[]` with `context: line`. */
14
+ readonly endpoints?: ReadonlyArray<Partial<ResolvedLineConfig> & {
15
+ readonly context?: string;
16
+ }>;
17
+ }
18
+ export interface ResolvedLineConfig {
19
+ readonly context: 'line';
20
+ readonly name: string;
21
+ readonly channelSecret: string;
22
+ readonly channelAccessToken: string;
23
+ readonly webhookPath: string;
24
+ readonly apiBaseUrl: string;
25
+ }
26
+ export interface LineUser {
27
+ readonly userId: string;
28
+ readonly displayName?: string;
29
+ readonly pictureUrl?: string;
30
+ readonly statusMessage?: string;
31
+ }
32
+ export interface LineMessageEvent {
33
+ readonly type: 'message';
34
+ readonly replyToken: string;
35
+ readonly source: LineSource;
36
+ readonly timestamp: number;
37
+ readonly message: LineMessage;
38
+ }
39
+ export interface LineFollowEvent {
40
+ readonly type: 'follow';
41
+ readonly replyToken: string;
42
+ readonly source: LineSource;
43
+ readonly timestamp: number;
44
+ }
45
+ export interface LineUnfollowEvent {
46
+ readonly type: 'unfollow';
47
+ readonly source: LineSource;
48
+ readonly timestamp: number;
49
+ }
50
+ export interface LineJoinEvent {
51
+ readonly type: 'join';
52
+ readonly replyToken: string;
53
+ readonly source: LineSource;
54
+ readonly timestamp: number;
55
+ }
56
+ export interface LineLeaveEvent {
57
+ readonly type: 'leave';
58
+ readonly source: LineSource;
59
+ readonly timestamp: number;
60
+ }
61
+ export interface LinePostbackEvent {
62
+ readonly type: 'postback';
63
+ readonly replyToken: string;
64
+ readonly source: LineSource;
65
+ readonly timestamp: number;
66
+ readonly postback: {
67
+ readonly data: string;
68
+ readonly params?: Record<string, string>;
69
+ };
70
+ }
71
+ export type LineEvent = LineMessageEvent | LineFollowEvent | LineUnfollowEvent | LineJoinEvent | LineLeaveEvent | LinePostbackEvent;
72
+ export interface LineSource {
73
+ readonly type: 'user' | 'group' | 'room';
74
+ readonly userId?: string;
75
+ readonly groupId?: string;
76
+ readonly roomId?: string;
77
+ }
78
+ export interface LineMessage {
79
+ readonly id: string;
80
+ readonly type: 'text' | 'image' | 'video' | 'audio' | 'file' | 'location' | 'sticker';
81
+ readonly text?: string;
82
+ readonly fileName?: string;
83
+ readonly fileSize?: number;
84
+ readonly title?: string;
85
+ readonly address?: string;
86
+ readonly latitude?: number;
87
+ readonly longitude?: number;
88
+ readonly packageId?: string;
89
+ readonly stickerId?: string;
90
+ readonly stickerResourceType?: string;
91
+ readonly duration?: number;
92
+ }
93
+ export interface LineWebhookBody {
94
+ readonly destination: string;
95
+ readonly events: readonly LineEvent[];
96
+ }
97
+ export interface LineReplyMessage {
98
+ readonly type: 'text' | 'image' | 'video' | 'audio' | 'location' | 'sticker' | 'flex';
99
+ readonly text?: string;
100
+ readonly originalContentUrl?: string;
101
+ readonly previewImageUrl?: string;
102
+ readonly packageId?: string;
103
+ readonly stickerId?: string;
104
+ readonly title?: string;
105
+ readonly address?: string;
106
+ readonly latitude?: number;
107
+ readonly longitude?: number;
108
+ readonly duration?: number;
109
+ readonly altText?: string;
110
+ readonly contents?: Record<string, unknown>;
111
+ }
112
+ export interface LineReplyRequest {
113
+ readonly replyToken: string;
114
+ readonly messages: readonly LineReplyMessage[];
115
+ }
116
+ export interface LinePushRequest {
117
+ readonly to: string;
118
+ readonly messages: readonly LineReplyMessage[];
119
+ }
120
+ export interface LineApiResponse {
121
+ readonly sentMessages?: ReadonlyArray<{
122
+ readonly id: string;
123
+ readonly quoteToken?: string;
124
+ }>;
125
+ }
126
+ export interface LineWireSegment {
127
+ readonly type: string;
128
+ readonly data?: Record<string, unknown>;
129
+ }
130
+ export interface LineChannel {
131
+ readonly channelType: 'private' | 'group' | 'channel';
132
+ readonly channelId: string;
133
+ }
134
+ export declare function resolveLineConfig(config?: LineAdapterConfig): ResolvedLineConfig;
135
+ export declare function normalizeWebhookPath(path: string): string;
136
+ export declare function isMessageEvent(event: LineEvent): event is LineMessageEvent;
137
+ export declare function isPostbackEvent(event: LineEvent): event is LinePostbackEvent;
138
+ export declare function resolveChannel(source: LineSource): LineChannel;
139
+ export declare function generateMessageId(event: LineEvent): string;
140
+ /** Build inbound text for MessageGateway.receive. */
141
+ export declare function formatInboundContent(event: LineEvent): string;
142
+ export declare function verifySignature(channelSecret: string, body: string, signature: string): boolean;
143
+ export declare function isValidLineRecipientId(id: string): boolean;
144
+ /**
145
+ * Wire-encode an already-rendered outbound payload into LINE Reply/Push messages.
146
+ * Segment canonicalization is intentionally not done here.
147
+ */
148
+ export declare function formatOutboundMessages(payload: unknown): LineReplyMessage[];
149
+ export declare function readTextBody(request: IncomingMessage, options?: {
150
+ readonly limit?: number;
151
+ }): Promise<string>;
@@ -0,0 +1,212 @@
1
+ /**
2
+ * LINE Messaging API protocol helpers — no legacy Adapter/Endpoint / segment-mapper.
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+ import { createHmac, timingSafeEqual } from 'node:crypto';
6
+ export function resolveLineConfig(config = {}) {
7
+ const entry = config.endpoints?.find((item) => item.context === 'line');
8
+ const channelSecret = config.channelSecret
9
+ ?? entry?.channelSecret
10
+ ?? process.env.LINE_CHANNEL_SECRET;
11
+ const channelAccessToken = config.channelAccessToken
12
+ ?? entry?.channelAccessToken
13
+ ?? process.env.LINE_CHANNEL_ACCESS_TOKEN;
14
+ if (!channelSecret || !channelAccessToken) {
15
+ throw new TypeError('LINE adapter requires channelSecret + channelAccessToken (plugins.<key> or endpoints with context: line)');
16
+ }
17
+ const name = (typeof config.name === 'string' && config.name)
18
+ || (typeof entry?.name === 'string' && entry.name)
19
+ || process.env.LINE_BOT_NAME
20
+ || 'line-bot';
21
+ const webhookPath = normalizeWebhookPath(config.webhookPath ?? entry?.webhookPath ?? '/line/webhook');
22
+ const apiBaseUrl = (config.apiBaseUrl ?? entry?.apiBaseUrl ?? 'https://api.line.me').replace(/\/$/, '');
23
+ return {
24
+ context: 'line',
25
+ name,
26
+ channelSecret,
27
+ channelAccessToken,
28
+ webhookPath,
29
+ apiBaseUrl,
30
+ };
31
+ }
32
+ export function normalizeWebhookPath(path) {
33
+ const trimmed = path.trim() || '/line/webhook';
34
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
35
+ }
36
+ export function isMessageEvent(event) {
37
+ return event.type === 'message' && 'message' in event && event.message != null;
38
+ }
39
+ export function isPostbackEvent(event) {
40
+ return event.type === 'postback' && 'postback' in event;
41
+ }
42
+ export function resolveChannel(source) {
43
+ switch (source.type) {
44
+ case 'user':
45
+ return { channelType: 'private', channelId: source.userId || '' };
46
+ case 'group':
47
+ return { channelType: 'group', channelId: source.groupId || '' };
48
+ case 'room':
49
+ return { channelType: 'channel', channelId: source.roomId || '' };
50
+ default:
51
+ return { channelType: 'private', channelId: '' };
52
+ }
53
+ }
54
+ export function generateMessageId(event) {
55
+ if (isMessageEvent(event) && event.message?.id)
56
+ return event.message.id;
57
+ return `${event.type}-${event.timestamp}`;
58
+ }
59
+ /** Build inbound text for MessageGateway.receive. */
60
+ export function formatInboundContent(event) {
61
+ if (isMessageEvent(event)) {
62
+ const msg = event.message;
63
+ switch (msg.type) {
64
+ case 'text':
65
+ return msg.text || '';
66
+ case 'location':
67
+ return msg.address || `[location: ${msg.latitude},${msg.longitude}]`;
68
+ case 'image':
69
+ return '[image]';
70
+ case 'video':
71
+ return '[video]';
72
+ case 'audio':
73
+ return '[audio]';
74
+ case 'file':
75
+ return msg.fileName ? `[file: ${msg.fileName}]` : '[file]';
76
+ case 'sticker':
77
+ return `[sticker: ${msg.packageId}/${msg.stickerId}]`;
78
+ default:
79
+ return `[${msg.type}]`;
80
+ }
81
+ }
82
+ if (event.type === 'follow')
83
+ return '[follow]';
84
+ if (event.type === 'join')
85
+ return '[join]';
86
+ if (event.type === 'unfollow')
87
+ return '[unfollow]';
88
+ if (event.type === 'leave')
89
+ return '[leave]';
90
+ if (event.type === 'postback')
91
+ return `[postback: ${event.postback.data}]`;
92
+ return '';
93
+ }
94
+ export function verifySignature(channelSecret, body, signature) {
95
+ const hmac = createHmac('sha256', channelSecret);
96
+ hmac.update(body, 'utf-8');
97
+ const computedSignature = hmac.digest('base64');
98
+ const sigBuf = Buffer.from(signature);
99
+ const computedBuf = Buffer.from(computedSignature);
100
+ if (sigBuf.length !== computedBuf.length)
101
+ return false;
102
+ return timingSafeEqual(sigBuf, computedBuf);
103
+ }
104
+ export function isValidLineRecipientId(id) {
105
+ return /^[UGR]/.test(id);
106
+ }
107
+ function buildTextMessage(text) {
108
+ const truncated = text.length > 5000 ? `${text.slice(0, 4997)}...` : text;
109
+ return { type: 'text', text: truncated };
110
+ }
111
+ /**
112
+ * Wire-encode an already-rendered outbound payload into LINE Reply/Push messages.
113
+ * Segment canonicalization is intentionally not done here.
114
+ */
115
+ export function formatOutboundMessages(payload) {
116
+ if (typeof payload === 'string') {
117
+ return [buildTextMessage(payload)];
118
+ }
119
+ const items = Array.isArray(payload)
120
+ ? payload
121
+ : payload && typeof payload === 'object' && 'type' in payload
122
+ ? [payload]
123
+ : [];
124
+ if (items.length === 0) {
125
+ const text = payload == null
126
+ ? ''
127
+ : typeof payload === 'object'
128
+ ? JSON.stringify(payload)
129
+ : String(payload);
130
+ return [buildTextMessage(text)];
131
+ }
132
+ const messages = [];
133
+ for (const item of items) {
134
+ if (typeof item === 'string') {
135
+ messages.push(buildTextMessage(item));
136
+ continue;
137
+ }
138
+ const data = item.data ?? {};
139
+ switch (item.type) {
140
+ case 'text':
141
+ messages.push(buildTextMessage(String(data.text ?? data.content ?? '')));
142
+ break;
143
+ case 'at':
144
+ if (data.id) {
145
+ messages.push(buildTextMessage(`@${String(data.name || data.id)}`));
146
+ }
147
+ break;
148
+ case 'image':
149
+ if (typeof data.url === 'string' && data.url) {
150
+ messages.push({
151
+ type: 'image',
152
+ originalContentUrl: data.url,
153
+ previewImageUrl: data.url,
154
+ });
155
+ }
156
+ break;
157
+ case 'video':
158
+ if (typeof data.url === 'string' && data.url) {
159
+ messages.push({
160
+ type: 'video',
161
+ originalContentUrl: data.url,
162
+ previewImageUrl: typeof data.previewUrl === 'string' ? data.previewUrl : data.url,
163
+ });
164
+ }
165
+ break;
166
+ case 'audio':
167
+ if (typeof data.url === 'string' && data.url) {
168
+ messages.push({
169
+ type: 'audio',
170
+ originalContentUrl: data.url,
171
+ duration: typeof data.duration === 'number' ? data.duration : 0,
172
+ });
173
+ }
174
+ break;
175
+ case 'location':
176
+ messages.push({
177
+ type: 'location',
178
+ title: String(data.title || 'Location'),
179
+ address: String(data.address || ''),
180
+ latitude: typeof data.latitude === 'number' ? data.latitude : 0,
181
+ longitude: typeof data.longitude === 'number' ? data.longitude : 0,
182
+ });
183
+ break;
184
+ case 'sticker':
185
+ messages.push({
186
+ type: 'sticker',
187
+ packageId: String(data.package_id || '1'),
188
+ stickerId: String(data.sticker_id || '1'),
189
+ });
190
+ break;
191
+ default:
192
+ messages.push(buildTextMessage(`[${item.type}]`));
193
+ }
194
+ }
195
+ // LINE allows at most 5 messages per Reply/Push request.
196
+ return messages.slice(0, 5);
197
+ }
198
+ export async function readTextBody(request, options = {}) {
199
+ const limit = options.limit ?? 1_048_576;
200
+ const chunks = [];
201
+ let size = 0;
202
+ for await (const chunk of request) {
203
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
204
+ size += buffer.length;
205
+ if (size > limit) {
206
+ request.destroy();
207
+ throw new Error(`Request body exceeds ${limit} bytes`);
208
+ }
209
+ chunks.push(buffer);
210
+ }
211
+ return Buffer.concat(chunks).toString('utf8');
212
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * LINE webhook HTTP: signature → parse → admit.
3
+ */
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
6
+ import { type LineEvent, type ResolvedLineConfig } from './protocol.js';
7
+ export interface LineWebhookHandler {
8
+ readonly config: ResolvedLineConfig;
9
+ readonly isOpen: boolean;
10
+ admit(event: LineEvent): void;
11
+ }
12
+ export declare function registerLineWebhookRoutes(http: HttpHost, handler: LineWebhookHandler): HttpRouteRegistration[];
13
+ export declare function handleLineWebhookRequest(request: IncomingMessage, response: ServerResponse, handler: LineWebhookHandler): Promise<void>;
package/lib/webhook.js ADDED
@@ -0,0 +1,50 @@
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { readTextBody, verifySignature, } from './protocol.js';
3
+ const logger = getLogger('line');
4
+ export function registerLineWebhookRoutes(http, handler) {
5
+ const path = handler.config.webhookPath;
6
+ return [
7
+ http.route('POST', path, async (request, response) => {
8
+ await handleLineWebhookRequest(request, response, handler);
9
+ }, { summary: 'LINE Messaging API webhook', tags: ['line'] }),
10
+ ];
11
+ }
12
+ export async function handleLineWebhookRequest(request, response, handler) {
13
+ try {
14
+ const signature = request.headers['x-line-signature'];
15
+ const signatureValue = Array.isArray(signature) ? signature[0] : signature;
16
+ if (!signatureValue) {
17
+ response.writeHead(403, { 'Content-Type': 'application/json' });
18
+ response.end(JSON.stringify({ message: 'Missing signature' }));
19
+ return;
20
+ }
21
+ const rawBody = await readTextBody(request);
22
+ if (!verifySignature(handler.config.channelSecret, rawBody, signatureValue)) {
23
+ logger.warn(formatCompact({ op: 'webhook', ok: false, error: 'invalid signature' }));
24
+ response.writeHead(403, { 'Content-Type': 'application/json' });
25
+ response.end(JSON.stringify({ message: 'Invalid signature' }));
26
+ return;
27
+ }
28
+ let body;
29
+ try {
30
+ body = JSON.parse(rawBody);
31
+ }
32
+ catch {
33
+ response.writeHead(200, { 'Content-Type': 'application/json' });
34
+ response.end(JSON.stringify({ message: 'OK' }));
35
+ return;
36
+ }
37
+ if (handler.isOpen && Array.isArray(body.events)) {
38
+ for (const event of body.events) {
39
+ handler.admit(event);
40
+ }
41
+ }
42
+ response.writeHead(200, { 'Content-Type': 'application/json' });
43
+ response.end(JSON.stringify({ message: 'OK' }));
44
+ }
45
+ catch (error) {
46
+ logger.error('LINE webhook error:', error);
47
+ response.writeHead(200, { 'Content-Type': 'application/json' });
48
+ response.end(JSON.stringify({ message: 'OK' }));
49
+ }
50
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zhin.js/adapter-line",
3
- "version": "2.0.1",
4
- "description": "Zhin.js adapter for LINE Messaging API",
3
+ "version": "2.0.3",
4
+ "description": "Zhin.js LINE Messaging API adapter for Plugin Runtime (HTTP webhook)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
7
7
  "types": "./lib/index.d.ts",
@@ -31,34 +31,47 @@
31
31
  "type": "git",
32
32
  "directory": "plugins/adapters/line"
33
33
  },
34
- "devDependencies": {
35
- "@types/node": "^26.1.0",
36
- "typescript": "^6.0.3",
37
- "@zhin.js/host-api": "2.0.4",
38
- "@zhin.js/host-router": "2.0.2",
39
- "@zhin.js/logger": "1.0.73",
40
- "zhin.js": "4.1.1",
41
- "@zhin.js/cli": "1.0.92"
34
+ "dependencies": {
35
+ "@zhin.js/adapter": "1.0.1",
36
+ "@zhin.js/core": "1.3.5",
37
+ "@zhin.js/host-http": "1.0.1",
38
+ "@zhin.js/logger": "1.0.75",
39
+ "@zhin.js/plugin-runtime": "1.0.1"
42
40
  },
43
41
  "peerDependencies": {
44
- "@zhin.js/host-api": "2.0.4",
45
- "@zhin.js/host-router": "2.0.2",
46
- "@zhin.js/logger": "1.0.73",
47
- "zhin.js": "4.1.1"
42
+ "zod": "^4.0.0",
43
+ "@zhin.js/adapter": "1.0.1",
44
+ "@zhin.js/agent": "1.0.4",
45
+ "@zhin.js/core": "1.3.5",
46
+ "@zhin.js/host-http": "1.0.1",
47
+ "@zhin.js/plugin-runtime": "1.0.1",
48
+ "zhin.js": "4.1.3"
48
49
  },
49
50
  "peerDependenciesMeta": {
50
- "@zhin.js/host-router": {
51
+ "zhin.js": {
52
+ "optional": true
53
+ },
54
+ "@zhin.js/agent": {
51
55
  "optional": true
52
56
  },
53
- "@zhin.js/host-api": {
57
+ "zod": {
54
58
  "optional": true
55
59
  }
56
60
  },
61
+ "devDependencies": {
62
+ "@types/node": "^26.1.0",
63
+ "typescript": "^6.0.3",
64
+ "vitest": "^4.1.10",
65
+ "zod": "^4.4.3",
66
+ "@zhin.js/agent": "1.0.4"
67
+ },
57
68
  "files": [
69
+ "adapters",
70
+ "plugin.ts",
71
+ "schema.json",
58
72
  "src",
59
73
  "lib",
60
- "skills",
61
- "plugin.yml",
74
+ "agent",
62
75
  "README.md",
63
76
  "CHANGELOG.md"
64
77
  ],
@@ -69,9 +82,23 @@
69
82
  "engines": {
70
83
  "node": "^20.19.0 || >=22.12.0"
71
84
  },
85
+ "zhin": {
86
+ "protocol": 1,
87
+ "type": "plugin",
88
+ "entry": "./plugin.ts",
89
+ "engine": "^1.0.0",
90
+ "runtime": "trusted",
91
+ "features": [
92
+ {
93
+ "package": "@zhin.js/adapter",
94
+ "api": "^1.0.0"
95
+ }
96
+ ],
97
+ "plugins": []
98
+ },
72
99
  "scripts": {
73
- "build": "zhin build",
74
- "clean": "rimraf lib dist",
75
- "build:node": "tsc"
100
+ "build": "tsc",
101
+ "clean": "rimraf lib",
102
+ "test": "NODE_OPTIONS=--experimental-strip-types vitest run --root ../../.. plugins/adapters/line/tests"
76
103
  }
77
104
  }
package/plugin.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { definePlugin } from '@zhin.js/plugin-runtime';
2
+
3
+ export default definePlugin({
4
+ name: 'line',
5
+ metadata: {
6
+ displayName: 'LINE Messaging API Adapter',
7
+ },
8
+ });