@theokit/gateway-line 0.1.1 → 0.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,73 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 8cbf136: **Every published export now carries documentation.** Forty-seven public symbols shipped with no docblock at all, so a consumer hovering `DiscordAdapter`, `SlackAdapter`, `WhatsAppCloudBackend`, `ThreadStore` or any of the error classes got an empty tooltip. Coverage across the eleven packages went from 71.2% to 100% (163/163), measured over the published declarations rather than the source, because a docblock is not documentation until it survives the build.
8
+
9
+ The text says what each symbol is for and what constrains it, not what its name already says. `TelegramAdapter` records that a bot cannot enumerate its chats nor speak into one that has not spoken first. `DiscordAdapter` records that reading message content needs a privileged intent enabled in the developer portal, without which every `event.text` arrives empty and nothing says why. `WhatsAppWebBackend` records that it is unofficial and can get a number banned. `shouldDispatchSyncEvent` records that Matrix replays history on sync, which is why a freshly started bot would otherwise answer every message it can still see.
10
+
11
+ **`gateway-slack`'s README documented a type that does not exist.** Its usage example imported `GatewayMessageEvent` from `@theokit/gateway`. That name is an internal alias inside the Discord and Telegram adapters (`MessageEvent as GatewayMessageEvent`), never an export. A reader who copied the example got code that did not compile. It now imports `MessageEvent`, which is what `onInbound` actually hands the handler.
12
+
13
+ Two docblocks that attached to nothing were reattached: `acquirePidLock` in `gateway-whatsapp` had its documentation stranded thirty lines above, over a different function, and shipped undocumented as a result.
14
+
15
+ - 82a5099: **A webhook dispatch that rejects no longer ends the process.** Both servers answer the provider before running the handler — deliberately, because LINE and the SMS providers retry a webhook they did not see a 200 for, and waiting on a slow handler turns latency into a duplicate delivery. The cost of answering early is that the dispatch is floated, and a floated rejection is an unhandled one, which terminates Node. It is now caught and written to stderr.
16
+
17
+ This is the same defect that was fixed across the other adapters in #41; these two were missed because the gate that catches it only recognised the shape `void this.…`, and both float through a local (`void adapter.dispatch…`). The gate now matches any floated call, which is how these two surfaced.
18
+
19
+ - b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
20
+
21
+ The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
22
+
23
+ **The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
24
+
25
+ - 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
26
+
27
+ **LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
28
+
29
+ **Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
30
+
31
+ **Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
32
+
33
+ **SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
34
+
35
+ **Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
36
+
37
+ **Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
38
+
39
+ Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
40
+
41
+ WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
42
+
43
+ ## 0.1.2
44
+
45
+ ### Patch Changes
46
+
47
+ - b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
48
+
49
+ The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
50
+
51
+ **The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
52
+
53
+ - 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
54
+
55
+ **LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
56
+
57
+ **Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
58
+
59
+ **Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
60
+
61
+ **SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
62
+
63
+ **Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
64
+
65
+ **Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
66
+
67
+ Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
68
+
69
+ WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
70
+
3
71
  ## 0.1.1
4
72
 
5
73
  ### Patch Changes
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 usetheo.dev
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -8,16 +8,10 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
9
9
 
10
10
  // src/adapter.ts
