@rhythmjs/rhythm 0.0.1 → 0.0.3

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
@@ -5,7 +5,7 @@ The core composition kernel `@rhythmjs/router` and `@rhythmjs/cli` are built on.
5
5
  ## Concepts
6
6
 
7
7
  - **Onion middleware** — `use()` wraps downstream steps, running code before _and_ after `next()`.
8
- - **Providers** — `provide()` registers a value or async factory that resolves once and is injected into every request's context. A returned key prefixed with `#` (e.g. `"#close"`) stays out of context but is still passed in full to `dispose()`.
8
+ - **Providers** — `provide()` registers a value or async factory that resolves once and joins the context at its position in the chain: only middleware (and mounted controllers) added after it see the value. A returned key prefixed with `#` (e.g. `"#close"`) stays out of context but is still passed in full to `dispose()`.
9
9
  - **Encapsulated modules** — `register()` mounts a child `Rhythm`; its context stays sealed unless you explicitly export fields from it.
10
10
  - **Readonly context** — the context passed to middleware is deeply readonly at the type level; state only changes via `next(extra)`, or through a value branded with the `RhythmMutable` symbol (how `RhythmRouter`/`RhythmCli`'s response objects stay mutable).
11
11
 
@@ -32,7 +32,7 @@ await app.run({ userId: "u1" });
32
32
  await app.teardown();
33
33
  ```
34
34
 
35
- `provide()` factories run once, in declaration order, each receiving everything resolved so far via `deps`. `use()` middleware runs on every `run()` call, in onion order.
35
+ `provide()` factories run once, in declaration order, each receiving everything resolved so far via `deps`. On each `run()`, the whole chain — middleware and provider injections alike — executes in registration order, onion-style: everything only applies to what was chained after it.
36
36
 
37
37
  ### Module registration
38
38
 
@@ -57,11 +57,11 @@ const app = new Rhythm<{ userId: string }>()
57
57
 
58
58
  - `new Rhythm<TInput>(options?)` — creates a pipeline; `options.name`/`options.type` label errors from `register()`.
59
59
  - `.use(fn: (ctx, next) => Promise<void> | void)` — add an onion middleware step.
60
- - `.provide(factory: (deps) => TValue | Promise<TValue>, dispose?)` — register a provider; resolved once, disposed in reverse order on `teardown()`.
61
- - `.register(other: Rhythm, exportValue?)` — mount a child module; sealed by default, opt in via `exportValue`.
60
+ - `.provide(factory: (deps) => TValue | Promise<TValue>, dispose?)` — register a provider; resolved once, injected at its chain position, disposed in reverse order on `teardown()`.
61
+ - `.register(other: Rhythm, exportValue?)` — mount a child `Rhythm` module; sealed by default, opt in via `exportValue`. Controllers (`RhythmRouter`, `RhythmCli`) are not modules — they mount via `.use()` instead.
62
62
  - `.run(input)` — runs `setup()` if needed, dispatches `input` through the middleware chain.
63
63
  - `.callback()` — returns the cached, reusable `(input) => Promise<TContext>` handler `run()` uses internally.
64
- - `.middleware()` — returns this instance as a plain middleware, for flat mounting into a parent via `.use()` instead of `.register()` (what `RhythmRouter.routes()`/`RhythmCli.commands()` build on).
64
+ - `.middleware()` — returns this instance as a plain middleware, for flat mounting into a parent via `.use()` instead of `.register()`.
65
65
  - `.setup()` — resolves all providers, cascading into registered modules. Idempotent; retryable on failure.
66
66
  - `.teardown()` — disposes all providers in reverse order, cascading into registered modules.
67
67
  - `compose(middleware[])` — the standalone Koa-style onion dispatcher `Rhythm` is built on.
@@ -0,0 +1,4 @@
1
+ import { Middleware, NextFn } from "./types.js";
2
+ //#region src/compose.d.ts
3
+ export declare function compose<TContext extends object>(middleware: Middleware<TContext>[]): (context: TContext, next?: NextFn<TContext>) => Promise<TContext>;
4
+ //#endregion
@@ -0,0 +1,24 @@
1
+ //#region src/compose.ts
2
+ function compose(middleware) {
3
+ if (!Array.isArray(middleware)) throw new TypeError("Middleware stack must be an array!");
4
+ for (const fn of middleware) if (typeof fn !== "function") throw new TypeError("Middleware must be composed of functions!");
5
+ return function(context, next) {
6
+ let index = -1;
7
+ return dispatch(0);
8
+ function dispatch(i) {
9
+ if (i <= index) return Promise.reject(/* @__PURE__ */ new Error("next() called multiple times"));
10
+ index = i;
11
+ const fn = i === middleware.length ? next : middleware[i];
12
+ if (!fn) return Promise.resolve(context);
13
+ const dispatchNext = () => dispatch(i + 1);
14
+ try {
15
+ const call = fn;
16
+ return Promise.resolve(call(context, dispatchNext)).then(() => context);
17
+ } catch (err) {
18
+ return Promise.reject(err);
19
+ }
20
+ }
21
+ };
22
+ }
23
+ //#endregion
24
+ export { compose };
package/dist/rhythm.d.ts CHANGED
@@ -1,26 +1,18 @@
1
+ import { DeriveMiddleware, Middleware, OmitHashKeys } from "./types.js";
1
2
  //#region src/rhythm.d.ts
2
- export declare const RhythmMutable: unique symbol;
3
- export type DeepReadonly<T> = T extends ((...args: any[]) => any) ? T : T extends ReadonlyArray<infer U> ? readonly DeepReadonly<U>[] : T extends Map<infer K, infer V> ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>> : T extends Set<infer U> ? ReadonlySet<DeepReadonly<U>> : T extends {
4
- readonly [RhythmMutable]: true;
5
- } ? T : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]>; } : T;
6
- export type OmitHashKeys<T> = { [K in keyof T as K extends `#${string}` ? never : K]: T[K]; };
7
- export type NextFn<TContext extends object> = {
8
- (): Promise<DeepReadonly<TContext>>;
9
- <TExtra extends object>(extra: TExtra): Promise<DeepReadonly<TContext & TExtra>>;
10
- };
11
- export type Middleware<TContext extends object> = (ctx: DeepReadonly<TContext>, next: NextFn<TContext>) => Promise<void> | void;
12
- export declare function compose<TContext extends object>(middleware: Middleware<TContext>[]): (context: TContext, next?: NextFn<TContext>) => Promise<TContext>;
13
3
  export interface RhythmOptions {
14
4
  name?: string;
15
5
  type?: string;
16
6
  [key: string]: unknown;
17
7
  }
8
+ export declare function derive<TContext extends object, TExtra extends object>(fn: (ctx: TContext) => TExtra | Promise<TExtra>): DeriveMiddleware<TContext, OmitHashKeys<TExtra>>;
18
9
  export declare class Rhythm<TInput extends object = {}, TContext extends object = TInput, TProviders extends object = {}> {
19
10
  #private;
20
11
  constructor(options?: RhythmOptions);
21
- use<TExtra extends object = {}>(fn: Middleware<TContext>): Rhythm<TInput, TContext & TExtra, TProviders>;
22
- provide<TValue extends object>(factory: (deps: DeepReadonly<TProviders>) => TValue | Promise<TValue>, dispose?: (value: TValue) => void | Promise<void>): Rhythm<TInput, TContext & OmitHashKeys<TValue>, TProviders & OmitHashKeys<TValue>>;
23
- register<TRegInput extends object, TRegContext extends object, TExported extends object = {}>(other: Rhythm<TRegInput, TRegContext, any> & (TContext extends TRegInput ? unknown : never), exportValue?: (result: DeepReadonly<TRegContext>) => TExported): Rhythm<TInput, TContext & TExported, TProviders>;
12
+ use<TExtra extends object>(fn: DeriveMiddleware<TContext, TExtra>): Rhythm<TInput, TContext & TExtra, TProviders>;
13
+ use(fn: Middleware<TContext>): this;
14
+ provide<TValue extends object>(factory: (deps: TProviders) => TValue | Promise<TValue>, dispose?: (value: TValue) => void | Promise<void>): Rhythm<TInput, TContext & OmitHashKeys<TValue>, TProviders & OmitHashKeys<TValue>>;
15
+ register<TRegInput extends object, TRegContext extends object, TExported extends object = {}>(other: Rhythm<TRegInput, TRegContext, any> & (TContext extends TRegInput ? unknown : never), exportValue?: (result: TRegContext) => TExported): Rhythm<TInput, TContext & TExported, TProviders>;
24
16
  setup(): Promise<void>;
25
17
  teardown(): Promise<void>;
26
18
  callback(): (input: TInput) => Promise<TContext>;
package/dist/rhythm.js CHANGED
@@ -1,50 +1,41 @@
1
+ import { compose } from "./compose.js";
1
2
  //#region src/rhythm.ts
2
- const RhythmMutable = Symbol("RhythmMutable");
3
- function compose(middleware) {
4
- if (!Array.isArray(middleware)) throw new TypeError("Middleware stack must be an array!");
5
- for (const fn of middleware) if (typeof fn !== "function") throw new TypeError("Middleware must be composed of functions!");
6
- return function(context, next) {
7
- let index = -1;
8
- return dispatch(0);
9
- function dispatch(i) {
10
- if (i <= index) return Promise.reject(/* @__PURE__ */ new Error("next() called multiple times"));
11
- index = i;
12
- const fn = i === middleware.length ? next : middleware[i];
13
- if (!fn) return Promise.resolve(context);
14
- const dispatchNext = ((extra) => {
15
- if (extra) Object.assign(context, extra);
16
- return dispatch(i + 1);
17
- });
18
- try {
19
- const call = fn;
20
- return Promise.resolve(call(context, dispatchNext)).then(() => context);
21
- } catch (err) {
22
- return Promise.reject(err);
23
- }
24
- }
3
+ function publicEntries(value) {
4
+ const exported = {};
5
+ for (const [key, val] of Object.entries(value)) if (!key.startsWith("#")) exported[key] = val;
6
+ return exported;
7
+ }
8
+ function derive(fn) {
9
+ if (typeof fn !== "function") throw new TypeError("derive factory must be a function!");
10
+ const middleware = async (ctx, next) => {
11
+ const value = await fn(ctx);
12
+ Object.assign(ctx, publicEntries(value));
13
+ await next();
25
14
  };
15
+ return middleware;
26
16
  }
27
17
  var Rhythm = class {
28
18
  #middleware = [];
29
19
  #options;
30
20
  #providers = [];
31
21
  #setupPromise = null;
32
- #providedCache = null;
33
- #composed = null;
34
- #callbackFn = null;
35
22
  constructor(options = {}) {
36
23
  this.#options = options;
37
24
  }
38
25
  use(fn) {
39
26
  if (typeof fn !== "function") throw new TypeError("middleware must be a function!");
40
27
  this.#middleware.push(fn);
41
- this.#invalidateCallback();
42
28
  return this;
43
29
  }
44
30
  provide(factory, dispose) {
45
- this.#providers.push({
31
+ const entry = {
46
32
  factory,
47
33
  dispose
34
+ };
35
+ this.#providers.push(entry);
36
+ this.#middleware.push(async (ctx, next) => {
37
+ Object.assign(ctx, publicEntries(entry.resolved));
38
+ await next();
48
39
  });
49
40
  return this;
50
41
  }
@@ -65,15 +56,11 @@ var Rhythm = class {
65
56
  const { type = "module", name = "anonymous" } = module.#options;
66
57
  throw new Error(`registered ${type} "${name}" failed`, { cause });
67
58
  }
68
- await next(exportValue ? exportValue(result) : {});
59
+ if (exportValue) Object.assign(ctx, exportValue(result));
60
+ await next();
69
61
  });
70
- this.#invalidateCallback();
71
62
  return this;
72
63
  }
