@pritzlaff/nano-core 0.2.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,34 +1,12 @@
1
1
  # @pritzlaff/nano-core
2
2
 
3
- Lift ordinary code into named coordinates that can be called, published from, subscribed to and observed.
3
+ The nano model: schemas, ops, interfaces, results, implementations, providers, the registry, pods, runtimes,
4
+ deployments (checked values) and the one live `Application`. The map is [design.md](../../design.md).
4
5
 
5
- | File | Purpose |
6
- |---|---|
7
- | `src/data.ts` | Names and plain data: `Op`, `Coord`, `Result`, `Event`, `Subscription`, `Delta`. |
8
- | `src/component.ts` | Wraps plain code: how to make a value, and the actions over it. |
9
- | `src/env.ts` | An instance's view of the registries it is in: one handle each, and its own ops. |
10
- | `src/registry.ts` | One place holding instances and subscriptions; reports every change as a `Delta`. |
11
- | `src/runtime.ts` | Calls and publishes by name over one registry; wrap it with a `Policy` to change the rules. |
12
-
13
- ## A counter
6
+ 0.4.0 replaces the 0.3 model. Components, runes and the old registry are gone; see the
7
+ [model spec](../../docs/superpowers/specs/2026-11-14-pods-runtimes-application-design.md).
14
8
 
15
9
  ```ts
16
- let counter = 0
17
- const increment = () => { counter = counter + 1 }
18
-
19
- const Updated = Ops.source('com.acme', 'counter-updated', Type.Number())
20
- const Inc = Ops.sink('com.acme', 'inc', Type.Null())
21
-
22
- const Counter = Components.create({ ns: 'com.acme', name: 'counter' }, () => ({ get: () => counter, increment }))
23
- Counter.action(Updated, c => c.get()) // a source's action reads the current value
24
- Counter.action(Inc, c => { c.increment() }, { emits: [Updated] }) // after inc, publish what Updated reads
25
-
26
- const rt = Runtimes.create(Registries.create('r'))
27
- rt.registry.add('counter', Components.instantiate(Counter))
28
- await rt.call({ registry: 'r', instance: 'me' }, 'counter', Ops.key(Inc), null)
10
+ import { AppDeployment, Registry } from '@pritzlaff/nano-core'
11
+ AppDeployment.assemble({ pods: {}, runtimes: {} }, Registry.create()) // success({})
29
12
  ```
