import { Connector } from '@toa.io/core' import { underlay } from '@toa.io/generic' import * as shortcuts from './shortcuts/index.js' export class Context extends Connector { env name region instance aspects operation #context #source constructor(context, operation) { super() this.operation = operation this.env = context.env this.name = context.name this.region = context.region this.instance = context.instance this.#context = context this.#source = source(context.locator, operation) this.depends(context) } async open() { this.aspects = this.#aspects(this.#context.aspects) } /** a new id, made as an entity's is */ id = () => this.#context.newid() /** milliseconds since the epoch */ now = () => this.#context.now() /** a number in `[0, 1)` */ random = () => this.#context.random() local = underlay(async ([endpoint], [request, options]) => { return this.#context.apply(endpoint, this.#attribute(request), options) }) remote = underlay(async (segments, [request, options]) => { if (segments.length === 2) segments.unshift('default') // default namespace const [namespace, name, endpoint] = segments return this.#context.call( namespace, name, endpoint, this.#attribute(request), options ) }) /** * Stamps the origin of the call, unless the caller has set one explicitly. */ #attribute(request) { if (this.#source === undefined) return request request ??= {} request.source ??= this.#source return request } #aspects(aspects) { const map = {} for (const aspect of aspects) { if (map[aspect.name] !== undefined) throw new Error(`Aspect conflict on '${aspect.name}'`) map[aspect.name] = aspect.invoke.bind(aspect) if (aspect.name in shortcuts) // the aspect names the shortcut // oxlint-disable-next-line import/namespace shortcuts[aspect.name](this, aspect) } return map } } /** * Events, guards and rc phases get a Context without an operation, * thus their calls are not attributed. */ function source(locator, operation) { if (locator === undefined || operation === undefined) return undefined return { namespace: locator.namespace, component: locator.name, operation } }