@makoojs/core 0.2.2 → 0.3.1

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,718 @@
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
+ capture?: boolean;
175
+ activitySignal?: () => ActivitySignalSource<boolean>;
176
+ };
177
+ ```
178
+
179
+ `id` 省略时,运行时使用 `listener-${listenAt}-${type}` 作为任务 ID。
180
+ `capture` 为 `true` 时会在 DOM 捕获阶段监听事件;默认保持浏览器行为,即 `false`,
181
+ 在冒泡阶段监听。listener 使用的 abort signal 仍由 Makoo 内部管理。
182
+
183
+ ### Returns
184
+
185
+ 返回 `MakooListenerDeclaration`。它可以作为独立任务启动,也可以赋给 `ArtifactOptions.on`。
186
+
187
+ ### Example
188
+
189
+ ```ts
190
+ const declaration = listen({
191
+ id: 'escape-close',
192
+ listenAt: 'body',
193
+ type: 'keydown',
194
+ capture: true,
195
+ callback: onEscape
119
196
  });
197
+ ```
120
198
 
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
- ]);
199
+ ## `createObserverHub()`
200
+
201
+ 创建事件中心。`logger` 默认使用 `new Logger()`。
202
+
203
+ ### Type
204
+
205
+ ```ts
206
+ function createObserverHub(logger?: ILogger): ObserverHub;
140
207
  ```
141
208
 
142
- `start()` 返回 `StartedTasks`,用于控制本批次任务:
209
+ ### Parameters
210
+
211
+ - `logger`:可选的 `ILogger`。省略时创建 `Logger`。
212
+
213
+ ### Returns
214
+
215
+ 返回 `ObserverHub`:
216
+
217
+ | 方法 | 返回值 | 说明 |
218
+ | --- | --- | --- |
219
+ | `on(event, hook)` | `() => void` | 注册指定事件的 hook |
220
+ | `onTask(taskId, event, hook)` | `() => void` | 注册指定任务的 hook |
221
+ | `onAny(hook)` | `() => void` | 注册接收全部事件的 hook |
222
+ | `off(event, hook?)` | `void` | 移除指定事件的 hook |
223
+ | `offTask(taskId, event?, hook?)` | `void` | 移除指定任务的 hook |
224
+ | `offAny(hook)` | `void` | 移除一个全局 hook |
225
+ | `clear()` | `void` | 移除全部 hook |
226
+ | `hasHooks(event?)` | `boolean` | 检查全部或指定事件是否存在 hook |
227
+ | `emit(event)` | `void` | 发出事件 |
228
+ | `emitOnTask(taskId, event)` | `void` | 为指定任务发出事件 |
229
+
230
+ 任务事件的调用顺序是:任务 hook、同名事件 hook、`onAny()` hook。
231
+ `stopPropagation()` 会阻止进入下一层;`stopImmediatePropagation()` 还会停止当前层剩余 hook。
232
+ 某个 hook 抛出异常时,异常会写入 logger,其他 hook 继续执行。
233
+
234
+ ### Example
143
235
 
144
236
  ```ts
145
- const toolbar = started.get('Toolbar@#toolbar');
237
+ const observer = createObserverHub();
238
+ const off = observer.on('artifact:mountSuccess', (event) => {
239
+ console.log(event.taskId);
240
+ });
146
241
 
147
- if (toolbar?.kind === 'component') {
148
- toolbar.disableAlive();
149
- toolbar.enableAlive();
150
- }
242
+ off();
243
+ ```
244
+
245
+ ## `createActivityStore()`
246
+
247
+ 创建一个可读取、订阅和修改的状态对象。
248
+
249
+ ### Type
151
250
 
152
- started.destroyAll();
251
+ ```ts
252
+ function createActivityStore<T>(initialValue: T): {
253
+ get(): T;
254
+ subscribe(listener: (value: T) => void): SignalUnsubscribe;
255
+ set(value: T): void;
256
+ update(updater: (value: T) => T): void;
257
+ };
153
258
  ```
154
259
 
155
- `started.destroyAll()` 只影响本次启动产生的任务。`makoo.destroyAll()` 会影响整个运行时中的全部任务。
260
+ ### Parameters
261
+
262
+ - `initialValue`:状态的初始值。
263
+
264
+ ### Returns
265
+
266
+ 返回包含 `get()`、`subscribe()`、`set()` 和 `update()` 的状态对象。
267
+
268
+ ### Details
156
269
 
157
- ## Adapter 协议
270
+ `set()` 或 `update()` 产生的新值与当前值通过 `Object.is()` 比较;值没有变化时不会通知订阅者。
158
271
 
159
- core 不关心 artifact 是 Vue 组件、React 组件还是其他对象。它只要求 adapter 实现统一挂载协议。
272
+ ### Example
160
273
 
161
274
  ```ts
