@theokit/gateway-line 0.3.0 → 0.5.0

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.
@@ -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":["GatewayConfigurationError","chunkByGrapheme","BasePlatformAdapter","crypto","loadPeer","rawBodyCapture","listenerLifecycle"],"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,EAAoB,GAAA,CAAI,oBAAoB,CAAA;AACpE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AAM,WAAA,EAAY;AACpC,EAAA,MAAM,GAAA,GAAe,IAAA,CAAK,GAAA,IAAO,SAAA,EAAU;AAC3C,EAAA,MAAM,IAAA,GAAO,KAAK,IAAA,IAAQ,OAAA;AAC1B,EAAA,GAAA,CAAI,IAAA,CAAK,MAAMC,sBAAA,CAAe,cAAc,GAAG,cAAA,CAAe,IAAA,CAAK,OAAO,CAAC,CAAA;AAK3E,EAAA,OAAOC,yBAAA,CAAkB,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,IAAQ,GAAA,EAAM,QAAA,EAAU,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F","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 // A LINE text message has no markup field. Reading the field is what makes the\n // discard visible — this is the platform where the silence was observed.\n this.warnFormatUnsupported(out.format);\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 /** Whether the \"this platform has no text formatting\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `format` has nowhere to go on this platform.\n *\n * A LINE text message carries `{ type: \"text\", text }` and nothing else — no markup field,\n * no parse flag, no alternative part. Flex Messages can render styled content, but they are a\n * different message type with a different payload, not a flag on this one.\n *\n * This is the platform whose silence was OBSERVED: an agent answered\n * `**Bom Sucesso (MG)**` and the person read literal asterisks, because the adapter dropped\n * the caller's declared intent without saying so.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-line] format=\"${format}\" was declared, and a LINE text message cannot carry it — ` +\n \"there is no markup field on this message type. Sending as-is; this is logged once.\\n\",\n );\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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\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 { listenerLifecycle, loadPeer, rawBodyCapture } from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { LineAdapter } from \"./adapter.js\";\n\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<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\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}\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 createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const path = opts.path ?? \"/line\";\n app.post(path, rawBodyCapture(\"gateway-line\"), handlerFactory(opts.adapter));\n\n // The lifecycle — and the latches that make a restart a restart — live in `@theokit/gateway`,\n // written once. They were duplicated here and in gateway-sms, and the same write-once bug had to\n // be fixed in both files by one commit, which is what made the duplication a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/envelope.ts","../src/signature.ts","../src/channel.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["GatewayConfigurationError","chunkByGrapheme","splitKeepingRows","BasePlatformAdapter","crypto","loadPeer","rawBodyCapture","listenerLifecycle"],"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,EA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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 == null) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source == null) 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 * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"line adapter cannot send attachments\" },\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), keeping table rows whole.\n *\n * LINE limits text messages to 5000 chars. A text within the limit goes through core\n * `chunkByGrapheme` as before. A longer one is cut at the last grapheme boundary within each part,\n * which is where `chunkByGrapheme`'s greedy walk ends a part, so emoji, regional indicators and\n * combining sequences are never severed and text with no table row splits exactly as it did\n * (pinned by `tests/split-no-table-baseline.test.ts` and the equivalence test in\n * `tests/split-tables.test.ts`).\n *\n * A cut that falls inside a Markdown table row which fits in a part moves back to the start of\n * that row, so the row arrives whole in the next message (B-556). The rule is core\n * `splitKeepingRows`, shared with gateway-sms.\n */\n\nimport { chunkByGrapheme, splitKeepingRows } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n if (text.length <= limit) return chunkByGrapheme(text, { limit });\n // The core's RangeError for a limit of 0, 1.5 or NaN, with the message it had before.\n chunkByGrapheme(\"\", { limit });\n return splitKeepingRows(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 { refuseAttachments } from \"./refuse-attachments.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 async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\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 private async sendText(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 // A LINE text message has no markup field. Reading the field is what makes the\n // discard visible — this is the platform where the silence was observed.\n this.warnFormatUnsupported(out.format);\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 /** Whether the \"this platform has no text formatting\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `format` has nowhere to go on this platform.\n *\n * A LINE text message carries `{ type: \"text\", text }` and nothing else — no markup field,\n * no parse flag, no alternative part. Flex Messages can render styled content, but they are a\n * different message type with a different payload, not a flag on this one.\n *\n * This is the platform whose silence was OBSERVED: an agent answered\n * `**Bom Sucesso (MG)**` and the person read literal asterisks, because the adapter dropped\n * the caller's declared intent without saying so.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-line] format=\"${format}\" was declared, and a LINE text message cannot carry it — ` +\n \"there is no markup field on this message type. Sending as-is; this is logged once.\\n\",\n );\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 AFTER signature validation. Iterates LINE's batch envelope and\n * dispatches each event.\n *\n * Answers `\"no_handler\"`, dispatching nothing and caching no reply token, when the batch holds an\n * event the handler would receive (a text message that passes the mention guard) and no handler\n * is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired\n * because its connect failed. A webhook route must not acknowledge that answer, or LINE does not\n * redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's\n * console verification, or only follow and media events) answers `\"ok\"` either way. The handler is\n * read once per batch, so one that unsubscribes while handling an event still gets the rest.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<\"ok\" | \"no_handler\"> {\n const handler = this.inboundHandler;\n const events = envelope.events.map((ev) => ({ ev, normalized: lineEventToMessageEvent(ev) }));\n const deliverable = events.some(\n ({ normalized }) => normalized !== undefined && this.passesMentionGuard(normalized),\n );\n if (handler === undefined && deliverable) return \"no_handler\";\n for (const { ev, normalized } of events) {\n await this.dispatchSingleEvent(ev, normalized, handler);\n }\n return \"ok\";\n }\n\n private async dispatchSingleEvent(\n ev: LineWebhookEvent,\n normalized: GatewayMessageEvent | undefined,\n handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined,\n ): Promise<void> {\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 (handler === undefined) return;\n try {\n await handler(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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n // The webhook path applies the same guard (D409); a dropped event is acknowledged, not delivered.\n if (!this.passesMentionGuard(event)) return \"ok\";\n return this.runHandler(this.inboundHandler, event);\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","import type { LineWebhookEnvelope } from \"./types.js\";\n\n/** A LINE webhook envelope: an object whose `events` is an array of objects. */\nexport function isEnvelope(payload: unknown): payload is LineWebhookEnvelope {\n if (typeof payload !== \"object\" || payload === null) return false;\n const events = (payload as { events?: unknown }).events;\n return (\n Array.isArray(events) && events.every((event) => typeof event === \"object\" && event !== null)\n );\n}\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 * `lineChannel` — the LINE channel described as data (FR-005 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { LineAdapter } from \"./adapter.js\";\nimport { isEnvelope } from \"./envelope.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineAdapterOptions } from \"./types.js\";\n\nconst SIGNATURE_HEADER = \"x-line-signature\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-line: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\n/** A required string; an empty one is left for the adapter's own check, which names it. */\nfunction requiredString(config: Readonly<Record<string, unknown>>, key: string): string {\n const value = config[key];\n if (typeof value !== \"string\") throw invalid(key, \"a string\");\n return value;\n}\n\n/** An optional value: `undefined`, `null` and `\"\"` are absent, anything else must pass `check`. */\nfunction optional<T>(\n config: Readonly<Record<string, unknown>>,\n key: string,\n check: (value: unknown) => value is T,\n expected: string,\n): T | undefined {\n const value = config[key];\n if (value === undefined || value === null || value === \"\") return undefined;\n if (!check(value)) throw invalid(key, expected);\n return value;\n}\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isBoolean = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction buildOptions(config: Readonly<Record<string, unknown>>): LineAdapterOptions {\n // Types are checked here, before the constructor: a numeric secret passes the constructor's\n // length check (`adapter.ts:32`) and would throw later, inside the signature HMAC, on the request\n // path. An empty secret or token is then refused by the constructor's own ConfigurationError.\n const channelSecret = requiredString(config, \"channelSecret\");\n const channelAccessToken = requiredString(config, \"channelAccessToken\");\n const botUserId = optional(config, \"botUserId\", isString, \"a string\");\n const requireMention = optional(config, \"requireMention\", isBoolean, \"a boolean\");\n return {\n channelSecret,\n channelAccessToken,\n ...(botUserId !== undefined ? { botUserId } : {}),\n ...(requireMention !== undefined ? { requireMention } : {}),\n };\n}\n\nfunction headerValue(\n headers: Readonly<Record<string, string | undefined>>,\n name: string,\n): string | undefined {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) return value;\n }\n return undefined;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"channelSecret\",\n required: true,\n secret: true,\n description: \"The channel secret that signs inbound webhooks (LINE Developers Console).\",\n },\n {\n key: \"channelAccessToken\",\n required: true,\n secret: true,\n description: \"The channel's long-lived access token (LINE Developers Console).\",\n },\n {\n key: \"botUserId\",\n required: false,\n secret: false,\n description: \"The bot's own user id; with requireMention, group messages must mention it.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description: \"Whether group messages must mention the bot. Default true.\",\n },\n];\n\n/**\n * The LINE channel: LINE delivers inbound events by webhook, so the app routes each request to\n * `webhook.verify` and then `webhook.ingest`.\n *\n * `verify` checks the `x-line-signature` header (any case) against the raw body with the adapter's\n * channel secret. `ingest` reports `\"malformed\"` for a payload with no `events` array or with an\n * event that is not an object, dispatching nothing; otherwise it dispatches through\n * `LineAdapter.dispatchWebhookBody`, which caches each event's reply token so the handler's reply\n * uses the reply API. A follow or other non-text event is skipped and still reports `\"delivered\"`.\n * It reports `\"no_handler\"`, dispatching nothing, when the payload holds a text message for the\n * handler and none is subscribed (before the runner started, after it stopped, or when this\n * adapter's connect failed under `connectFailure: \"isolate\"`). Only `\"delivered\"` should be\n * answered with 200: with webhook redelivery turned on, LINE redelivers a request answered\n * otherwise.\n * `create` refuses a field of the wrong type, and the adapter refuses an empty secret or token,\n * both with this package's `ConfigurationError`.\n *\n * @public\n */\nexport const lineChannel = {\n platform: \"line\" as const,\n transport: \"webhook\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): LineAdapter {\n return new LineAdapter(buildOptions(config));\n },\n webhook: {\n verify(\n adapter: LineAdapter,\n request: {\n readonly rawBody: string;\n readonly headers: Readonly<Record<string, string | undefined>>;\n },\n ): boolean {\n const signature = headerValue(request.headers, SIGNATURE_HEADER);\n return verifyLineSignature(adapter.getChannelSecret(), request.rawBody, signature);\n },\n async ingest(\n adapter: LineAdapter,\n payload: unknown,\n ): Promise<\"delivered\" | \"malformed\" | \"no_handler\"> {\n if (!isEnvelope(payload)) return \"malformed\";\n const outcome = await adapter.dispatchWebhookBody(payload);\n return outcome === \"no_handler\" ? \"no_handler\" : \"delivered\";\n },\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 { listenerLifecycle, loadPeer, rawBodyCapture } from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { LineAdapter } from \"./adapter.js\";\n\nimport { isEnvelope } from \"./envelope.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.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<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\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}\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: unknown;\n try {\n envelope = JSON.parse(rawBody);\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!isEnvelope(envelope)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array of objects\");\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 createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const path = opts.path ?? \"/line\";\n app.post(path, rawBodyCapture(\"gateway-line\"), handlerFactory(opts.adapter));\n\n // The lifecycle — and the latches that make a restart a restart — live in `@theokit/gateway`,\n // written once. They were duplicated here and in gateway-sms, and the same write-once bug had to\n // be fixed in both files by one commit, which is what made the duplication a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n","/**\n * The LINE half of a framework channel webhook, in the shape `theokit/server/webhook` validators\n * take: `(request) => Promise<{ ok: true } | { ok: false; reason }>`. The shape is structural, so\n * this package imports nothing from the framework.\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { line: lineWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport { verifyLineSignature } from \"./signature.js\";\n\n/** What a verifier answers. @public */\nexport type LineWebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/**\n * Build a verifier for one channel secret (or an adapter exposing `getChannelSecret()`).\n *\n * The request body is READ as raw text, because LINE signs the exact bytes; pass a clone if the\n * body is needed afterwards.\n *\n * @public\n */\nexport function lineWebhookVerifier(\n source: string | { getChannelSecret(): string },\n): (request: Request) => Promise<LineWebhookVerifyResult> {\n return async (request: Request): Promise<LineWebhookVerifyResult> => {\n const rawBody = await request.text();\n const signature = request.headers.get(\"x-line-signature\") ?? undefined;\n if (signature === undefined) return { ok: false, reason: \"missing x-line-signature header\" };\n const secret = typeof source === \"string\" ? source : source.getChannelSecret();\n return verifyLineSignature(secret, rawBody, signature)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -129,16 +129,25 @@ declare class LineAdapter extends BasePlatformAdapter {
129
129
  connect(): Promise<boolean>;