11
-
12
- // src/errors.ts
13
- var ConfigurationError = class extends Error {
11
+ var ConfigurationError = class extends gateway.GatewayConfigurationError {
14
12
  name = "ConfigurationError";
15
- code;
16
- detail;
17
13
  constructor(opts) {
18
- super(opts.message ?? `gateway-line: ${opts.code}`);
19
- this.code = opts.code;
20
- this.detail = opts.detail;
14
+ super("gateway-line", opts);
21
15
  }
22
16
  };
23
17
  var SDKNotInstalledError = class extends ConfigurationError {
@@ -40,8 +34,20 @@ async function loadLineSdk() {
40
34
  }
41
35
  }
42
36
  function makeClient(mod, cfg) {
43
- if (mod.messagingApi?.MessagingApiClient !== void 0) {
44
- return new mod.messagingApi.MessagingApiClient({ channelAccessToken: cfg.channelAccessToken });
37
+ const v9 = mod.messagingApi?.MessagingApiClient;
38
+ if (v9 !== void 0) {
39
+ const client = new v9({ channelAccessToken: cfg.channelAccessToken });
40
+ return {
41
+ async replyMessage(replyToken, messages) {
42
+ return client.replyMessage({ replyToken, messages });
43
+ },
44
+ async pushMessage(to, messages) {
45
+ return client.pushMessage({ to, messages });
46
+ },
47
+ async getBotInfo() {
48
+ return client.getBotInfo();
49
+ }
50
+ };
45
51
  }
46
52
  return new mod.Client(cfg);
47
53
  }
@@ -117,24 +123,8 @@ var ReplyTokenCache = class {
117
123
  if (firstKey !== void 0) this.cache.delete(firstKey);
118
124
  }
119
125
  };
120
-
121
- // src/split.ts
122
126
  function splitForLine(text, limit = 5e3) {
123
- if (text.length === 0) return [""];
124
- if (text.length <= limit) return [text];
125
- const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
126
- const segments = Array.from(segmenter.segment(text), (s) => s.segment);
127
- const parts = [];
128
- let buf = "";
129
- for (const seg of segments) {
130
- if (buf.length + seg.length > limit) {
131
- if (buf.length > 0) parts.push(buf);
132
- buf = "";
133
- }
134
- buf += seg;
135
- }
136
- if (buf.length > 0) parts.push(buf);
137
- return parts;
127
+ return gateway.chunkByGrapheme(text, { limit });
138
128
  }
139
129
 
140
130
  // src/adapter.ts
@@ -164,11 +154,17 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
164
154
  async connect() {
165
155
  if (this.connected) return true;
166
156
  try {
167
- const mod = await loadLineSdk();
168
- this.client = makeClient(mod, {
169
- channelAccessToken: this.opts.channelAccessToken,
170
- channelSecret: this.opts.channelSecret
171
- });
157
+ const factory = this.opts.__clientFactory;
158
+ if (factory === void 0) {
159
+ const mod = await loadLineSdk();
160
+ this.client = makeClient(mod, {
161
+ channelAccessToken: this.opts.channelAccessToken,
162
+ channelSecret: this.opts.channelSecret
163
+ });
164
+ } else {
165
+ this.client = factory();
166
+ }
167
+ await this.client.getBotInfo();
172
168
  this.connected = true;
173
169
  return true;
174
170
  } catch (err) {
@@ -332,6 +328,14 @@ async function loadExpress() {
332
328
  }
333
329
  }
334
330
  function rawCapture(req, _res, next) {
331
+ if (req.readableEnded || req.complete) {
332
+ process.stderr.write(
333
+ "[gateway] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash\n"
334
+ );
335
+ req.rawBody = "";
336
+ next();
337
+ return;
338
+ }
335
339
  let buf = "";
336
340
  req.setEncoding("utf8");
337
341
  req.on("data", (chunk) => {
@@ -362,7 +366,11 @@ function handlerFactory(adapter) {
362
366
  res.status(400).type("text/plain").send("missing 'events' array");
363
367
  return;
364
368
  }
365
- void adapter.dispatchWebhookBody(envelope);
369
+ void adapter.dispatchWebhookBody(envelope).catch((err) => {
370
+ const message = err instanceof Error ? err.message : String(err);
371
+ process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}
372
+ `);
373
+ });
366
374
  res.status(200).end();
367
375
  };
368
376
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":["BasePlatformAdapter","crypto"],"mappings":";;;;;;;;;;;;AAWO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAC1B,IAAA,GAAO,oBAAA;AAAA,EAChB,IAAA;AAAA,EACA,MAAA;AAAA,EACT,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,IAAA,CAAK,OAAA,IAAW,CAAA,cAAA,EAAiB,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AAClD,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,EACrB;AACF;AAEO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,wBAAA,EAA2B,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MACpF,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A;AACV,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n */\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport interface ConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\nexport class ConfigurationError extends Error {\n override readonly name = \"ConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n constructor(opts: ConfigurationErrorOptions) {\n super(opts.message ?? `gateway-line: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineSdkClient;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a Client compatible with both legacy (`Client`) and v9 (`messagingApi.MessagingApiClient`).\n * We return the legacy shape (`replyMessage` / `pushMessage`) — v9 SDK exposes both styles.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n if (mod.messagingApi?.MessagingApiClient !== undefined) {\n return new mod.messagingApi.MessagingApiClient({ channelAccessToken: cfg.channelAccessToken });\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. We segment with `Intl.Segmenter`\n * so emoji, regional indicators, and combining sequences are never\n * severed.\n */\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const segments = Array.from(segmenter.segment(text), (s) => s.segment);\n const parts: string[] = [];\n let buf = \"\";\n for (const seg of segments) {\n if (buf.length + seg.length > limit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += seg;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n void adapter.dispatchWebhookBody(envelope);\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":["GatewayConfigurationError","chunkByGrapheme","BasePlatformAdapter","crypto"],"mappings":";;;;;;;;;;AAsBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,gBAAgB,IAAI,CAAA;AAAA,EAC5B;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,wBAAA,EAA2B,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MACpF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACKA,eAAsB,WAAA,GAAsC;AAC1D,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,eAAe,CAAA;AACxC,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,eAAe,CAAA;AAAA,EAChD;AACF;AAeO,SAAS,UAAA,CACd,KACA,GAAA,EACe;AACf,EAAA,MAAM,EAAA,GAAK,IAAI,YAAA,EAAc,kBAAA;AAC7B,EAAA,IAAI,OAAO,MAAA,EAAW;AACpB,IAAA,MAAM,SAAS,IAAI,EAAA,CAAG,EAAE,kBAAA,EAAo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CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2) — only the package prefix is package-specific. Name,\n * message shape, `code`/`detail` fields, and `instanceof` are byte-identical\n * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-line\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-line\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n /**\n * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.\n *\n * `connect()` needs it because building a client performs no I/O at all: it\n * would otherwise report success for any string, and the operator would find\n * out at the first send. Telegram, Discord, Slack and Mattermost all surface a\n * bad credential from connect(); Matrix did not until 2026-08-17, and this was\n * the second adapter with the same gap.\n */\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n}\n\n/**\n * The v9 `MessagingApiClient` surface, as declared by the installed\n * `@line/bot-sdk` v9 `messagingApiClient.d.ts`. Both methods take ONE request\n * object — this is not the same shape as {@link LineSdkClient}, and conflating\n * the two is what broke every outbound message before 2026-08-17.\n */\ninterface LineV9Client {\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n replyMessage(request: {\n replyToken: string;\n messages: Array<{ type: \"text\"; text: string }>;\n }): Promise<unknown>;\n pushMessage(\n request: { to: string; messages: Array<{ type: \"text\"; text: string }> },\n xLineRetryKey?: string,\n ): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineV9Client;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a client exposing the positional {@link LineSdkClient} shape the adapter\n * calls, from either the legacy (`Client`) or the v9\n * (`messagingApi.MessagingApiClient`) SDK.\n *\n * The v9 client is WRAPPED, not returned directly. An earlier version returned\n * it as-is on the claim that \"v9 SDK exposes both styles\" — it does not. v9\n * declares `replyMessage(request)` and `pushMessage(request, retryKey?)`, each\n * taking a single object, so the adapter's positional call arrived as\n * `{replyToken: undefined, messages: undefined}` and LINE rejected every send\n * with a 400. Since `@line/bot-sdk` is pinned at `^9.0.0`, this branch is the\n * one that always runs: the bug was total, not conditional.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n const v9 = mod.messagingApi?.MessagingApiClient;\n if (v9 !== undefined) {\n const client = new v9({ channelAccessToken: cfg.channelAccessToken });\n return {\n async replyMessage(replyToken, messages) {\n return client.replyMessage({ replyToken, messages });\n },\n async pushMessage(to, messages) {\n return client.pushMessage({ to, messages });\n },\n async getBotInfo() {\n return client.getBotInfo();\n },\n };\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text\n * message.\n *\n * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.\n * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. Thin wrapper over core\n * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme\n * walk so emoji, regional indicators, and combining sequences are never severed.\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n return chunkByGrapheme(text, { limit });\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const factory = this.opts.__clientFactory;\n if (factory === undefined) {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n } else {\n this.client = factory() as LineSdkClient;\n }\n // Validate the credential before reporting success. Building the client\n // performs NO network I/O, so without this connect() answered true for any\n // string and the failure surfaced only at the first send — as a 401 that\n // looks like a send bug rather than a bad token.\n await this.client.getBotInfo();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify LINE's `x-line-signature` header against the raw request body.\n *\n * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile\n * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any\n * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.\n */\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n // Someone else already drained the stream — a global `express.json()` or\n // `express.urlencoded()` mounted ahead of this router is the usual cause.\n // Without this branch, `req.on(\"end\")` never fires for a stream that already\n // ended, `next()` is never called, and the request HANGS with no response at\n // all: the provider times out and retries, and no error is logged anywhere.\n // Failing loudly and continuing is strictly better — verification then\n // refuses the empty body with a 401, which is at least a visible symptom that\n // points at the real cause.\n if (req.readableEnded || req.complete) {\n process.stderr.write(\n \"[gateway] raw body already consumed before signature capture — mount this router \" +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as Request & { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n // Answered before dispatch, on purpose: LINE retries a webhook it did not see a 200 for,\n // and waiting on the handler turns a slow one into a duplicate delivery. What that costs is\n // that the dispatch is floated — and a floated rejection is an unhandled one, which ends the\n // process (the defect fixed across the other adapters in #41). The catch is what makes the\n // early answer safe rather than merely fast.\n void adapter.dispatchWebhookBody(envelope).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}\\n`);\n });\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\n/**\n * Build the HTTP listener that receives LINE's webhook deliveries.\n *\n * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE\n * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`\n * is loaded lazily, so a project that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, LineMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, LineMessageEvent } from '@theokit/gateway';
2
2
  import { Express } from 'express';
3
3
 
4
4
  /**
@@ -13,6 +13,19 @@ interface LineSdkClient {
13
13
  type: "text";
14
14
  text: string;
15
15
  }>): Promise<unknown>;
16
+ /**
17
+ * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.
18
+ *
19
+ * `connect()` needs it because building a client performs no I/O at all: it
20
+ * would otherwise report success for any string, and the operator would find
21
+ * out at the first send. Telegram, Discord, Slack and Mattermost all surface a
22
+ * bad credential from connect(); Matrix did not until 2026-08-17, and this was
23
+ * the second adapter with the same gap.
24
+ */
25
+ getBotInfo(): Promise<{
26
+ userId?: string;
27
+ displayName?: string;
28
+ }>;
16
29
  }
17
30
 
18
31
  /**
@@ -122,19 +135,34 @@ declare class LineAdapter extends BasePlatformAdapter {
122
135
 
123
136
  /**
124
137
  * Typed errors for `@theokit/gateway-line`.
138
+ *
139
+ * `ConfigurationError` extends the shared core `GatewayConfigurationError`
140
+ * base (roadmap M2) — only the package prefix is package-specific. Name,
141
+ * message shape, `code`/`detail` fields, and `instanceof` are byte-identical
142
+ * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).
125
143
  */
144
+
126
145
  /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
127
- interface ConfigurationErrorOptions {
128
- readonly code: string;
129
- readonly message?: string;
130
- readonly detail?: string;
131
- }
132
- declare class ConfigurationError extends Error {
146
+ type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
147
+ /**
148
+ * Misconfiguration of this adapter, raised before any network call.
149
+ *
150
+ * Extends the shared core base so every gateway package reports configuration faults in one shape:
151
+ * a structured `code` the caller can branch on, tagged with `"gateway-line"` as the origin. A
152
+ * missing credential or an unsupported option is a programmer error, not a transient failure —
153
+ * these are never retried.
154
+ */
155
+ declare class ConfigurationError extends GatewayConfigurationError {
133
156
  readonly name = "ConfigurationError";
134
- readonly code: string;
135
- readonly detail: string | undefined;
136
157
  constructor(opts: ConfigurationErrorOptions);
137
158
  }
159
+ /**
160
+ * The platform SDK this adapter needs is declared as a peer dependency and is not installed.
161
+ *
162
+ * Raised at connect time rather than at import, so a project that installs several gateway packages
163
+ * only pays for the SDKs of the ones it actually starts. The message names the exact package and
164
+ * the command that installs it.
165
+ */
138
166
  declare class SDKNotInstalledError extends ConfigurationError {
139
167
  constructor(pkgName: string);
140
168
  }
@@ -151,6 +179,13 @@ declare class SDKNotInstalledError extends ConfigurationError {
151
179
  */
152
180
 
153
181
  declare function mapSourceType(sourceType: string): "dm" | "group" | "thread";
182
+ /**
183
+ * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text
184
+ * message.
185
+ *
186
+ * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.
187
+ * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.
188
+ */
154
189
  declare function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined;
155
190
 
156
191
  /**
@@ -188,14 +223,23 @@ declare class ReplyTokenCache {
188
223
  * Always uses `crypto.timingSafeEqual` to prevent timing attacks.
189
224
  */
190
225
  declare function computeLineSignature(channelSecret: string, rawBody: string): string;
226
+ /**
227
+ * Verify LINE's `x-line-signature` header against the raw request body.
228
+ *
229
+ * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile
230
+ * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any
231
+ * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.
232
+ */
191
233
  declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
192
234
 
193
235
  /**
194
236
  * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
195
237
  *
196
- * LINE limits text messages to 5000 chars. We segment with `Intl.Segmenter`
197
- * so emoji, regional indicators, and combining sequences are never
198
- * severed.
238
+ * LINE limits text messages to 5000 chars. Thin wrapper over core
239
+ * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme
240
+ * walk so emoji, regional indicators, and combining sequences are never severed.
241
+ * Output is byte-identical to the previous implementation (pinned by
242
+ * `tests/split.test.ts`).
199
243
  */
200
244
  declare function splitForLine(text: string, limit?: number): string[];
201
245
 
@@ -217,10 +261,18 @@ interface WebhookServerOptions {
217
261
  /** Inject an existing Express app. */
218
262
  readonly app?: Express;
219
263
  }
264
+ /** A started HTTP listener, with the handle needed to shut it down again. */
220
265
  interface WebhookServer {
221
266
  start(): Promise<void>;
222
267
  stop(): Promise<void>;
223
268
  }
269
+ /**
270
+ * Build the HTTP listener that receives LINE's webhook deliveries.
271
+ *
272
+ * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE
273
+ * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`
274
+ * is loaded lazily, so a project that only sends messages never pays for it.
275
+ */
224
276
  declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
225
277
 
226
278
  export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, LineMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, LineMessageEvent } from '@theokit/gateway';
2
2
  import { Express } from 'express';
3
3
 
4
4
  /**
@@ -13,6 +13,19 @@ interface LineSdkClient {
13
13
  type: "text";
14
14
  text: string;
15
15
  }>): Promise<unknown>;
16
+ /**
17
+ * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.
18
+ *
19
+ * `connect()` needs it because building a client performs no I/O at all: it
20
+ * would otherwise report success for any string, and the operator would find
21
+ * out at the first send. Telegram, Discord, Slack and Mattermost all surface a
22
+ * bad credential from connect(); Matrix did not until 2026-08-17, and this was
23
+ * the second adapter with the same gap.
24
+ */
25
+ getBotInfo(): Promise<{
26
+ userId?: string;
27
+ displayName?: string;
28
+ }>;
16
29
  }
17
30
 
18
31
  /**
@@ -122,19 +135,34 @@ declare class LineAdapter extends BasePlatformAdapter {
122
135
 
123
136
  /**
124
137
  * Typed errors for `@theokit/gateway-line`.
138
+ *
139
+ * `ConfigurationError` extends the shared core `GatewayConfigurationError`
140
+ * base (roadmap M2) — only the package prefix is package-specific. Name,
141
+ * message shape, `code`/`detail` fields, and `instanceof` are byte-identical
142
+ * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).
125
143
  */
144
+
126
145
  /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
127
- interface ConfigurationErrorOptions {
128
- readonly code: string;
129
- readonly message?: string;
130
- readonly detail?: string;
131
- }
132
- declare class ConfigurationError extends Error {
146
+ type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
147
+ /**
148
+ * Misconfiguration of this adapter, raised before any network call.
149
+ *
150
+ * Extends the shared core base so every gateway package reports configuration faults in one shape:
151
+ * a structured `code` the caller can branch on, tagged with `"gateway-line"` as the origin. A
152
+ * missing credential or an unsupported option is a programmer error, not a transient failure —
153
+ * these are never retried.
154
+ */
155
+ declare class ConfigurationError extends GatewayConfigurationError {
133
156
  readonly name = "ConfigurationError";
134
- readonly code: string;
135
- readonly detail: string | undefined;
136
157
  constructor(opts: ConfigurationErrorOptions);
137
158
  }
159
+ /**
160
+ * The platform SDK this adapter needs is declared as a peer dependency and is not installed.
161
+ *
162
+ * Raised at connect time rather than at import, so a project that installs several gateway packages
163
+ * only pays for the SDKs of the ones it actually starts. The message names the exact package and
164
+ * the command that installs it.
165
+ */
138
166
  declare class SDKNotInstalledError extends ConfigurationError {
139
167
  constructor(pkgName: string);
140
168
  }
@@ -151,6 +179,13 @@ declare class SDKNotInstalledError extends ConfigurationError {
151
179
  */
152
180
 
153
181
  declare function mapSourceType(sourceType: string): "dm" | "group" | "thread";
182
+ /**
183
+ * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text
184
+ * message.
185
+ *
186
+ * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.
187
+ * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.
188
+ */
154
189
  declare function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined;
155
190
 
156
191
  /**
@@ -188,14 +223,23 @@ declare class ReplyTokenCache {
188
223
  * Always uses `crypto.timingSafeEqual` to prevent timing attacks.
189
224
  */
190
225
  declare function computeLineSignature(channelSecret: string, rawBody: string): string;
226
+ /**
227
+ * Verify LINE's `x-line-signature` header against the raw request body.
228
+ *
229
+ * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile
230
+ * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any
231
+ * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.
232
+ */
191
233
  declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
192
234
 
193
235
  /**
194
236
  * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
195
237
  *
196
- * LINE limits text messages to 5000 chars. We segment with `Intl.Segmenter`
197
- * so emoji, regional indicators, and combining sequences are never
198
- * severed.
238
+ * LINE limits text messages to 5000 chars. Thin wrapper over core
239
+ * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme
240
+ * walk so emoji, regional indicators, and combining sequences are never severed.
241
+ * Output is byte-identical to the previous implementation (pinned by
242
+ * `tests/split.test.ts`).
199
243
  */
200
244
  declare function splitForLine(text: string, limit?: number): string[];
201
245
 
@@ -217,10 +261,18 @@ interface WebhookServerOptions {
217
261
  /** Inject an existing Express app. */
218
262
  readonly app?: Express;
219
263
  }
264
+ /** A started HTTP listener, with the handle needed to shut it down again. */
220
265
  interface WebhookServer {
221
266
  start(): Promise<void>;
222
267
  stop(): Promise<void>;
223
268
  }
269
+ /**
270
+ * Build the HTTP listener that receives LINE's webhook deliveries.
271
+ *
272
+ * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE
273
+ * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`
274
+ * is loaded lazily, so a project that only sends messages never pays for it.
275
+ */
224
276
  declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
225
277
 
226
278
  export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };
package/dist/index.js CHANGED
@@ -1,17 +1,11 @@
1
- import { BasePlatformAdapter } from '@theokit/gateway';
1
+ import { GatewayConfigurationError, chunkByGrapheme, BasePlatformAdapter } from '@theokit/gateway';
2
2
  import crypto from 'crypto';
3
3
 
4
4
  // src/adapter.ts
5
-
6
- // src/errors.ts
7
- var ConfigurationError = class extends Error {
5
+ var ConfigurationError = class extends GatewayConfigurationError {
8
6
  name = "ConfigurationError";
9
- code;
10
- detail;
11
7
  constructor(opts) {
12
- super(opts.message ?? `gateway-line: ${opts.code}`);
13
- this.code = opts.code;
14
- this.detail = opts.detail;
8
+ super("gateway-line", opts);
15
9
  }
16
10
  };
17
11
  var SDKNotInstalledError = class extends ConfigurationError {
@@ -34,8 +28,20 @@ async function loadLineSdk() {
34
28
  }
35
29
  }
36
30
  function makeClient(mod, cfg) {
37
- if (mod.messagingApi?.MessagingApiClient !== void 0) {
38
- return new mod.messagingApi.MessagingApiClient({ channelAccessToken: cfg.channelAccessToken });
31
+ const v9 = mod.messagingApi?.MessagingApiClient;
32
+ if (v9 !== void 0) {
33
+ const client = new v9({ channelAccessToken: cfg.channelAccessToken });
34
+ return {
35
+ async replyMessage(replyToken, messages) {
36
+ return client.replyMessage({ replyToken, messages });
37
+ },
38
+ async pushMessage(to, messages) {
39
+ return client.pushMessage({ to, messages });
40
+ },
41
+ async getBotInfo() {
42
+ return client.getBotInfo();
43
+ }
44
+ };
39
45
  }
40
46
  return new mod.Client(cfg);
41
47
  }
@@ -111,24 +117,8 @@ var ReplyTokenCache = class {
111
117
  if (firstKey !== void 0) this.cache.delete(firstKey);
112
118
  }
113
119
  };
114
-
115
- // src/split.ts
116
120
  function splitForLine(text, limit = 5e3) {
117
- if (text.length === 0) return [""];
118
- if (text.length <= limit) return [text];
119
- const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
120
- const segments = Array.from(segmenter.segment(text), (s) => s.segment);
121
- const parts = [];
122
- let buf = "";
123
- for (const seg of segments) {
124
- if (buf.length + seg.length > limit) {
125
- if (buf.length > 0) parts.push(buf);
126
- buf = "";
127
- }
128
- buf += seg;
129
- }
130
- if (buf.length > 0) parts.push(buf);
131
- return parts;
121
+ return chunkByGrapheme(text, { limit });
132
122
  }
133
123
 
134
124
  // src/adapter.ts
@@ -158,11 +148,17 @@ var LineAdapter = class extends BasePlatformAdapter {
158
148
  async connect() {
159
149
  if (this.connected) return true;
160
150
  try {
161
- const mod = await loadLineSdk();
162
- this.client = makeClient(mod, {
163
- channelAccessToken: this.opts.channelAccessToken,
164
- channelSecret: this.opts.channelSecret
165
- });
151
+ const factory = this.opts.__clientFactory;
152
+ if (factory === void 0) {
153
+ const mod = await loadLineSdk();
154
+ this.client = makeClient(mod, {
155
+ channelAccessToken: this.opts.channelAccessToken,
156
+ channelSecret: this.opts.channelSecret
157
+ });
158
+ } else {
159
+ this.client = factory();
160
+ }
161
+ await this.client.getBotInfo();
166
162
  this.connected = true;
167
163
  return true;
168
164
  } catch (err) {
@@ -326,6 +322,14 @@ async function loadExpress() {
326
322
  }
327
323
  }
328
324
  function rawCapture(req, _res, next) {
325
+ if (req.readableEnded || req.complete) {
326
+ process.stderr.write(
327
+ "[gateway] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash\n"
328
+ );
329
+ req.rawBody = "";
330
+ next();
331
+ return;
332
+ }
329
333
  let buf = "";
330
334
  req.setEncoding("utf8");
331
335
  req.on("data", (chunk) => {
@@ -356,7 +360,11 @@ function handlerFactory(adapter) {
356
360
  res.status(400).type("text/plain").send("missing 'events' array");
357
361
  return;
358
362
  }
359
- void adapter.dispatchWebhookBody(envelope);
363
+ void adapter.dispatchWebhookBody(envelope).catch((err) => {
364
+ const message = err instanceof Error ? err.message : String(err);
365
+ process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}
366
+ `);
367
+ });
360
368
  res.status(200).end();
361
369
  };
362
370
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":[],"mappings":";;;;;;AAWO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAC1B,IAAA,GAAO,oBAAA;AAAA,EAChB,IAAA;AAAA,EACA,MAAA;AAAA,EACT,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,IAAA,CAAK,OAAA,IAAW,CAAA,cAAA,EAAiB,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AAClD,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAA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AAY;AACnC,QAAA,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,IAAA,EAAM,MAAM,SAAS,CAAA;AAAA,MAC3C,CAAC,CAAA;AACD,MAAA,OAAA,GAAU,IAAA;AAAA,IACZ,CAAA;AAAA,IACA,MAAM,IAAA,GAAsB;AAC1B,MAAA,IAAI,OAAA,EAAS;AACb,MAAA,OAAA,GAAU,IAAA;AACV,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n */\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport interface ConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\nexport class ConfigurationError extends Error {\n override readonly name = \"ConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n constructor(opts: ConfigurationErrorOptions) {\n super(opts.message ?? `gateway-line: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineSdkClient;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a Client compatible with both legacy (`Client`) and v9 (`messagingApi.MessagingApiClient`).\n * We return the legacy shape (`replyMessage` / `pushMessage`) — v9 SDK exposes both styles.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n if (mod.messagingApi?.MessagingApiClient !== undefined) {\n return new mod.messagingApi.MessagingApiClient({ channelAccessToken: cfg.channelAccessToken });\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. We segment with `Intl.Segmenter`\n * so emoji, regional indicators, and combining sequences are never\n * severed.\n */\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const segments = Array.from(segmenter.segment(text), (s) => s.segment);\n const parts: string[] = [];\n let buf = \"\";\n for (const seg of segments) {\n if (buf.length + seg.length > limit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += seg;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n void adapter.dispatchWebhookBody(envelope);\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":[],"mappings":";;;;AAsBO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,gBAAgB,IAAI,CAAA;AAAA,EAC5B;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,wBAAA,EAA2B,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MACpF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACKA,eAAsB,WAAA,GAAsC;AAC1D,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,eAAe,CAAA;AACxC,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,eAAe,CAAA;AAAA,EAChD;AACF;A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EAAS;AACb,MAAA,OAAA,GAAU,IAAA;AACV,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2) — only the package prefix is package-specific. Name,\n * message shape, `code`/`detail` fields, and `instanceof` are byte-identical\n * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-line\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-line\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n /**\n * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.\n *\n * `connect()` needs it because building a client performs no I/O at all: it\n * would otherwise report success for any string, and the operator would find\n * out at the first send. Telegram, Discord, Slack and Mattermost all surface a\n * bad credential from connect(); Matrix did not until 2026-08-17, and this was\n * the second adapter with the same gap.\n */\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n}\n\n/**\n * The v9 `MessagingApiClient` surface, as declared by the installed\n * `@line/bot-sdk` v9 `messagingApiClient.d.ts`. Both methods take ONE request\n * object — this is not the same shape as {@link LineSdkClient}, and conflating\n * the two is what broke every outbound message before 2026-08-17.\n */\ninterface LineV9Client {\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n replyMessage(request: {\n replyToken: string;\n messages: Array<{ type: \"text\"; text: string }>;\n }): Promise<unknown>;\n pushMessage(\n request: { to: string; messages: Array<{ type: \"text\"; text: string }> },\n xLineRetryKey?: string,\n ): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineV9Client;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a client exposing the positional {@link LineSdkClient} shape the adapter\n * calls, from either the legacy (`Client`) or the v9\n * (`messagingApi.MessagingApiClient`) SDK.\n *\n * The v9 client is WRAPPED, not returned directly. An earlier version returned\n * it as-is on the claim that \"v9 SDK exposes both styles\" — it does not. v9\n * declares `replyMessage(request)` and `pushMessage(request, retryKey?)`, each\n * taking a single object, so the adapter's positional call arrived as\n * `{replyToken: undefined, messages: undefined}` and LINE rejected every send\n * with a 400. Since `@line/bot-sdk` is pinned at `^9.0.0`, this branch is the\n * one that always runs: the bug was total, not conditional.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n const v9 = mod.messagingApi?.MessagingApiClient;\n if (v9 !== undefined) {\n const client = new v9({ channelAccessToken: cfg.channelAccessToken });\n return {\n async replyMessage(replyToken, messages) {\n return client.replyMessage({ replyToken, messages });\n },\n async pushMessage(to, messages) {\n return client.pushMessage({ to, messages });\n },\n async getBotInfo() {\n return client.getBotInfo();\n },\n };\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text\n * message.\n *\n * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.\n * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. Thin wrapper over core\n * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme\n * walk so emoji, regional indicators, and combining sequences are never severed.\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n return chunkByGrapheme(text, { limit });\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const factory = this.opts.__clientFactory;\n if (factory === undefined) {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n } else {\n this.client = factory() as LineSdkClient;\n }\n // Validate the credential before reporting success. Building the client\n // performs NO network I/O, so without this connect() answered true for any\n // string and the failure surfaced only at the first send — as a 401 that\n // looks like a send bug rather than a bad token.\n await this.client.getBotInfo();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify LINE's `x-line-signature` header against the raw request body.\n *\n * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile\n * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any\n * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.\n */\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n // Someone else already drained the stream — a global `express.json()` or\n // `express.urlencoded()` mounted ahead of this router is the usual cause.\n // Without this branch, `req.on(\"end\")` never fires for a stream that already\n // ended, `next()` is never called, and the request HANGS with no response at\n // all: the provider times out and retries, and no error is logged anywhere.\n // Failing loudly and continuing is strictly better — verification then\n // refuses the empty body with a 401, which is at least a visible symptom that\n // points at the real cause.\n if (req.readableEnded || req.complete) {\n process.stderr.write(\n \"[gateway] raw body already consumed before signature capture — mount this router \" +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as Request & { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n // Answered before dispatch, on purpose: LINE retries a webhook it did not see a 200 for,\n // and waiting on the handler turns a slow one into a duplicate delivery. What that costs is\n // that the dispatch is floated — and a floated rejection is an unhandled one, which ends the\n // process (the defect fixed across the other adapters in #41). The catch is what makes the\n // early answer safe rather than merely fast.\n void adapter.dispatchWebhookBody(envelope).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}\\n`);\n });\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\n/**\n * Build the HTTP listener that receives LINE's webhook deliveries.\n *\n * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE\n * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`\n * is loaded lazily, so a project that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,8 +1,13 @@
1
1
  {
2
2
  "name": "@theokit/gateway-line",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "LINE Messaging API platform adapter for @theokit/gateway. ADRs D405-D412.",
5
5
  "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/usetheokit/theokit-gateways.git",
9
+ "directory": "packages/gateway-line"
10
+ },
6
11
  "type": "module",
7
12
  "engines": {
8
13
  "node": ">=22.12.0"
@@ -31,9 +36,9 @@
31
36
  ],
32
37
  "peerDependencies": {
33
38
  "@line/bot-sdk": "^9.0.0",
39
+ "@theokit/gateway": ">=0.6.0 <1.0.0",
34
40
  "@theokit/sdk": "^2.18.0",
35
- "express": "^4.18.0",
36
- "@theokit/gateway": "^0.4.1"
41
+ "express": "^4.18.0"
37
42
  },
38
43
  "peerDependenciesMeta": {
39
44
  "@line/bot-sdk": {
@@ -46,11 +51,16 @@
46
51
  "devDependencies": {
47
52
  "@theokit/sdk": "^2.18.0",
48
53
  "@types/express": "^4.17.0",
54
+ "express": "^4.18.0",
49
55
  "tsup": "^8.5.0",
50
56
  "typescript": "^5.8.0",
51
57
  "vitest": "^4.1.8",
52
58
  "zod": "^4.0.0",
53
- "@theokit/gateway": "0.4.1"
59
+ "@theokit/gateway": "0.6.0"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public",
63
+ "provenance": true
54
64
  },
55
65
  "scripts": {
56
66
  "build": "tsup",