Comctx
Introduction

Getting Started

Build your first Comctx connection with the core Comctx quick start flow.

This page follows the core Comctx quick start flow.

Installation

Install comctx in your project:

pnpm install comctx
npm install comctx
yarn add comctx
bun add comctx

Define the shared service

shared.ts
import { defineProxy } from 'comctx'

class Counter {
  public value: number

  constructor(initialValue: number = 0) {
    this.value = initialValue
  }

  async getValue() {
    return this.value
  }

  async onChange(callback: (value: number) => void) {
    let oldValue = this.value
    setInterval(() => {
      const newValue = this.value
      if (oldValue !== newValue) {
        callback(newValue)
        oldValue = newValue
      }
    })
  }

  async increment() {
    return ++this.value
  }

  async decrement() {
    return --this.value
  }
}

export const [provideCounter, injectCounter] = defineProxy(() => new Counter(), {
  namespace: '__comctx-example__'
})

Define the adapter

adapter.ts
import type { Adapter, SendMessage, OnMessage } from 'comctx'

export default class CustomAdapter implements Adapter {
  // Implement message sending
  sendMessage: SendMessage = (message) => {
    postMessage(message)
  }

  // Implement message listener
  onMessage: OnMessage = (callback) => {
    const handler = (event: MessageEvent) => callback(event.data)
    addEventListener('message', handler)
    return () => removeEventListener('message', handler)
  }
}

Create the Provider

provider.ts
import CustomAdapter from 'CustomAdapter'
import { provideCounter } from './shared'

const originCounter = provideCounter(new CustomAdapter())

originCounter.onChange(console.log)

originCounter directly references the real Counter instance.

Create the Injector

injector.ts
import CustomAdapter from 'CustomAdapter'
import { injectCounter } from './shared'

const proxyCounter = injectCounter(new CustomAdapter())

// Support for callbacks
proxyCounter.onChange(console.log)

// Transparently call remote methods
await proxyCounter.increment()
const count = await proxyCounter.getValue()

proxyCounter is a virtual proxy that forwards requests to the Counter on the Provider side.

Important notes

  • originCounter and proxyCounter share the same Counter instance.
  • The Injector side cannot directly use get and set; it must interact with Counter via asynchronous methods.
  • Callbacks are supported.
  • To support operations like Reflect.has(proxyCounter, 'key'), you can set backup to true.
  • provideCounter and injectCounter require user-defined adapters for different environments that implement onMessage and sendMessage.

Next steps

On this page