@makoojs/core 0.3.0 → 0.4.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,713 +1,287 @@
1
- # 核心 API
1
+ # @makoojs/core
2
2
 
3
- ## API 索引
3
+ `@makoojs/core` 是 Makoo 的框架无关运行时核心。它负责声明注入任务、启动任务批次、等待目标 DOM、挂载 artifact、管理 alive 重新注入、绑定事件监听,并提供生命周期观察、日志和错误基础设施。
4
4
 
5
- ### 任务
5
+ > [!NOTE]
6
+ > `@makoojs/core` 提供 Makoo 的公共运行时协议,其他 Makoo 包会直接或间接使用这里的类型和能力。
6
7
 
7
- - [`createMakoo()`](#createmakoo):创建运行时
8
- - [`inject()`](#inject):声明 component 任务
9
- - [`listen()`](#listen):声明 listener 任务
8
+ ## 使用场景
10
9
 
11
- ### 观察和状态
10
+ - 编写自定义 `ResolvableMountAdapter`,让 Makoo 挂载新的 artifact 类型。
11
+ - 使用 `createMakoo()` 创建运行时,并显式启动任务声明。
12
+ - 监听注入生命周期事件,用于调试、埋点、错误上报或可视化开发工具。
13
+ - 使用 `DOMWatcher`、`createActivityStore` 等底层工具构建自定义运行时集成。
12
14
 
13
- - [`createObserverHub()`](#createobserverhub):创建生命周期事件中心
14
- - [`createActivityStore()`](#createactivitystore):创建可订阅状态
15
- - [`DOMWatcher`](#domwatcher):观察 DOM 目标
15
+ ## 安装
16
16
 
17
- ### 基础能力
18
-
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;
17
+ ```bash
18
+ # npm install @makoojs/core
19
+ # yarn add @makoojs/core
20
+ pnpm add @makoojs/core
40
21
  ```
41
22
 
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` 的最终默认值:
23
+ ## 最小运行时示例
57
24
 
58
25
  ```ts
59
- {
60
- alive: false,
61
- scope: 'local',
62
- timeout: 5000
63
- }
64
- ```
65
-
66
- ### Returns
67
-
68
- 返回 `MakooRuntime`:
26
+ import {
27
+ createMakoo,
28
+ inject,
29
+ type ResolvableMountAdapter
30
+ } from '@makoojs/core';
69
31
 
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` 中。
32
+ type TextArtifact = {
33
+ kind: 'text';
34
+ text: string;
35
+ };
88
36
 
89
- ### Example
37
+ const textAdapter: ResolvableMountAdapter<TextArtifact, HTMLElement> = {
38
+ name: 'text',
39
+ matches(artifact): artifact is TextArtifact {
40
+ return (
41
+ typeof artifact === 'object' &&
42
+ artifact !== null &&
43
+ (artifact as { kind?: unknown }).kind === 'text'
44
+ );
45
+ },
46
+ mount({ mountPoint, artifact }) {
47
+ const el = document.createElement('span');
48
+ el.textContent = artifact.text;
49
+ mountPoint.appendChild(el);
50
+
51
+ return { handle: el };
52
+ },
53
+ unmount({ handle }) {
54
+ handle.remove();
55
+ }
56
+ };
90
57
 
91
- ```ts
92
58
  const makoo = createMakoo({
93
- adapters: [adapter]
59
+ defaults: {
60
+ alive: true,
61
+ scope: 'local',
62
+ timeout: 5000
63
+ },
64
+ adapters: [textAdapter]
94
65
  });
95
66
 
96
- const started = makoo.start([
97
- inject({ injectAt: '#app', artifact })
67
+ makoo.start([
68
+ inject({
69
+ id: 'text',
70
+ injectAt: '#app',
71
+ artifact: {
72
+ kind: 'text',
73
+ text: 'Hello from Makoo core'
74
+ }
75
+ })
98
76
  ]);
99
77
  ```
100
78
 
101
- ## `inject()`
102
-
103
- 创建 component 任务声明。调用 `inject()` 不会注册或启动任务,返回值需要传给
104
- `MakooRuntime.start()`。
105
-
106
- ### Type
107
-
108
- ```ts
109
- function inject<TArtifact>(
110
- input: MakooInjectionInput<TArtifact>
111
- ): MakooInjectionDeclaration<TArtifact>;
112
- ```
113
-
114
- ### Parameters
79
+ ## 运行时基础
115
80
 
116
- ```ts
117
- type MakooInjectionInput<TArtifact = unknown> = {
118
- id?: string;
119
- injectAt: string;
120
- artifact: TArtifact;
121
- options?: ArtifactOptions;
122
- };
123
- ```
81
+ `inject()` 和 `listen()` 用于声明任务。它们不会触碰 DOM,也不会自己注册任务。`makoo.start([...])` 会注册传入批次里的声明,并立即调度这些任务。
124
82
 
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
83
+ `inject()` 接收包含目标、artifact 和任务选项的对象。可选的 `id` 会作为任务 ID,适合后续需要查找或控制这个任务的场景:
142
84
 
143
85
  ```ts
144
- const declaration = inject({
86
+ inject({
145
87
  id: 'settings-panel',
146
88
  injectAt: '#settings',
147
- artifact: settingsPanel,
89
+ artifact: settingsArtifact,
148
90
  options: {
149
- alive: true,
150
- scope: 'global'
91
+ alive: true
151
92
  }
152
93
  });
153
94
  ```
154
95
 
155
- ## `listen()`
156
-
157
- 创建 listener 任务声明。调用 `listen()` 不会注册或启动任务,返回值需要传给
158
- `MakooRuntime.start()`,或者作为 `ArtifactOptions.on` 使用。
159
-
160
- ### Type
161
-
162
- ```ts
163
- function listen(input: MakooListenerInput): MakooListenerDeclaration;
164
- ```
165
-
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
192
- });
193
- ```
194
-
195
- ## `createObserverHub()`
196
-
197
- 创建事件中心。`logger` 默认使用 `new Logger()`。
198
-
199
- ### Type
200
-
201
- ```ts
202
- function createObserverHub(logger?: ILogger): ObserverHub;
203
- ```
204
-
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
231
-
232
- ```ts
233
- const observer = createObserverHub();
234
- const off = observer.on('artifact:mountSuccess', (event) => {
235
- console.log(event.taskId);
236
- });
237
-
238
- off();
239
- ```
240
-
241
- ## `createActivityStore()`
242
-
243
- 创建一个可读取、订阅和修改的状态对象。
244
-
245
- ### Type
246
-
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
- };
254
- ```
255
-
256
- ### Parameters
257
-
258
- - `initialValue`:状态的初始值。
259
-
260
- ### Returns
261
-
262
- 返回包含 `get()`、`subscribe()`、`set()` 和 `update()` 的状态对象。
263
-
264
- ### Details
265
-
266
- `set()` 或 `update()` 产生的新值与当前值通过 `Object.is()` 比较;值没有变化时不会通知订阅者。
267
-
268
- ### Example
269
-
270
- ```ts
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` 监听后续新增元素。
286
-
287
- #### Type
96
+ 没有传 `id` 时,Makoo 会根据 artifact 和目标 selector 推导任务 ID。
288
97
 
289
98
  ```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;
303
- }
304
- ): () => void;
305
- ```
99
+ import { createMakoo, inject, listen } from '@makoojs/core';
306
100
 
307
- #### Details
308
-
309
- - 找到元素时调用 `callback`。
310
- - `once: true` 会在首次找到元素后停止观察。
311
- - 设置 `timeout` 后,超时会停止观察。
312
- - 返回值用于手动停止观察。
313
-
314
- ### `DOMWatcher.onDomAlive()`
315
-
316
- 监听 `target` 被移除,并在 `selector` 对应的新元素出现时调用 `onRestore`。
317
-
318
- #### Type
319
-
320
- ```ts
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;
101
+ const makoo = createMakoo({
102
+ defaults: {
103
+ alive: false,
104
+ scope: 'local',
105
+ timeout: 5000
106
+ },
107
+ adapters: [myAdapter],
108
+ hooks: {
109
+ 'start:requested': (event) => {
110
+ console.log(event.name);
111
+ }
336
112
  }
337
- ): () => void;
338
- ```
339
-
340
- #### Returns
341
-
342
- 返回一个停止函数,用于停止移除和恢复观察。
343
-
344
- ## `Logger`
345
-
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
- }
363
- ```
364
-
365
- 默认日志等级为 `info`。等级顺序为 `debug`、`info`、`warn`、`error`;低于当前等级的日志不会输出。
366
-
367
- ## 错误类
368
-
369
- ### `MakooError`
370
-
371
- ```ts
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
- ```
385
-
386
- `message` 会添加 `[makoo]` 前缀,并包含 `issues` 和 `cause` 错误链。
387
-
388
- ### `AdapterError`
389
-
390
- ```ts
391
- class AdapterError extends MakooError;
392
- ```
393
-
394
- 默认错误码:`ErrorCode.ADAPTER_NOT_FOUND`。
395
-
396
- ### `SignalError`
397
-
398
- ```ts
399
- class SignalError extends MakooError;
400
- ```
401
-
402
- 默认错误码:`ErrorCode.TASK_SIGNAL_INVALID`。
403
-
404
- ### `TaskError`
405
-
406
- ```ts
407
- class TaskError extends MakooError;
408
- ```
409
-
410
- 默认错误码:`ErrorCode.TASK_NO_REGISTERED`。
411
-
412
- ## 常量
413
-
414
- ### `Action`
415
-
416
- ```ts
417
- enum Action {
418
- OPEN = 'OPEN',
419
- CLOSE = 'CLOSE'
420
- }
113
+ });
421
114
 
422
- type ActionEvent = `${Action}`;
115
+ const started = makoo.start([
116
+ inject({
117
+ id: 'toolbar',
118
+ injectAt: '#toolbar',
119
+ artifact: toolbarArtifact,
120
+ options: {
121
+ alive: true
122
+ }
123
+ }),
124
+ inject({
125
+ id: 'settings-panel',
126
+ injectAt: '#settings',
127
+ artifact: settingsArtifact,
128
+ options: {
129
+ alive: true
130
+ }
131
+ }),
132
+ inject({
133
+ id: 'save-tip',
134
+ injectAt: '#save-tip',
135
+ artifact: saveTipArtifact,
136
+ options: {
137
+ on: listen({
138
+ listenAt: '#save',
139
+ type: 'click',
140
+ callback: () => {
141
+ console.log('save clicked');
142
+ }
143
+ })
144
+ }
145
+ }),
146
+ listen({
147
+ id: 'escape-close',
148
+ listenAt: '#escape',
149
+ type: 'keydown',
150
+ callback: onEscape
151
+ })
152
+ ]);
423
153
  ```
424
154
 
425
- ### `OBSERVE_EVENT_NAMES`
155
+ `start()` 返回 `StartedTasks`,用于控制本批次任务:
426
156
 
427
157
  ```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`
158
+ const toolbar = started.get('toolbar');
463
159
 
464
- | 字段 | 值 |
465
- | --- | --- |
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;
160
+ if (toolbar?.kind === 'component') {
161
+ toolbar.disableAlive();
162
+ toolbar.enableAlive();
505
163
  }
506
- ```
507
164
 
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
- }
165
+ started.destroyAll();
515
166
  ```
516
167
 
517
- ### `AdapterMountInput`
168
+ `started.destroyAll()` 只影响本次启动产生的任务。`makoo.destroyAll()` 会影响整个运行时中的全部任务。
518
169
 
519
- | 字段 | 类型 |
520
- | --- | --- |
521
- | `host` | `HTMLElement` |
522
- | `mountPoint` | `HTMLElement` |
523
- | `artifact` | `TArtifact` |
524
- | `taskId` | `string` |
525
- | `injectAt` | `string` |
526
- | `makoo` | `MakooContext` |
170
+ ## Adapter 协议
527
171
 
528
- ### `AdapterMountResult`
172
+ core 不关心 artifact 是 Vue 组件、React 组件还是其他对象。它只要求 adapter 实现统一挂载协议。
529
173
 
530
174
  ```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` |
175
+ import type { ResolvableMountAdapter } from '@makoojs/core';
547
176
 
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;
177
+ const adapter: ResolvableMountAdapter<MyArtifact, MyHandle, MyInstance> = {
178
+ name: 'my-adapter',
179
+ matches(artifact): artifact is MyArtifact {
180
+ return isMyArtifact(artifact);
181
+ },
182
+ mount(input) {
183
+ return {
184
+ handle,
185
+ instance
186
+ };
187
+ },
188
+ unmount(input) {
189
+ // 根据 input.reason 清理资源。
190
+ }
570
191
  };
571
192
  ```
