Skip to content

Commit d1b6137

Browse files
committed
✨ node-first Api with middleware over Context
1 parent f75d047 commit d1b6137

3 files changed

Lines changed: 361 additions & 0 deletions

File tree

‎packages/tree/src/api.test.ts‎

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
// oxlint-disable max-params -- Api cores include the dispatch node before method arguments.
2+
import { describe, expect, test } from 'vitest';
3+
import { createApi } from './api.ts';
4+
import { createNode } from './node.ts';
5+
import type { Node } from './node.ts';
6+
7+
describe('createApi', () => {
8+
test('methods call a core with the node as its first argument', () => {
9+
const api = createApi('test', {
10+
add: (_node: Node, a: number, b: number) => a + b,
11+
});
12+
expect(api.methods.add(createNode(), 2, 3)).toBe(5);
13+
});
14+
15+
test('a core receives the node it is invoked on', () => {
16+
const api = createApi('test', {
17+
self: (node: Node) => node,
18+
});
19+
const n = createNode();
20+
expect(api.methods.self(n)).toBe(n);
21+
});
22+
23+
test('invoke calls a core using the first argument as the node', () => {
24+
const api = createApi('test', {
25+
add: (_node: Node, a: number, b: number) => a + b,
26+
});
27+
expect(api.invoke('add', [createNode(), 2, 3])).toBe(5);
28+
});
29+
30+
test('invokes the core directly when no middleware is installed', () => {
31+
const api = createApi('test', {
32+
num: (_node: Node, value: number) => value,
33+
});
34+
expect(api.methods.num(createNode(), 7)).toBe(7);
35+
});
36+
37+
test('middleware surrounds a core function', () => {
38+
const api = createApi('test', {
39+
num: (_node: Node, value: number) => value,
40+
});
41+
const n = createNode();
42+
api.around(n, {
43+
num: (args, next) => next(...args) * 2,
44+
});
45+
expect(api.methods.num(n, 5)).toBe(10);
46+
});
47+
48+
test('middleware receives the invocation node as its first argument', () => {
49+
const api = createApi('test', {
50+
num: (_node: Node, value: number) => value,
51+
});
52+
const n = createNode();
53+
let seen: Node | undefined;
54+
api.around(n, {
55+
num: (args, next) => {
56+
seen = args[0];
57+
return next(...args);
58+
},
59+
});
60+
api.methods.num(n, 1);
61+
expect(seen).toBe(n);
62+
});
63+
64+
test('middleware can substitute the node passed on to the core', () => {
65+
const api = createApi('test', {
66+
self: (node: Node) => node,
67+
});
68+
const root = createNode();
69+
const target = createNode(root);
70+
api.around(root, {
71+
self: (_args, next) => next(target),
72+
});
73+
expect(api.methods.self(root)).toBe(target);
74+
});
75+
76+
test('a child node inherits middleware from its parent', () => {
77+
const api = createApi('test', {
78+
num: (_node: Node, value: number) => value,
79+
});
80+
const parent = createNode();
81+
api.around(parent, {
82+
num: (args, next) => next(...args) * 2,
83+
});
84+
expect(api.methods.num(createNode(parent), 5)).toBe(10);
85+
});
86+
87+
test('composes middleware on a node in the order it was installed', () => {
88+
const api = createApi('test', {
89+
seq: (_node: Node, order: string[]) => order,
90+
});
91+
const n = createNode();
92+
api.around(n, {
93+
seq: (args, next) => next(args[0], args[1].concat('one')).concat('/one'),
94+
});
95+
api.around(n, {
96+
seq: (args, next) => next(args[0], args[1].concat('two')).concat('/two'),
97+
});
98+
api.around(n, {
99+
seq: (args, next) => next(args[0], args[1].concat('three')).concat('/three'),
100+
});
101+
expect(api.methods.seq(n, [])).toEqual(['one', 'two', 'three', '/three', '/two', '/one']);
102+
});
103+
104+
test('middleware on one key does not affect another key', () => {
105+
const api = createApi('test', {
106+
foo: (_node: Node) => 1,
107+
bar: (_node: Node) => 1,
108+
});
109+
const n = createNode();
110+
api.around(n, {
111+
foo: (args, next) => next(...args) * 100,
112+
});
113+
expect(api.methods.foo(n)).toBe(100);
114+
expect(api.methods.bar(n)).toBe(1);
115+
});
116+
117+
test('sibling nodes are isolated from each other’s middleware', () => {
118+
const api = createApi('test', {
119+
seq: (_node: Node, order: string[]) => order,
120+
});
121+
const root = createNode();
122+
const a = createNode(root);
123+
api.around(a, {
124+
seq: (args, next) => next(args[0], args[1].concat('a')).concat('/a'),
125+
});
126+
const b = createNode(root);
127+
api.around(b, {
128+
seq: (args, next) => next(args[0], args[1].concat('b')).concat('/b'),
129+
});
130+
expect(api.methods.seq(a, [])).toEqual(['a', '/a']);
131+
expect(api.methods.seq(b, [])).toEqual(['b', '/b']);
132+
expect(api.methods.seq(root, [])).toEqual([]);
133+
});
134+
135+
test('composes middleware across a three-level node tree, ancestor outermost', () => {
136+
const api = createApi('test', {
137+
seq: (_node: Node, order: string[]) => order,
138+
});
139+
const grand = createNode();
140+
api.around(grand, {
141+
seq: (args, next) => next(args[0], args[1].concat('grand')).concat('/grand'),
142+
});
143+
const parent = createNode(grand);
144+
api.around(parent, {
145+
seq: (args, next) => next(args[0], args[1].concat('parent')).concat('/parent'),
146+
});
147+
const child = createNode(parent);
148+
api.around(child, {
149+
seq: (args, next) => next(args[0], args[1].concat('child')).concat('/child'),
150+
});
151+
expect(api.methods.seq(child, [])).toEqual([
152+
'grand',
153+
'parent',
154+
'child',
155+
'/child',
156+
'/parent',
157+
'/grand',
158+
]);
159+
});
160+
161+
test('does not duplicate ancestor middleware when an ancestor is extended later', () => {
162+
const api = createApi('test', {
163+
seq: (_node: Node, order: string[]) => order,
164+
});
165+
const parent = createNode();
166+
const child = createNode(parent);
167+
parent.children.add(child);
168+
169+
api.around(parent, {
170+
seq: (args, next) => next(args[0], args[1].concat('parent-one')),
171+
});
172+
api.around(child, {
173+
seq: (args, next) => next(args[0], args[1].concat('child')),
174+
});
175+
api.around(parent, {
176+
seq: (args, next) => next(args[0], args[1].concat('parent-two')),
177+
});
178+
179+
expect(api.methods.seq(child, [])).toEqual(['parent-one', 'parent-two', 'child']);
180+
});
181+
182+
test('a child’s middleware does not leak back to its parent', () => {
183+
const api = createApi('test', {
184+
num: (_node: Node, value: number) => value,
185+
});
186+
const parent = createNode();
187+
const child = createNode(parent);
188+
api.around(child, {
189+
num: (args, next) => next(...args) * 2,
190+
});
191+
expect(api.methods.num(child, 5)).toBe(10);
192+
expect(api.methods.num(parent, 5)).toBe(5);
193+
});
194+
});

