Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature websocket #14691

Open
wants to merge 3 commits into
base: 3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/taro-plugin-websocket/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# @tarojs/plugin-websocket

`Taro` 运行时扩展插件, 扩展了 `web` 开发中网络请求相关的能力,让 `taro` 可以使用 socket.io-client 等socket请求封装库。

> 本插件需搭配 taro 3.6.0 及其以上版本使用

### WebSocket

在小程序端模仿浏览器的 `WebSocket` 实现的对象,在浏览器环境中返回浏览器本身的 `WebSocket`。此对象通过 Webpack 的 [ProvidePlugin](https://webpack.js.org/plugins/provide-plugin/) 注入到全局对象以供第三方库调用。

```js
// config/index.js
config = {
// ...
plugins: [
['@tarojs/plugin-websocket']
],
}
```
3 changes: 3 additions & 0 deletions packages/taro-plugin-websocket/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = require('./dist/index.js').default

module.exports.default = module.exports
44 changes: 44 additions & 0 deletions packages/taro-plugin-websocket/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const path = require('path')

module.exports = {
collectCoverage: false,
coveragePathIgnorePatterns: [
'nerv.js',
'vue.js',
'utils.js'
],
globals: {
ENABLE_INNER_HTML: true,
ENABLE_ADJACENT_HTML: true,
ENABLE_SIZE_APIS: true,
ENABLE_TEMPLATE_CONTENT: true,
ENABLE_MUTATION_OBSERVER: true,
ENABLE_CLONE_NODE: true,
ENABLE_CONTAINS: true,
ENABLE_COOKIE: true,
},
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
moduleNameMapper: {
'@tarojs/shared': path.resolve(__dirname, '..', '..', 'packages/shared/src/index.ts')
},
preset: 'ts-jest',
setupFiles: [path.resolve(__dirname, './src/__tests__/setup.js')],
testEnvironment: 'node',
testEnvironmentOptions: {
url: 'http://localhost/'
},
testMatch: ['**/__tests__/?(*.)+(spec|test).[jt]s?(x)'],
testPathIgnorePatterns: [
'node_modules',
'utils'
],
transform: {
'^.+\\.m?[tj]sx?$': ['ts-jest', {
diagnostics: false,
tsconfig: 'tsconfig.test.json'
}],
},
transformIgnorePatterns: [
'node_modules/(?!(lodash-es)/)'
]
}
49 changes: 49 additions & 0 deletions packages/taro-plugin-websocket/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"name": "@tarojs/plugin-websocket",
"version": "3.6.17",
"description": "Taro 小程序端支持使用 websocket 请求 的插件",
"main": "index.js",
"scripts": {
"dev": "rollup -c -w --bundleConfigAsCjs",
"build": "rollup -c --bundleConfigAsCjs",
"test": "jest",
"test:ci": "jest --ci -i --coverage false"
},
"files": [
"src",
"dist",
"index.js",
"package.json"
],
"repository": {
"type": "git",
"url": "git+https://github.com/NervJS/taro.git"
},
"keywords": [
"Taro"
],
"author": "bigmeow <https://github.com/bigmeow>",
"license": "MIT",
"bugs": {
"url": "https://github.com/NervJS/taro/issues"
},
"homepage": "https://github.com/NervJS/taro#readme",
"dependencies": {
"@tarojs/runtime": "workspace:*",
"@tarojs/service": "workspace:*",
"@tarojs/shared": "workspace:*"
},
"devDependencies": {
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^15.0.1",
"jest": "^29.3.1",
"jest-cli": "^29.3.1",
"jest-environment-node": "^29.5.0",
"rollup": "^3.8.1",
"rollup-plugin-node-externals": "^5.0.0",
"rollup-plugin-ts": "^3.0.2",
"ts-jest": "^29.0.5",
"tslib": "^2.5.0",
"typescript": "^4.7.4"
}
}
39 changes: 39 additions & 0 deletions packages/taro-plugin-websocket/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import json from '@rollup/plugin-json'
import nodeResolve from '@rollup/plugin-node-resolve'
import * as path from 'path'
import { externals } from 'rollup-plugin-node-externals'
import ts from 'rollup-plugin-ts'

const cwd = __dirname

// 供 CLI 编译时使用的 Taro 插件入口
const compileConfig = {
input: path.join(cwd, 'src/index.ts'),
output: {
file: path.join(cwd, 'dist/index.js'),
format: 'cjs',
exports: 'named',
},
plugins: [
externals({
deps: true,
devDeps: false,
}),
nodeResolve(),
json(),
ts()
]
}

// 运行时入口
const runtimeConfig = {
input: path.join(cwd, 'src/runtime/index.ts'),
output: {
file: path.join(cwd, 'dist/runtime.js'),
format: 'es'
},
external: ['@tarojs/taro', '@tarojs/runtime', '@tarojs/shared'],
plugins: [nodeResolve(), ts()]
}

module.exports = [compileConfig, runtimeConfig]
45 changes: 45 additions & 0 deletions packages/taro-plugin-websocket/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import path from 'path'

import { name as packageName } from '../package.json'

import type { IPluginContext, TaroPlatformBase } from '@tarojs/service'

