Skip to content

Commit

Permalink
refa: separate router to standalone plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Oct 26, 2023
1 parent 5db7c77 commit 9564c4c
Show file tree
Hide file tree
Showing 19 changed files with 182 additions and 113 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,20 @@ await ctx.start()
### Specifying protocol

```ts
import { Context } from '@satorijs/satori'
import router from '@satorijs/router'
import telegram from '@satorijs/adapter-telegram'

// your application will be listening http://localhost:8080
// and be available at https://example.com
const ctx = new Context({
port: 8080,
selfUrl: 'https://example.com',
})

// you need a router plugin to handle http requests
ctx.plugin(router)

ctx.plugin(telegram, {
// telegram supports two ways of connection: server and polling
protocol: 'server',
Expand Down
1 change: 1 addition & 0 deletions adapters/dingtalk/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Adapter, Context, Logger } from '@satorijs/satori'
import {} from '@satorijs/router'
import { DingtalkBot } from './bot'
import crypto from 'node:crypto'
import { Message } from './types'
Expand Down
1 change: 1 addition & 0 deletions adapters/kook/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Adapter, Context, Logger, sanitize, Schema } from '@satorijs/satori'
import {} from '@satorijs/router'
import { KookBot } from './bot'
import { adaptSession } from './utils'

Expand Down
2 changes: 1 addition & 1 deletion adapters/lark/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import internal from 'stream'

import { Adapter, Context, Logger, Schema } from '@satorijs/satori'
import {} from '@satorijs/router'

import { FeishuBot } from './bot'
import { AllEvents } from './types'
Expand Down
5 changes: 3 additions & 2 deletions adapters/line/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Adapter, Context, Logger } from '@satorijs/satori'
import { LineBot } from './bot'
import {} from '@satorijs/router'
import crypto from 'node:crypto'
import { LineBot } from './bot'
import { WebhookRequestBody } from './types'
import { adaptSessions } from './utils'
import internal from 'stream'
Expand Down Expand Up @@ -50,7 +51,7 @@ export class HttpServer<C extends Context = Context> extends Adapter<C, LineBot<
})
await bot.getLogin()
await bot.internal.setWebhookEndpoint({
endpoint: bot.ctx.root.config.selfUrl + '/line',
endpoint: bot.ctx.router.config.selfUrl + '/line',
})
this.logger.debug('listening updates %c', 'line:' + bot.selfId)
bot.online()
Expand Down
1 change: 1 addition & 0 deletions adapters/matrix/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Adapter, Context, Logger } from '@satorijs/satori'
import { Context as KoaContext } from 'koa'
import {} from '@satorijs/router'
import { MatrixBot } from './bot'
import { dispatchSession } from './utils'
import { ClientEvent, M_ROOM_MEMBER } from './types'
Expand Down
1 change: 1 addition & 0 deletions adapters/slack/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Adapter, Context, Logger, Schema } from '@satorijs/satori'
import {} from '@satorijs/router'
import { SlackBot } from './bot'
import crypto from 'node:crypto'
import { EnvelopedEvent, SlackEvent, SocketEvent } from './types'
Expand Down
3 changes: 2 additions & 1 deletion adapters/telegram/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Adapter, Context, Logger, sanitize, Schema, trimSlash } from '@satorijs/satori'
import {} from '@satorijs/router'
import { TelegramBot } from './bot'
import { handleUpdate } from './utils'
import * as Telegram from './types'
Expand All @@ -14,7 +15,7 @@ export class HttpServer<C extends Context = Context> extends Adapter<C, Telegram
if (selfUrl) {
selfUrl = trimSlash(selfUrl)
} else {
selfUrl = bot.ctx.root.config.selfUrl
selfUrl = bot.ctx.router.config.selfUrl
}

bot.ctx.router.post(path, async (ctx) => {
Expand Down
1 change: 1 addition & 0 deletions adapters/wechat-official/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Adapter, Context } from '@satorijs/satori'
import {} from '@satorijs/router'
import { WechatOfficialBot } from './bot'
import xml2js from 'xml2js'
import { Message } from './types'
Expand Down
1 change: 1 addition & 0 deletions adapters/wecom/src/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Adapter, Context } from '@satorijs/satori'
import {} from '@satorijs/router'
import { WecomBot } from './bot'
import xml2js from 'xml2js'
import { Message } from './types'
Expand Down
1 change: 1 addition & 0 deletions adapters/whatsapp/src/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Adapter, Context, Logger, Quester, remove, Schema } from '@satorijs/satori'
import {} from '@satorijs/router'
import { Internal } from './internal'
import { WhatsAppBot } from './bot'
import { WebhookBody } from './types'
Expand Down
2 changes: 2 additions & 0 deletions packages/router/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.DS_Store
tsconfig.tsbuildinfo
56 changes: 56 additions & 0 deletions packages/router/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"name": "@satorijs/router",
"description": "Router plugin for cordis",
"version": "1.0.1",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"exports": {
".": {
"node": "./lib/index.js",
"browser": "./lib/index.mjs",
"types": "./lib/index.d.ts"
},
"./package.json": "./package.json"
},
"files": [
"lib",
"src"
],
"author": "Shigma <[email protected]>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/satorijs/satori.git",
"directory": "packages/router"
},
"bugs": {
"url": "https://github.com/satorijs/satori/issues"
},
"homepage": "https://github.com/satorijs/satori/tree/master/packages/router",
"keywords": [
"cordis",
"router",
"http",
"ws",
"websocket",
"server",
"service"
],
"devDependencies": {
"@types/parseurl": "^1.3.1"
},
"dependencies": {
"@koa/router": "^10.1.1",
"@types/koa": "*",
"@types/koa__router": "*",
"@types/ws": "^8.5.6",
"koa": "^2.14.2",
"koa-bodyparser": "^4.4.1",
"parseurl": "^1.3.3",
"path-to-regexp": "^6.2.1",
"ws": "^8.14.2"
},
"peerDependencies": {
"@satorijs/satori": "^3.0.2"
}
}
59 changes: 38 additions & 21 deletions packages/satori/src/router.ts → packages/router/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Context, Logger } from '@satorijs/core'
import { Context, Logger, Schema } from '@satorijs/core'
import { MaybeArray, remove, trimSlash } from 'cosmokit'
import { createServer, IncomingMessage, Server } from 'http'
import { pathToRegexp } from 'path-to-regexp'
Expand Down Expand Up @@ -35,7 +35,7 @@ export class WebSocketLayer {
}

accept(socket: WebSocket, request: IncomingMessage) {
if (!this.regexp.test(parseUrl(request).pathname)) return
if (!this.regexp.test(parseUrl(request)!.pathname!)) return
this.clients.add(socket)
socket.addEventListener('close', () => {
this.clients.delete(socket)
Expand All @@ -53,14 +53,14 @@ export class WebSocketLayer {
}

export class Router extends KoaRouter {
public _http?: Server
public _ws?: WebSocket.Server
public _http: Server
public _ws: WebSocket.Server
public wsStack: WebSocketLayer[] = []

public host: string
public port: number
public host!: string
public port!: number

constructor(ctx: Context) {
constructor(ctx: Context, public config: Router.Config) {
super()

// create server
Expand All @@ -83,25 +83,26 @@ export class Router extends KoaRouter {
socket.close()
})

ctx.root.decline(['selfUrl', 'host', 'port', 'maxPort'])
ctx.decline(['selfUrl', 'host', 'port', 'maxPort'])

if (ctx.root.config.selfUrl) {
ctx.root.config.selfUrl = trimSlash(ctx.root.config.selfUrl)
if (config.selfUrl) {
config.selfUrl = trimSlash(config.selfUrl)
}

ctx.on('ready', async () => {
const { host, port } = ctx.root.config
const { host = '127.0.0.1', port } = config
if (!port) return
ctx.router.host = host
ctx.router.port = await listen(ctx.root.config)
ctx.router._http.listen(ctx.router.port, host)
logger.info('server listening at %c', ctx.router.selfUrl)
ctx.on('dispose', () => {
logger.info('http server closing')
ctx.router._ws?.close()
ctx.router._http?.close()
})
this.host = host
this.port = await listen(config)
this._http.listen(this.port, host)
logger.info('server listening at %c', this.selfUrl)
}, true)

ctx.on('dispose', () => {
logger.info('http server closing')
this._ws?.close()
this._http?.close()
})
}

get selfUrl() {
Expand Down Expand Up @@ -131,4 +132,20 @@ export class Router extends KoaRouter {
}
}

Context.service('router', Router)
export namespace Router {
export interface Config {
host: string
port: number
maxPort?: number
selfUrl?: string
}

export const Config: Schema<Config> = Schema.object({
host: Schema.string().default('127.0.0.1').description('要监听的 IP 地址。如果将此设置为 `0.0.0.0` 将监听所有地址,包括局域网和公网地址。'),
port: Schema.natural().max(65535).description('要监听的初始端口号。'),
maxPort: Schema.natural().max(65535).description('允许监听的最大端口号。'),
selfUrl: Schema.string().role('link').description('应用暴露在公网的地址。'),
})
}

export default Router
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import net from 'net'

export interface ListenOptions {
host?: string
port?: number
host: string
port: number
maxPort?: number
}

Expand Down
12 changes: 12 additions & 0 deletions packages/router/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.base",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib",
"strict": true,
"noImplicitAny": false,
},
"include": [
"src",
],
}
57 changes: 0 additions & 57 deletions packages/satori/src/axios.ts

This file was deleted.

Loading

0 comments on commit 9564c4c

Please sign in to comment.