@makoojs/core 0.2.1 → 0.3.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.CN.md CHANGED
@@ -1,272 +1,713 @@
1
- # @makoojs/core
1
+ # 核心 API
2
2
 
3
- `@makoojs/core` 是 Makoo 的框架无关运行时核心。它负责声明注入任务、启动任务批次、等待目标 DOM、挂载 artifact、管理 alive 重新注入、绑定事件监听,并提供生命周期观察、日志和错误基础设施。
3
+ ## API 索引
4
4
 
5
- 普通项目通常从 `@makoojs/cli` 开始。只有在你想绕过 CLI 生成入口、手动集成运行时时,才需要直接使用 core。
5
+ ### 任务
6
6
 
7
- > [!NOTE]
8
- > `@makoojs/core`包是其他包的父包,其他的包都直接或间接的依赖该包的类型或功能
7
+ - [`createMakoo()`](#createmakoo):创建运行时
8
+ - [`inject()`](#inject):声明 component 任务
9
+ - [`listen()`](#listen):声明 listener 任务
9
10
 
10
- ## 使用场景
11
+ ### 观察和状态
11
12
 
12
- - 编写自定义 `ResolvableMountAdapter`,让 Makoo 挂载新的 artifact 类型。
13
- - 使用 `createMakoo()` 创建运行时,并显式启动任务声明。
14
- - 监听注入生命周期事件,用于调试、埋点、错误上报或可视化开发工具。
15
- - 使用 `DOMWatcher`、`createActivityStore` 等底层工具构建自定义运行时集成。
13
+ - [`createObserverHub()`](#createobserverhub):创建生命周期事件中心
14
+ - [`createActivityStore()`](#createactivitystore):创建可订阅状态
15
+ - [`DOMWatcher`](#domwatcher):观察 DOM 目标
16
16
 
17
- ## 安装
17
+ ### 基础能力
18
18
 
19
- ```bash
20
- // npm install @makoojs/core
21
- // yarn add @makoojs/core
22
- pnpm add @makoojs/core
19
+ - [`Logger`](#logger):日志实现
20
+ - [错误类](#错误类):结构化错误
21
+ - [常量](#常量):动作、事件名和错误码
22
+
23
+ ### TypeScript 类型
24
+
25
+ - [Adapter 类型](#adapter-类型)
26
+ - [任务类型](#任务类型)
27
+ - [观察类型](#观察类型)
28
+ - [Signal 类型](#signal-类型)
29
+ - [日志类型](#日志类型)
30
+ - [错误类型](#错误类型)
31
+
32
+ ## `createMakoo()`
33
+
34
+ 创建一个 Makoo 运行时。
35
+
36
+ ### Type
37
+
38
+ ```ts
39
+ function createMakoo(options?: CreateMakooOptions): MakooRuntime;
23
40
  ```
24
41
 
25
- ## 最小运行时示例
42
+ ### Parameters
43
+
44
+ `options` 使用 `CreateMakooOptions`:
45
+
46
+ | 字段 | 类型 | 默认值 | 说明 |
47
+ | --- | --- | --- | --- |
48
+ | `defaults` | `Partial<MakooDefaults>` | `{}` | 设置 injection 的默认选项 |
49
+ | `adapters` | `ResolvableMountAdapter[]` | `[]` | 注册可用于挂载 artifact 的 adapter |
50
+ | `hooks` | `LifecycleHookMap` | `undefined` | 注册全局生命周期 hooks |
51
+ | `logger` | `ILogger` | `new Logger()` | 设置日志实现 |
52
+ | `observer` | `ObserverHub` | `createObserverHub(logger)` | 设置生命周期事件中心 |
53
+
54
+ ### Details
55
+
56
+ `defaults` 的最终默认值:
26
57
 
27
58
  ```ts
28
- import {
29
- createMakoo,
30
- inject,
31
- type ResolvableMountAdapter
32
- } from '@makoojs/core';
59
+ {
60
+ alive: false,
61
+ scope: 'local',
62
+ timeout: 5000
63
+ }
64
+ ```
33
65
 
34
- type TextArtifact = {
35
- kind: 'text';
36
- text: string;
37
- };
66
+ ### Returns
38
67
 
39
- const textAdapter: ResolvableMountAdapter<TextArtifact, HTMLElement> = {
40
- name: 'text',
41
- matches(artifact): artifact is TextArtifact {
42
- return (
43
- typeof artifact === 'object' &&
44
- artifact !== null &&
45
- (artifact as { kind?: unknown }).kind === 'text'
46
- );
47
- },
48
- mount({ mountPoint, artifact }) {
49
- const el = document.createElement('span');
50
- el.textContent = artifact.text;
51
- mountPoint.appendChild(el);
52
-
53
- return { handle: el };
54
- },
55
- unmount({ handle }) {
56
- handle.remove();
57
- }
58
- };
68
+ 返回 `MakooRuntime`:
69
+
70
+ | 方法 | 返回值 | 说明 |
71
+ | --- | --- | --- |
72
+ | `start(tasks)` | `StartedTasks` | 注册并启动一批 `MakooTaskDeclaration`;空数组会抛出 `TaskError` |
73
+ | `reset(taskId)` | `void` | 重置指定任务并释放当前资源 |
74
+ | `destroy(taskId)` | `void` | 销毁并移除指定任务 |
75
+ | `resetAll()` | `void` | 重置当前运行时中的全部任务 |
76
+ | `destroyAll()` | `void` | 销毁当前运行时中的全部任务 |
77
+ | `enableAlive(taskId)` | `void` | 为 component 任务启用 alive 观察 |
78
+ | `disableAlive(taskId)` | `void` | 为 component 任务关闭 alive 观察 |
79
+ | `on(event, hook)` | `() => void` | 监听指定事件,返回取消监听函数 |
80
+ | `onTask(taskId, event, hook)` | `() => void` | 监听指定任务的指定事件,返回取消监听函数 |
81
+ | `onAny(hook)` | `() => void` | 监听全部事件,返回取消监听函数 |
82
+ | `off(event, hook?)` | `void` | 移除指定事件的一个或全部 hook |
83
+ | `offTask(taskId, event?, hook?)` | `void` | 按任务移除 hook |
84
+ | `offAny(hook)` | `void` | 移除通过 `onAny()` 注册的 hook |
85
+ | `getLogger()` | `ILogger` | 返回当前日志实现 |
86
+
87
+ 重复的任务 ID 不会再次注册,也不会出现在本次 `start()` 返回的 `StartedTasks.tasks` 中。
88
+
89
+ ### Example
59
90
 
91
+ ```ts
60
92
  const makoo = createMakoo({
61
- defaults: {
62
- alive: true,
63
- scope: 'local',
64
- timeout: 5000
65
- },
66
- adapters: [textAdapter]
93
+ adapters: [adapter]
67
94
  });
68
95
 
69
- makoo.start([
70
- inject('#app', {
71
- kind: 'text',
72
- text: 'Hello from Makoo core'
73
- })
96
+ const started = makoo.start([
97
+ inject({ injectAt: '#app', artifact })
74
98
  ]);
75
99
  ```
76
100
 
77
- ## 运行时基础
101
+ ## `inject()`
78
102
 
79
- `inject()` 和 `listen()` 是声明 helper。它们不会触碰 DOM,也不会自己注册任务。`makoo.start([...])` 会注册传入批次里的声明,并立即调度这些任务。
103
+ 创建 component 任务声明。调用 `inject()` 不会注册或启动任务,返回值需要传给
104
+ `MakooRuntime.start()`。
80
105
 
81
- `inject()` 有两种写法。参数形式比较简洁:
106
+ ### Type
82
107
 
83
108
  ```ts
84
- inject('#toolbar', toolbarArtifact, {
85
- alive: true
86
- });
109
+ function inject<TArtifact>(
110
+ input: MakooInjectionInput<TArtifact>
111
+ ): MakooInjectionDeclaration<TArtifact>;
112
+ ```
113
+
114
+ ### Parameters
115
+
116
+ ```ts
117
+ type MakooInjectionInput<TArtifact = unknown> = {
118
+ id?: string;
119
+ injectAt: string;
120
+ artifact: TArtifact;
121
+ options?: ArtifactOptions;
122
+ };
87
123
  ```
88
124
 
89
- 对象形式会把声明字段放在一起。里面可选的 `id` 会作为任务 ID,适合后续需要查找或控制这个任务的场景:
125
+ `id` 省略时,运行时会根据 artifact 和 `injectAt` 生成任务 ID。
126
+
127
+ #### `ArtifactOptions`
128
+
129
+ | 字段 | 类型 | 说明 |
130
+ | --- | --- | --- |
131
+ | `alive` | `boolean` | 是否在目标被替换后尝试重新挂载 |
132
+ | `scope` | `'local' \| 'global'` | alive 观察范围 |
133
+ | `timeout` | `number` | 等待目标元素的毫秒数 |
134
+ | `on` | `MakooListenerDeclaration` | 随 component 一起注册的事件监听 |
135
+ | `hooks` | `LifecycleHookMap` | 当前任务的生命周期 hooks |
136
+
137
+ ### Returns
138
+
139
+ 返回 `MakooInjectionDeclaration<TArtifact>`。
140
+
141
+ ### Example
90
142
 
91
143
  ```ts
92
- inject({
144
+ const declaration = inject({
93
145
  id: 'settings-panel',
94
146
  injectAt: '#settings',
95
- artifact: settingsArtifact,
147
+ artifact: settingsPanel,
96
148
  options: {
97
- alive: true
149
+ alive: true,
150
+ scope: 'global'
98
151
  }
99
152
  });
100
153
  ```
101
154
 
102
- 没有传 `id` 时,Makoo 会根据 artifact 和目标 selector 推导任务 ID。
155
+ ## `listen()`
156
+
157
+ 创建 listener 任务声明。调用 `listen()` 不会注册或启动任务,返回值需要传给
158
+ `MakooRuntime.start()`,或者作为 `ArtifactOptions.on` 使用。
159
+
160
+ ### Type
103
161
 
104
162
  ```ts
105
- import { createMakoo, inject, listen } from '@makoojs/core';
163
+ function listen(input: MakooListenerInput): MakooListenerDeclaration;
164
+ ```
106
165
 
107
- const makoo = createMakoo({
108
- defaults: {
109
- alive: false,
110
- scope: 'local',
111
- timeout: 5000
112
- },
113
- adapters: [myAdapter],
114
- hooks: {
115
- 'start:requested': (event) => {
116
- console.log(event.name);
117
- }
118
- }
166
+ ### Parameters
167
+
168
+ ```ts
169
+ type MakooListenerInput = {
170
+ id?: string;
171
+ listenAt: string;
172
+ type: string;
173
+ callback: EventListener;
174
+ activitySignal?: () => ActivitySignalSource<boolean>;
175
+ };
176
+ ```
177
+
178
+ `id` 省略时,运行时使用 `listener-${listenAt}-${type}` 作为任务 ID。
179
+
180
+ ### Returns
181
+
182
+ 返回 `MakooListenerDeclaration`。它可以作为独立任务启动,也可以赋给 `ArtifactOptions.on`。
183
+
184
+ ### Example
185
+
186
+ ```ts
187
+ const declaration = listen({
188
+ id: 'escape-close',
189
+ listenAt: 'body',
190
+ type: 'keydown',
191
+ callback: onEscape
119
192
  });
193
+ ```
120
194
 
121
- const started = makoo.start([
122
- inject('#toolbar', toolbarArtifact, {
123
- alive: true
124
- }),
125
- inject({
126
- id: 'settings-panel',
127
- injectAt: '#settings',
128
- artifact: settingsArtifact,
129
- options: {
130
- alive: true
131
- }
132
- }),
133
- inject('#save-tip', saveTipArtifact, {
134
- on: listen('#save', 'click', () => {
135
- console.log('save clicked');
136
- })
137
- }),
138
- listen('#escape', 'keydown', onEscape)
139
- ]);
195
+ ## `createObserverHub()`
196
+
197
+ 创建事件中心。`logger` 默认使用 `new Logger()`。
198
+
199
+ ### Type
200
+
201
+ ```ts
202
+ function createObserverHub(logger?: ILogger): ObserverHub;
140
203
  ```
141
204
 
142
- `start()` 返回 `StartedTasks`,用于控制本批次任务:
205
+ ### Parameters
206
+
207
+ - `logger`:可选的 `ILogger`。省略时创建 `Logger`。
208
+
209
+ ### Returns
210
+
211
+ 返回 `ObserverHub`:
212
+
213
+ | 方法 | 返回值 | 说明 |
214
+ | --- | --- | --- |
215
+ | `on(event, hook)` | `() => void` | 注册指定事件的 hook |
216
+ | `onTask(taskId, event, hook)` | `() => void` | 注册指定任务的 hook |
217
+ | `onAny(hook)` | `() => void` | 注册接收全部事件的 hook |
218
+ | `off(event, hook?)` | `void` | 移除指定事件的 hook |
219
+ | `offTask(taskId, event?, hook?)` | `void` | 移除指定任务的 hook |
220
+ | `offAny(hook)` | `void` | 移除一个全局 hook |
221
+ | `clear()` | `void` | 移除全部 hook |
222
+ | `hasHooks(event?)` | `boolean` | 检查全部或指定事件是否存在 hook |
223
+ | `emit(event)` | `void` | 发出事件 |
224
+ | `emitOnTask(taskId, event)` | `void` | 为指定任务发出事件 |
225
+
226
+ 任务事件的调用顺序是:任务 hook、同名事件 hook、`onAny()` hook。
227
+ `stopPropagation()` 会阻止进入下一层;`stopImmediatePropagation()` 还会停止当前层剩余 hook。
228
+ 某个 hook 抛出异常时,异常会写入 logger,其他 hook 继续执行。
229
+
230
+ ### Example
143
231
 
144
232
  ```ts
145
- const toolbar = started.get('Toolbar@#toolbar');
233
+ const observer = createObserverHub();
234
+ const off = observer.on('artifact:mountSuccess', (event) => {
235
+ console.log(event.taskId);
236
+ });
146
237
 
147
- if (toolbar?.kind === 'component') {
148
- toolbar.disableAlive();
149
- toolbar.enableAlive();
150
- }
238
+ off();
239
+ ```
240
+
241
+ ## `createActivityStore()`
242
+
243
+ 创建一个可读取、订阅和修改的状态对象。
244
+
245
+ ### Type
151
246
 
152
- started.destroyAll();
247
+ ```ts
248
+ function createActivityStore<T>(initialValue: T): {
249
+ get(): T;
250
+ subscribe(listener: (value: T) => void): SignalUnsubscribe;
251
+ set(value: T): void;
252
+ update(updater: (value: T) => T): void;
253
+ };
153
254
  ```
154
255
 
155
- `started.destroyAll()` 只影响本次启动产生的任务。`makoo.destroyAll()` 会影响整个运行时中的全部任务。
256
+ ### Parameters
257
+
258
+ - `initialValue`:状态的初始值。
259
+
260
+ ### Returns
261
+
262
+ 返回包含 `get()`、`subscribe()`、`set()` 和 `update()` 的状态对象。
263
+
264
+ ### Details
156
265
 
157
- ## Adapter 协议
266
+ `set()` 或 `update()` 产生的新值与当前值通过 `Object.is()` 比较;值没有变化时不会通知订阅者。
158
267
 
159
- core 不关心 artifact 是 Vue 组件、React 组件还是其他对象。它只要求 adapter 实现统一挂载协议。
268
+ ### Example
160
269
 
161
270
  ```ts
162
- import type { ResolvableMountAdapter } from '@makoojs/core';
271
+ const active = createActivityStore(true);
272
+ const unsubscribe = active.subscribe((value) => {
273
+ console.log(value);
274
+ });
275
+
276
+ active.set(false);
277
+ active.update((value) => !value);
278
+ unsubscribe();
279
+ ```
280
+
281
+ ## `DOMWatcher`
282
+
283
+ ### `DOMWatcher.onDomReady()`
284
+
285
+ 立即查找匹配元素,并通过 `MutationObserver` 监听后续新增元素。
163
286
 
164
- const adapter: ResolvableMountAdapter<MyArtifact, MyHandle, MyInstance> = {
165
- name: 'my-adapter',
166
- matches(artifact): artifact is MyArtifact {
167
- return isMyArtifact(artifact);
168
- },
169
- mount(input) {
170
- return {
171
- handle,
172
- instance
173
- };
174
- },
175
- unmount(input) {
176
- // 根据 input.reason 清理资源。
287
+ #### Type
288
+
289
+ ```ts
290
+ DOMWatcher.onDomReady(
291
+ selector: string,
292
+ callback: (element: HTMLElement, observer?: MutationObserver) => void,
293
+ root: Document | HTMLElement = document,
294
+ options: { once: boolean; timeout?: number } | { once?: boolean; timeout: number },
295
+ runtime?: {
296
+ logger: ILogger;
297
+ emit: (name:
298
+ | 'dom:targetFound'
299
+ | 'dom:targetTimeout'
300
+ | 'dom:targetRemoved'
301
+ | 'dom:targetRestored'
302
+ ) => void;
177
303
  }
178
- };
304
+ ): () => void;
179
305
  ```
180
306
 
181
- `mount(input)` 会收到目标宿主节点、生成的挂载点、artifact、taskId、selector,以及任务级 `makoo` 上下文。
307
+ #### Details
182
308
 
183
- ## Listener 和 activity signal
309
+ - 找到元素时调用 `callback`。
310
+ - `once: true` 会在首次找到元素后停止观察。
311
+ - 设置 `timeout` 后,超时会停止观察。
312
+ - 返回值用于手动停止观察。
184
313
 
185
- 独立监听任务通过 `listen()` 声明。
314
+ ### `DOMWatcher.onDomAlive()`
315
+
316
+ 监听 `target` 被移除,并在 `selector` 对应的新元素出现时调用 `onRestore`。
317
+
318
+ #### Type
186
319
 
187
320
  ```ts
188
- import { createActivityStore, createMakoo, listen } from '@makoojs/core';
321
+ DOMWatcher.onDomAlive(
322
+ target: HTMLElement,
323
+ selector: string,
324
+ onRemove: () => void,
325
+ onRestore: (element: HTMLElement, observer?: MutationObserver) => void,
326
+ root: Document | HTMLElement = document,
327
+ options: { once: boolean; timeout?: number } | { once?: boolean; timeout: number },
328
+ runtime?: {
329
+ logger: ILogger;
330
+ emit: (name:
331
+ | 'dom:targetFound'
332
+ | 'dom:targetTimeout'
333
+ | 'dom:targetRemoved'
334
+ | 'dom:targetRestored'
335
+ ) => void;
336
+ }
337
+ ): () => void;
338
+ ```
189
339
 
190
- const enabled = createActivityStore(true);
191
- const makoo = createMakoo();
340
+ #### Returns
192
341
 
193
- makoo.start([
194
- listen(
195
- '#save',
196
- 'click',
197
- () => {
198
- console.log('save clicked');
199
- },
200
- {
201
- activitySignal: () => enabled
202
- }
203
- )
204
- ]);
342
+ 返回一个停止函数,用于停止移除和恢复观察。
343
+
344
+ ## `Logger`
205
345
 
206
- enabled.set(false);
207
- enabled.set(true);
346
+ Makoo 默认提供的日志实现。
347
+
348
+ ### Type
349
+
350
+ ```ts
351
+ class Logger implements ILogger {
352
+ static readonly PREFIX = '[Makoo]';
353
+
354
+ constructor(level?: LoggerLevel);
355
+ setLevel(level: LoggerLevel): void;
356
+ getLevel(): LoggerLevel;
357
+ log(level: LoggerLevel, message: string, ...args: unknown[]): void;
358
+ debug(message: string, ...args: unknown[]): void;
359
+ info(message: string, ...args: unknown[]): void;
360
+ warn(message: string, ...args: unknown[]): void;
361
+ error(message: string, ...args: unknown[]): void;
362
+ }
208
363
  ```
209
364
 
210
- ## 观察事件
365
+ 默认日志等级为 `info`。等级顺序为 `debug`、`info`、`warn`、`error`;低于当前等级的日志不会输出。
366
+
367
+ ## 错误类
211
368
 
212
- core 会在声明注册、启动、挂载、监听、alive 模式、DOM 观察和任务状态变化时发出观察事件。
369
+ ### `MakooError`
213
370
 
214
371
  ```ts
215
- const off = makoo.on('artifact:mountSuccess', (event) => {
216
- console.log(event.taskId, event.injectAt);
217
- });
372
+ class MakooError extends Error {
373
+ readonly code: string;
374
+ readonly issues: MakooIssue[];
375
+ override readonly cause?: Error;
376
+
377
+ constructor(
378
+ message: string,
379
+ issues?: MakooIssue[],
380
+ code?: string,
381
+ cause?: Error
382
+ );
383
+ }
384
+ ```
218
385
 
219
- makoo.onAny((event, ctrl) => {
220
- if (event.name === 'artifact:mountFail') {
221
- ctrl.stopPropagation();
222
- }
223
- });
386
+ `message` 会添加 `[makoo]` 前缀,并包含 `issues` 和 `cause` 错误链。
224
387
 
225
- off();
388
+ ### `AdapterError`
389
+
390
+ ```ts
391
+ class AdapterError extends MakooError;
226
392
  ```
227
393
 
228
- 常见事件包括:
394
+ 默认错误码:`ErrorCode.ADAPTER_NOT_FOUND`。
229
395
 
230
- - `register:start`
231
- - `register:success`
232
- - `start:requested`
233
- - `start:taskScheduled`
234
- - `artifact:mountStart`
235
- - `artifact:mountSuccess`
236
- - `artifact:mountFail`
237
- - `listener:attached`
238
- - `alive:enabled`
239
- - `alive:observerStarted`
240
- - `task:statusChange`
241
- - `dom:targetFound`
242
- - `dom:targetTimeout`
396
+ ### `SignalError`
243
397
 
244
- 完整事件名列表可从 `OBSERVE_EVENT_NAMES` 获取。
398
+ ```ts
399
+ class SignalError extends MakooError;
400
+ ```
245
401
 
246
- ## DOMWatcher
402
+ 默认错误码:`ErrorCode.TASK_SIGNAL_INVALID`。
247
403
 
248
- `DOMWatcher` 是 core 的底层 DOM 观察工具。通常你不需要直接使用它,因为 `makoo.start()` 和 alive 模式已经封装了目标等待和恢复逻辑。
404
+ ### `TaskError`
249
405
 
250
- ## 日志和错误
406
+ ```ts
407
+ class TaskError extends MakooError;
408
+ ```
409
+
410
+ 默认错误码:`ErrorCode.TASK_NO_REGISTERED`。
411
+
412
+ ## 常量
251
413
 
252
- core 默认使用 `Logger`,并用 `[Makoo]` 前缀打印日志。你可以通过 `createMakoo({ logger })` 传入自定义 logger。
414
+ ### `Action`
253
415
 
254
- core 也导出这些错误相关类型:
416
+ ```ts
417
+ enum Action {
418
+ OPEN = 'OPEN',
419
+ CLOSE = 'CLOSE'
420
+ }
255
421
 
256
- - `MakooError`
257
- - `AdapterError`
258
- - `TaskError`
259
- - `ErrorCode`
260
- - `MakooIssue`
422
+ type ActionEvent = `${Action}`;
423
+ ```
261
424
 
262
- ## Public Exports 概览
425
+ ### `OBSERVE_EVENT_NAMES`
263
426
 
264
- | 分类 | 代表导出 |
427
+ ```ts
428
+ const OBSERVE_EVENT_NAMES = [
429
+ 'register:start',
430
+ 'register:success',
431
+ 'register:duplicate',
432
+ 'register:error',
433
+ 'start:requested',
434
+ 'start:taskScheduled',
435
+ 'start:taskSkipped',
436
+ 'artifact:mountStart',
437
+ 'artifact:mountSuccess',
438
+ 'artifact:mountFail',
439
+ 'listener:attached',
440
+ 'listener:detached',
441
+ 'listener:attachFail',
442
+ 'alive:enabled',
443
+ 'alive:disabled',
444
+ 'alive:observerStarted',
445
+ 'alive:observerStopped',
446
+ 'task:targetReady',
447
+ 'task:statusChange',
448
+ 'task:beforeReset',
449
+ 'task:afterReset',
450
+ 'task:beforeDestroy',
451
+ 'task:afterDestroy',
452
+ 'signal:watcherReleased',
453
+ 'resource:listenerReleased',
454
+ 'artifact:unmounted',
455
+ 'dom:targetFound',
456
+ 'dom:targetTimeout',
457
+ 'dom:targetRemoved',
458
+ 'dom:targetRestored'
459
+ ] as const;
460
+ ```
461
+
462
+ ### `ErrorCode`
463
+
464
+ | 字段 | 值 |
265
465
  | --- | --- |
266
- | 运行时 API | `createMakoo`, `inject`, `listen`, `MakooRuntime`, `StartedTasks` |
267
- | Adapter 协议 | `MountAdapter`, `ResolvableMountAdapter`, `AdapterMountInput`, `AdapterUnmountInput`, `MakooContext` |
268
- | 生命周期观察 | `ObserverHub`, `OBSERVE_EVENT_NAMES`, `ObserveEvent`, `ObserveHook`, `LifecycleHookMap` |
269
- | DOM 观察 | `DOMWatcher` |
270
- | 监听 signal | `createActivityStore`, `ActivitySignalSource` |
271
- | 日志 | `Logger`, `ILogger`, `LoggerLevel` |
272
- | 错误 | `MakooError`, `AdapterError`, `TaskError`, `ErrorCode` |
466
+ | `UNKNOWN` | `MAKOO_UNKNOWN` |
467
+ | `ADAPTER_NOT_FOUND` | `MAKOO_ADAPTER_NOT_FOUND` |
468
+ | `ADAPTER_MOUNT_FAIL` | `MAKOO_ADAPTER_MOUNT_FAIL` |
469
+ | `ADAPTER_UNMOUNT_FAIL` | `MAKOO_ADAPTER_UNMOUNT_FAIL` |
470
+ | `TASK_NO_REGISTERED` | `MAKOO_TASK_NO_REGISTERED` |
471
+ | `TASK_NOT_FOUND` | `MAKOO_TASK_NOT_FOUND` |
472
+ | `TASK_INJECT_FAIL` | `MAKOO_TASK_INJECT_FAIL` |
473
+ | `TASK_ALREADY_MOUNTED` | `MAKOO_TASK_ALREADY_MOUNTED` |
474
+ | `TASK_TARGET_DETACHED` | `MAKOO_TASK_TARGET_DETACHED` |
475
+ | `TASK_LISTENER_ATTACH_FAIL` | `MAKOO_TASK_LISTENER_ATTACH_FAIL` |
476
+ | `TASK_SIGNAL_INVALID` | `MAKOO_TASK_SIGNAL_INVALID` |
477
+ | `TASK_SIGNAL_BIND_FAIL` | `MAKOO_TASK_SIGNAL_BIND_FAIL` |
478
+ | `CLI_SOURCE_DIR_NOT_FOUND` | `MAKOO_CLI_SOURCE_DIR_NOT_FOUND` |
479
+ | `CLI_MANIFEST_LOAD_FAIL` | `MAKOO_CLI_MANIFEST_LOAD_FAIL` |
480
+ | `CLI_MODULE_MANIFEST_LOAD_FAIL` | `MAKOO_CLI_MODULE_MANIFEST_LOAD_FAIL` |
481
+ | `CLI_MANIFEST_NOT_FOUND` | `MAKOO_CLI_MANIFEST_NOT_FOUND` |
482
+ | `CLI_MANIFEST_BINDING_NOT_FOUND` | `MAKOO_CLI_MANIFEST_BINDING_NOT_FOUND` |
483
+ | `CLI_MANIFEST_IMPORT_NOT_FOUND` | `MAKOO_CLI_MANIFEST_IMPORT_NOT_FOUND` |
484
+ | `CLI_FUNCTION_SERIALIZATION_UNSUPPORTED` | `MAKOO_CLI_FUNCTION_SERIALIZATION_UNSUPPORTED` |
485
+ | `CLI_NO_ENABLED_TASKS` | `MAKOO_CLI_NO_ENABLED_TASKS` |
486
+ | `CLI_COMPONENT_NOT_FOUND` | `MAKOO_CLI_COMPONENT_NOT_FOUND` |
487
+ | `CLI_CONFIG_INVALID` | `MAKOO_CLI_CONFIG_INVALID` |
488
+ | `CLI_UNKNOWN_FRAMEWORK` | `MAKOO_CLI_UNKNOWN_FRAMEWORK` |
489
+ | `CLI_UNSUPPORTED_FRAMEWORK` | `MAKOO_CLI_UNSUPPORTED_FRAMEWORK` |
490
+ | `CLI_MODULE_ALREADY_EXISTS` | `MAKOO_CLI_MODULE_ALREADY_EXISTS` |
491
+ | `CLI_MANIFEST_VALIDATION_FAIL` | `MAKOO_CLI_MANIFEST_VALIDATION_FAIL` |
492
+ | `CLI_VITE_CONFIG_NOT_FOUND` | `MAKOO_CLI_VITE_CONFIG_NOT_FOUND` |
493
+ | `CLI_PLUGIN_NOT_FOUND` | `MAKOO_CLI_PLUGIN_NOT_FOUND` |
494
+ | `CLI_RUNTIME_SETUP_NOT_FOUND` | `MAKOO_CLI_RUNTIME_SETUP_NOT_FOUND` |
495
+
496
+ ## Adapter 类型
497
+
498
+ ### `MountAdapter`
499
+
500
+ ```ts
501
+ interface MountAdapter<TArtifact = unknown, THandle = unknown, TInstance = unknown> {
502
+ name: string;
503
+ mount(input: AdapterMountInput<TArtifact>): AdapterMountResult<THandle, TInstance>;
504
+ unmount(input: AdapterUnmountInput<THandle>): void;
505
+ }
506
+ ```
507
+
508
+ ### `ResolvableMountAdapter`
509
+
510
+ ```ts
511
+ interface ResolvableMountAdapter<TArtifact = unknown, THandle = unknown, TInstance = unknown>
512
+ extends MountAdapter<TArtifact, THandle, TInstance> {
513
+ matches(artifact: unknown): artifact is TArtifact;
514
+ }
515
+ ```
516
+
517
+ ### `AdapterMountInput`
518
+
519
+ | 字段 | 类型 |
520
+ | --- | --- |
521
+ | `host` | `HTMLElement` |
522
+ | `mountPoint` | `HTMLElement` |
523
+ | `artifact` | `TArtifact` |
524
+ | `taskId` | `string` |
525
+ | `injectAt` | `string` |
526
+ | `makoo` | `MakooContext` |
527
+
528
+ ### `AdapterMountResult`
529
+
530
+ ```ts
531
+ type AdapterMountResult<THandle = unknown, TInstance = unknown> = {
532
+ handle: THandle;
533
+ instance?: TInstance;
534
+ };
535
+ ```
536
+
537
+ ### `AdapterUnmountInput`
538
+
539
+ | 字段 | 类型 |
540
+ | --- | --- |
541
+ | `host` | `HTMLElement \| undefined` |
542
+ | `mountPoint` | `HTMLElement` |
543
+ | `handle` | `THandle` |
544
+ | `taskId` | `string` |
545
+ | `injectAt` | `string` |
546
+ | `reason` | `AdapterUnmountReason` |
547
+
548
+ ```ts
549
+ type AdapterUnmountReason = 'destroy' | 'reset' | 'remount' | 'manual';
550
+ type AdapterResolver = (artifact: unknown) => MountAdapter | undefined;
551
+ ```
552
+
553
+ ### `MakooContext`
554
+
555
+ ```ts
556
+ type MakooContext = {
557
+ taskId: string;
558
+ injectAt: string;
559
+ enableAlive(): void;
560
+ disableAlive(): void;
561
+ reset(): void;
562
+ destroy(): void;
563
+ on(event: ObserveEventName, hook: ObserveHook): () => void;
564
+ onTask(event: ObserveEventName, hook: ObserveHook): () => void;
565
+ off(event: ObserveEventName, hook?: ObserveHook): void;
566
+ offTask(event?: ObserveEventName, hook?: ObserveHook): void;
567
+ getLogger(): ILogger;
568
+ bindListenerSignal(source: ActivitySignalSource<boolean>): boolean;
569
+ controlListener(event: ActionEvent): boolean;
570
+ };
571
+ ```
572
+
573
+ ## 任务类型
574
+
575
+ ```ts
576
+ type MakooDefaults = {
577
+ alive: boolean;
578
+ scope: 'local' | 'global';
579
+ timeout: number;
580
+ };
581
+
582
+ type MakooInjectionDeclaration<TArtifact = unknown> = {
583
+ kind: 'component';
584
+ id?: string;
585
+ injectAt: string;
586
+ artifact: TArtifact;
587
+ options?: ArtifactOptions;
588
+ };
589
+
590
+ type MakooListenerDeclaration = {
591
+ kind: 'listener';
592
+ id?: string;
593
+ listenAt: string;
594
+ event: string;
595
+ type: string;
596
+ callback: EventListener;
597
+ activitySignal?: () => ActivitySignalSource<boolean>;
598
+ };
599
+
600
+ type MakooTaskDeclaration<TArtifact = unknown> =
601
+ | MakooInjectionDeclaration<TArtifact>
602
+ | MakooListenerDeclaration;
603
+ ```
604
+
605
+ ### `StartedTasks`
606
+
607
+ ```ts
608
+ type StartedComponentTask = {
609
+ kind: 'component';
610
+ taskId: string;
611
+ enableAlive(): void;
612
+ disableAlive(): void;
613
+ reset(): void;
614
+ destroy(): void;
615
+ };
616
+
617
+ type StartedListenerTask = {
618
+ kind: 'listener';
619
+ taskId: string;
620
+ open(): boolean;
621
+ close(): boolean;
622
+ destroy(): void;
623
+ };
624
+
625
+ type StartedTask = StartedComponentTask | StartedListenerTask;
626
+
627
+ type StartedTasks = {
628
+ tasks: StartedTask[];
629
+ get(taskId: string): StartedTask | undefined;
630
+ resetAll(): void;
631
+ destroyAll(): void;
632
+ };
633
+ ```
634
+
635
+ `StartedTasks.resetAll()` 和 `StartedTasks.destroyAll()` 只操作当前 `start()` 返回的任务批次。
636
+
637
+ ### `InjectionConfig`
638
+
639
+ ```ts
640
+ type InjectionConfig = MakooDefaults & {
641
+ logger: ILogger;
642
+ observer?: ObserverHub;
643
+ hooks?: LifecycleHookMap;
644
+ };
645
+ ```
646
+
647
+ ## 观察类型
648
+
649
+ ```ts
650
+ type ObserveEventName = (typeof OBSERVE_EVENT_NAMES)[number];
651
+
652
+ type ObserveEvent = {
653
+ name: ObserveEventName;
654
+ ts: number;
655
+ taskId?: string;
656
+ kind?: 'component' | 'listener';
657
+ injectAt?: string;
658
+ status?: 'idle' | 'pending' | 'active';
659
+ durationMs?: number;
660
+ error?: unknown;
661
+ preStatus?: 'idle' | 'pending' | 'active';
662
+ meta?: Record<string, unknown>;
663
+ };
664
+
665
+ type ObserveHook = (
666
+ event: ObserveEvent,
667
+ ctrl: {
668
+ stopPropagation(): void;
669
+ stopImmediatePropagation(): void;
670
+ }
671
+ ) => void;
672
+
673
+ type LifecycleHookMap = Partial<
674
+ Record<ObserveEventName, ObserveHook | ObserveHook[]>
675
+ >;
676
+ ```
677
+
678
+ ## Signal 类型
679
+
680
+ ```ts
681
+ type SignalUnsubscribe = (() => void) | { unsubscribe(): void };
682
+
683
+ type ActivitySignalSource<T = boolean> = {
684
+ get(): T;
685
+ subscribe(listener: (value: T) => void): SignalUnsubscribe;
686
+ };
687
+
688
+ type ActivitySignalSubscribable<T = boolean> = ActivitySignalSource<T>;
689
+ ```
690
+
691
+ ## 日志类型
692
+
693
+ ```ts
694
+ type LoggerLevel = 'debug' | 'info' | 'warn' | 'error';
695
+
696
+ interface ILogger {
697
+ info(message: string, ...args: unknown[]): void;
698
+ warn(message: string, ...args: unknown[]): void;
699
+ error(message: string, ...args: unknown[]): void;
700
+ debug(message: string, ...args: unknown[]): void;
701
+ }
702
+ ```
703
+
704
+ ## 错误类型
705
+
706
+ ```ts
707
+ type MakooIssue = {
708
+ path: string;
709
+ message: string;
710
+ };
711
+
712
+ type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];
713
+ ```