30
-
31
- The registry is in itself as the instance `registry`. Its changes (`instance-added`, `op-added`,
32
- `subscription-opened`, …) are events from it, so watching a registry is subscribing to it, and changing one
33
- is calling it. `test/examples.test.ts` walks through watching, subscribing at runtime, one instance in two
34
- registries, a "subscribe only yourself" policy, and adding ops at runtime.
@@ -0,0 +1,7 @@
1
+ import type { AppDeployment } from '../deployment.js';
2
+ export declare function diff(a: AppDeployment, b: AppDeployment): {
3
+ added: string[];
4
+ removed: string[];
5
+ changed: string[];
6
+ rewired: string[];
7
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Runtimes composed into the application's deployment: the pods they place, described by their one `Pods` and in its
3
+ * order, the runtimes' placing and wiring in the order given, and the tags their scopes carry. A pod in no runtime
4
+ * is not in it, nor are its tags. Each runtime was checked by `Runtime.create`; this checks only what the application owns,
5
+ * and that no runtime has both a code policy (in `policies`) and a `policy` in its deployment.
6
+ *
7
+ * compose({ chat, support }) // success({ deployment: { pods, runtimes, tags? }, registry }), or invalid-input naming the offender
8
+ */
9
+ import { type AppDeployment } from '../deployment.js';
10
+ import type { Policy } from '../policy.js';
11
+ import type { Registry } from '../registry.js';
12
+ import { type NanoResult } from '../result.js';
13
+ /** Never throws; `registry` is that of the runtimes' `Pods`, absent when there are no runtimes. */
14
+ export declare function compose(runtimes: unknown, policies?: Record<string, Policy>): NanoResult<{
15
+ deployment: AppDeployment;
16
+ registry?: Registry;
17
+ }>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Subscribing is a message. `connect` sends `subscribe` from the On's owner (`to`: a pod or 'host') to its source pod
3
+ * in its runtime: `delivered` once live, or `denied` when the runtime's policy refuses (then nothing is added). The
4
+ * On's `end`, which every way an On ends goes through, sends `unsubscribe` (caused by the subscribe): `delivered` with
5
+ * `success` when stopped, or with the `Fail` that ended it (the policy refusing it on apply).
6
+ *
7
+ * const c = connect(live, { runtime, from: 'store', port, to: 'host', gone, fn }, fail => …) // c.ok: c.value is the live On
8
+ */
9
+ import { type Fail, type NanoResult } from '../result.js';
10
+ import { type Live, type On } from './messages.js';
11
+ export declare function connect(live: Live, w: Omit<On, 'end'>, ended?: (fail?: Fail) => void): NanoResult<On>;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The context a pod's factory gets, for pod `name`: it reads the deployment as it is at each call, over the call
3
+ * subscriptions from `name` in every runtime that lists one (placed there or not), each a `Selection`. `onClose` adds a listener to the
4
+ * build this context belongs to; the `on` subscriptions this build made are dropped through it. With `invoked` it is a
5
+ * handler invocation's: `callingOp` is its port, and its calls and publishes continue that message's chain
6
+ * (`correlation`, `cause` = its id); `on` and listeners stay the build's.
7
+ *
8
+ * const ctx = contextFor(live, 'send', fn => …)
9
+ * ctx.one(KV) // success(the one KV wired from send, in whichever runtime), or not-found / not-unique
10
+ * kv.call.put('k'); kv.on(KV.ops.put, fn) // sent in that runtime; hear its put calls ({ input, output }) there until this build closes
11
+ * await ctx.publish(tick, 1) // emitted: one message per pipe from send with that source, and to `on` subscribers
12
+ */
13
+ import type { NanoContext } from '../context.js';
14
+ import { type Live } from './messages.js';
15
+ export declare function contextFor(live: Live, name: string, onClose: NanoContext['addOnCloseListener'], invoked?: {
16
+ id: string;
17
+ correlation: string;
18
+ port: string;
19
+ }): Omit<NanoContext, 'deps'>;
@@ -0,0 +1,19 @@
1
+ import { type NanoResult } from '../result.js';
2
+ import { type Live, type On } from './messages.js';
3
+ type Chain = {
4
+ id?: string;
5
+ correlation?: string;
6
+ cause?: string;
7
+ };
8
+ /**
9
+ * `from`'s emission at port `port`. With no `chain` (a published event) it starts one: the first delivery's id is the
10
+ * correlation of every delivery, none with a cause. An action's emission (`travelled`: the runtime its call went in)
11
+ * reaches only the `On`s in that runtime. Resolves once the pipe deliveries settle, not the `on` ones.
12
+ */
13
+ export declare function emit(live: Live, from: string, port: string, e: Parameters<On['fn']>[0], chain?: Chain, travelled?: string): Promise<unknown>;
14
+ /**
15
+ * A client by op name from `from` to `to` in `runtime`. `gone()` is asked at each call, before anything is sent: a
16
+ * Fail it gives is the call's result. With `chain` each call continues it (its `correlation`, `cause`).
17
+ */
18
+ export declare function client(live: Live, runtime: string, from: string, to: string, gone: () => NanoResult<never> | undefined, chain?: Chain): Record<string, (input: unknown) => Promise<NanoResult<unknown>>>;
19
+ export {};
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The Application: the one live thing. It is created from runtimes (values), builds eager pods at once and lazy ones
3
+ * on first need, carries every message through the runtime it travels in, and reports all of it on one stream.
4
+ *
5
+ * const app = (await Application.create(AppDeployment.assemble(appDeployment, registry).value, {})).value
6
+ * const front = app.runtime('front') // the host as a member of runtime 'front': what it places, policed by its policy
7
+ * await front.call('counter').inc(null) // from 'host', through runtime 'front' (app.call('front', 'counter') too)
8
+ * await front.get(Counter).inc() // the one pod there providing Counter, as a plain object; a Fail throws
9
+ * app.resolve(Counter) // app.runtime(the one runtime).resolve(Counter); several: not-unique
10
+ * const app = await Application.load(new URL('./nano.json', import.meta.url)) // modules loaded, assembled, created
11
+ * app.listen(e => …) // built, sent, delivered, denied, failure, …
12
+ * await app.close() // every instance closed, deliveries under way settled; later calls not-found
13
+ */
14
+ import { AppDeployment } from '../deployment.js';
15
+ import type { Implementation } from '../implementation.js';
16
+ import type { Pod } from '../pod.js';
17
+ import type { Policy } from '../policy.js';
18
+ import { type DeploymentPolicy } from '../deployment-policy.js';
19
+ import { type NanoResult } from '../result.js';
20
+ import type { Runtime } from '../runtime.js';
21
+ import { type RuntimeView } from './resolve.js';
22
+ import { type AppEvent } from './stream.js';
23
+ export type { AppEvent } from './stream.js';
24
+ export type { Resolution } from './resolve.js';
25
+ export type { PodStatus } from './instances.js';
26
+ export { lookup, type Lookup } from './lookup.js';
27
+ export type Application = {
28
+ /** The runtime `id` as the host sees it; `resolve`, `get`, `call` and `subscribe` below are those of the one runtime (else `not-unique`). */
29
+ runtime(id: string): RuntimeView;
30
+ /** `app.call(pod)`; `app.call(runtime, pod)` is `app.runtime(runtime).call(pod)`. */
31
+ call(...at: [pod: string] | [runtime: string, pod: string]): ReturnType<RuntimeView['call']>;
32
+ get: RuntimeView['get'];
33
+ resolve: RuntimeView['resolve'];
34
+ subscribe: RuntimeView['subscribe'];
35
+ /** `caller` (default `'host'`) is asked of the deployment policy and recorded on `applied`. */
36
+ apply(next: AppDeployment, opts?: {
37
+ caller?: string;
38
+ }): Promise<NanoResult<void>>;
39
+ restart(pod: string): Promise<NanoResult<void>>;
40
+ deployment(): AppDeployment;
41
+ listen(fn: (e: AppEvent) => void): () => void;
42
+ close(): Promise<NanoResult<void>>;
43
+ };
44
+ /** `isolate` gives the host's stand-in for a pod whose isolation isn't 'host' (same coord); without it such a pod fails. */
45
+ type Opts = {
46
+ policies?: Record<string, Policy>;
47
+ deploymentPolicy?: DeploymentPolicy;
48
+ timeoutMs?: number;
49
+ isolate?: (name: string, pod: Pod) => Implementation;
50
+ };
51
+ /**
52
+ * `runtimes` live. The application's deployment is its own: nobody else holds it, so only `apply` changes it; and its
53
+ * maps have no prototype, so a pod or runtime named `constructor` or `toString` is only ever a name.
54
+ */
55
+ declare function create(runtimes: Record<string, Runtime>, opts?: Opts): Promise<NanoResult<Application>>;
56
+ /** `create` from a nano.json: its `modules` loaded, assembled and created; the first failure throws an Error carrying it. */
57
+ declare function load(url: string | URL, opts?: Opts): Promise<Application>;
58
+ export declare const Application: {
59
+ create: typeof create;
60
+ load: typeof load;
61
+ };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Instances: at most one build per pod name, shared by everyone who needs it meanwhile. Each build has its own close
3
+ * listeners. A failed build closes (`closed`) and caches nothing, so the next need builds again; forgetting drops the
4
+ * entry and closes that build at once, even one still under way (a listener it adds later runs as it is added), without
5
+ * waiting for or touching calls already handed it. A pod being closed is built again only once its close has settled,
6
+ * and a build forgotten meanwhile never starts. `close` also waits for builds under way, which then build nothing.
7
+ *
8
+ * const pods = instances(live)
9
+ * await pods.get('db') // NanoResult<{ implementation, handlers by port }>: built now, or the build already made or under way
10
+ * await pods.forget('db', 'restarted') // its listeners have run; the next get builds a fresh closure; calls in flight keep the old one
11
+ * await pods.close() // every build closed (`closed`); every later get is not-found
12
+ * pods.status('db') // 'running', 'not started', 'stopped' or 'failed'
13
+ */
14
+ import type { NanoContext } from '../context.js';
15
+ import { type Live } from './messages.js';
16
+ type Made = ReturnType<Live['instance']>;
17
+ type OnClose = Parameters<NanoContext['addOnCloseListener']>[0];
18
+ type Reason = Parameters<OnClose>[0]['reason'];
19
+ /** A placed pod's lifecycle now: built, never built (or forgotten since), closed with the application, or its last build failed. */
20
+ export type PodStatus = 'running' | 'not started' | 'stopped' | 'failed';
21
+ export declare function instances(live: Live): {
22
+ get(name: string): Made;
23
+ forget: (name: string, why: Reason) => Promise<void>;
24
+ status: (name: string) => PodStatus;
25
+ close(): Promise<void>;
26
+ };
27
+ export {};
@@ -0,0 +1,18 @@
1
+ import type { Fail } from '../result.js';
2
+ /**
3
+ * The AsyncIterable form of a subscription (`on(op)`, `subscribe(op)` with no callback). Its behaviour, as a caller sees it:
4
+ * - **It connects when it is made**, exactly like the callback form: it hears every emission from that line on, and a
5
+ * refusal or a missing source throws there (from `listen`), not at the loop.
6
+ * - **It is iterated once.** A second `for await` over the same iterable throws; subscribe again for another.
7
+ * - **It ends in one of two ways.** `done` when it simply stops (the loop's `break`, the build or the application
8
+ * closing, `apply` removing its source); or, after yielding what it had already received, by throwing an `Error`
9
+ * carrying the `Fail` that ended it (a policy refusing it on a later `apply`).
10
+ * - **It never ends by itself while nobody iterates it**: an iterable made and not looped over keeps its listener
11
+ * until it is ended as above.
12
+ *
13
+ * `ended(stop)` hands over the way nano ends it (before connecting, so a listener dropped at once still ends);
14
+ * `listen(fn)` connects and gives the unsubscribe that `break` calls.
15
+ *
16
+ * for await (const e of iterate(fn => on(op, fn), stop => …)) … // values pushed by `fn`, in order, until ended
17
+ */
18
+ export declare function iterate<T>(listen: (fn: (v: T) => void) => () => void, ended: (stop: (fail?: Fail) => void) => void): AsyncIterable<T>;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `runtimeView.listen`: the one stream (`trace`) filtered to runtime `runtime`: its `sent` messages and their
3
+ * `delivered`/`denied`, `applied` narrowed to the pods placed there (now or before), and the lifecycle of those pods, even as `apply` removes
4
+ * them. Warnings are the operator's: `app.listen` only. A subscribe is a message too, so a refused one shows here.
5
+ *
6
+ * const off = listen(live, 'front', e => …) // nothing from another runtime
7
+ */
8
+ import type { Live } from './messages.js';
9
+ import type { AppEvent } from './stream.js';
10
+ export declare function listen(live: Live, runtime: string, fn: (e: AppEvent) => void): () => void;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What `Application.load(url)` reads: a `nano.json` and the providers its `modules` name (each a module whose default
3
+ * export is a `Provider`, imported relative to the nano.json), as a registry. The first failure is the result.
4
+ * The document's shape is checked before anything is imported. `modules` URLs are code that will run: load only
5
+ * trusted documents.
6
+ *
7
+ * const r = await loaded(new URL('./nano.json', import.meta.url)) // success({ deployment, registry })
8
+ */
9
+ import { AppDeployment } from '../deployment.js';
10
+ import { Registry } from '../registry.js';
11
+ import { type NanoResult } from '../result.js';
12
+ export declare function loaded(url: string | URL): Promise<NanoResult<{
13
+ deployment: AppDeployment;
14
+ registry: Registry;
15
+ }>>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * What a message needs to know about a deployment, found once per deployment object rather than scanned per message:
3
+ * where each pod is placed, the call edges and pipes from each pod, and each runtime's compiled policy. `apply` makes a
4
+ * new deployment object, so the cache follows it. It caches by object identity: treat `d` as immutable once looked up.
5
+ *
6
+ * lookup(d).placed.get('backend')?.has('store') // placed there?
7
+ * lookup(d).pipes.get(`${pod} ${port}`) // the pipes carrying that emission, runtimes then subscriptions in order
8
+ */
9
+ import type { AppDeployment } from '../deployment.js';
10
+ import { type Policy } from '../policy.js';
11
+ type Pipe = {
12
+ runtime: string;
13
+ to: string;
14
+ target: string;
15
+ };
16
+ export type Lookup = {
17
+ /** Pods placed in each runtime. */
18
+ placed: ReadonlyMap<string, ReadonlySet<string>>;
19
+ /** For each pod, the runtimes it is placed in, in order. */
20
+ placedIn: ReadonlyMap<string, readonly string[]>;
21
+ /** For each pod, its call edges (wherever listed): runtimes in order, then subscriptions in order. */
22
+ callsFrom: ReadonlyMap<string, readonly {
23
+ runtime: string;
24
+ to: string;
25
+ }[]>;
26
+ /** `${runtime} ${from} ${to}` for each call edge. */
27
+ calls: ReadonlySet<string>;
28
+ /** For `${from} ${port}`, its pipes. */
29
+ pipes: ReadonlyMap<string, readonly Pipe[]>;
30
+ /** Each runtime's policy from the deployment (`allow-all` when it has none). */
31
+ policy(runtime: string): Policy;
32
+ };
33
+ export declare function lookup(d: AppDeployment): Lookup;
34
+ export {};
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Messages: one message in one runtime — `sent` (with its kind and chain), policed, its input checked, the target built
3
+ * or reused, run with the timeout, its output checked, then `delivered` (or `denied`). What follows from a message
4
+ * (emissions) is `emit.ts`'s.
5
+ *
6
+ * await send(live, 'r', 'host', 'db', 'acme.KV/get', 'k') // NanoResult<unknown>; a call starting a chain
7
+ * await attempt(live, 'db', 'closing db', fn) // fn within the timeout; a throw or timeout a `failure`
8
+ */
9
+ import type { AppDeployment } from '../deployment.js';
10
+ import type { Handler, Implementation } from '../implementation.js';
11
+ import type { Pod } from '../pod.js';
12
+ import type { Ask, Policy } from '../policy.js';
13
+ import type { Registry } from '../registry.js';
14
+ import type { NanoContext } from '../context.js';
15
+ import { type Fail, type NanoResult } from '../result.js';
16
+ import type { stream } from './stream.js';
17
+ /** What a message needs of the application, read live. */
18
+ export type Live = {
19
+ now(): AppDeployment;
20
+ readonly registry: Registry;
21
+ readonly policies: Record<string, Policy>;
22
+ readonly timeoutMs: number;
23
+ readonly trace: ReturnType<typeof stream>;
24
+ /** A build: the handlers by port, the implementation they were made from, and its `addOnCloseListener`. */
25
+ instance(pod: string): Promise<NanoResult<{
26
+ implementation: Implementation;
27
+ handlers: ReadonlyMap<string, Handler>;
28
+ onClose: NanoContext['addOnCloseListener'];
29
+ }>>;
30
+ /** The live listeners, in the order made: `on` subscriptions (a pod's, or the host's; `heard` the same by `${from} ${port}`, what `emit` reads) and pod-change listeners (`ctx.addOnPodChangeListener`). */
31
+ readonly listeners: {
32
+ ons: Set<On>;
33
+ heard: Map<string, Set<On>>;
34
+ podChanges: Set<{
35
+ pod: string;
36
+ fn: Parameters<NanoContext['addOnPodChangeListener']>[0];
37
+ }>;
38
+ };
39
+ /** Deliveries under way, so `close()` can let them settle. */
40
+ readonly flying: Set<Promise<unknown>>;
41
+ /** Whether `close()` has been called: nothing new is delivered. */
42
+ closed(): boolean;
43
+ /** The host's stand-in implementation for a pod whose isolation isn't 'host'. */
44
+ readonly isolate?: (name: string, pod: Pod) => Implementation;
45
+ };
46
+ /** A subscription made in code: `to` (a pod, or 'host') hears pod `from`'s port `port` in `runtime`, while `gone()` gives nothing. `end(fail?)` ends it: sends `unsubscribe` and ends its iteration (`connection.ts`). */
47
+ export type On = {
48
+ runtime: string;
49
+ from: string;
50
+ port: string;
51
+ to: string;
52
+ gone(): unknown;
53
+ fn(e: {
54
+ input?: unknown;
55
+ output: unknown;
56
+ }): unknown;
57
+ end(fail?: Fail): void;
58
+ };
59
+ /** A message's kind, its chain (`correlation`, `cause`), its id if already taken, and its `work` if not an action. */
60
+ type How = {
61
+ kind: 'call' | 'pipe' | 'on';
62
+ id?: string;
63
+ correlation?: string;
64
+ cause?: string;
65
+ work?: () => Promise<NanoResult<unknown>>;
66
+ };
67
+ /** `work()` within `ms`: its value, or `threw` / `timeout` naming `what`. Never throws. */
68
+ export declare function within<T>(work: () => T | Promise<T>, ms: number, what: string): Promise<NanoResult<T>>;
69
+ /** `work()` within the timeout, as `pod`'s: a throw or a timeout is also a `failure` on the stream. */
70
+ export declare function attempt<T>(live: Live, pod: string, what: string, work: () => T | Promise<T>): Promise<NanoResult<T>>;
71
+ /** The implementation of `pod` in the deployment now, if it has one. */
72
+ export declare const impl: (live: Live, pod: string) => Implementation | undefined;
73
+ /** Every runtime `pod` is placed in, as [id, runtime deployment], in order. */
74
+ export declare const placedIn: (live: Live, pod: string) => (readonly [string, import("../runtime.js").RuntimeDeployment])[];
75
+ /** Why the policy of `ask.runtime` in `d` (the deployment now, or the one `apply` brings) refuses `ask`, or undefined. A throw, a Promise or no verdict refuses. */
76
+ export declare function refusal(live: Live, ask: Omit<Ask, 'outside'>, d?: AppDeployment): string | undefined;
77
+ /**
78
+ * One message from `from` to `to`'s port `p`, in runtime `runtime`: `sent` (as `how.id`, or a new id), policed by
79
+ * `refusal`, carried by `how.work` (by default the action at `p`), then `delivered`. With no `correlation` it starts a
80
+ * chain. It sends exactly this one message.
81
+ */
82
+ export declare function send(live: Live, runtime: string, from: string, to: string, p: string, input: unknown, how?: How): Promise<NanoResult<unknown>>;
83
+ export {};
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Pod changes: after an apply, each pod listening (`ctx.addOnPodChangeListener`) hears the other pods added to or
3
+ * removed from the runtimes it is placed in, if that runtime's policy allows `'lifecycle'`.
4
+ *
5
+ * await notifyPodChanges(live, before) // `before`: the deployment the apply replaced; `live.now()` is the new one
6
+ */
7
+ import type { AppDeployment } from '../deployment.js';
8
+ import { type Live } from './messages.js';
9
+ export declare function notifyPodChanges(live: Live, before: AppDeployment): Promise<void>;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * A runtime as the host sees it (`app.runtime(id)`): only the pods placed there, every message
3
+ * policed by its policy. `resolve(api, where?)` answers the one pod providing `api` there, narrowed by `where.pod`, with
4
+ * the implementation found and the plain object over it; or why not (`not-found`, `not-unique`). A call the policy refuses is `denied` at the call.
5
+ *
6
+ * const r = app.runtime('frontend').resolve(TodoList) // r.ok: r.pod, r.runtime, r.implementation, r.value; else r.reason
7
+ * const todos = r.getOrThrow() // the plain object, or an Error carrying r.fail
8
+ */
9
+ import type { Static, TSchema } from 'typebox';
10
+ import { type Interface } from '../iface.js';
11
+ import type { Op } from '../op.js';
12
+ import { type Fail, type NanoResult } from '../result.js';
13
+ import type { AppEvent } from './stream.js';
14
+ import { type Live } from './messages.js';
15
+ import type { PodStatus } from './instances.js';
16
+ type Reason = 'not-found' | 'not-unique' | 'denied';
17
+ export type Resolution<T> = {
18
+ readonly ok: true;
19
+ readonly runtime: string;
20
+ readonly pod: string;
21
+ readonly implementation: string;
22
+ readonly value: T;
23
+ getOrThrow(): T;
24
+ } | {
25
+ readonly ok: false;
26
+ readonly reason: Reason;
27
+ readonly fail: Fail;
28
+ getOrThrow(): never;
29
+ };
30
+ /** A success, or a Fail whose type is one of the resolution reasons. */
31
+ type Found<T> = {
32
+ ok: true;
33
+ value: T;
34
+ } | {
35
+ ok: false;
36
+ fail: Fail & {
37
+ type: Reason;
38
+ };
39
+ };
40
+ type Where = {
41
+ pod?: string;
42
+ };
43
+ type Placed = {
44
+ pod: string;
45
+ runtime: string;
46
+ implementation: string;
47
+ };
48
+ type Client = Record<string, (input: unknown) => Promise<NanoResult<unknown>>>;
49
+ /** A runtime as the host sees it. */
50
+ export type RuntimeView = {
51
+ resolve<I extends Interface>(api: I, where?: Where): Resolution<Interface.Type<I>>;
52
+ get<I extends Interface>(api: I, where?: Where): Interface.Type<I>;
53
+ call(pod: string): Client;
54
+ /**
55
+ * Each successful call of action `op` travelling in this runtime, as `{ input, output }`, after it returns; gives an
56
+ * unsubscribe. Like a pod's `on`: it connects at the call, and throws there an `Error` carrying the `Fail` when it
57
+ * can't (`not-found`, `not-unique`, `denied`).
58
+ */
59
+ subscribe<O extends Op>(op: O, fn: (call: {
60
+ input: In<O>;
61
+ output: Out<O>;
62
+ }) => unknown): () => void;
63
+ /** The same calls as an AsyncIterable, connected and checked at the call, iterated once: `break` unsubscribes; `done`
64
+ * when the source or the application goes; the `Fail` thrown when a later `apply`'s policy refuses it. */
65
+ subscribe<O extends Op>(op: O): AsyncIterable<{
66
+ input: In<O>;
67
+ output: Out<O>;
68
+ }>;
69
+ /** The application's one stream, filtered to this runtime: its messages and their outcomes, `applied`, and the lifecycle of its pods; gives an unsubscribe. */
70
+ listen(fn: (e: AppEvent) => void): () => void;
71
+ /** `pod`'s lifecycle now (`running`, `not started`, `stopped`, `failed`); `not-found` if it is not placed here. */
72
+ status(pod: string): NanoResult<PodStatus>;
73
+ /** Build `pod`, placed here and not running, by a `start` message from the host (ADR-0031): `not-found`, `invalid-input` "already running", `denied`, or the build's `Fail`. */
74
+ start(pod: string): Promise<NanoResult<void>>;
75
+ /** `pod` running, reused (`started: false`) or started now (`true`), with `call(pod)`'s client; or `start`'s `Fail`. */
76
+ getOrCreate(pod: string): Promise<NanoResult<{
77
+ started: boolean;
78
+ pod: Client;
79
+ }>>;
80
+ };
81
+ type DataOf<S> = S extends TSchema ? Static<S> : unknown;
82
+ type In<O> = O extends Op<infer I, any> ? DataOf<I> : unknown;
83
+ type Out<O> = O extends Op<any, infer S> ? DataOf<S> : unknown;
84
+ /** The one pod placed in `runtime` providing `api` now, narrowed by `where`. */
85
+ export declare function placement(live: Live, runtime: string, api: Interface, where: Where): Found<Placed>;
86
+ /**
87
+ * Runtime `id` (or, absent, the application's one runtime) as the host sees it, looked up again at each use, so one
88
+ * added later by `apply` works and a missing one is `not-found`.
89
+ * Its plain objects resolve again at each call, so a rewired placement is followed. `status` is the instances'; `start` and `getOrCreate` are `start.ts`'s.
90
+ */
91
+ export declare function runtimeView(live: Live, status: (pod: string) => PodStatus, id?: string): RuntimeView;
92
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A build's sources, run by the application as it runs handlers: each starts once, when its pod is built; each value
3
+ * it yields is published as the pod's event (`ctx.publish`: checked against the event's schema, along pipes and to `on`
4
+ * subscribers); it is stopped (`return()`) when the build closes; a throw is a `failure` of that pod on the stream, and
5
+ * the pod's actions keep working.
6
+ *
7
+ * start(live, 'todos', ctx, built.sources, c.add) // after make succeeds
8
+ */
9
+ import type { NanoContext } from '../context.js';
10
+ import type { Source } from '../implementation.js';
11
+ import type { Live } from './messages.js';
12
+ export declare function start(live: Live, pod: string, ctx: Omit<NanoContext, 'deps'>, sources: ReadonlyMap<string, Source>, onClose: NanoContext['addOnCloseListener']): void;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A pod started explicitly, in one runtime (ADR-0031). `start(pod)` is a message of kind `start` from the host, with no
3
+ * port: `sent`, asked of the runtime's policy, then `delivered` with the build's result (or `denied`). It builds through
4
+ * `live.instance`, the one build per pod however many ask. `getOrCreate(pod)` reuses a running pod, or starts it, and
5
+ * gives `call(pod)`'s client. Of callers racing on one pod in one runtime, one starts it; the rest find it started once it settles.
6
+ *
7
+ * const s = starter(live, at, status, call)
8
+ * await s.start('db') // NanoResult<void>: not-found, invalid-input "already running", denied, or the build's Fail
9
+ * await s.getOrCreate('db') // NanoResult<{ started, pod }>
10
+ */
11
+ import { type Fail, type NanoResult } from '../result.js';
12
+ import type { client } from './emit.js';
13
+ import type { PodStatus } from './instances.js';
14
+ import { type Live } from './messages.js';
15
+ type Client = ReturnType<typeof client>;
16
+ type At = () => {
17
+ ok: true;
18
+ value: string;
19
+ } | {
20
+ ok: false;
21
+ fail: Fail;
22
+ };
23
+ export declare function starter(live: Live, at: At, status: (pod: string) => PodStatus, call: (pod: string) => Client): {
24
+ start(pod: string): Promise<NanoResult<void>>;
25
+ getOrCreate(pod: string): Promise<NanoResult<{
26
+ started: boolean;
27
+ pod: Client;
28
+ }>>;
29
+ };
30
+ export {};
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The application's one stream: builds, closes, restarts, changes, messages (`sent`, then `delivered` or `denied`) and problems,
3
+ * in order, synchronously. A `sent` names its kind and its chain (a `start` has no port, ADR-0031): `correlation` is the first message's id, `cause` the
4
+ * message that led to it. A throwing listener is swallowed.
5
+ *
6
+ * const s = stream()
7
+ * const off = s.listen(e => { if (e.type === 'denied') log(e.id, e.reason) })
8
+ * s.emit({ type: 'warning', reason: '…' }); s.id() // 'm1', then 'm2', …
9
+ */
10
+ import type { NanoContext } from '../context.js';
11
+ import type { NanoResult } from '../result.js';
12
+ type Reason = Parameters<Parameters<NanoContext['addOnCloseListener']>[0]>[0]['reason'];
13
+ export type AppEvent = {
14
+ type: 'built';
15
+ pod: string;
16
+ } | {
17
+ type: 'closed';
18
+ pod: string;
19
+ reason: Reason;
20
+ } | {
21
+ type: 'restarted';
22
+ pod: string;
23
+ } | {
24
+ type: 'applied';
25
+ caller: string;
26
+ added: string[];
27
+ removed: string[];
28
+ changed: string[];
29
+ rewired: string[];
30
+ } | {
31
+ type: 'sent';
32
+ id: string;
33
+ runtime: string;
34
+ kind: 'call' | 'pipe' | 'on' | 'subscribe' | 'unsubscribe';
35
+ from: string;
36
+ to: string;
37
+ port: string;
38
+ correlation: string;
39
+ cause?: string;
40
+ input?: unknown;
41
+ } | {
42
+ type: 'sent';
43
+ id: string;
44
+ runtime: string;
45
+ kind: 'start';
46
+ from: 'host';
47
+ to: string;
48
+ correlation: string;
49
+ port?: never;
50
+ cause?: never;
51
+ input?: never;
52
+ } | {
53
+ type: 'delivered';
54
+ id: string;
55
+ result: NanoResult<unknown>;
56
+ ms: number;
57
+ } | {
58
+ type: 'denied';
59
+ id: string;
60
+ reason: string;
61
+ } | {
62
+ type: 'failure';
63
+ pod?: string;
64
+ reason: string;
65
+ } | {
66
+ type: 'warning';
67
+ reason: string;
68
+ };
69
+ export declare function stream(): {
70
+ emit(e: AppEvent): void;
71
+ listen(fn: (e: AppEvent) => void): () => void;
72
+ id: () => string;
73
+ };
74
+ export {};