572
193
 
573
- ## 任务类型
194
+ `mount(input)` 会收到目标宿主节点、生成的挂载点、artifact、taskId、selector,以及任务级 `makoo` 上下文。
574
195
 
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
- };
196
+ ## Listener 和 activity signal
599
197
 
600
- type MakooTaskDeclaration<TArtifact = unknown> =
601
- | MakooInjectionDeclaration<TArtifact>
602
- | MakooListenerDeclaration;
603
- ```
198
+ 独立监听任务使用 `listen()` 的对象形式声明。可选的 `id` 是任务 ID;后续需要稳定地查找或控制任务时应提供它。组件的 `on` listener 归属于组件任务本身,不需要单独的 ID。
604
199
 
605
- ### `StartedTasks`
200
+ `capture` 默认为 `false`;设置为 `true` 后,监听器会在 DOM 捕获阶段执行。
606
201
 
607
202
  ```ts
608
- type StartedComponentTask = {
609
- kind: 'component';
610
- taskId: string;
611
- enableAlive(): void;
612
- disableAlive(): void;
613
- reset(): void;
614
- destroy(): void;
615
- };
203
+ import { createActivityStore, createMakoo, listen } from '@makoojs/core';
616
204
 
617
- type StartedListenerTask = {
618
- kind: 'listener';
619
- taskId: string;
620
- open(): boolean;
621
- close(): boolean;
622
- destroy(): void;
623
- };
205
+ const enabled = createActivityStore(true);
206
+ const makoo = createMakoo();
624
207
 