162
- import type { ResolvableMountAdapter } from '@makoojs/core';
275
+ const active = createActivityStore(true);
276
+ const unsubscribe = active.subscribe((value) => {
277
+ console.log(value);
278
+ });
279
+
280
+ active.set(false);
281
+ active.update((value) => !value);
282
+ unsubscribe();
283
+ ```
284
+
285
+ ## `DOMWatcher`
286
+
287
+ ### `DOMWatcher.onDomReady()`
288
+
289
+ 立即查找匹配元素,并通过 `MutationObserver` 监听后续新增元素。
163
290
 
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 清理资源。
291
+ #### Type
292
+
293
+ ```ts
294
+ DOMWatcher.onDomReady(
295
+ selector: string,
296
+ callback: (element: HTMLElement, observer?: MutationObserver) => void,
297
+ root: Document | HTMLElement = document,
298
+ options: { once: boolean; timeout?: number } | { once?: boolean; timeout: number },
299
+ runtime?: {
300
+ logger: ILogger;
301
+ emit: (name:
302
+ | 'dom:targetFound'
303
+ | 'dom:targetTimeout'
304
+ | 'dom:targetRemoved'
305
+ | 'dom:targetRestored'
306
+ ) => void;
177
307
  }
178
- };
308
+ ): () => void;
179
309
  ```
180
310
 
181
- `mount(input)` 会收到目标宿主节点、生成的挂载点、artifact、taskId、selector,以及任务级 `makoo` 上下文。
311
+ #### Details
182
312
 
183
- ## Listener 和 activity signal
313
+ - 找到元素时调用 `callback`。
314
+ - `once: true` 会在首次找到元素后停止观察。
315
+ - 设置 `timeout` 后,超时会停止观察。
316
+ - 返回值用于手动停止观察。
184
317
 
185
- 独立监听任务通过 `listen()` 声明。
318
+ ### `DOMWatcher.onDomAlive()`
319
+
320
+ 监听 `target` 被移除,并在 `selector` 对应的新元素出现时调用 `onRestore`。
321
+
322
+ #### Type
186
323
 
187
324
  ```ts
188
- import { createActivityStore, createMakoo, listen } from '@makoojs/core';
325
+ DOMWatcher.onDomAlive(
326
+ target: HTMLElement,
327
+ selector: string,
328
+ onRemove: () => void,
329
+ onRestore: (element: HTMLElement, observer?: MutationObserver) => void,
330
+ root: Document | HTMLElement = document,
331
+ options: { once: boolean; timeout?: number } | { once?: boolean; timeout: number },
332
+ runtime?: {
333
+ logger: ILogger;
334
+ emit: (name:
335
+ | 'dom:targetFound'
336
+ | 'dom:targetTimeout'
337
+ | 'dom:targetRemoved'
338
+ | 'dom:targetRestored'
339
+ ) => void;
340
+ }
341
+ ): () => void;
342
+ ```
189
343
 
190
- const enabled = createActivityStore(true);
191
- const makoo = createMakoo();
344
+ #### Returns
192
345
 
193
- makoo.start([
194
- listen(
195
- '#save',
196
- 'click',
197
- () => {
198
- console.log('save clicked');
199
- },
200
- {
201
- activitySignal: () => enabled
202
- }
203
- )
204
- ]);
346
+ 返回一个停止函数,用于停止移除和恢复观察。
347
+
348
+ ## `Logger`
205
349
 
206
- enabled.set(false);
207
- enabled.set(true);
350
+ Makoo 默认提供的日志实现。
351
+
352
+ ### Type
353
+
354
+ ```ts
355
+ class Logger implements ILogger {
356
+ static readonly PREFIX = '[Makoo]';
357
+
358
+ constructor(level?: LoggerLevel);
359
+ setLevel(level: LoggerLevel): void;
360
+ getLevel(): LoggerLevel;
361
+ log(level: LoggerLevel, message: string, ...args: unknown[]): void;
362
+ debug(message: string, ...args: unknown[]): void;
363
+ info(message: string, ...args: unknown[]): void;
364
+ warn(message: string, ...args: unknown[]): void;
365
+ error(message: string, ...args: unknown[]): void;
366
+ }
208
367
  ```
209
368
 
210
- ## 观察事件
369
+ 默认日志等级为 `info`。等级顺序为 `debug`、`info`、`warn`、`error`;低于当前等级的日志不会输出。
370
+
371
+ ## 错误类
211
372
 
212
- core 会在声明注册、启动、挂载、监听、alive 模式、DOM 观察和任务状态变化时发出观察事件。
373
+ ### `MakooError`
213
374
 
214
375
  ```ts