‎packages/tree/src/api.ts‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
// oxlint-disable no-explicit-any
2+
import { createContext } from './context.ts';
3+
import type { Node } from './node.ts';
4+
5+
/**
6+
* The shape every api core must satisfy: each member is a function whose first
7+
* parameter is the {@link Node} it operates on.
8+
*/
9+
export type Core = Record<string, (node: Node, ...args: any[]) => any>;
10+
11+
/**
12+
* A function that surrounds a core member, optionally delegating to the next
13+
* link in the stack.
14+
*
15+
* @param args - the member's full parameter tuple, with the node as `args[0]`.
16+
* @param next - the next link in the chain; accepts the same arguments.
17+
* @returns a value of the same shape as `next()`'s return value.
18+
*/
19+
export interface Middleware<TArgs extends unknown[], TReturn> {
20+
(args: TArgs, next: (...args: TArgs) => TReturn): TReturn;
21+
}
22+
23+
/**
24+
* The set of middlewares that can surround a core `A`. Each member is wrapped
25+
* by a {@link Middleware} over that member's own signature — node included.
26+
*/
27+
export type Around<A> = {
28+
[K in keyof A]: A[K] extends (...args: infer TArgs) => infer TReturn
29+
? Middleware<TArgs, TReturn>
30+
: never;
31+
};
32+
33+
export interface Api<A extends Core> {
34+
/**
35+
* Every core member, node-first, with the middleware installed on a node
36+
* (and inherited from its ancestors) woven in. `methods.foo(node, ...args)`
37+
* is the ergonomic way to call member `foo` on `node`.
38+
*/
39+
methods: A;
40+
41+
/**
42+
* Call member `key` as it exists on `args[0]`, threading `args` through every
43+
* middleware installed on that node and its ancestors. The first argument is
44+
* both the node used to resolve middleware and the node handed to the core.
45+
*/
46+
invoke<K extends keyof A>(key: K, args: Parameters<A[K]>): ReturnType<A[K]>;
47+
48+
/**
49+
* Install middleware around this api within `node`. Descendants of `node`
50+
* inherit it; ancestors compose outermost.
51+
*/
52+
around(node: Node, middlewares: Partial<Around<A>>): void;
53+
}
54+
55+
export function createApi<A extends Core>(name: string, core: A): Api<A> {
56+
const fields = Object.keys(core) as (keyof A)[];
57+
const context = createContext<Installed<A>>(`api::${name}`);
58+
59+
// Merge `inner`'s middlewares into `outer`, combining any key both define so
60+
// that `outer` wraps `inner`.
61+
function append(outer: Partial<Around<A>>, inner: Partial<Around<A>>): Partial<Around<A>> {
62+
const result: Partial<Around<A>> = { ...outer };
63+
for (const key of Object.keys(inner) as (keyof A)[]) {
64+
const current = outer[key];
65+
const decoration = inner[key];
66+
if (!current) {
67+
result[key] = decoration;
68+
} else {
69+
result[key] = combine([current as any, decoration as any]) as Around<A>[keyof A];
70+
}
71+
}
72+
return result;
73+
}
74+
75+
// Eagerly reify a set of middlewares into a concrete handle: every core member
76+
// is either wrapped by its middleware or copied through untouched.
77+
function createHandle(around: Partial<Around<A>>): A {
78+
if (isEmpty(around)) {
79+
return core;
80+
} else {
81+
const handle = {} as A;
82+
for (const key of fields) {
83+
const middleware = around[key] as Middleware<any[], any> | undefined;
84+
if (!middleware) {
85+
handle[key] = core[key];
86+
} else {
87+
handle[key] = ((...args: any[]) => middleware(args, core[key] as any)) as A[keyof A];
88+
}
89+
}
90+
return handle;
91+
}
92+
}
93+
94+
// Recompute `node`'s handle from the total inherited from its parent, then
95+
// push the new total down to its children.
96+
function install(node: Node, total: Partial<Around<A>>): void {
97+
if (context.hasOwn(node)) {
98+
const installed = context.expect(node);
99+
installed.total = total;
100+
total = append(total, installed.local);
101+
installed.handle = createHandle(total);
102+
}
103+
for (const child of node.children) {
104+
install(child, total);
105+
}
106+
}
107+
108+
const api: Api<A> = {
109+
methods: fields.reduce((methods, key) => {
110+
return Object.assign(methods, {
111+
[key]: (node: Node, ...args: any[]) => api.invoke(key, [node, ...args] as any),
112+
});
113+
}, {} as A),
114+
115+
invoke(key, args) {
116+
const node = args[0] as Node;
117+
const handle = context.get(node)?.handle ?? core;
118+
const member = handle[key] as (...args: any[]) => any;
119+
return member(...args);
120+
},
121+
122+
around(node, middlewares) {
123+
let current: Installed<A>;
124+
if (!context.hasOwn(node)) {
125+
const parent = context.get(node);
126+
current = {
127+
total: parent ? append(parent.total, parent.local) : {},
128+
local: middlewares,
129+
handle: core,
130+
};
131+
context.set(node, current);
132+
} else {
133+
current = context.expect(node);
134+
current.local = append(current.local, middlewares);
135+
}
136+
install(node, current.total);
137+
},
138+
};
139+
140+
return api;
141+
}
142+
143+
/** The locally reified middleware stack installed on a node. */
144+
interface Installed<A> {
145+
local: Partial<Around<A>>;
146+
total: Partial<Around<A>>;
147+
handle: A;
148+
}
149+
150+
/** Fold a stack of middlewares into one; the first is outermost. */
151+
function combine(middlewares: Middleware<any[], any>[]): Middleware<any[], any> {
152+
if (middlewares.length === 0) {
153+
return (args, next) => next(...args);
154+
} else {
155+
return middlewares.reduceRight(
156+
(next, middleware) => (args, base) => middleware(args, (...args) => next(args, base)),
157+
);
158+
}
159+
}
160+
161+
function isEmpty(object: object): boolean {
162+
for (const _ in object) {
163+
return false;
164+
}
165+
return true;
166+
}

‎packages/tree/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1+
export * from './api.ts';
12
export * from './context.ts';
23
export * from './node.ts';

0 commit comments

Comments
 (0)