export interface IOptions {
/** 支持 document.cookie 和 http 设置 cookie (默认false) */
enableCookie?: boolean
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这几个配置你这里需要吗?

/** 禁用掉 FormData 全局对象 (默认true禁用) */
disabledFormData?: boolean
/** 禁用掉 Blob 全局对象 (默认true禁用) */
disabledBlob?: boolean
}

export default (ctx: IPluginContext) => {
ctx.modifyWebpackChain(({ chain }) => {
if (process.env.TARO_PLATFORM === 'mini') {
chain.plugin('definePlugin').tap(args => args)

const runtimeAlias = `${packageName}/dist/runtime`
chain.resolve.alias.set(runtimeAlias, path.join(__dirname, 'runtime.js'))
// 注入相关全局BOM对象
chain.plugin('providerPlugin').tap(args => {
args[0].WebSocket = [runtimeAlias, 'WebSocket']

return args
})
}
})

ctx.registerMethod({
name: 'onSetupClose',
fn (platform: TaroPlatformBase) {
if (process.env.TARO_PLATFORM === 'mini') {
const injectedPath = `post:${packageName}/dist/runtime`
if (Array.isArray(platform.runtimePath)) {
platform.runtimePath.push(injectedPath)
} else if (typeof platform.runtimePath === 'string') {
platform.runtimePath = [platform.runtimePath, injectedPath]
}
}
},
})
}
164 changes: 164 additions & 0 deletions packages/taro-plugin-websocket/src/runtime/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import { document, window } from '@tarojs/runtime'
import Taro from '@tarojs/taro'

const START_TIME = Date.now()

class Event {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

事件这里可以参考 XMLHttpRequest 直接继承 Events, 不用自己再实现一个
import { Events } from '@tarojs/runtime'

fns: any[] = []

on (fn) {
this.fns.push(fn)
}

off (fn) {
this.fns = this.fns.filter(item => item !== fn)
}

tigger (...data) {
this.fns.forEach(fn => fn(...data))
}
}

class WebSocket {
static CLOSED = 3
static CLOSING = 2
static CONNECTING = 0
static OPEN = 1

CLOSED = 3
CLOSING = 2
CONNECTING = 0
OPEN = 1

url = ''
binaryType = 'blob'
bufferedAmount = 0
extensions = ''

onopen = null
onmessage = null
onclose = null
onerror = null

private _miniappTask: Taro.SocketTask | null = null
private _error: any | null = null
private _waitEvent = new Event()
private _events: { type: string, fn: any }[] = []

_wait () {
return new Promise<void>(resolve => {
const fn = () => {
resolve()
this._waitEvent.off(fn)
}

if (this._miniappTask) {
this._waitEvent.off(fn)
return resolve()
}

if (this._error) {
this._waitEvent.off(fn)
return resolve()
}

this._waitEvent.on(fn)
})
}

_execEvent (type, val) {
const _val = {
isTrusted: true,
bubbles: false,
cancelBubble: false,
cancelable: false,
composed: false,
currentTarget: this,
defaultPrevented: false,
eventPhase: 0,
lastEventId: '',
origin: this.url,
ports: [],
returnValue: true,
source: null,
srcElement: this,
target: this,
timeStamp: Date.now() - START_TIME,
type,
userActivation: null,
wasClean: true,
...val,
}

this[`on${type}`](_val)
this._events.forEach(item => item.type === type && item.fn(_val))
}

constructor (url) {
this.url = url
Taro.connectSocket({ url }).then(task => {
task.onOpen(val => this._execEvent('open', val))

task.onMessage(val => this._execEvent('message', val))

task.onClose(val => this._execEvent('close', val))

task.onError(val => this._execEvent('error', val))

this._miniappTask = task
}).catch(err => {
this._error = err
}).finally(() => {
this._waitEvent.tigger()
})
}

close (code, reason) {
this._wait().then(() => {
this._miniappTask?.close({ code, reason })
})
}

send (data) {
if (!this._miniappTask) {
throw new Error(`Failed to execute 'send' on 'WebSocket': Still in CONNECTING state`)
}
this._miniappTask.send({ data })
}

addEventListener (type, fn) {
this._events.push({ type, fn })
}

removeEventListener (type, fn) {
this._events = this._events.filter(item => item.type === type && item.fn === fn)
}
}

class _WebSocket {
constructor (url) {
const socket = new WebSocket(url)
Object.defineProperties(
socket,
['onopen', 'onerror', 'onmessage', 'onclose'].reduce((p, c) => ({
...p,
[c]: {
set (value) {
socket._wait().then(() => {
this[`_${c}`] = value
})
},
get () {
return this[`_${c}`]
},
},
}), {}),
)

return socket
}
}

window.WebSocket = _WebSocket

export { document, _WebSocket as WebSocket }
13 changes: 13 additions & 0 deletions packages/taro-plugin-websocket/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.root.json",
"compilerOptions": {
"baseUrl": ".",
"module": "ESNext",
"target": "ES2017",
"sourceMap": true,
"declaration": true,
"declarationDir": "./dist"
},
"include": ["./src"],
"exclude": ["./src/__tests__"]
}
7 changes: 7 additions & 0 deletions packages/taro-plugin-websocket/tsconfig.test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.root.json",
"compilerOptions": {
"jsx": "react",
"allowJs": true
}
}
Loading
Loading