215
- const off = makoo.on('artifact:mountSuccess', (event) => {
216
- console.log(event.taskId, event.injectAt);
217
- });
376
+ class MakooError extends Error {
377
+ readonly code: string;
378
+ readonly issues: MakooIssue[];
379
+ override readonly cause?: Error;
380
+
381
+ constructor(
382
+ message: string,
383
+ issues?: MakooIssue[],
384
+ code?: string,
385
+ cause?: Error
386
+ );
387
+ }
388
+ ```
218
389
 
219
- makoo.onAny((event, ctrl) => {
220
- if (event.name === 'artifact:mountFail') {
221
- ctrl.stopPropagation();
222
- }
223
- });
390
+ `message` 会添加 `[makoo]` 前缀,并包含 `issues` 和 `cause` 错误链。
224
391
 
225
- off();
392
+ ### `AdapterError`
393
+
394
+ ```ts
395
+ class AdapterError extends MakooError;
226
396
  ```
227
397
 
228
- 常见事件包括:
398
+ 默认错误码:`ErrorCode.ADAPTER_NOT_FOUND`。
229
399
 
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`
400
+ ### `SignalError`
243
401
 
244
- 完整事件名列表可从 `OBSERVE_EVENT_NAMES` 获取。
402
+ ```ts
403
+ class SignalError extends MakooError;
404
+ ```
245
405
 
246
- ## DOMWatcher
406
+ 默认错误码:`ErrorCode.TASK_SIGNAL_INVALID`。
247
407
 
248
- `DOMWatcher` 是 core 的底层 DOM 观察工具。通常你不需要直接使用它,因为 `makoo.start()` 和 alive 模式已经封装了目标等待和恢复逻辑。
408
+ ### `TaskError`
249
409
 
250
- ## 日志和错误
410
+ ```ts
411
+ class TaskError extends MakooError;
412
+ ```
413
+
414
+ 默认错误码:`ErrorCode.TASK_NO_REGISTERED`。
415
+
416
+ ## 常量
251
417
 
252
- core 默认使用 `Logger`,并用 `[Makoo]` 前缀打印日志。你可以通过 `createMakoo({ logger })` 传入自定义 logger。
418
+ ### `Action`
253
419
 
254
- core 也导出这些错误相关类型:
420
+ ```ts
421
+ enum Action {
422
+ OPEN = 'OPEN',
423
+ CLOSE = 'CLOSE'
424
+ }
255
425
 
256
- - `MakooError`
257
- - `AdapterError`
258
- - `TaskError`
259
- - `ErrorCode`
260
- - `MakooIssue`
426
+ type ActionEvent = `${Action}`;
427
+ ```
261
428
 
262
- ## Public Exports 概览
429
+ ### `OBSERVE_EVENT_NAMES`
263
430
 
