From e634ee82a4db1eb33986fa59c8b813eeb0556300 Mon Sep 17 00:00:00 2001 From: Romain Lanz Date: Fri, 7 Jul 2023 21:31:53 +0200 Subject: [PATCH] chore: initial commit --- .editorconfig | 15 ++++ .github/lock.yml | 26 +++++++ .github/stale.yml | 24 +++++++ .github/workflows/test.yml | 39 +++++++++++ .gitignore | 5 ++ .npmrc | 1 + .prettierignore | 4 ++ LICENSE.md | 9 +++ README.md | 122 +++++++++++++++++++++++++++++++++ bin/test.ts | 31 +++++++++ index.ts | 0 package.json | 100 +++++++++++++++++++++++++++ providers/transmit_provider.ts | 48 +++++++++++++ services/transmit.ts | 10 +++ src/secure_channel_store.ts | 20 ++++++ src/storage_bag.ts | 49 +++++++++++++ src/stream.ts | 84 +++++++++++++++++++++++ src/transmit.ts | 106 ++++++++++++++++++++++++++++ src/types.ts | 7 ++ tests/maths.spec.ts | 7 ++ tsconfig.json | 7 ++ 21 files changed, 714 insertions(+) create mode 100644 .editorconfig create mode 100644 .github/lock.yml create mode 100644 .github/stale.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .npmrc create mode 100644 .prettierignore create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 bin/test.ts create mode 100644 index.ts create mode 100644 package.json create mode 100644 providers/transmit_provider.ts create mode 100644 services/transmit.ts create mode 100644 src/secure_channel_store.ts create mode 100644 src/storage_bag.ts create mode 100644 src/stream.ts create mode 100644 src/transmit.ts create mode 100644 src/types.ts create mode 100644 tests/maths.spec.ts create mode 100644 tsconfig.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4d8e8a7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# http://editorconfig.org + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.json] +insert_final_newline = ignore + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/lock.yml b/.github/lock.yml new file mode 100644 index 0000000..74eee94 --- /dev/null +++ b/.github/lock.yml @@ -0,0 +1,26 @@ +--- +ignoreUnless: { { STALE_BOT } } +--- +# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app + +# Number of days of inactivity before a closed issue or pull request is locked +daysUntilLock: 60 + +# Skip issues and pull requests created before a given timestamp. Timestamp must +# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable +skipCreatedBefore: false + +# Issues and pull requests with these labels will be ignored. Set to `[]` to disable +exemptLabels: ['Type: Security'] + +# Label to add before locking, such as `outdated`. Set to `false` to disable +lockLabel: false + +# Comment to post before locking. Set to `false` to disable +lockComment: > + This thread has been automatically locked since there has not been + any recent activity after it was closed. Please open a new issue for + related bugs. + +# Assign `resolved` as the reason for locking. Set to `false` to disable +setLockReason: false diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 0000000..8b47808 --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,24 @@ +--- +ignoreUnless: { { STALE_BOT } } +--- +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 60 + +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 + +# Issues with these labels will never be considered stale +exemptLabels: + - 'Type: Security' + +# Label to use when marking an issue as stale +staleLabel: 'Status: Abandoned' + +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. + +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..8f4b292 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,39 @@ +name: test +on: + - push + - pull_request +jobs: + linux: + runs-on: ubuntu-latest + strategy: + matrix: + node-version: + - 18.x + - 19.x + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install + run: npm install + - name: Run tests + run: npm test + windows: + runs-on: windows-latest + strategy: + matrix: + node-version: + - 18.x + - 19.x + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install + run: npm install + - name: Run tests + run: npm test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40eb237 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules +build +coverage +.idea +.vscode diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..43c97e7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +package-lock=false diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..da1f07a --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +build +docs +coverage +*.html diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..28e92fe --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +# The MIT License + +Copyright (c) 2023, Romain Lanz, AdonisJS Core Team, contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..72073e3 --- /dev/null +++ b/README.md @@ -0,0 +1,122 @@ +# AdonisJS package starter kit + +> A boilerplate for creating AdonisJS packages + +This repo contains the default folder structure, development, and peer dependencies to create a package for AdonisJS v6. + +You can create a package from scratch with your folder structure and workflow. However, using a default starter kit can speed up the process, as you have fewer decisions to make. + +## Folder structure + +The starter kit mimics the folder structure of the official packages. Feel free to rename files and folders as per your requirements. + +``` +├── providers +├── src +├── stubs +├── index.ts +├── LICENSE.md +├── package.json +├── README.md +└── tsconfig.json +``` + +- The `providers` directory is used to store service providers. +- The `src` directory contains the source code of the package. All business logic should be inside this folder. +- The `stubs` directory is used to keep scaffolding stubs. You might copy some stubs to the user application once they configure the package. +- The `index.ts` file is the main entry point of the package. + +### File system naming convention + +We use `snake_case` naming conventions for the file system. The rule is enforced using ESLint. However, feel free to disable the rule and use your preferred naming conventions. + +## Peer dependencies + +The starter kit has a peer dependency on `@adonisjs/core@6`. Since you are creating a package for AdonisJS, you must make it against a specific version of the framework core. + +If your package needs Lucid to be functional, you may install `@adonisjs/lucid` as a development dependency and add it to the list of `peerDependencies`. + +As a rule of thumb, packages installed in the user application should be part of the `peerDependencies` of your package and not the main dependency. + +For example, if you install `@adonisjs/core` as a main dependency, then essentially, you are importing a separate copy of `@adonisjs/core` and not sharing the one from the user application. Here is a great article explaining [peer dependencies](https://blog.bitsrc.io/understanding-peer-dependencies-in-javascript-dbdb4ab5a7be). + +## Published files + +Instead of publishing all the source code of your repo to npm, you must cherry-pick files and folders to publish only the required files. + +The cherry-picking is done using the `files` property inside the `package.json` file. By default, we publish the following files and folders. + +```json +{ + "files": [ + "src", + "providers", + "index.ts", + "build/src", + "build/providers", + "build/stubs", + "build/index.d.ts", + "build/index.d.ts.map", + "build/index.js" + ] +} +``` + +If you notice, we are publishing both the source code (written in TypeScript) and the compiled output (JavaScript) to npm. + +- The JavaScript runtime requires compiled output. So that is something you will have to publish. +- Publishing source code is optional. However, if you generate [declaration maps](https://www.typescriptlang.org/tsconfig#declarationMap), then the TypeScript language server (used by code editors like VSCode) will be able to jump to the actual source code when you perform `CTRL + CLICK`. + +If you create additional folders or files, mention them inside the `files` array. + +## Exports + +[Node.js Subpath exports](https://nodejs.org/api/packages.html#subpath-exports) allows you to define the exports of your package regardless of the folder structure. This starter kit defines the following exports. + +```json +{ + "exports": { + ".": "./build/index.js", + "./types": "./build/src/types.js" + } +} +``` + +- The dot `.` export is the main export. +- The `./types` exports all the types defined inside the `./build/src/types.js` file (the compiled output). + +Feel free to change the exports as per your requirements. + +## Testing + +We configure the [Japa test runner](https://japa.dev/) with this starter kit. Japa is used in AdonisJS applications as well. Just run one of the following commands to execute tests. + +- `npm run test`: This command will first lint the code using ESlint and then run tests and report the test coverage using [c8](https://github.com/bcoe/c8). +- `npm run quick:test`: Runs only the tests without linting or coverage reporting. + +The starter kit also comes with a Github workflow file to run tests using Github Actions. The tests are executed against `Node.js 18.x` and `Node.js 19.x` versions on both Linux and Windows. Feel free to edit the workflow file in the `.github/workflows` directory. + +## TypeScript workflow + +- The starter kit uses [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) for compiling the TypeScript to JavaScript at the time of publishing the package. +- [TS-Node](https://typestrong.org/ts-node/) and [SWC](https://swc.rs/) are used to run tests without compiling the source code. +- The `tsconfig.json` file is extended from [`@adonisjs/tsconfig`](https://github.com/adonisjs/tooling-config/tree/main/packages/typescript-config) and uses `NodeNext` module system. Meaning the packages are written using ES modules. +- You can perform type checking without compiling the source code using `npm run typecheck` script. + +Feel free to explore the `tsconfig.json` file for all the configured options. + +## ESLint and Prettier setup + +The starter kit configures ESLint and Prettier. The configuration for both is stored within the `package.json` file, and use our [shared config](https://github.com/adonisjs/tooling-config/tree/main/packages). Feel free to change the config, use custom plugins or remove both tools altogether. + +## Using Stale bot (optional) + +The [Stale bot](https://github.com/apps/stale) is a Github application that automatically marks issues and PRs as stale and closes after a certain duration of inactivity. + +You may optionally configure it at the time of scaffolding the package. + +## Unconfigurable bits + +- **License**: The `LICENSE.md` file and the `license` property inside the `package.json` file are set to `MIT`. You can change them manually. +- **Editorconfig**: The `.editorconfig` file is used to define the formatting rules. +- **No package-lock file**: The `.npmrc` file is created with the rule to diable `package-lock.json` file. Feel free to revert the setting or use a different package manager. diff --git a/bin/test.ts b/bin/test.ts new file mode 100644 index 0000000..a512ba2 --- /dev/null +++ b/bin/test.ts @@ -0,0 +1,31 @@ +import { assert } from '@japa/assert' +import { processCLIArgs, configure, run } from '@japa/runner' + +/* +|-------------------------------------------------------------------------- +| Configure tests +|-------------------------------------------------------------------------- +| +| The configure method accepts the configuration to configure the Japa +| tests runner. +| +| The first method call "processCLIArgs" process the command line arguments +| and turns them into a config object. Using this method is not mandatory. +| +| Please consult japa.dev/runner-config for the config docs. +*/ +processCLIArgs(process.argv.slice(2)) +configure({ + files: ['tests/**/*.spec.ts'], + plugins: [assert()], +}) + +/* +|-------------------------------------------------------------------------- +| Run tests +|-------------------------------------------------------------------------- +| +| The following "run" method is required to execute all the tests. +| +*/ +run() diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..e69de29 diff --git a/package.json b/package.json new file mode 100644 index 0000000..92a7656 --- /dev/null +++ b/package.json @@ -0,0 +1,100 @@ +{ + "name": "@adonisjs/transmit", + "version": "0.0.1", + "description": "Server-Sent-Event module for AdonisJS.", + "keywords": [ + "sse", + "server-sent-event", + "adonis", + "adonisjs", + "adonis-framework" + ], + "license": "MIT", + "author": "Romain Lanz ", + "type": "module", + "main": "build/index.js", + "exports": { + ".": "./build/index.js", + "./providers": "./build/providers/transmit_provider.js", + "./services/transmit": "./build/src/services/transmit.js", + "./types": "./build/src/types.js" + }, + "scripts": { + "clean": "del-cli build", + "copy:templates": "copyfiles \"stubs/**/*.stub\" build", + "typecheck": "tsc --no-emit", + "lint": "eslint . --ext=.ts", + "format": "prettier --write .", + "quick:test": "node --enable-source-maps --loader=ts-node/esm bin/test.ts", + "pretest": "npm run lint", + "test": "c8 npm run quick:test", + "prebuild": "npm run lint && npm run clean", + "build": "tsc", + "postbuild": "npm run copy:templates", + "release": "np", + "version": "npm run build", + "prepublishOnly": "npm run build" + }, + "dependencies": { + "@poppinss/matchit": "^3.1.2", + "emittery": "^1.0.1" + }, + "devDependencies": { + "@adonisjs/core": "^6.1.5-5", + "@adonisjs/eslint-config": "^1.1.7", + "@adonisjs/prettier-config": "^1.1.7", + "@adonisjs/tsconfig": "^1.1.7", + "@japa/assert": "2.0.0-1", + "@japa/runner": "3.0.0-3", + "@swc/core": "^1.3.68", + "@types/node": "^20.3.3", + "c8": "^8.0.0", + "copyfiles": "^2.4.1", + "del-cli": "^5.0.0", + "eslint": "^8.44.0", + "np": "^8.0.4", + "prettier": "^2.8.8", + "ts-node": "^10.9.1", + "typescript": "^5.1.6" + }, + "peerDependencies": { + "@adonisjs/core": "^6.1.5-5" + }, + "files": [ + "src", + "providers", + "index.ts", + "build/src", + "build/providers", + "build/stubs", + "build/index.d.ts", + "build/index.d.ts.map", + "build/index.js" + ], + "engines": { + "node": ">=18.16.0" + }, + "eslintConfig": { + "extends": "@adonisjs/eslint-config/package" + }, + "prettier": "@adonisjs/prettier-config", + "publishConfig": { + "access": "public", + "tag": "latest" + }, + "np": { + "message": "chore(release): %s", + "tag": "latest", + "branch": "main", + "anyBranch": false + }, + "c8": { + "reporter": [ + "text", + "html" + ], + "exclude": [ + "tests/**" + ] + } +} diff --git a/providers/transmit_provider.ts b/providers/transmit_provider.ts new file mode 100644 index 0000000..a53fca7 --- /dev/null +++ b/providers/transmit_provider.ts @@ -0,0 +1,48 @@ +import { Transmit } from '../src/transmit.js' +import type { ApplicationService } from '@adonisjs/core/types' + +export default class TransmitProvider { + constructor(protected app: ApplicationService) {} + + register() { + this.app.container.singleton('transmit', () => { + return new Transmit() + }) + } + + boot() { + this.app.container.resolving('router', async (router) => { + const transmit = await this.app.container.make('transmit') + + router.get('__transmit/events', ({ request, response }) => { + transmit.createStream(request, response) + }) + + router.post('__transmit/subscribe', (ctx) => { + const uid = ctx.request.input('uid') + const channel = ctx.request.input('channel') + + const success = transmit.subscribeToChannel(uid, channel, ctx) + + if (!success) { + return ctx.response.badRequest() + } + + return ctx.response.noContent() + }) + + router.post('__transmit/unsubscribe', ({ request, response }) => { + const uid = request.input('uid') + const channel = request.input('channel') + + const success = transmit.unsubscribeFromChannel(uid, channel) + + if (!success) { + return response.badRequest() + } + + return response.noContent() + }) + }) + } +} diff --git a/services/transmit.ts b/services/transmit.ts new file mode 100644 index 0000000..b82c563 --- /dev/null +++ b/services/transmit.ts @@ -0,0 +1,10 @@ +import app from '@adonisjs/core/services/app' +import { Transmit } from '../src/transmit.js' + +let transmit: Transmit + +await app.booted(async () => { + transmit = await app.container.make('transmit') +}) + +export { transmit as default } diff --git a/src/secure_channel_store.ts b/src/secure_channel_store.ts new file mode 100644 index 0000000..a2d510d --- /dev/null +++ b/src/secure_channel_store.ts @@ -0,0 +1,20 @@ +import matchit from '@poppinss/matchit' + +export class SecureChannelStore { + #securedChannelsDefinition: any[] = [] + + add(channel: string) { + const encodedDefinition = matchit.parse(channel) + + this.#securedChannelsDefinition.push(encodedDefinition) + } + + match(channel: string) { + const matchedChannel = matchit.match(channel, this.#securedChannelsDefinition) + + if (matchedChannel) { + const params = matchit.exec(channel, matchedChannel) + return { params, url: matchedChannel[0].old } + } + } +} diff --git a/src/storage_bag.ts b/src/storage_bag.ts new file mode 100644 index 0000000..aa4e100 --- /dev/null +++ b/src/storage_bag.ts @@ -0,0 +1,49 @@ +import type { Stream } from './stream.js' + +export class StorageBag { + #subscribers = new Map>() + #channelByUid = new Map>() + + push(stream: Stream) { + const channels = new Set() + this.#subscribers.set(stream, channels) + this.#channelByUid.set(stream.getUid(), channels) + } + + remove(stream: Stream) { + this.#subscribers.delete(stream) + this.#channelByUid.delete(stream.getUid()) + } + + addChannelToStream(uid: string, channel: string): boolean { + const channels = this.#channelByUid.get(uid) + + if (!channels) return false + + channels.add(channel) + + return true + } + + removeChannelFromStream(uid: string, channel: string): boolean { + const channels = this.#channelByUid.get(uid) + + if (!channels) return false + + channels.delete(channel) + + return true + } + + findByChannel(channel: string) { + const subscribers = new Set() + + for (const [stream, streamChannels] of this.#subscribers) { + if (streamChannels.has(channel)) { + subscribers.add(stream) + } + } + + return subscribers + } +} diff --git a/src/stream.ts b/src/stream.ts new file mode 100644 index 0000000..0c7b978 --- /dev/null +++ b/src/stream.ts @@ -0,0 +1,84 @@ +import { Transform } from 'node:stream' +import type { IncomingMessage, OutgoingHttpHeaders } from 'node:http' + +function dataString(data: string | object): string { + if (typeof data === 'object') return dataString(JSON.stringify(data)) + return data + .split(/\r\n|\r|\n/) + .map((line) => `data: ${line}\n`) + .join('') +} + +interface Message { + data: string | object + comment?: string + event?: string + id?: string + retry?: number +} + +interface WriteHeaders { + writeHead?(statusCode: number, headers?: OutgoingHttpHeaders): WriteHeaders + flushHeaders?(): void +} + +export type HeaderStream = NodeJS.WritableStream & WriteHeaders + +export class Stream extends Transform { + readonly #uid: string + + constructor(uid: string, request: IncomingMessage) { + super({ objectMode: true }) + + this.#uid = uid + + if (request.socket) { + request.socket.setKeepAlive(true) + request.socket.setNoDelay(true) + request.socket.setTimeout(0) + } + } + + getUid() { + return this.#uid + } + + pipe(destination: T, options?: { end?: boolean }): T { + if (destination.writeHead) { + destination.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Transfer-Encoding': 'identity', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive', + }) + + destination.flushHeaders?.() + } + + // Some clients (Safari) don't trigger onopen until the first frame is received. + destination.write(':ok\n\n') + return super.pipe(destination, options) + } + + _transform( + message: Message, + _encoding: string, + callback: (error?: Error | null, data?: any) => void + ) { + if (message.comment) this.push(`: ${message.comment}\n`) + if (message.event) this.push(`event: ${message.event}\n`) + if (message.id) this.push(`id: ${message.id}\n`) + if (message.retry) this.push(`retry: ${message.retry}\n`) + if (message.data) this.push(dataString(message.data)) + this.push('\n') + callback() + } + + writeMessage( + message: Message, + encoding?: BufferEncoding, + cb?: (error: Error | null | undefined) => void + ): boolean { + return this.write(message, encoding, cb) + } +} diff --git a/src/transmit.ts b/src/transmit.ts new file mode 100644 index 0000000..88af142 --- /dev/null +++ b/src/transmit.ts @@ -0,0 +1,106 @@ +import Emittery from 'emittery' +import { Stream } from './stream.js' +import { StorageBag } from './storage_bag.js' +import { SecureChannelStore } from './secure_channel_store.js' +import type { HttpContext, Request, Response } from '@adonisjs/core/http' + +interface TransmitHooks { + connect: { uid: string } + disconnect: { uid: string } + broadcast: { channel: string; payload: Record } + subscribe: { uid: string; channel: string } + unsubscribe: { uid: string; channel: string } +} + +export class Transmit extends Emittery { + /** + * The storage bag instance to store all the streams. + */ + #storage: StorageBag + + /** + * The secure channel store instance to store all the secure channel definitions. + */ + #secureChannelStore: SecureChannelStore + + /** + * The secure channel store instance to store all the secure channel callbacks. + */ + #secureChannelCallbacks: Map Promise> = + new Map() + + constructor() { + super() + + this.#storage = new StorageBag() + this.#secureChannelStore = new SecureChannelStore() + } + + /** + * Creates and register a new stream for the given request and pipes it to the response. + */ + createStream(request: Request, response: Response): void { + const stream = new Stream(request.input('uid'), request.request) + stream.pipe(response.response) + + void this.emit('connect', { uid: stream.getUid() }) + + this.#storage.push(stream) + + response.response.on('close', () => { + void this.emit('disconnect', { uid: stream.getUid() }) + this.#storage.remove(stream) + }) + + response.stream(stream) + } + + /** + * Store the authorization callback for the given channel. + */ + authorizeChannel( + channel: string, + callback: (ctx: HttpContext, params: T) => Promise + ) { + this.#secureChannelStore.add(channel) + this.#secureChannelCallbacks.set(channel, callback) + } + + async subscribeToChannel(uid: string, channel: string, ctx: HttpContext): Promise { + const definitions = this.#secureChannelStore.match(channel) + + if (definitions) { + const callback = this.#secureChannelCallbacks.get(definitions.url) + + if (!callback) { + return false + } + + const result = await callback(ctx, definitions.params) + + if (!result) { + return false + } + } + + void this.emit('subscribe', { uid, channel }) + + return this.#storage.addChannelToStream(uid, channel) + } + + unsubscribeFromChannel(uid: string, channel: string): boolean { + void this.emit('unsubscribe', { uid, channel }) + + return this.#storage.removeChannelFromStream(uid, channel) + } + + broadcast(channel: string, payload: Record) { + const subscribers = this.#storage.findByChannel(channel) + + for (const subscriber of subscribers) { + subscriber.writeMessage({ data: { channel, payload } }) + } + + void this.emit('broadcast', { channel, payload }) + } +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..c8e8e45 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,7 @@ +import type { Transmit } from './transmit.js' + +declare module '@adonisjs/core/types' { + export interface ContainerBindings { + transmit: Transmit + } +} diff --git a/tests/maths.spec.ts b/tests/maths.spec.ts new file mode 100644 index 0000000..b1dfcb3 --- /dev/null +++ b/tests/maths.spec.ts @@ -0,0 +1,7 @@ +import { test } from '@japa/runner' + +test.group('maths', (group) => { + test('My Test', ({ assert }) => { + assert.equal(1 + 1, 2) + }) +}) diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..ad0cc44 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "@adonisjs/tsconfig/tsconfig.package.json", + "compilerOptions": { + "rootDir": "./", + "outDir": "./build" + } +}