625
- type StartedTask = StartedComponentTask | StartedListenerTask;
208
+ makoo.start([
209
+ listen({
210
+ id: 'save-listener',
211
+ listenAt: '#save',
212
+ type: 'click',
213
+ callback: () => {
214
+ console.log('save clicked');
215
+ },
216
+ activitySignal: () => enabled
217
+ })
218
+ ]);
626
219
 
627
- type StartedTasks = {
628
- tasks: StartedTask[];
629
- get(taskId: string): StartedTask | undefined;
630
- resetAll(): void;
631
- destroyAll(): void;
632
- };
220
+ enabled.set(false);
221
+ enabled.set(true);
633
222
  ```
634
223
 
635
- `StartedTasks.resetAll()` 和 `StartedTasks.destroyAll()` 只操作当前 `start()` 返回的任务批次。
224
+ ## 观察事件
636
225
 
637
- ### `InjectionConfig`
226
+ core 会在声明注册、启动、挂载、监听、alive 模式、DOM 观察和任务状态变化时发出观察事件。
638
227
 
639
228
  ```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
- };
229
+ const off = makoo.on('artifact:mountSuccess', (event) => {
230
+ console.log(event.taskId, event.injectAt);
231
+ });
664
232
 
665
- type ObserveHook = (
666
- event: ObserveEvent,
667
- ctrl: {
668
- stopPropagation(): void;
669
- stopImmediatePropagation(): void;
233
+ makoo.onAny((event, ctrl) => {
234
+ if (event.name === 'artifact:mountFail') {
235
+ ctrl.stopPropagation();
670
236
  }
671
- ) => void;
237
+ });
672
238
 
673
- type LifecycleHookMap = Partial<
674
- Record<ObserveEventName, ObserveHook | ObserveHook[]>
675
- >;
239
+ off();
676
240
  ```
677
241
 
678
- ## Signal 类型
242
+ 常见事件包括:
679
243
 
680
- ```ts
681
- type SignalUnsubscribe = (() => void) | { unsubscribe(): void };
244
+ - `register:start`
245
+ - `register:success`
246
+ - `start:requested`
247
+ - `start:taskScheduled`
248
+ - `artifact:mountStart`
249
+ - `artifact:mountSuccess`
250
+ - `artifact:mountFail`
251
+ - `listener:attached`
252
+ - `alive:enabled`
253
+ - `alive:observerStarted`
254
+ - `task:statusChange`
255
+ - `dom:targetFound`
256
+ - `dom:targetTimeout`
682
257
 
683
- type ActivitySignalSource<T = boolean> = {
684
- get(): T;
685
- subscribe(listener: (value: T) => void): SignalUnsubscribe;
686
- };
258
+ 完整事件名列表可从 `OBSERVE_EVENT_NAMES` 获取。
687
259
 
688
- type ActivitySignalSubscribable<T = boolean> = ActivitySignalSource<T>;
689
- ```
260
+ ## DOMWatcher
690
261
 
691
- ## 日志类型
262
+ `DOMWatcher` 是 core 的底层 DOM 观察工具。通常你不需要直接使用它,因为 `makoo.start()` 和 alive 模式已经封装了目标等待和恢复逻辑。
692
263
 
693
- ```ts
694
- type LoggerLevel = 'debug' | 'info' | 'warn' | 'error';
264
+ ## 日志和错误
695
265
 
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
- ```
266
+ core 默认使用 `Logger`,并用 `[Makoo]` 前缀打印日志。你可以通过 `createMakoo({ logger })` 传入自定义 logger。
703
267
 
704
- ## 错误类型
268
+ core 也导出这些错误相关类型:
705
269
 
706
- ```ts
707
- type MakooIssue = {
708
- path: string;
709
- message: string;
710
- };
270
+ - `MakooError`
271
+ - `AdapterError`
272
+ - `TaskError`
273
+ - `SignalError`
274
+ - `ErrorCode`
275
+ - `MakooIssue`
711
276
 
712
- type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];
713
- ```
277
+ ## Public Exports 概览
278
+
279
+ | 分类 | 代表导出 |
280
+ | --- | --- |
281
+ | 运行时 API | `createMakoo`, `inject`, `listen`, `MakooRuntime`, `StartedTasks` |
282
+ | Adapter 协议 | `MountAdapter`, `ResolvableMountAdapter`, `AdapterMountInput`, `AdapterUnmountInput`, `MakooContext` |
283
+ | 生命周期观察 | `ObserverHub`, `OBSERVE_EVENT_NAMES`, `ObserveEvent`, `ObserveHook`, `LifecycleHookMap` |
284
+ | DOM 观察 | `DOMWatcher` |
285
+ | 监听 signal | `createActivityStore`, `ActivitySignalSource` |
286
+ | 日志 | `Logger`, `ILogger`, `LoggerLevel` |
287
+ | 错误 | `MakooError`, `AdapterError`, `TaskError`, `SignalError`, `ErrorCode` |