@zhin.js/middleware 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 凉菜
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # @zhin.js/middleware
2
+
3
+ Zhin Plugin Runtime 的 Middleware Feature。它从 `middlewares/**/*.ts` 发现定义,并按
4
+ phase、order、Plugin topology 与 capability identity 形成稳定执行链。
5
+
6
+ ```ts
7
+ import { defineMiddleware } from '@zhin.js/middleware';
8
+
9
+ export default defineMiddleware({
10
+ phase: 'before-dispatch',
11
+ async handle(_context, next) { await next(); },
12
+ });
13
+ ```
14
+
15
+ Middleware 不直接持有 Root 或运行时 registry;每次执行使用同一 generation snapshot,
16
+ 更新时由 Feature Slot 原子替换。
17
+
18
+ 验证:`pnpm --filter @zhin.js/middleware test && pnpm --filter @zhin.js/middleware build`。
19
+
20
+ 生命周期与 HMR 说明见 [目标架构](../../docs/target-architecture.md)。
@@ -0,0 +1,22 @@
1
+ import type { CapabilityContext } from '@zhin.js/feature-kit';
2
+ declare const middlewareBrand: "zhin.middleware/1";
3
+ export type MiddlewarePhase = 'before-dispatch' | 'after-dispatch';
4
+ export type MiddlewareTarget = 'inbound' | 'outbound';
5
+ export type MiddlewareNext = () => Promise<void>;
6
+ export interface MiddlewareContext<TInput = unknown, TConfig = unknown> extends CapabilityContext<TConfig> {
7
+ readonly input: TInput;
8
+ }
9
+ export interface MiddlewareDefinition<TInput = unknown, TConfig = unknown> {
10
+ readonly $feature: typeof middlewareBrand;
11
+ readonly phase: MiddlewarePhase;
12
+ readonly target: MiddlewareTarget;
13
+ readonly order: number;
14
+ handle(context: MiddlewareContext<TInput, TConfig>, next: MiddlewareNext): void | Promise<void>;
15
+ }
16
+ export declare function defineMiddleware<TInput = unknown, TConfig = unknown>(definition: Omit<MiddlewareDefinition<TInput, TConfig>, '$feature' | 'phase' | 'target' | 'order'> & {
17
+ readonly phase?: MiddlewarePhase;
18
+ readonly target?: MiddlewareTarget;
19
+ readonly order?: number;
20
+ }): Readonly<MiddlewareDefinition<TInput, TConfig>>;
21
+ export declare function parseMiddlewareDefinition(value: unknown): MiddlewareDefinition;
22
+ export {};
@@ -0,0 +1,33 @@
1
+ const middlewareBrand = 'zhin.middleware/1';
2
+ export function defineMiddleware(definition) {
3
+ if (typeof definition.handle !== 'function') {
4
+ throw new TypeError('Middleware handle must be a function');
5
+ }
6
+ const phase = definition.phase ?? 'before-dispatch';
7
+ if (phase !== 'before-dispatch' && phase !== 'after-dispatch') {
8
+ throw new TypeError(`Invalid Middleware phase: ${String(phase)}`);
9
+ }
10
+ const target = definition.target ?? 'inbound';
11
+ if (target !== 'inbound' && target !== 'outbound') {
12
+ throw new TypeError(`Invalid Middleware target: ${String(target)}`);
13
+ }
14
+ const order = definition.order ?? 0;
15
+ if (!Number.isSafeInteger(order))
16
+ throw new TypeError('Middleware order must be a safe integer');
17
+ return Object.freeze({ ...definition, $feature: middlewareBrand, phase, target, order });
18
+ }
19
+ export function parseMiddlewareDefinition(value) {
20
+ if (!value || typeof value !== 'object')
21
+ throw invalidMiddleware();
22
+ const definition = value;
23
+ if (definition.$feature !== middlewareBrand
24
+ || typeof definition.handle !== 'function'
25
+ || (definition.phase !== 'before-dispatch' && definition.phase !== 'after-dispatch')
26
+ || (definition.target !== 'inbound' && definition.target !== 'outbound')
27
+ || !Number.isSafeInteger(definition.order))
28
+ throw invalidMiddleware();
29
+ return definition;
30
+ }
31
+ function invalidMiddleware() {
32
+ return new TypeError('Middleware module must default-export defineMiddleware(...)');
33
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './definition.js';
2
+ export * from './middleware-index.js';
3
+ export * from './provider.js';
4
+ export { default } from './provider.js';
package/lib/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './definition.js';
2
+ export * from './middleware-index.js';
3
+ export * from './provider.js';
4
+ export { default } from './provider.js';
@@ -0,0 +1,19 @@
1
+ import type { CapabilitySlot, PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
+ import type { MiddlewareDefinition, MiddlewareNext, MiddlewarePhase, MiddlewareTarget } from './definition.js';
3
+ export interface MiddlewareDescriptor {
4
+ readonly owner: PluginId;
5
+ readonly name: string;
6
+ readonly source: string;
7
+ readonly phase: MiddlewarePhase;
8
+ readonly target: MiddlewareTarget;
9
+ readonly order: number;
10
+ }
11
+ export declare class MiddlewareIndex {
12
+ #private;
13
+ private readonly snapshot;
14
+ readonly $projection: "zhin.middleware-index/1";
15
+ constructor(slots: readonly Readonly<CapabilitySlot<MiddlewareDefinition>>[], snapshot: RuntimeSnapshot);
16
+ list(): readonly MiddlewareDescriptor[];
17
+ run<TInput>(input: TInput, terminal?: MiddlewareNext, target?: MiddlewareTarget): Promise<void>;
18
+ }
19
+ export declare function isMiddlewareIndex(value: unknown): value is MiddlewareIndex;
@@ -0,0 +1,66 @@
1
+ import { createCapabilityContext } from '@zhin.js/feature-kit';
2
+ export class MiddlewareIndex {
3
+ snapshot;
4
+ $projection = 'zhin.middleware-index/1';
5
+ #records;
6
+ constructor(slots, snapshot) {
7
+ this.snapshot = snapshot;
8
+ const topology = topologyOrder(snapshot);
9
+ this.#records = Object.freeze(slots.map((slot) => Object.freeze({
10
+ owner: slot.owner,
11
+ name: slot.localName,
12
+ source: slot.source,
13
+ phase: slot.definition.phase,
14
+ target: slot.definition.target,
15
+ order: slot.definition.order,
16
+ slot,
17
+ })).sort((left, right) => compareMiddleware(left, right, topology)));
18
+ }
19
+ list() {
20
+ return this.#records.map(({ slot: _slot, ...descriptor }) => descriptor);
21
+ }
22
+ async run(input, terminal = async () => undefined, target = 'inbound') {
23
+ const records = this.#records.filter((record) => record.target === target);
24
+ let cursor = -1;
25
+ const dispatch = async (index) => {
26
+ if (index <= cursor)
27
+ throw new Error('Middleware next() called more than once');
28
+ cursor = index;
29
+ const record = records[index];
30
+ if (!record)
31
+ return terminal();
32
+ const context = Object.freeze({
33
+ ...createCapabilityContext(this.snapshot, record.owner),
34
+ input,
35
+ });
36
+ await record.slot.definition.handle(context, () => dispatch(index + 1));
37
+ };
38
+ await dispatch(0);
39
+ }
40
+ }
41
+ export function isMiddlewareIndex(value) {
42
+ return !!value && typeof value === 'object'
43
+ && value.$projection === 'zhin.middleware-index/1';
44
+ }
45
+ function compareMiddleware(left, right, topology) {
46
+ return phaseOrder(left.phase) - phaseOrder(right.phase)
47
+ || left.order - right.order
48
+ || (topology.get(left.owner) ?? Number.MAX_SAFE_INTEGER)
49
+ - (topology.get(right.owner) ?? Number.MAX_SAFE_INTEGER)
50
+ || left.slot.id.localeCompare(right.slot.id);
51
+ }
52
+ function phaseOrder(phase) {
53
+ return phase === 'before-dispatch' ? 0 : 1;
54
+ }
55
+ function topologyOrder(snapshot) {
56
+ const result = new Map();
57
+ const visit = (owner) => {
58
+ if (result.has(owner))
59
+ return;
60
+ result.set(owner, result.size);
61
+ for (const child of snapshot.tree.get(owner)?.children ?? [])
62
+ visit(child);
63
+ };
64
+ visit(snapshot.root);
65
+ return result;
66
+ }
@@ -0,0 +1,5 @@
1
+ import { MiddlewareIndex } from './middleware-index.js';
2
+ export declare const middlewareFeatureId: import("@zhin.js/plugin-runtime").FeatureId;
3
+ declare const middlewareFeature: Readonly<import("@zhin.js/feature-kit").FeatureProvider<import("./definition.js").MiddlewareDefinition<unknown, unknown>, MiddlewareIndex>>;
4
+ export { middlewareFeature };
5
+ export default middlewareFeature;
@@ -0,0 +1,23 @@
1
+ import { featureId } from '@zhin.js/plugin-runtime';
2
+ import { defineFeatureProvider, typeScriptModules } from '@zhin.js/feature-kit';
3
+ import { parseMiddlewareDefinition } from './definition.js';
4
+ import { MiddlewareIndex } from './middleware-index.js';
5
+ export const middlewareFeatureId = featureId('zhin.middleware');
6
+ const middlewareFeature = defineFeatureProvider({
7
+ protocol: 1,
8
+ id: middlewareFeatureId,
9
+ authoring: {
10
+ conventions: [typeScriptModules({
11
+ id: 'middlewares-ts',
12
+ directory: 'middlewares',
13
+ })],
14
+ validate: parseMiddlewareDefinition,
15
+ },
16
+ runtime: {
17
+ project(slots, context) {
18
+ return { value: new MiddlewareIndex(slots, context.snapshot) };
19
+ },
20
+ },
21
+ });
22
+ export { middlewareFeature };
23
+ export default middlewareFeature;
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@zhin.js/middleware",
3
+ "version": "1.0.0",
4
+ "description": "Convention-based Middleware Feature for Zhin Plugin Runtime",
5
+ "type": "module",
6
+ "main": "./lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "development": "./src/index.ts",
12
+ "import": "./lib/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "lib",
17
+ "src"
18
+ ],
19
+ "dependencies": {
20
+ "@zhin.js/feature-kit": "1.0.0",
21
+ "@zhin.js/plugin-runtime": "1.0.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^26.1.0",
25
+ "typescript": "^6.0.3"
26
+ },
27
+ "zhin": {
28
+ "protocol": 1,
29
+ "type": "feature",
30
+ "entry": "./lib/provider.js",
31
+ "engine": "^1.0.0",
32
+ "featureApi": "1.0.0"
33
+ },
34
+ "engines": {
35
+ "node": "^20.19.0 || >=22.12.0"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/zhinjs/zhin.git",
40
+ "directory": "packages/im/middleware"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "registry": "https://registry.npmjs.org"
45
+ },
46
+ "license": "MIT",
47
+ "private": false,
48
+ "scripts": {
49
+ "build": "tsc",
50
+ "clean": "rimraf lib",
51
+ "test": "vitest run --root ../../.. packages/im/middleware/tests"
52
+ }
53
+ }
@@ -0,0 +1,63 @@
1
+ import type { CapabilityContext } from '@zhin.js/feature-kit';
2
+
3
+ const middlewareBrand = 'zhin.middleware/1' as const;
4
+
5
+ export type MiddlewarePhase = 'before-dispatch' | 'after-dispatch';
6
+ export type MiddlewareTarget = 'inbound' | 'outbound';
7
+ export type MiddlewareNext = () => Promise<void>;
8
+
9
+ export interface MiddlewareContext<TInput = unknown, TConfig = unknown>
10
+ extends CapabilityContext<TConfig> {
11
+ readonly input: TInput;
12
+ }
13
+
14
+ export interface MiddlewareDefinition<TInput = unknown, TConfig = unknown> {
15
+ readonly $feature: typeof middlewareBrand;
16
+ readonly phase: MiddlewarePhase;
17
+ readonly target: MiddlewareTarget;
18
+ readonly order: number;
19
+ handle(context: MiddlewareContext<TInput, TConfig>, next: MiddlewareNext): void | Promise<void>;
20
+ }
21
+
22
+ export function defineMiddleware<TInput = unknown, TConfig = unknown>(
23
+ definition: Omit<
24
+ MiddlewareDefinition<TInput, TConfig>,
25
+ '$feature' | 'phase' | 'target' | 'order'
26
+ > & {
27
+ readonly phase?: MiddlewarePhase;
28
+ readonly target?: MiddlewareTarget;
29
+ readonly order?: number;
30
+ },
31
+ ): Readonly<MiddlewareDefinition<TInput, TConfig>> {
32
+ if (typeof definition.handle !== 'function') {
33
+ throw new TypeError('Middleware handle must be a function');
34
+ }
35
+ const phase = definition.phase ?? 'before-dispatch';
36
+ if (phase !== 'before-dispatch' && phase !== 'after-dispatch') {
37
+ throw new TypeError(`Invalid Middleware phase: ${String(phase)}`);
38
+ }
39
+ const target = definition.target ?? 'inbound';
40
+ if (target !== 'inbound' && target !== 'outbound') {
41
+ throw new TypeError(`Invalid Middleware target: ${String(target)}`);
42
+ }
43
+ const order = definition.order ?? 0;
44
+ if (!Number.isSafeInteger(order)) throw new TypeError('Middleware order must be a safe integer');
45
+ return Object.freeze({ ...definition, $feature: middlewareBrand, phase, target, order });
46
+ }
47
+
48
+ export function parseMiddlewareDefinition(value: unknown): MiddlewareDefinition {
49
+ if (!value || typeof value !== 'object') throw invalidMiddleware();
50
+ const definition = value as Partial<MiddlewareDefinition>;
51
+ if (
52
+ definition.$feature !== middlewareBrand
53
+ || typeof definition.handle !== 'function'
54
+ || (definition.phase !== 'before-dispatch' && definition.phase !== 'after-dispatch')
55
+ || (definition.target !== 'inbound' && definition.target !== 'outbound')
56
+ || !Number.isSafeInteger(definition.order)
57
+ ) throw invalidMiddleware();
58
+ return definition as MiddlewareDefinition;
59
+ }
60
+
61
+ function invalidMiddleware(): TypeError {
62
+ return new TypeError('Middleware module must default-export defineMiddleware(...)');
63
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './definition.js';
2
+ export * from './middleware-index.js';
3
+ export * from './provider.js';
4
+ export { default } from './provider.js';
@@ -0,0 +1,100 @@
1
+ import type { CapabilitySlot, PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
+ import { createCapabilityContext } from '@zhin.js/feature-kit';
3
+ import type {
4
+ MiddlewareContext,
5
+ MiddlewareDefinition,
6
+ MiddlewareNext,
7
+ MiddlewarePhase,
8
+ MiddlewareTarget,
9
+ } from './definition.js';
10
+
11
+ export interface MiddlewareDescriptor {
12
+ readonly owner: PluginId;
13
+ readonly name: string;
14
+ readonly source: string;
15
+ readonly phase: MiddlewarePhase;
16
+ readonly target: MiddlewareTarget;
17
+ readonly order: number;
18
+ }
19
+
20
+ interface MiddlewareRecord extends MiddlewareDescriptor {
21
+ readonly slot: Readonly<CapabilitySlot<MiddlewareDefinition>>;
22
+ }
23
+
24
+ export class MiddlewareIndex {
25
+ readonly $projection = 'zhin.middleware-index/1' as const;
26
+ readonly #records: readonly MiddlewareRecord[];
27
+
28
+ constructor(
29
+ slots: readonly Readonly<CapabilitySlot<MiddlewareDefinition>>[],
30
+ private readonly snapshot: RuntimeSnapshot,
31
+ ) {
32
+ const topology = topologyOrder(snapshot);
33
+ this.#records = Object.freeze(slots.map((slot) => Object.freeze({
34
+ owner: slot.owner,
35
+ name: slot.localName,
36
+ source: slot.source,
37
+ phase: slot.definition.phase,
38
+ target: slot.definition.target,
39
+ order: slot.definition.order,
40
+ slot,
41
+ })).sort((left, right) => compareMiddleware(left, right, topology)));
42
+ }
43
+
44
+ list(): readonly MiddlewareDescriptor[] {
45
+ return this.#records.map(({ slot: _slot, ...descriptor }) => descriptor);
46
+ }
47
+
48
+ async run<TInput>(
49
+ input: TInput,
50
+ terminal: MiddlewareNext = async () => undefined,
51
+ target: MiddlewareTarget = 'inbound',
52
+ ): Promise<void> {
53
+ const records = this.#records.filter((record) => record.target === target);
54
+ let cursor = -1;
55
+ const dispatch = async (index: number): Promise<void> => {
56
+ if (index <= cursor) throw new Error('Middleware next() called more than once');
57
+ cursor = index;
58
+ const record = records[index];
59
+ if (!record) return terminal();
60
+ const context: MiddlewareContext<TInput> = Object.freeze({
61
+ ...createCapabilityContext(this.snapshot, record.owner),
62
+ input,
63
+ });
64
+ await record.slot.definition.handle(context, () => dispatch(index + 1));
65
+ };
66
+ await dispatch(0);
67
+ }
68
+ }
69
+
70
+ export function isMiddlewareIndex(value: unknown): value is MiddlewareIndex {
71
+ return !!value && typeof value === 'object'
72
+ && (value as { readonly $projection?: unknown }).$projection === 'zhin.middleware-index/1';
73
+ }
74
+
75
+ function compareMiddleware(
76
+ left: MiddlewareRecord,
77
+ right: MiddlewareRecord,
78
+ topology: ReadonlyMap<PluginId, number>,
79
+ ): number {
80
+ return phaseOrder(left.phase) - phaseOrder(right.phase)
81
+ || left.order - right.order
82
+ || (topology.get(left.owner) ?? Number.MAX_SAFE_INTEGER)
83
+ - (topology.get(right.owner) ?? Number.MAX_SAFE_INTEGER)
84
+ || left.slot.id.localeCompare(right.slot.id);
85
+ }
86
+
87
+ function phaseOrder(phase: MiddlewarePhase): number {
88
+ return phase === 'before-dispatch' ? 0 : 1;
89
+ }
90
+
91
+ function topologyOrder(snapshot: RuntimeSnapshot): ReadonlyMap<PluginId, number> {
92
+ const result = new Map<PluginId, number>();
93
+ const visit = (owner: PluginId): void => {
94
+ if (result.has(owner)) return;
95
+ result.set(owner, result.size);
96
+ for (const child of snapshot.tree.get(owner)?.children ?? []) visit(child);
97
+ };
98
+ visit(snapshot.root);
99
+ return result;
100
+ }
@@ -0,0 +1,26 @@
1
+ import { featureId } from '@zhin.js/plugin-runtime';
2
+ import { defineFeatureProvider, typeScriptModules } from '@zhin.js/feature-kit';
3
+ import { parseMiddlewareDefinition } from './definition.js';
4
+ import { MiddlewareIndex } from './middleware-index.js';
5
+
6
+ export const middlewareFeatureId = featureId('zhin.middleware');
7
+
8
+ const middlewareFeature = defineFeatureProvider({
9
+ protocol: 1,
10
+ id: middlewareFeatureId,
11
+ authoring: {
12
+ conventions: [typeScriptModules({
13
+ id: 'middlewares-ts',
14
+ directory: 'middlewares',
15
+ })],
16
+ validate: parseMiddlewareDefinition,
17
+ },
18
+ runtime: {
19
+ project(slots, context) {
20
+ return { value: new MiddlewareIndex(slots, context.snapshot) };
21
+ },
22
+ },
23
+ });
24
+
25
+ export { middlewareFeature };
26
+ export default middlewareFeature;