diff --git a/.github/actions/create-artifact/action.yaml b/.github/actions/create-artifact/action.yaml deleted file mode 100644 index bcfbc16..0000000 --- a/.github/actions/create-artifact/action.yaml +++ /dev/null @@ -1,32 +0,0 @@ -name: Create Artifact -description: Upload an artifact to S3. -inputs: - artifact: - description: The raw file contents. - required: true - aws-access-key-id: - description: AWS access key ID. - required: true - aws-secret-access-key: - description: AWS secret access key. - required: true - cache-control: - description: HTTP cache control directive for the S3 object - required: false - public: - description: Make this artifact public - required: false - default: "false" - s3-bucket-name: - description: The name of the S3 bucket. - required: true - s3-object-key: - description: The object key used to store the file in S3. - required: true -outputs: - success: - description: The value will be 'true' if the operation succeeded, otherwise - 'false'. -runs: - using: node16 - main: main.mjs diff --git a/.github/actions/create-artifact/main.mjs b/.github/actions/create-artifact/main.mjs deleted file mode 100644 index 81009c1..0000000 --- a/.github/actions/create-artifact/main.mjs +++ /dev/null @@ -1,46 +0,0 @@ -import core from "@actions/core"; -import aws from "aws-sdk"; -import mime from "mime-types"; - -const run = async () => { - const artifact = core.getInput("artifact", { required: true }); - const awsAccessKeyId = core.getInput("aws-access-key-id", { required: true }); - const awsSecretAccessKey = core.getInput("aws-secret-access-key", { - required: true, - }); - const cacheControl = core.getInput("cache-control"); - const isPublic = core.getBooleanInput("public"); - const s3BucketName = core.getInput("s3-bucket-name", { required: true }); - const s3ObjectKey = core.getInput("s3-object-key", { required: true }); - - const s3 = new aws.S3({ - accessKeyId: awsAccessKeyId, - secretAccessKey: awsSecretAccessKey, - }); - - await s3 - .putObject({ - ACL: isPublic ? "public-read" : undefined, - Body: artifact, - Bucket: s3BucketName, - CacheControl: cacheControl, - ContentType: mime.lookup(s3ObjectKey), - Key: s3ObjectKey, - }) - .promise() - .then(() => { - core.info(`Artifact saved using key ${s3ObjectKey}`); - core.setOutput("success", "true"); - }) - .catch( - /** - * @param {aws.AWSError | NodeJS.ErrnoException} error - */ - (error) => { - core.setOutput("success", "false"); - throw error; - } - ); -}; - -run(); diff --git a/.github/actions/install-dependencies/action.yaml b/.github/actions/install-dependencies/action.yaml index 996859e..661cc2e 100644 --- a/.github/actions/install-dependencies/action.yaml +++ b/.github/actions/install-dependencies/action.yaml @@ -1,13 +1,13 @@ -name: Install Workspace Dependencies -description: Installs all workspace dependencies. +name: Install Dependencies +description: Install all dependencies. runs: using: "composite" steps: - name: Install asdf - uses: asdf-vm/actions/setup@v1 + uses: asdf-vm/actions/setup@v2 - name: Hydrate asdf cache id: hydrate-asdf-cache - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ${{ env.ASDF_DIR }} key: ${{ runner.os }}-${{ hashFiles('.tool-versions') }} @@ -15,10 +15,10 @@ runs: if: steps.hydrate-asdf-cache.outputs.cache-hit != 'true' uses: asdf-vm/actions/install@v1 - name: Hydrate node modules cache - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: "**/node_modules" - key: ${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} + key: ${{ runner.os }}-${{ hashFiles('**/bun.lockb') }} - name: Install node modules - run: yarn install --frozen-lockfile + run: bun install --frozen-lockfile shell: bash diff --git a/.github/actions/install-playwright-dependencies/action.yaml b/.github/actions/install-playwright-dependencies/action.yaml new file mode 100644 index 0000000..ef35c03 --- /dev/null +++ b/.github/actions/install-playwright-dependencies/action.yaml @@ -0,0 +1,28 @@ +name: Install Playwright Dependencies +description: Install playwright dependencies and cache browser binaries. +runs: + using: "composite" + steps: + - name: Get playwright version + id: playwright-info + run: | + version=$( + npm ls @playwright/test --json \ + | jq --raw-output '.dependencies["@playwright/test"].version' + ) + echo "version=$version" >> $GITHUB_OUTPUT + shell: bash + - name: Cache playwright browser binaries + uses: actions/cache@v3 + id: playwright-cache + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ steps.playwright-info.outputs.version }} + - name: Install playwright browsers + if: steps.playwright-cache.outputs.cache-hit != 'true' + run: npx playwright install --with-deps + shell: bash + - name: Install playwright system dependencies + if: steps.playwright-cache.outputs.cache-hit == 'true' + run: npx playwright install-deps + shell: bash diff --git a/.github/actions/jest-coverage-calculator/action.yaml b/.github/actions/jest-coverage-calculator/action.yaml deleted file mode 100644 index 9cba2c7..0000000 --- a/.github/actions/jest-coverage-calculator/action.yaml +++ /dev/null @@ -1,12 +0,0 @@ -name: Jest Coverage Calculator -description: Computes the mean percent coverage -inputs: - coverage: - description: The json-summary coverage report from Jest - required: true -outputs: - percent: - description: The mean percent coverage -runs: - using: node16 - main: main.mjs diff --git a/.github/actions/jest-coverage-calculator/main.mjs b/.github/actions/jest-coverage-calculator/main.mjs deleted file mode 100644 index 2b4acd7..0000000 --- a/.github/actions/jest-coverage-calculator/main.mjs +++ /dev/null @@ -1,18 +0,0 @@ -import core from "@actions/core"; - -const coverageJson = core.getInput("coverage", { required: true }); -const coverage = JSON.parse(coverageJson); - -const sumBy = (list, callback) => - list.reduce((acc, item) => acc + callback(item), 0); - -const percent = [Object.values(coverage.total)] - .map((group) => [ - sumBy(group, ({ covered }) => covered), - sumBy(group, ({ total }) => total), - ]) - .map(([covered, total]) => (total > 0 ? covered / total : 0)) - .map((percent) => parseFloat((percent * 100).toFixed(2))) - .shift(); - -core.setOutput("percent", percent); diff --git a/.github/actions/jest/action.yaml b/.github/actions/jest/action.yaml deleted file mode 100644 index a211d76..0000000 --- a/.github/actions/jest/action.yaml +++ /dev/null @@ -1,60 +0,0 @@ -name: Jest -description: Run Jest tests and collect coverage data -inputs: - aws-access-key-id: - description: AWS access key ID - required: true - aws-secret-access-key: - description: AWS secret access key - required: true - generate-artifacts: - description: Generate coverage artifacts and upload them to S3 - required: false - default: "false" - s3-bucket-name: - description: The S3 bucket to upload artifacts to - required: true - s3-object-path: - description: Where the artifacts will be stored - required: true -runs: - using: "composite" - steps: - - name: Run Jest tests - run: yarn test --collectCoverage - shell: bash - - name: Read Jest coverage output - id: read-jest-coverage - run: | - json=$(cat coverage/coverage-summary.json) - echo "::set-output name=json::${json//$'\n'/'%0A'}" - shell: bash - - name: Calculate percent coverage - id: calculate-percent-coverage - uses: ./.github/actions/jest-coverage-calculator - with: - coverage: ${{ steps.read-jest-coverage.outputs.json }} - - name: Create coverage badge artifact - env: - percent: ${{ steps.calculate-percent-coverage.outputs.percent }} - if: inputs.generate-artifacts == 'true' - uses: ./.github/actions/create-artifact - with: - artifact: | - { - "schemaVersion": 1, - "label": "coverage", - "message": "${{ env.percent }}%", - "color": "${{ - (env.percent < 25 && 'red') || - (env.percent < 50 && 'orange') || - (env.percent < 75 && 'yellow') || - 'brightgreen' - }}" - } - aws-access-key-id: ${{ inputs.aws-access-key-id }} - aws-secret-access-key: ${{ inputs.aws-secret-access-key }} - cache-control: no-cache - public: true - s3-bucket-name: ${{ inputs.s3-bucket-name }} - s3-object-key: ${{ inputs.s3-object-path }}/coverage-shield.json diff --git a/.github/workflows/ci-browser.yaml b/.github/workflows/ci-browser.yaml new file mode 100644 index 0000000..af07448 --- /dev/null +++ b/.github/workflows/ci-browser.yaml @@ -0,0 +1,57 @@ +name: CI +on: + pull_request: + paths: + - packages/browser/** + - packages/core/** + paths-ignore: + - packages/**/.gitignore + - packages/**/README.md + push: + branches: + - main + paths: + - packages/browser/** + - packages/core/** + paths-ignore: + - packages/**/.gitignore + - packages/**/README.md +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Build package + run: bun --cwd packages/browser build + eslint: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Check code style + run: bun --cwd packages/browser eslint + prettier: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Check code style + run: bun --cwd packages/browser prettier + test: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Install playwright dependencies + uses: ./.github/actions/install-playwright-dependencies + - name: Run tests + run: bun --cwd packages/browser test diff --git a/.github/workflows/ci-core.yaml b/.github/workflows/ci-core.yaml new file mode 100644 index 0000000..13862b6 --- /dev/null +++ b/.github/workflows/ci-core.yaml @@ -0,0 +1,53 @@ +name: CI +on: + pull_request: + paths: + - packages/core/** + paths-ignore: + - packages/core/.gitignore + - packages/core/README.md + push: + branches: + - main + paths: + - packages/core/** + paths-ignore: + - packages/core/.gitignore + - packages/core/README.md +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Build package + run: bun --cwd packages/core build + eslint: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Check code style + run: bun --cwd packages/core eslint + prettier: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Check code style + run: bun --cwd packages/core prettier + test: + runs-on: ubuntu-latest + steps: + - name: Checkout commit + uses: actions/checkout@v3 + - name: Install dependencies + uses: ./.github/actions/install-dependencies + - name: Run tests + run: bun --cwd packages/core test diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml deleted file mode 100644 index 198a24b..0000000 --- a/.github/workflows/ci.yaml +++ /dev/null @@ -1,52 +0,0 @@ -name: CI -on: - pull_request: - paths-ignore: - - .gitignore - - .prettierignore - - LICENSE - - package.json - - README.md - push: - branches: - - main - paths-ignore: - - .gitignore - - .prettierignore - - LICENSE - - package.json - - README.md -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Checkout commit - uses: actions/checkout@v2 - - name: Install dependencies - uses: ./.github/actions/install-dependencies - - name: Build package - run: yarn build - check: - runs-on: ubuntu-latest - steps: - - name: Checkout commit - uses: actions/checkout@v2 - - name: Install dependencies - uses: ./.github/actions/install-dependencies - - name: Check code style - run: yarn code:check - test: - runs-on: ubuntu-latest - steps: - - name: Checkout commit - uses: actions/checkout@v2 - - name: Install dependencies - uses: ./.github/actions/install-dependencies - - name: Run tests - uses: ./.github/actions/jest - with: - aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} - aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - generate-artifacts: ${{ github.ref == 'refs/heads/main' }} - s3-bucket-name: blvd-corp-github-ci-artifacts - s3-object-path: ${{ github.repository }}/workflows/ci diff --git a/.gitignore b/.gitignore index 00543e5..e194fa6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -build -coverage +.DS_Store +.vscode node_modules \ No newline at end of file diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 5498e0f..0000000 --- a/.prettierignore +++ /dev/null @@ -1,2 +0,0 @@ -build -coverage diff --git a/.tool-versions b/.tool-versions index d00cddc..2263cc3 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,2 +1 @@ -nodejs 14.19.0 -yarn 1.22.5 +bun 1.0.17 diff --git a/LICENSE b/LICENSE index 367375b..85bf3e6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,201 @@ -MIT License - -Copyright (c) 2022 Boulevard - -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. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2023 Daniel Nagy + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md index 3ed3b6b..10120de 100644 --- a/README.md +++ b/README.md @@ -1,360 +1,59 @@ -# Transporter - -![](https://img.shields.io/endpoint?url=https%3A%2F%2Fblvd-corp-github-ci-artifacts.s3.amazonaws.com%2FBoulevard%2Ftransporter%2Fworkflows%2Fci%2Fcoverage-shield.json) - -Transporter is a framework for inter-process communication. The Transporter API was influenced by [comlink](https://github.com/GoogleChromeLabs/comlink), [OIS](https://en.wikipedia.org/wiki/OSI_protocols), [OpenRPC](https://github.com/open-rpc), and [rxjs](https://github.com/ReactiveX/rxjs). - -![image](https://user-images.githubusercontent.com/1622446/163908100-bb2f24e3-e393-43bf-a656-0e182da41a0e.png) - -#### Contents - -- [Introduction](#introduction) -- [Install](#install) -- [API](#api) - - [Functions](#functions) - - [Types](#types) -- [Memory Management](#memory-management) -- [Examples](#examples-2) +
+
+ +
+ Typesafe distributed computing in TypeScript. +
## Introduction -Transporter simplifies the implementation of inter-process communication. It provides structure on top of primitive message passing that improves semantics, maintenance, and productivity so you can focus on code and not on boilerplate. - -Let's look at an example. Suppose we have a worker that contains some reusable math functions and we want to use those math functions in our application. First let's look at the worker code. - -```typescript -import { createServer, createService } from "@boulevard/transporter"; -import { createSessionManager } from "@boulevard/transporter/worker"; - -const add = (...values) => values.reduce((sum, num) => sum + num, 0); - -const subtract = (value, ...values) => - values.reduce((diff, num) => diff - num, value); - -const math = createService({ add, subtract }); - -createServer({ - router: [{ path: "math", provide: math }], - scheme: "blvd", - sessionManagers: [createSessionManager()], -}); -``` - -Our worker creates a math service as well as a server that can accept incoming requests and route them to the math service. Next let's look at how our application uses this service. - -```typescript -import { createSession } from "@boulevard/transporter/worker"; - -const { link } = createSession(new Worker("math.js", { type: "module" })); -const { add, subtract } = link("blvd:math"); - -const main = async () => { - const sum = await add(1, 2); - const diff = await subtract(2, 1); -}; - -main(); -``` - -Our application establishes a connection to the worker and then links the math service using a URI. Notice when our application calls a function provided by the math service it must `await` the response. When we call a function provided by the math service that function will be evaluated inside the worker. If we want the return value of the function we must wait for the result to be returned from the worker thread. - -## Install - -Transporter is available from the npm registry. - -> Transporter is currently in beta. Expect breaking API changes. - -``` -npm add @boulevard/transporter -``` - -## API - -### Functions - -#### `createClient` +Transporter is an RPC library for typesafe distributed computing. The Transporter API was influenced by [comlink](https://github.com/GoogleChromeLabs/comlink) and [rxjs](https://github.com/ReactiveX/rxjs). -```typescript -function createClient(from: { port: SessionPort; timeout?: number }): Client; -``` - -Creates a client that is able to link to services. - -> You know my fourth rule? Never make a promise you can't keep. โ€” Frank - -Whenever a response is required Transporter will send a message to the server to validate the connection. The server must respond within the timeout limit. This validation is independent of the time it takes to fulfill the request. Once the connection is validated there is no time limit to fulfill the request. - -#### `createServer` - -```typescript -function createServer(from: { - router: Router; - scheme: string; - sessionManagers: [SessionManager, ...SessionManager[]]; - timeout?: number; -}): Server; -``` - -Creates a server that can manage client sessions and route incoming requests to the correct service. Transporter is connection-oriented and transport agnostic. However, a duplex transport is required to support observables and callback arguments. - -The scheme is similar to custom URL schemes on iOS and Android. The scheme acts as a namespace. It is used to disambiguate multiple servers running on the same host. - -#### `createService` - -```typescript -function createService(provide: T): Service; -``` - -Creates a service. Services may provide functions or observables. Functions act as a pull mechanism and observables act as a push mechanism. If a service provides a value that is not an observable it will be wrapped in an observable that emits the value and then completes. - -##### Examples +Message passing can quickly grow in complexity, cause race conditions, and make apps difficult to maintain. Transporter eliminates the cognitive overhead associated with message passing by enabling the use of functions as a means of communication between distributed systems. -```typescript -const list = createService({ concat: (left, right) => [...left, ...right] }); -const string = createService({ concat: (left, right) => `${left}${right}` }); +### Features -createServer({ - router: [ - { path: "list", provide: list }, - { path: "string", provide: string }, - ], - scheme: "blvd", - sessionManagers: [createSessionManager()], -}); -``` +- ๐Ÿ‘Œ Typesaftey without code generation.[^1] +- ๐Ÿ˜ Support for generic functions. +- ๐Ÿคฉ The core API works in any JavaScript runtime.[^2][^3] +- ๐Ÿ˜Ž Easily integrates into your existing codebase. +- ๐Ÿ‘ No schema builders required, though you may still use them. +- ๐Ÿฅน Dependency injection. +- ๐Ÿซถ FP friendly. +- ๐Ÿค˜ Memoization of remote functions. +- ๐Ÿซก Small footprint with 0 dependencies. +- ๐Ÿš€ Configurable subprotocols. +- ๐Ÿšฐ Flow control and protocol stacking using Observables. +- ๐Ÿคฏ Recursive RPC for select subprotocols. +- ๐ŸŒถ๏ธ PubSub using Observables for select subprotocols. +- ๐Ÿ‘ Resource management. +- ๐Ÿฅณ No globals.[^4] +- ๐Ÿงช Easy to test. -Pub/Sub communication is possible using observables. +[^1]: Transporter is tested using the latest version of TypeScript with strict typechecking enabled. +[^2]: Transporter works in Node, Bun, Deno, Chrome, Safari, Firefox, Edge, and React Native. +[^3]: Hermes, a popular JavaScript runtime for React Native apps, does not support `FinalizationRegistry`. It also requires a polyfill for `crypto.randomUUID`. +[^4]: Transporter has a global `AddressBook` that is used to ensure every server has a unique address. -```typescript -const darkMode = new BehaviorSubject(false); -createService({ darkMode: darkMode.asObservable() }); -darkMode.next(true); -``` +### Practical Usage -The client can get the value of an observable imperatively using the `firstValueFrom` function exported by Transporter. It is advised to only use `firstValueFrom` if you know the observable will emit a value, otherwise your program may hang indefinitely. +Transporter may be used to build typesafe APIs for fullstack TypeScript applications. -```typescript -const { definitelyEmits } = session.link("org:example"); -const value = await firstValueFrom(definitelyEmits); -``` +Transporter may be used in the browser to communicate with other browsing contexts (windows, tabs, iframes) or workers (dedicated workers, shared workers, service workers). The browser is ripe for distributed computing and parallel processing but not many developers take advantage of this because the `postMessage` API is very primitive. -The client can subscribe to an observable to receive new values overtime. +Transporter may also be used in React Native apps to communicate with webviews. You could take this to the extreme and build your entire native app as a Web app that is wrapped in a React Native shell. The Web app could use Transporter to call out to the React Native app to access native APIs not available in the browser. -```typescript -const { darkMode } = session.link("org:client/preferences"); -darkMode.subscribe(onDarkModeChange); -``` +## Getting Started -### Types +To get started using Transporter install the package from the npm registry using your preferred package manager. -#### `Client` - -```typescript -type Client = { - link(uri: string): RemoteService; -}; ``` - -A client is connected to a host. A client is able to link to services provided by a server running on the host. - -##### Example - -```typescript -import { createSession as createBrowserSession } from "@boulevard/transporter/browser"; -import { createSession as createWorkerSession } from "@boulevard/transporter/worker"; - -const browserSession = createBrowserSession({ - origin: "https://trusted.com", - window: self.parent, -}); - -const workerSession = createWorkerSession(new Worker("crypto.0beec7b.js")); - -type Auth = { - login(userName: string, password: string): { apiToken: string }; -}; - -type Crypto = { - encrypt(value: string): string; -}; - -const auth = browserSession.link("blvd:auth"); -const crypto = workerSession.link("blvd:crypto"); - -const { apiToken } = await auth.login("chow", await crypto.encrypt("bologna1")); +bun add @daniel-nagy/transporter ``` -#### `RemoteService` +As of beta 3 Transporter is nearing API stability but there may still be some breaking changes to the API. For API docs see the README for each package. -```typescript -type RemoteService = { - [name: string]: ObservableLike | TransportedFunction; -}; -``` - -A remote service is a group of remote functions or observables. It is a service but from a client's perspective. While a remote service looks like an object it does not have an object's prototype. You can think of it as an object with a `null` prototype. Notably the remote service's properties are not iterable. - -#### `Router` - -```typescript -type Router = { path: string; provide: Service }[]; -``` - -A router is a data structure for mapping paths to services. - -#### `Server` - -```typescript -export type Server = { - stop(): void; -}; -``` - -A server is able to accept connections from clients and route incoming requests to the correct service. - -#### `Service` - -```typescript -export type Service = { - [name: string]: ObservableLike | TransportableFunction; -}; -``` - -A service is a group of functions or observables. A service can be thought of as a secondary router. - -#### `SessionManager` - -```typescript -export type SessionManager = { - connect: ObservableLike; -}; -``` - -A session manager is the glue between a server and a client. It is responsible for monitoring incoming requests and creating a connection between the server and the client. - -A session manager sits between the server and the transport layer. Transporter provides session managers for browser windows, Web workers, React Native, and React Native Webviews. However, it is possible to create your own session managers. This allows Transporter to be agnostic of the transport layer. Keep in mind that callback arguments and observables do require a duplex transport layer though. - -##### Example - -```typescript -createServer({ - ..., - sessionManagers: [ - createBrowserSessionManager(), - createWebViewSessionManager() - ] -}); -``` - -The session manager factory functions provided by Transporter allow you to intercept the connection before it is created. This enables proxying the session port or rejecting the connection. To prevent the connection from being created return `null` from the `connect` function. - -```typescript -createBrowserSessionManager({ - ..., - connect({ delegate, origin }) { - return new URL(origin).hostname.endsWith("trusted.com") ? delegate() : null; - } -}); -``` - -#### `SessionPort` - -```typescript -type SessionPort = { - receive: ObservableLike; - send(message: string): void; -}; -``` - -A session port represents a connection between a server and a client. - -#### `Transportable` - -```typescript -type Transportable = - | boolean - | null - | number - | string - | undefined - | Transportable[] - | { [key: string]: Transportable } - | (...args: Transported[]) => (Transportable | Promise); -``` - -A transportable value may be transported between processes. If the value is serializable it will be cloned. If it is not serializable it will be proxied. If the return value of a function is a promise then the response will be sent once the promise settles. - -## Memory Management - -If a value cannot be serialized, such as a function, the value is proxied. However, if the proxy is garbage collected this would continue to hold a strong reference to the value, thus creating a memory leak. Transporter uses `FinalizationRegistry` to receive a notification when a proxy is garbage collected. When a proxy is garbage collected a message is sent to release the value, allowing it to be garbage collected as well. - -## Examples - -### Composing React Apps - -Transporter can be used to easily compose React applications in iframes or React Native Webviews. Here is an example app that has a reusable `` component that renders a React app that provides an app service with a `render` method inside an iframe. - -```tsx -import { createSession } from "@boulevard/transporter/browser"; -import { useEffect, useState } from "react"; -import { createRoot } from "react-dom/client"; - -const MicroApp = ({ src, uri, ...props }: MicroApp.Props) => { - const [app, setApp] = useState(null); - - const onLoad = ({ currentTarget: frame }) => - setApp(() => createSession(frame.contentWindow).link(uri)); - - useEffect(() => { - app?.render(props); - }); - - return