264
- | 分类 | 代表导出 |
431
+ ```ts
432
+ const OBSERVE_EVENT_NAMES = [
433
+ 'register:start',
434
+ 'register:success',
435
+ 'register:duplicate',
436
+ 'register:error',
437
+ 'start:requested',
438
+ 'start:taskScheduled',
439
+ 'start:taskSkipped',
440
+ 'artifact:mountStart',
441
+ 'artifact:mountSuccess',
442
+ 'artifact:mountFail',
443
+ 'listener:attached',
444
+ 'listener:detached',
445
+ 'listener:attachFail',
446
+ 'alive:enabled',
447
+ 'alive:disabled',
448
+ 'alive:observerStarted',
449
+ 'alive:observerStopped',
450
+ 'task:targetReady',
451
+ 'task:statusChange',
452
+ 'task:beforeReset',
453
+ 'task:afterReset',
454
+ 'task:beforeDestroy',
455
+ 'task:afterDestroy',
456
+ 'signal:watcherReleased',
457
+ 'resource:listenerReleased',
458
+ 'artifact:unmounted',
459
+ 'dom:targetFound',
460
+ 'dom:targetTimeout',
461
+ 'dom:targetRemoved',
462
+ 'dom:targetRestored'
463
+ ] as const;
464
+ ```
465
+
466
+ ### `ErrorCode`
467
+
468
+ | 字段 | 值 |
265
469
  | --- | --- |
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` |
470
+ | `UNKNOWN` | `MAKOO_UNKNOWN` |
471
+ | `ADAPTER_NOT_FOUND` | `MAKOO_ADAPTER_NOT_FOUND` |
472
+ | `ADAPTER_MOUNT_FAIL` | `MAKOO_ADAPTER_MOUNT_FAIL` |
473
+ | `ADAPTER_UNMOUNT_FAIL` | `MAKOO_ADAPTER_UNMOUNT_FAIL` |
474
+ | `TASK_NO_REGISTERED` | `MAKOO_TASK_NO_REGISTERED` |
475
+ | `TASK_NOT_FOUND` | `MAKOO_TASK_NOT_FOUND` |
476
+ | `TASK_INJECT_FAIL` | `MAKOO_TASK_INJECT_FAIL` |
477
+ | `TASK_ALREADY_MOUNTED` | `MAKOO_TASK_ALREADY_MOUNTED` |
478
+ | `TASK_TARGET_DETACHED` | `MAKOO_TASK_TARGET_DETACHED` |
479
+ | `TASK_LISTENER_ATTACH_FAIL` | `MAKOO_TASK_LISTENER_ATTACH_FAIL` |
480
+ | `TASK_SIGNAL_INVALID` | `MAKOO_TASK_SIGNAL_INVALID` |
481
+ | `TASK_SIGNAL_BIND_FAIL` | `MAKOO_TASK_SIGNAL_BIND_FAIL` |
482
+ | `CLI_SOURCE_DIR_NOT_FOUND` | `MAKOO_CLI_SOURCE_DIR_NOT_FOUND` |
483
+ | `CLI_MANIFEST_LOAD_FAIL` | `MAKOO_CLI_MANIFEST_LOAD_FAIL` |
484
+ | `CLI_MODULE_MANIFEST_LOAD_FAIL` | `MAKOO_CLI_MODULE_MANIFEST_LOAD_FAIL` |
485
+ | `CLI_MANIFEST_NOT_FOUND` | `MAKOO_CLI_MANIFEST_NOT_FOUND` |
486
+ | `CLI_MANIFEST_BINDING_NOT_FOUND` | `MAKOO_CLI_MANIFEST_BINDING_NOT_FOUND` |
487
+ | `CLI_MANIFEST_IMPORT_NOT_FOUND` | `MAKOO_CLI_MANIFEST_IMPORT_NOT_FOUND` |
488
+ | `CLI_FUNCTION_SERIALIZATION_UNSUPPORTED` | `MAKOO_CLI_FUNCTION_SERIALIZATION_UNSUPPORTED` |
489
+ | `CLI_NO_ENABLED_TASKS` | `MAKOO_CLI_NO_ENABLED_TASKS` |
490
+ | `CLI_COMPONENT_NOT_FOUND` | `MAKOO_CLI_COMPONENT_NOT_FOUND` |
491
+ | `CLI_CONFIG_INVALID` | `MAKOO_CLI_CONFIG_INVALID` |
492
+ | `CLI_UNKNOWN_FRAMEWORK` | `MAKOO_CLI_UNKNOWN_FRAMEWORK` |
493
+ | `CLI_UNSUPPORTED_FRAMEWORK` | `MAKOO_CLI_UNSUPPORTED_FRAMEWORK` |
494
+ | `CLI_MODULE_ALREADY_EXISTS` | `MAKOO_CLI_MODULE_ALREADY_EXISTS` |
495
+ | `CLI_MANIFEST_VALIDATION_FAIL` | `MAKOO_CLI_MANIFEST_VALIDATION_FAIL` |
496
+ | `CLI_VITE_CONFIG_NOT_FOUND` | `MAKOO_CLI_VITE_CONFIG_NOT_FOUND` |
497
+ | `CLI_PLUGIN_NOT_FOUND` | `MAKOO_CLI_PLUGIN_NOT_FOUND` |
498
+ | `CLI_RUNTIME_SETUP_NOT_FOUND` | `MAKOO_CLI_RUNTIME_SETUP_NOT_FOUND` |
499
+
500
+ ## Adapter 类型
501
+
502
+ ### `MountAdapter`
503
+
504
+ ```ts
505
+ interface MountAdapter<TArtifact = unknown, THandle = unknown, TInstance = unknown> {
506
+ name: string;
507
+ mount(input: AdapterMountInput<TArtifact>): AdapterMountResult<THandle, TInstance>;
508
+ unmount(input: AdapterUnmountInput<THandle>): void;
509
+ }
510
+ ```
511
+
512
+ ### `ResolvableMountAdapter`
513
+
514
+ ```ts
515
+ interface ResolvableMountAdapter<TArtifact = unknown, THandle = unknown, TInstance = unknown>
516
+ extends MountAdapter<TArtifact, THandle, TInstance> {
517
+ matches(artifact: unknown): artifact is TArtifact;
518
+ }
519
+ ```
520
+
521
+ ### `AdapterMountInput`
522
+
523
+ | 字段 | 类型 |
524
+ | --- | --- |
525
+ | `host` | `HTMLElement` |
526
+ | `mountPoint` | `HTMLElement` |
527
+ | `artifact` | `TArtifact` |
528
+ | `taskId` | `string` |
529
+ | `injectAt` | `string` |
530
+ | `makoo` | `MakooContext` |
531
+
532
+ ### `AdapterMountResult`
533
+
534
+ ```ts
535
+ type AdapterMountResult<THandle = unknown, TInstance = unknown> = {
536
+ handle: THandle;
537
+ instance?: TInstance;
538
+ };
539
+ ```
540
+
541
+ ### `AdapterUnmountInput`
542
+
543
+ | 字段 | 类型 |
544
+ | --- | --- |
545
+ | `host` | `HTMLElement \| undefined` |
546
+ | `mountPoint` | `HTMLElement` |
547
+ | `handle` | `THandle` |
548
+ | `taskId` | `string` |
549
+ | `injectAt` | `string` |
550
+ | `reason` | `AdapterUnmountReason` |
551
+
552
+ ```ts
553
+ type AdapterUnmountReason = 'destroy' | 'reset' | 'remount' | 'manual';
554
+ type AdapterResolver = (artifact: unknown) => MountAdapter | undefined;
555
+ ```
556
+
557
+ ### `MakooContext`
558
+
559
+ ```ts
560
+ type MakooContext = {
561
+ taskId: string;
562
+ injectAt: string;
563
+ enableAlive(): void;
564
+ disableAlive(): void;
565
+ reset(): void;
566
+ destroy(): void;
567
+ on(event: ObserveEventName, hook: ObserveHook): () => void;
568
+ onTask(event: ObserveEventName, hook: ObserveHook): () => void;
569
+ off(event: ObserveEventName, hook?: ObserveHook): void;
570
+ offTask(event?: ObserveEventName, hook?: ObserveHook): void;
571
+ getLogger(): ILogger;
572
+ bindListenerSignal(source: ActivitySignalSource<boolean>): boolean;
573
+ controlListener(event: ActionEvent): boolean;
574
+ };
575
+ ```
576
+
577
+ ## 任务类型
578
+
579
+ ```ts
580
+ type MakooDefaults = {
581
+ alive: boolean;
582
+ scope: 'local' | 'global';
583
+ timeout: number;
584
+ };
585
+
586
+ type MakooInjectionDeclaration<TArtifact = unknown> = {
587
+ kind: 'component';
588
+ id?: string;
589
+ injectAt: string;
590
+ artifact: TArtifact;
591
+ options?: ArtifactOptions;
592
+ };
593
+
594
+ type MakooListenerDeclaration = {
595
+ kind: 'listener';
596
+ id?: string;
597
+ listenAt: string;
598
+ event: string;
599
+ type: string;
600
+ callback: EventListener;
601
+ capture?: boolean;
602
+ activitySignal?: () => ActivitySignalSource<boolean>;
603
+ };
604
+
605
+ type MakooTaskDeclaration<TArtifact = unknown> =
606
+ | MakooInjectionDeclaration<TArtifact>
607
+ | MakooListenerDeclaration;
608
+ ```
609
+
610
+ ### `StartedTasks`
611
+
612
+ ```ts
613
+ type StartedComponentTask = {
614
+ kind: 'component';
615
+ taskId: string;
616
+ enableAlive(): void;
617
+ disableAlive(): void;
618
+ reset(): void;
619
+ destroy(): void;
620
+ };
621
+
622
+ type StartedListenerTask = {
623
+ kind: 'listener';
624
+ taskId: string;
625
+ open(): boolean;
626
+ close(): boolean;
627
+ destroy(): void;
628
+ };
629
+
630
+ type StartedTask = StartedComponentTask | StartedListenerTask;
631
+
632
+ type StartedTasks = {
633
+ tasks: StartedTask[];
634
+ get(taskId: string): StartedTask | undefined;
635
+ resetAll(): void;
636
+ destroyAll(): void;
637
+ };
638
+ ```
639
+
640
+ `StartedTasks.resetAll()` 和 `StartedTasks.destroyAll()` 只操作当前 `start()` 返回的任务批次。
641
+
642
+ ### `InjectionConfig`
643
+
644
+ ```ts
645
+ type InjectionConfig = MakooDefaults & {
646
+ logger: ILogger;
647
+ observer?: ObserverHub;
648
+ hooks?: LifecycleHookMap;
649
+ };
650
+ ```
651
+
652
+ ## 观察类型
653
+
654
+ ```ts
655
+ type ObserveEventName = (typeof OBSERVE_EVENT_NAMES)[number];
656
+
657
+ type ObserveEvent = {
658
+ name: ObserveEventName;
659
+ ts: number;
660
+ taskId?: string;
661
+ kind?: 'component' | 'listener';
662
+ injectAt?: string;
663
+ status?: 'idle' | 'pending' | 'active';
664
+ durationMs?: number;
665
+ error?: unknown;
666
+ preStatus?: 'idle' | 'pending' | 'active';
667
+ meta?: Record<string, unknown>;
668
+ };
669
+
670
+ type ObserveHook = (
671
+ event: ObserveEvent,
672
+ ctrl: {
673
+ stopPropagation(): void;
674
+ stopImmediatePropagation(): void;
675
+ }
676
+ ) => void;
677
+
678
+ type LifecycleHookMap = Partial<
679
+ Record<ObserveEventName, ObserveHook | ObserveHook[]>
680
+ >;
681
+ ```
682
+
683
+ ## Signal 类型
684
+
685
+ ```ts
686
+ type SignalUnsubscribe = (() => void) | { unsubscribe(): void };
687
+
688
+ type ActivitySignalSource<T = boolean> = {
689
+ get(): T;
690
+ subscribe(listener: (value: T) => void): SignalUnsubscribe;
691
+ };
692
+
693
+ type ActivitySignalSubscribable<T = boolean> = ActivitySignalSource<T>;
694
+ ```
695
+
696
+ ## 日志类型
697
+
698
+ ```ts
699
+ type LoggerLevel = 'debug' | 'info' | 'warn' | 'error';
700
+
701
+ interface ILogger {
702
+ info(message: string, ...args: unknown[]): void;
703
+ warn(message: string, ...args: unknown[]): void;
704
+ error(message: string, ...args: unknown[]): void;
705
+ debug(message: string, ...args: unknown[]): void;
706
+ }
707
+ ```
708
+
709
+ ## 错误类型
710
+
711
+ ```ts
712
+ type MakooIssue = {
713
+ path: string;
714
+ message: string;
715
+ };
716
+
717
+ type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];
718
+ ```