130
130
  disconnect(): Promise<void>;
131
131
  sendMessage(out: OutboundMessage): Promise<SendResult>;
132
+ private sendText;
132
133
  /** Whether the "this platform has no text formatting" warning has already been emitted. */
133
134
  private warnedAboutFormat;
134
135
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
135
136
  /** Escape hatch: caller drives Flex/Carousel/etc directly. */
136
137
  getClient(): LineSdkClient | undefined;
137
138
  /**
138
- * Webhook entrypoint — called by `createWebhookServer` AFTER signature
139
- * validation. Iterates LINE's batch envelope and dispatches each event.
139
+ * Webhook entrypoint — called AFTER signature validation. Iterates LINE's batch envelope and
140
+ * dispatches each event.
141
+ *
142
+ * Answers `"no_handler"`, dispatching nothing and caching no reply token, when the batch holds an
143
+ * event the handler would receive (a text message that passes the mention guard) and no handler
144
+ * is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired
145
+ * because its connect failed. A webhook route must not acknowledge that answer, or LINE does not
146
+ * redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's
147
+ * console verification, or only follow and media events) answers `"ok"` either way. The handler is
148
+ * read once per batch, so one that unsubscribes while handling an event still gets the rest.
140
149
  */
141
- dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void>;
150
+ dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<"ok" | "no_handler">;
142
151
  private dispatchSingleEvent;