73
- #invalidateCallback() {
74
- this.#composed = null;
75
- this.#callbackFn = null;
76
- }
77
64
  setup() {
78
65
  if (!this.#setupPromise) this.#setupPromise = this.#resolveProviders().catch((err) => {
79
66
  this.#setupPromise = null;
@@ -85,39 +72,34 @@ var Rhythm = class {
85
72
  const resolved = {};
86
73
  for (const entry of this.#providers) {
87
74
  entry.resolved = await entry.factory(resolved);
88
- for (const [key, value] of Object.entries(entry.resolved)) if (!key.startsWith("#")) resolved[key] = value;
75
+ Object.assign(resolved, publicEntries(entry.resolved));
89
76
  }
90
- this.#providedCache = resolved;
91
77
  }
92
78
  async teardown() {
93
- for (const entry of [...this.#providers].reverse()) await entry.dispose?.(entry.resolved);
79
+ for (const entry of [...this.#providers].reverse()) {
80
+ if (entry.resolved === void 0) continue;
81
+ await entry.dispose?.(entry.resolved);
82
+ entry.resolved = void 0;
83
+ }
84
+ this.#setupPromise = null;
94
85
  }
95
86
  callback() {
96
- if (!this.#callbackFn) {
97
- if (!this.#composed) this.#composed = compose(this.#middleware);
98
- const fn = this.#composed;
99
- this.#callbackFn = async (input) => {
100
- await this.setup();
101
- return fn({
102
- ...this.#providedCache,
103
- ...input
104
- });
105
- };
106
- }
107
- return this.#callbackFn;
87
+ const fn = compose([...this.#middleware]);
88
+ return async (input) => {
89
+ await this.setup();
90
+ return fn({ ...input });
91
+ };
108
92
  }
109
93
  run(input) {
110
94
  return this.callback()(input);
111
95
  }
112
96
  middleware() {
97
+ const fn = compose([...this.#middleware]);
113
98
  return async (ctx, next) => {
114
99
  await this.setup();
115
- if (!this.#composed) this.#composed = compose(this.#middleware);
116
- const context = ctx;
117
- Object.assign(context, this.#providedCache);
118
- await this.#composed(context, next);
100
+ await fn(ctx, next);
119
101
  };
120
102
  }
121
103
  };
122
104
  //#endregion
123
- export { Rhythm, RhythmMutable, compose };
105
+ export { Rhythm, derive };
@@ -0,0 +1,8 @@
1
+ //#region src/types.d.ts
2
+ export type OmitHashKeys<T> = { [K in keyof T as K extends `#${string}` ? never : K]: T[K]; };
3
+ export type NextFn<TContext extends object> = () => Promise<TContext>;
4
+ export type Middleware<TContext extends object> = (ctx: TContext, next: NextFn<TContext>) => Promise<void> | void;
5
+ export type DeriveMiddleware<TContext extends object, TExtra extends object> = Middleware<TContext> & {
6
+ readonly "~derive": TExtra;
7
+ };
8
+ //#endregion
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@rhythmjs/rhythm",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "A minimal, type-safe onion-middleware and provider composition kernel.",
5
+ "homepage": "https://rhythm.js.org/rhythm",
5
6
  "license": "ISC",
6
7
  "repository": {
7
8
  "type": "git",
@@ -18,6 +19,14 @@
18
19
  "types": "./dist/rhythm.d.ts",
19
20
  "default": "./dist/rhythm.js"
20
21
  },
22
+ "./compose": {
23
+ "types": "./dist/compose.d.ts",
24
+ "default": "./dist/compose.js"
25
+ },
26
+ "./types": {
27
+ "types": "./dist/types.d.ts",
28
+ "default": "./dist/types.js"
29
+ },
21
30
  "./package.json": "./package.json"
22
31
  },
23
32
  "publishConfig": {
@@ -30,10 +39,5 @@
30
39
  },
31
40
  "engines": {
32
41
  "node": ">=20.19.0"
33
- },
34
- "scripts": {
35
- "build": "vp pack",
36
- "typecheck": "tsc --noEmit",
37
- "test": "vp test"
38
42
  }
39
43
  }