143
152
  private passesMentionGuard;
144
153
  /** Expose channel secret for the webhook server (signature middleware). */
@@ -154,6 +163,55 @@ declare class LineAdapter extends BasePlatformAdapter {
154
163
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
155
164
  }
156
165
 
166
+ /**
167
+ * `lineChannel` — the LINE channel described as data (FR-005 of B-018).
168
+ *
169
+ * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as
170
+ * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on
171
+ * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the
172
+ * integration package assigns it to one, and its typecheck is where a drift between the two fails.
173
+ */
174
+
175
+ /** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */
176
+ interface ConfigField {
177
+ readonly key: string;
178
+ readonly required: boolean;
179
+ readonly secret: boolean;
180
+ readonly description: string;
181
+ }
182
+ /**
183
+ * The LINE channel: LINE delivers inbound events by webhook, so the app routes each request to
184
+ * `webhook.verify` and then `webhook.ingest`.
185
+ *
186
+ * `verify` checks the `x-line-signature` header (any case) against the raw body with the adapter's
187
+ * channel secret. `ingest` reports `"malformed"` for a payload with no `events` array or with an
188
+ * event that is not an object, dispatching nothing; otherwise it dispatches through
189
+ * `LineAdapter.dispatchWebhookBody`, which caches each event's reply token so the handler's reply
190
+ * uses the reply API. A follow or other non-text event is skipped and still reports `"delivered"`.
191
+ * It reports `"no_handler"`, dispatching nothing, when the payload holds a text message for the
192
+ * handler and none is subscribed (before the runner started, after it stopped, or when this
193
+ * adapter's connect failed under `connectFailure: "isolate"`). Only `"delivered"` should be
194
+ * answered with 200: with webhook redelivery turned on, LINE redelivers a request answered
195
+ * otherwise.
196
+ * `create` refuses a field of the wrong type, and the adapter refuses an empty secret or token,
197
+ * both with this package's `ConfigurationError`.
198
+ *
199
+ * @public
200
+ */
201
+ declare const lineChannel: {
202
+ platform: "line";
203
+ transport: "webhook";
204
+ config: readonly ConfigField[];
205
+ create(config: Readonly<Record<string, unknown>>): LineAdapter;
206
+ webhook: {
207
+ verify(adapter: LineAdapter, request: {
208
+ readonly rawBody: string;
209
+ readonly headers: Readonly<Record<string, string | undefined>>;
210
+ }): boolean;
211
+ ingest(adapter: LineAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
212
+ };
213
+ };
214
+
157
215
  /**
158
216
  * Typed errors for `@theokit/gateway-line`.
159
217
  *
@@ -254,13 +312,18 @@ declare function computeLineSignature(channelSecret: string, rawBody: string): s
254
312
  declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
255
313
 
256
314
  /**
257
- * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
315
+ * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7), keeping table rows whole.
316
+ *
317
+ * LINE limits text messages to 5000 chars. A text within the limit goes through core
318
+ * `chunkByGrapheme` as before. A longer one is cut at the last grapheme boundary within each part,
319
+ * which is where `chunkByGrapheme`'s greedy walk ends a part, so emoji, regional indicators and
320
+ * combining sequences are never severed and text with no table row splits exactly as it did
321
+ * (pinned by `tests/split-no-table-baseline.test.ts` and the equivalence test in
322
+ * `tests/split-tables.test.ts`).
258
323
  *
259
- * LINE limits text messages to 5000 chars. Thin wrapper over core
260
- * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme
261
- * walk so emoji, regional indicators, and combining sequences are never severed.
262
- * Output is byte-identical to the previous implementation (pinned by
263
- * `tests/split.test.ts`).
324
+ * A cut that falls inside a Markdown table row which fits in a part moves back to the start of
325
+ * that row, so the row arrives whole in the next message (B-556). The rule is core
326
+ * `splitKeepingRows`, shared with gateway-sms.
264
327
  */
265
328
  declare function splitForLine(text: string, limit?: number): string[];
266
329
 
@@ -296,4 +359,36 @@ interface WebhookServer {
296
359
  */
297
360
  declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
298
361
 
299
- 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 };
362
+ /**
363
+ * The LINE half of a framework channel webhook, in the shape `theokit/server/webhook` validators
364
+ * take: `(request) => Promise<{ ok: true } | { ok: false; reason }>`. The shape is structural, so
365
+ * this package imports nothing from the framework.
366
+ *
367
+ * ```ts
368
+ * await handleChannelWebhook(request, pathname, {
369
+ * validators: { line: lineWebhookVerifier(adapter) },
370
+ * })
371
+ * ```
372
+ *
373
+ * @public
374
+ */
375
+ /** What a verifier answers. @public */
376
+ type LineWebhookVerifyResult = {
377
+ readonly ok: true;
378
+ } | {
379
+ readonly ok: false;
380
+ readonly reason: string;
381
+ };
382
+ /**
383
+ * Build a verifier for one channel secret (or an adapter exposing `getChannelSecret()`).
384
+ *
385
+ * The request body is READ as raw text, because LINE signs the exact bytes; pass a clone if the
386
+ * body is needed afterwards.
387
+ *
388
+ * @public
389
+ */
390
+ declare function lineWebhookVerifier(source: string | {
391
+ getChannelSecret(): string;
392
+ }): (request: Request) => Promise<LineWebhookVerifyResult>;
393
+
394
+ export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, type LineWebhookVerifyResult, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, lineWebhookVerifier, mapSourceType, splitForLine, verifyLineSignature };
package/dist/index.d.ts CHANGED
@@ -129,16 +129,25 @@ declare class LineAdapter extends BasePlatformAdapter {
129
129
  connect(): Promise<boolean>;
130
130
  disconnect(): Promise<void>;
131
131
  sendMessage(out: OutboundMessage): Promise<SendResult>;
132
+ private sendText;
132
133
  /** Whether the "this platform has no text formatting" warning has already been emitted. */
133
134
  private warnedAboutFormat;
134
135
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
135
136
  /** Escape hatch: caller drives Flex/Carousel/etc directly. */
136
137
  getClient(): LineSdkClient | undefined;
137
138
  /**
138
- * Webhook entrypoint — called by `createWebhookServer` AFTER signature
139
- * validation. Iterates LINE's batch envelope and dispatches each event.
139
+ * Webhook entrypoint — called AFTER signature validation. Iterates LINE's batch envelope and
140
+ * dispatches each event.
141
+ *
142
+ * Answers `"no_handler"`, dispatching nothing and caching no reply token, when the batch holds an
143
+ * event the handler would receive (a text message that passes the mention guard) and no handler
144
+ * is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired
145
+ * because its connect failed. A webhook route must not acknowledge that answer, or LINE does not
146
+ * redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's
147
+ * console verification, or only follow and media events) answers `"ok"` either way. The handler is
148
+ * read once per batch, so one that unsubscribes while handling an event still gets the rest.
140
149
  */
141
- dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void>;
150
+ dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<"ok" | "no_handler">;
142
151
  private dispatchSingleEvent;
143
152
  private passesMentionGuard;
144
153
  /** Expose channel secret for the webhook server (signature middleware). */
@@ -154,6 +163,55 @@ declare class LineAdapter extends BasePlatformAdapter {
154
163
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
155
164
  }
156
165
 
166
+ /**
167
+ * `lineChannel` — the LINE channel described as data (FR-005 of B-018).
168
+ *
169
+ * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as
170
+ * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on
171
+ * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the
172
+ * integration package assigns it to one, and its typecheck is where a drift between the two fails.
173
+ */
174
+
175
+ /** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */
176
+ interface ConfigField {
177
+ readonly key: string;
178
+ readonly required: boolean;
179
+ readonly secret: boolean;
180
+ readonly description: string;
181
+ }
182
+ /**
183
+ * The LINE channel: LINE delivers inbound events by webhook, so the app routes each request to
184
+ * `webhook.verify` and then `webhook.ingest`.
185
+ *
186
+ * `verify` checks the `x-line-signature` header (any case) against the raw body with the adapter's
187
+ * channel secret. `ingest` reports `"malformed"` for a payload with no `events` array or with an
188
+ * event that is not an object, dispatching nothing; otherwise it dispatches through
189
+ * `LineAdapter.dispatchWebhookBody`, which caches each event's reply token so the handler's reply
190
+ * uses the reply API. A follow or other non-text event is skipped and still reports `"delivered"`.
191
+ * It reports `"no_handler"`, dispatching nothing, when the payload holds a text message for the
192
+ * handler and none is subscribed (before the runner started, after it stopped, or when this
193
+ * adapter's connect failed under `connectFailure: "isolate"`). Only `"delivered"` should be
194
+ * answered with 200: with webhook redelivery turned on, LINE redelivers a request answered
195
+ * otherwise.
196
+ * `create` refuses a field of the wrong type, and the adapter refuses an empty secret or token,
197
+ * both with this package's `ConfigurationError`.
198
+ *
199
+ * @public
200
+ */
201
+ declare const lineChannel: {
202
+ platform: "line";
203
+ transport: "webhook";
204
+ config: readonly ConfigField[];
205
+ create(config: Readonly<Record<string, unknown>>): LineAdapter;
206
+ webhook: {
207
+ verify(adapter: LineAdapter, request: {
208
+ readonly rawBody: string;
209
+ readonly headers: Readonly<Record<string, string | undefined>>;
210
+ }): boolean;
211
+ ingest(adapter: LineAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
212
+ };
213
+ };
214
+
157
215
  /**
158
216
  * Typed errors for `@theokit/gateway-line`.
159
217
  *
@@ -254,13 +312,18 @@ declare function computeLineSignature(channelSecret: string, rawBody: string): s
254
312
  declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
255
313
 
256
314
  /**
257
- * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
315
+ * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7), keeping table rows whole.
316
+ *
317
+ * LINE limits text messages to 5000 chars. A text within the limit goes through core
318
+ * `chunkByGrapheme` as before. A longer one is cut at the last grapheme boundary within each part,
319
+ * which is where `chunkByGrapheme`'s greedy walk ends a part, so emoji, regional indicators and
320
+ * combining sequences are never severed and text with no table row splits exactly as it did
321
+ * (pinned by `tests/split-no-table-baseline.test.ts` and the equivalence test in
322
+ * `tests/split-tables.test.ts`).
258
323
  *
259
- * LINE limits text messages to 5000 chars. Thin wrapper over core
260
- * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme
261
- * walk so emoji, regional indicators, and combining sequences are never severed.
262
- * Output is byte-identical to the previous implementation (pinned by
263
- * `tests/split.test.ts`).
324
+ * A cut that falls inside a Markdown table row which fits in a part moves back to the start of
325
+ * that row, so the row arrives whole in the next message (B-556). The rule is core
326
+ * `splitKeepingRows`, shared with gateway-sms.
264
327
  */
265
328
  declare function splitForLine(text: string, limit?: number): string[];
266
329
 
@@ -296,4 +359,36 @@ interface WebhookServer {
296
359
  */
297
360
  declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
298
361
 
299
- 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 };
362
+ /**
363
+ * The LINE half of a framework channel webhook, in the shape `theokit/server/webhook` validators
364
+ * take: `(request) => Promise<{ ok: true } | { ok: false; reason }>`. The shape is structural, so
365
+ * this package imports nothing from the framework.
366
+ *
367
+ * ```ts
368
+ * await handleChannelWebhook(request, pathname, {
369
+ * validators: { line: lineWebhookVerifier(adapter) },
370
+ * })
371
+ * ```
372
+ *
373
+ * @public
374
+ */
375
+ /** What a verifier answers. @public */
376
+ type LineWebhookVerifyResult = {
377
+ readonly ok: true;
378
+ } | {
379
+ readonly ok: false;
380
+ readonly reason: string;
381
+ };
382
+ /**
383
+ * Build a verifier for one channel secret (or an adapter exposing `getChannelSecret()`).
384
+ *
385
+ * The request body is READ as raw text, because LINE signs the exact bytes; pass a clone if the
386
+ * body is needed afterwards.
387
+ *
388
+ * @public
389
+ */
390
+ declare function lineWebhookVerifier(source: string | {
391
+ getChannelSecret(): string;
392
+ }): (request: Request) => Promise<LineWebhookVerifyResult>;
393
+
394
+ export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, type LineWebhookVerifyResult, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, lineWebhookVerifier, mapSourceType, splitForLine, verifyLineSignature };