alemonjs 2.1.91 → 2.1.93

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
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2013-present, Yuxi (Evan) You
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
13
+ all 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
21
+ THE SOFTWARE.
package/bin/publish.js CHANGED
@@ -2,7 +2,8 @@
2
2
  import fs from 'fs';
3
3
  import { join } from 'path';
4
4
  import os from 'os';
5
- import { execSync, spawnSync } from 'child_process';
5
+ import { execSync } from 'child_process';
6
+ import spawn from 'cross-spawn';
6
7
 
7
8
  const RELEASE_TYPES = new Set(['patch', 'minor', 'major', 'prepatch', 'preminor', 'premajor', 'prerelease']);
8
9
  const PRERELEASE_IDS = new Set(['alpha', 'beta', 'rc', 'next']);
@@ -24,7 +25,7 @@ function readPackageJson() {
24
25
  }
25
26
 
26
27
  function runCommand(command, args, options = {}) {
27
- const result = spawnSync(command, args, {
28
+ const result = spawn.sync(command, args, {
28
29
  cwd: process.cwd(),
29
30
  stdio: 'inherit',
30
31
  shell: false,
@@ -49,7 +50,7 @@ function getCommandOutput(command) {
49
50
  }
50
51
 
51
52
  function hasCommand(command) {
52
- const result = spawnSync(command, ['--version'], {
53
+ const result = spawn.sync(command, ['--version'], {
53
54
  cwd: process.cwd(),
54
55
  stdio: 'ignore'
55
56
  });
@@ -293,7 +294,7 @@ function getLatestReleaseVersion() {
293
294
  }
294
295
 
295
296
  function remoteBranchExists(branch) {
296
- const result = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', branch], {
297
+ const result = spawn.sync('git', ['ls-remote', '--exit-code', '--heads', 'origin', branch], {
297
298
  cwd: process.cwd(),
298
299
  stdio: 'ignore'
299
300
  });
@@ -302,7 +303,7 @@ function remoteBranchExists(branch) {
302
303
  }
303
304
 
304
305
  function localBranchExists(branch) {
305
- const result = spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], {
306
+ const result = spawn.sync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], {
306
307
  cwd: process.cwd(),
307
308
  stdio: 'ignore'
308
309
  });
@@ -330,7 +331,7 @@ function cleanupWorktree(worktreeDir) {
330
331
  return;
331
332
  }
332
333
 
333
- spawnSync('git', ['worktree', 'remove', '--force', worktreeDir], {
334
+ spawn.sync('git', ['worktree', 'remove', '--force', worktreeDir], {
334
335
  cwd: process.cwd(),
335
336
  stdio: 'ignore'
336
337
  });
@@ -428,7 +429,7 @@ export async function publish(release, options = {}) {
428
429
  copyDirContents(publishDir, worktreeDir);
429
430
 
430
431
  runCommand('git', ['-C', worktreeDir, 'add', '-A']);
431
- const hasChanges = spawnSync('git', ['-C', worktreeDir, 'diff', '--cached', '--quiet']).status !== 0;
432
+ const hasChanges = spawn.sync('git', ['-C', worktreeDir, 'diff', '--cached', '--quiet']).status !== 0;
432
433
  if (!hasChanges) {
433
434
  console.log('release 分支无文件变化,跳过提交');
434
435
  } else {
@@ -0,0 +1,40 @@
1
+ import type { EventKeys, Events } from '../types/index.js';
2
+ type ContextState = Record<string, unknown>;
3
+ export type ContextAction<T = unknown> = {
4
+ readonly payload: T;
5
+ readonly signal: AbortSignal;
6
+ pass: () => void;
7
+ close: () => void;
8
+ };
9
+ export type ContextHandler<S extends ContextState, T = unknown> = (event: Events[EventKeys], state: S, action: ContextAction<T>) => void | Promise<void>;
10
+ type ContextConfig<S extends ContextState, R extends Record<string, ContextHandler<S, any>>> = {
11
+ name: string;
12
+ events: readonly EventKeys[];
13
+ scope: readonly string[];
14
+ conflict?: 'replace' | 'reject';
15
+ onError?: 'close' | 'keep';
16
+ expiresIn?: number | string;
17
+ initialState: S | ((payload: unknown) => S);
18
+ handlers: R;
19
+ };
20
+ export type Context = {
21
+ name: string;
22
+ [handler: string]: unknown;
23
+ };
24
+ export type ContextConfiguration = {
25
+ contexts: Record<string, Context>;
26
+ };
27
+ export type ContextPhase = 'middleware' | 'response';
28
+ export declare const configureContext: (config: ContextConfiguration) => ContextConfiguration;
29
+ export declare const createContext: <S extends ContextState, R extends Record<string, ContextHandler<S, any>>>(config: ContextConfig<S, R>) => {
30
+ name: string;
31
+ cancel: () => boolean;
32
+ } & { [K in keyof R]: (payload?: unknown) => void; };
33
+ export declare const validateContextRegistration: (register?: {
34
+ middlewareContent?: ContextConfiguration;
35
+ responseContent?: ContextConfiguration;
36
+ }) => void;
37
+ export declare const expendContext: <T extends EventKeys>(event: Events[T], select: T, next: () => void, phase: ContextPhase) => Promise<boolean>;
38
+ export declare const clearContexts: () => void;
39
+ export declare const clearContextsByApp: (appName: string) => void;
40
+ export {};
@@ -0,0 +1,340 @@
1
+ import { showErrorModule } from '../common/utils.js';
2
+ import { withEventContext, finishCurrentTrace, getCurrentEvent, getCurrentAppName } from './runtime/hook-event-context.js';
3
+ import { dispatchEventError } from './runtime/event-error.js';
4
+ import { getChildrenApp } from './runtime/store.js';
5
+ import { scheduleTimeout, scheduleCancel } from './runtime/schedule-store.js';
6
+ import { clearActiveContexts, clearActiveContextsByApp, getActiveContextKeys, activeContexts, removeActiveContext, putActiveContext } from './runtime/context-registry.js';
7
+
8
+ const contextQueues = new Map();
9
+ let contextSequence = 0;
10
+ const contextDefinitionSymbol = Symbol('alemonjs.contextDefinition');
11
+ const contextDefinitionSymbolForContent = Symbol('alemonjs.contextDefinitionForContent');
12
+ const parseExpiresIn = (value) => {
13
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
14
+ return value;
15
+ }
16
+ if (typeof value !== 'string') {
17
+ return undefined;
18
+ }
19
+ const match = /^(\d+)\s*(ms|s|m|h|d)?$/i.exec(value.trim());
20
+ if (!match) {
21
+ throw new Error(`Invalid context expiresIn: ${value}`);
22
+ }
23
+ const amount = Number(match[1]);
24
+ const unit = match[2]?.toLowerCase() ?? 'ms';
25
+ const factor = unit === 'd' ? 86_400_000 : unit === 'h' ? 3_600_000 : unit === 'm' ? 60_000 : unit === 's' ? 1_000 : 1;
26
+ return amount * factor;
27
+ };
28
+ const cloneState = (state) => {
29
+ if (!state || typeof state !== 'object' || Array.isArray(state)) {
30
+ throw new Error('Context initialState must be an object');
31
+ }
32
+ try {
33
+ return globalThis.structuredClone(state);
34
+ }
35
+ catch {
36
+ throw new Error('Context initialState must be structured-cloneable');
37
+ }
38
+ };
39
+ const clonePayload = (payload) => {
40
+ try {
41
+ return globalThis.structuredClone(payload);
42
+ }
43
+ catch {
44
+ throw new Error('Context payload must be structured-cloneable');
45
+ }
46
+ };
47
+ const getScopeKey = (appName, definition, event) => {
48
+ const values = definition.scope.map(key => {
49
+ const value = event[key];
50
+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
51
+ throw new Error(`Invalid context scope value: ${key} must be a string, number or boolean`);
52
+ }
53
+ return [key, String(value)];
54
+ });
55
+ return JSON.stringify([appName, definition.name, values]);
56
+ };
57
+ const isExpired = (context, now = Date.now()) => context.expiresAt !== undefined && context.expiresAt <= now;
58
+ const configureContext = (config) => {
59
+ const contexts = Object.values(config.contexts ?? {});
60
+ const names = new Set();
61
+ if (contexts.length === 0) {
62
+ throw new Error('configureContext requires at least one context');
63
+ }
64
+ for (const context of contexts) {
65
+ const definition = context[contextDefinitionSymbolForContent];
66
+ if (!definition) {
67
+ throw new Error('configureContext only accepts contexts created by createContext');
68
+ }
69
+ if (names.has(definition.name)) {
70
+ throw new Error(`Duplicate context name: ${definition.name}`);
71
+ }
72
+ names.add(definition.name);
73
+ }
74
+ return Object.freeze({
75
+ ...config,
76
+ contexts: Object.freeze({ ...config.contexts })
77
+ });
78
+ };
79
+ const createContext = (config) => {
80
+ if (!config.name) {
81
+ throw new Error('Context name is required');
82
+ }
83
+ if (config.events.length === 0) {
84
+ throw new Error(`Context events are required: ${config.name}`);
85
+ }
86
+ if (config.scope.length === 0) {
87
+ throw new Error(`Context scope is required: ${config.name}`);
88
+ }
89
+ if (Object.keys(config.handlers).length === 0) {
90
+ throw new Error(`Context handlers are required: ${config.name}`);
91
+ }
92
+ if (Object.prototype.hasOwnProperty.call(config.handlers, 'cancel')) {
93
+ throw new Error(`Context handler name is reserved: ${config.name}/cancel`);
94
+ }
95
+ const initialState = typeof config.initialState === 'function' ? config.initialState : cloneState(config.initialState);
96
+ const definition = {
97
+ name: config.name,
98
+ events: Object.freeze([...config.events]),
99
+ scope: Object.freeze([...config.scope]),
100
+ conflict: config.conflict ?? 'replace',
101
+ onError: config.onError ?? 'close',
102
+ expiresIn: parseExpiresIn(config.expiresIn),
103
+ initialState: payload => {
104
+ const state = typeof initialState === 'function' ? initialState(payload) : initialState;
105
+ return cloneState(state);
106
+ },
107
+ handlers: Object.freeze({ ...config.handlers })
108
+ };
109
+ const actions = Object.fromEntries(Object.keys(config.handlers).map(handler => [
110
+ handler,
111
+ (payload) => {
112
+ const action = { type: `${config.name}/${handler}`, payload };
113
+ Object.defineProperty(action, contextDefinitionSymbol, {
114
+ value: { definition, handler }
115
+ });
116
+ dispatchContext(action);
117
+ }
118
+ ]));
119
+ const context = {
120
+ name: config.name,
121
+ ...actions,
122
+ cancel: () => cancelContext(definition)
123
+ };
124
+ Object.defineProperty(context, contextDefinitionSymbolForContent, {
125
+ value: definition
126
+ });
127
+ return Object.freeze(context);
128
+ };
129
+ const getRegisteredContexts = (appName, phase) => {
130
+ const register = getChildrenApp(appName)?.register;
131
+ const content = phase === 'middleware' ? register?.middlewareContent : register?.responseContent;
132
+ return content ? Object.values(content.contexts) : [];
133
+ };
134
+ const getContextPhases = (appName, definition) => {
135
+ return ['middleware', 'response'].filter(phase => {
136
+ return getRegisteredContexts(appName, phase).some(context => context[contextDefinitionSymbolForContent] === definition);
137
+ });
138
+ };
139
+ const isRegistered = (appName, definition, phase) => {
140
+ const phases = getContextPhases(appName, definition);
141
+ return phase ? phases.includes(phase) : phases.length > 0;
142
+ };
143
+ const validateContextRegistration = (register) => {
144
+ const owners = new Map();
145
+ for (const phase of ['middleware', 'response']) {
146
+ const content = phase === 'middleware' ? register?.middlewareContent : register?.responseContent;
147
+ for (const context of (content ? Object.values(content.contexts) : [])) {
148
+ const definition = context[contextDefinitionSymbolForContent];
149
+ if (!definition) {
150
+ throw new Error('Context registration only accepts contexts created by createContext');
151
+ }
152
+ if (owners.has(definition)) {
153
+ throw new Error(`Context cannot be registered in multiple phases: ${definition.name}`);
154
+ }
155
+ owners.set(definition, phase);
156
+ }
157
+ }
158
+ };
159
+ const cancelContext = (definition) => {
160
+ const event = getCurrentEvent();
161
+ if (!event || typeof event !== 'object') {
162
+ throw new Error('Context actions must be called inside an event handler');
163
+ }
164
+ const appName = getCurrentAppName() ?? 'main';
165
+ const key = getScopeKey(appName, definition, event);
166
+ return removeActiveContext(key);
167
+ };
168
+ const dispatchContext = (action, event) => {
169
+ const internalAction = action;
170
+ const metadata = internalAction[contextDefinitionSymbol];
171
+ const definition = metadata?.definition;
172
+ if (!definition) {
173
+ throw new Error(`Invalid context action: ${action.type}`);
174
+ }
175
+ const handler = metadata.handler;
176
+ const currentEvent = getCurrentEvent();
177
+ if (!currentEvent || typeof currentEvent !== 'object') {
178
+ throw new Error('Context actions must be dispatched with an event or inside an event handler');
179
+ }
180
+ const appName = getCurrentAppName() ?? 'main';
181
+ const phases = getContextPhases(appName, definition);
182
+ if (phases.length === 0) {
183
+ throw new Error(`Context action is not registered for app: ${action.type}`);
184
+ }
185
+ if (phases.length > 1) {
186
+ throw new Error(`Context is registered in multiple phases: ${action.type}`);
187
+ }
188
+ const key = getScopeKey(appName, definition, currentEvent);
189
+ const previous = activeContexts.get(key);
190
+ if (previous && definition.conflict === 'reject') {
191
+ throw new Error(`Context is already active: ${action.type}`);
192
+ }
193
+ const now = Date.now();
194
+ const id = `${now.toString(36)}-${Math.random().toString(36).slice(2)}`;
195
+ const payload = clonePayload(action.payload);
196
+ const expiresAt = definition.expiresIn ? now + definition.expiresIn : undefined;
197
+ const controller = new AbortController();
198
+ let expirationTimerId;
199
+ const context = {
200
+ key,
201
+ id,
202
+ appName,
203
+ phase: phases[0],
204
+ events: definition.events,
205
+ definition,
206
+ handler,
207
+ payload,
208
+ state: definition.initialState(payload),
209
+ expiresAt,
210
+ createdAt: now,
211
+ order: ++contextSequence,
212
+ controller,
213
+ onRemove: () => {
214
+ controller.abort();
215
+ if (expirationTimerId) {
216
+ scheduleCancel(expirationTimerId);
217
+ }
218
+ }
219
+ };
220
+ if (definition.expiresIn) {
221
+ expirationTimerId = scheduleTimeout(() => {
222
+ removeActiveContext(key, id);
223
+ }, definition.expiresIn, appName);
224
+ }
225
+ putActiveContext(context);
226
+ };
227
+ const expendContext = async (event, select, next, phase) => {
228
+ const now = Date.now();
229
+ let current;
230
+ for (const key of getActiveContextKeys(select)) {
231
+ const context = activeContexts.get(key);
232
+ if (!context) {
233
+ continue;
234
+ }
235
+ if (context.phase !== phase) {
236
+ continue;
237
+ }
238
+ if (isExpired(context, now)) {
239
+ removeActiveContext(key, context.id);
240
+ continue;
241
+ }
242
+ if (!isRegistered(context.appName, context.definition, context.phase)) {
243
+ removeActiveContext(key, context.id);
244
+ continue;
245
+ }
246
+ let scopeKey;
247
+ try {
248
+ scopeKey = getScopeKey(context.appName, context.definition, event);
249
+ }
250
+ catch {
251
+ continue;
252
+ }
253
+ if (scopeKey === key && (!current || context.order > current.order)) {
254
+ current = context;
255
+ }
256
+ }
257
+ if (!current) {
258
+ next();
259
+ return false;
260
+ }
261
+ const key = current.key;
262
+ const previous = contextQueues.get(key) ?? Promise.resolve();
263
+ const run = previous
264
+ .catch(() => undefined)
265
+ .then(async () => {
266
+ const active = activeContexts.get(key);
267
+ if (!active) {
268
+ next();
269
+ return;
270
+ }
271
+ const handler = active.definition.handlers[active.handler];
272
+ if (!handler) {
273
+ removeActiveContext(active.key, active.id);
274
+ next();
275
+ return;
276
+ }
277
+ let shouldPass = false;
278
+ let shouldClose = false;
279
+ const control = {
280
+ payload: active.payload,
281
+ signal: active.controller.signal,
282
+ pass: () => {
283
+ shouldPass = true;
284
+ },
285
+ close: () => {
286
+ shouldClose = true;
287
+ }
288
+ };
289
+ try {
290
+ await withEventContext(event, () => control.pass(), () => handler(event, active.state, control), {
291
+ appName: active.appName,
292
+ phase: active.phase === 'middleware' ? 'middleware-content' : 'response-content'
293
+ });
294
+ }
295
+ catch (error) {
296
+ showErrorModule(error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Context handler failed'));
297
+ const shouldContinue = await dispatchEventError({
298
+ event,
299
+ error,
300
+ appName: active.appName,
301
+ phase: active.phase === 'middleware' ? 'middleware-content' : 'response-content'
302
+ });
303
+ if (active.definition.onError === 'close') {
304
+ removeActiveContext(active.key, active.id);
305
+ }
306
+ if (shouldContinue) {
307
+ next();
308
+ return;
309
+ }
310
+ finishCurrentTrace('error');
311
+ return;
312
+ }
313
+ if (shouldClose) {
314
+ removeActiveContext(active.key, active.id);
315
+ }
316
+ if (shouldPass) {
317
+ next();
318
+ }
319
+ else {
320
+ finishCurrentTrace('consumed');
321
+ }
322
+ })
323
+ .finally(() => {
324
+ if (contextQueues.get(key) === run) {
325
+ contextQueues.delete(key);
326
+ }
327
+ });
328
+ contextQueues.set(key, run);
329
+ await run;
330
+ return true;
331
+ };
332
+ const clearContexts = () => {
333
+ clearActiveContexts();
334
+ contextQueues.clear();
335
+ };
336
+ const clearContextsByApp = (appName) => {
337
+ clearActiveContextsByApp(appName);
338
+ };
339
+
340
+ export { clearContexts, clearContextsByApp, configureContext, createContext, expendContext, validateContextRegistration };
@@ -5,6 +5,8 @@ export { defineMiddleware } from './define-middleware.js';
5
5
  export { defineRouter, lazy, runHandler } from './define-router.js';
6
6
  export * from './expose.js';
7
7
  export * from './hooks/index.js';
8
+ export { createContext, configureContext } from './context.js';
9
+ export type { Context, ContextAction, ContextConfiguration, ContextHandler, ContextPhase } from './context.js';
8
10
  export * from './schedule.js';
9
11
  export * from './format/message-api.js';
10
12
  export * from './format/message-format.js';
@@ -22,6 +22,7 @@ export { useRoute } from './hooks/route.js';
22
22
  export { useUser } from './hooks/user.js';
23
23
  export { useObserver, useSubscribe } from './hooks/subscribe.js';
24
24
  export { createEvent, useEvent } from './hooks/event.js';
25
+ export { configureContext, createContext } from './context.js';
25
26
  export { clearInterval, clearTimeout, listSchedule, pauseSchedule, resumeSchedule, setCron, setInterval, setTimeout } from './schedule.js';
26
27
  export { MessageDirect, createDataFormat, format, getMessageIntent, sendToChannel, sendToUser } from './format/message-api.js';
27
28
  export { Format, FormatButtonGroup, FormatMarkDown, FormatSelect } from './format/message-format.js';
@@ -25,6 +25,7 @@ import { createServer } from './http-server.js';
25
25
  import { disposeAllRuntimeApps } from './store.js';
26
26
  import { scheduleCancelByApp, unregisterAppDir } from './schedule-store.js';
27
27
  import { dispatchDisposeAllApps } from './lifecycle-callbacks.js';
28
+ import { clearActiveContexts } from './context-registry.js';
28
29
 
29
30
  global.__client_loaded = true;
30
31
  let runtimeDisposed = false;
@@ -35,6 +36,7 @@ const disposeClientRuntime = async () => {
35
36
  }
36
37
  runtimeDisposed = true;
37
38
  await dispatchDisposeAllApps();
39
+ clearActiveContexts();
38
40
  const apps = disposeAllRuntimeApps();
39
41
  apps.forEach(app => {
40
42
  scheduleCancelByApp(app.name);
@@ -0,0 +1,14 @@
1
+ import type { EventKeys } from '../../types/index.js';
2
+ export type ContextRegistryEntry = {
3
+ key: string;
4
+ id: string;
5
+ appName: string;
6
+ events: readonly EventKeys[];
7
+ onRemove?: () => void;
8
+ };
9
+ export declare const activeContexts: Map<string, ContextRegistryEntry>;
10
+ export declare const putActiveContext: (context: ContextRegistryEntry) => void;
11
+ export declare const removeActiveContext: (key: string, id?: string) => boolean;
12
+ export declare const getActiveContextKeys: (event: EventKeys) => Set<string>;
13
+ export declare const clearActiveContextsByApp: (appName: string) => void;
14
+ export declare const clearActiveContexts: () => void;
@@ -0,0 +1,49 @@
1
+ const activeContexts = new Map();
2
+ const activeContextKeysByEvent = new Map();
3
+ const putActiveContext = (context) => {
4
+ const previous = activeContexts.get(context.key);
5
+ if (previous) {
6
+ removeActiveContext(previous.key, previous.id);
7
+ }
8
+ activeContexts.set(context.key, context);
9
+ for (const event of context.events) {
10
+ const keys = activeContextKeysByEvent.get(event) ?? new Set();
11
+ keys.add(context.key);
12
+ activeContextKeysByEvent.set(event, keys);
13
+ }
14
+ };
15
+ const removeActiveContext = (key, id) => {
16
+ const context = activeContexts.get(key);
17
+ if (!context || (id && context.id !== id)) {
18
+ return false;
19
+ }
20
+ activeContexts.delete(key);
21
+ for (const event of context.events) {
22
+ const keys = activeContextKeysByEvent.get(event);
23
+ keys?.delete(key);
24
+ if (keys?.size === 0) {
25
+ activeContextKeysByEvent.delete(event);
26
+ }
27
+ }
28
+ try {
29
+ context.onRemove?.();
30
+ }
31
+ catch {
32
+ }
33
+ return true;
34
+ };
35
+ const getActiveContextKeys = (event) => activeContextKeysByEvent.get(event) ?? new Set();
36
+ const clearActiveContextsByApp = (appName) => {
37
+ for (const context of activeContexts.values()) {
38
+ if (context.appName === appName) {
39
+ removeActiveContext(context.key, context.id);
40
+ }
41
+ }
42
+ };
43
+ const clearActiveContexts = () => {
44
+ for (const context of [...activeContexts.values()]) {
45
+ removeActiveContext(context.key, context.id);
46
+ }
47
+ };
48
+
49
+ export { activeContexts, clearActiveContexts, clearActiveContextsByApp, getActiveContextKeys, putActiveContext, removeActiveContext };
@@ -2,6 +2,7 @@ import { expendEvent } from './event-processor-event.js';
2
2
  import { expendMiddleware } from './event-processor-middleware.js';
3
3
  import { expendSubscribeCreate, expendSubscribeMount, expendSubscribeUnmount } from './event-processor-subscribe.js';
4
4
  import { finishCurrentTrace } from './hook-event-context.js';
5
+ import { expendContext } from '../context.js';
5
6
 
6
7
  const expendCycle = (valueEvent, select, _config) => {
7
8
  const nextEnd = () => {
@@ -21,19 +22,33 @@ const expendCycle = (valueEvent, select, _config) => {
21
22
  }
22
23
  void expendEvent(valueEvent, select, nextUnMount);
23
24
  };
24
- const nextMount = (cn, ...cns) => {
25
+ const nextResponseContent = (cn, ...cns) => {
25
26
  if (cn) {
26
27
  nextEvent(...cns);
27
28
  return;
28
29
  }
29
- void expendSubscribeMount(valueEvent, select, nextEvent);
30
+ void expendContext(valueEvent, select, nextEvent, 'response');
30
31
  };
31
- const nextCreate = (cn, ...cns) => {
32
+ const nextMount = (cn, ...cns) => {
33
+ if (cn) {
34
+ nextResponseContent(...cns);
35
+ return;
36
+ }
37
+ void expendSubscribeMount(valueEvent, select, nextResponseContent);
38
+ };
39
+ const nextMiddlewareContent = (cn, ...cns) => {
32
40
  if (cn) {
33
41
  nextMount(...cns);
34
42
  return;
35
43
  }
36
- void expendMiddleware(valueEvent, select, nextMount);
44
+ void expendContext(valueEvent, select, nextMount, 'middleware');
45
+ };
46
+ const nextCreate = (cn, ...cns) => {
47
+ if (cn) {
48
+ nextMiddlewareContent(...cns);
49
+ return;
50
+ }
51
+ void expendMiddleware(valueEvent, select, nextMiddlewareContent);
37
52
  };
38
53
  void expendSubscribeCreate(valueEvent, select, nextCreate);
39
54
  };
@@ -5,6 +5,7 @@ import { registerRuntimeApp, updateRuntimeAppStatus, ChildrenApp, clearRuntimeAp
5
5
  import { registerExpose } from '../../expose.js';
6
6
  import { ResultCode, fileSuffixMiddleware } from '../../../common/variable.js';
7
7
  import { registerAppDir, scheduleCancelByApp, unregisterAppDir } from '../schedule-store.js';
8
+ import { validateContextRegistration } from '../../context.js';
8
9
  import module$1 from 'module';
9
10
  import { dispatchRuntimeStatusChange, dispatchAppDispose, dispatchAppReady } from '../lifecycle-callbacks.js';
10
11
 
@@ -168,10 +169,11 @@ const loadChildren = async (mainPath, appName) => {
168
169
  }
169
170
  const registerMounted = async () => {
170
171
  const res = await app?.register();
171
- const hasEventCapability = Boolean(res && (res?.response || res?.middleware || res?.responseRouter || res?.middlewareRouter));
172
+ validateContextRegistration(res);
173
+ const hasEventCapability = Boolean(res && (res?.response || res?.middleware || res?.responseRouter || res?.middlewareRouter || res?.middlewareContent || res?.responseContent));
172
174
  const hasExposeCapability = Boolean(res?.expose);
173
175
  const hasKoaRouterCapability = Boolean(res?.koaRouter);
174
- if (res && (res?.response || res?.middleware || res?.responseRouter || res?.middlewareRouter)) {
176
+ if (res && (res?.response || res?.middleware || res?.responseRouter || res?.middlewareRouter || res?.middlewareContent || res?.responseContent)) {
175
177
  App.register(res);
176
178
  }
177
179
  setRuntimeAppKoaRouters(appName, res?.koaRouter);
@@ -1,6 +1,7 @@
1
1
  import { SinglyLinkedList } from '../../common/SinglyLinkedList.js';
2
2
  import { disposeExpose } from '../expose.js';
3
3
  import { dispatchRuntimeStatusChange } from './lifecycle-callbacks.js';
4
+ import { clearActiveContextsByApp } from './context-registry.js';
4
5
  export { Logger, logger } from '../../common/logger.js';
5
6
 
6
7
  class Core {
@@ -548,6 +549,7 @@ class ChildrenApp {
548
549
  }
549
550
  un() {
550
551
  disposeExpose(this.#name);
552
+ clearActiveContextsByApp(this.#name);
551
553
  Reflect.deleteProperty(alemonjsCore.storeChildrenApp, this.#name);
552
554
  bumpStoreVersion();
553
555
  }
@@ -1,4 +1,3 @@
1
- import { WebSocket } from 'ws';
2
1
  export declare const childrenClient: Map<string, WebSocket>;
3
2
  export declare const platformClient: Map<string, WebSocket>;
4
3
  export declare const fullClient: Map<string, WebSocket>;
package/lib/index.js CHANGED
@@ -28,6 +28,7 @@ export { cbpClient } from './application/runtime/cbp/connects/client.js';
28
28
  export { cbpPlatform } from './platform/cbp-platform.js';
29
29
  export { checkFallbackHint } from './application/router/fallback.js';
30
30
  export { clearInterval, clearTimeout, listSchedule, pauseSchedule, resumeSchedule, setCron, setInterval, setTimeout } from './application/schedule.js';
31
+ export { configureContext, createContext } from './application/context.js';
31
32
  export { createActionRequestEnvelope, createActionResponseEnvelope, createApiRequestEnvelope, createApiResponseEnvelope, createEventEnvelope, getNormalizedDeviceId, getNormalizedEventRouteId, isCBPEnvelope, isNormalizedActionRequest, isNormalizedApiRequest, normalizeInboundMessage, toLegacyActionData, toLegacyApiData } from './common/cbp/normalize.js';
32
33
  export { createDirectClient, createDirectServer, generateSocketPath } from './common/direct-channel.js';
33
34
  export { createEvent, useEvent } from './application/hooks/event.js';
@@ -9,7 +9,7 @@ type StroreParam = {
9
9
  };
10
10
  middleware: StoreMiddlewareItem[];
11
11
  };
12
- export type EventErrorPhase = 'middleware' | 'response' | 'subscribe' | 'route';
12
+ export type EventErrorPhase = 'middleware' | 'response' | 'subscribe' | 'route' | 'context' | 'middleware-content' | 'response-content';
13
13
  export type EventTraceReason = 'filtered' | 'completed' | 'consumed' | 'error';
14
14
  export type RuntimeLifecycleStatus = 'discovered' | 'loading' | 'ready' | 'failed' | 'disposed';
15
15
  export type EventStartContext<T extends EventKeys = EventKeys> = {
@@ -4,6 +4,7 @@ import { EventKeys, Events } from './map';
4
4
  import { DataEnums } from '../message';
5
5
  import { Expose } from '../../application/expose';
6
6
  import type KoaRouter from 'koa-router';
7
+ import type { ContextConfiguration } from '../../application/context';
7
8
  export type Current<T extends EventKeys> = (event: Events[T], next: Next) => Promise<boolean | void | undefined> | boolean | void | undefined;
8
9
  export type OnResponseValue<C, T extends EventKeys> = {
9
10
  current: C;
@@ -60,6 +61,8 @@ export type childrenCallbackRes = {
60
61
  middlewareRouter?: ReturnType<DefineRouterFunc>;
61
62
  koaRouter?: KoaRouter | KoaRouter[];
62
63
  expose?: Expose;
64
+ responseContent?: ContextConfiguration;
65
+ middlewareContent?: ContextConfiguration;
63
66
  } | undefined;
64
67
  export type childrenCallback = ChildrenCycle & {
65
68
  register?: () => (childrenCallbackRes | undefined) | Promise<childrenCallbackRes | undefined>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alemonjs",
3
- "version": "2.1.91",
3
+ "version": "2.1.93",
4
4
  "description": "bot script",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
@@ -49,32 +49,27 @@
49
49
  "dependencies": {
50
50
  "@koa/cors": "^5.0.0",
51
51
  "axios": "^1.14.0",
52
- "chalk": "^5.6.2",
53
52
  "commander": "^13.1.0",
54
53
  "cron": "^4.4.0",
54
+ "cross-spawn": "^7.0.6",
55
55
  "file-type": "21.0.0",
56
56
  "flatted": "^3.3.3",
57
+ "https-proxy-agent": "^9.0.0",
57
58
  "koa": "^3.0.1",
58
59
  "koa-router": "^14.0.0",
59
- "koa-static": "^5.0.0",
60
+ "lodash": "^4.18.1",
60
61
  "log4js": "^6.9.1",
61
62
  "mime-types": "^3.0.1",
62
63
  "public-ip": "^7.0.1",
63
64
  "qrcode": "^1.5.4",
64
- "uuid": "11.1.0",
65
65
  "ws": "^8.18.0",
66
- "https-proxy-agent": "^9.0.0",
67
66
  "yaml": "^2.5.1"
68
67
  },
69
68
  "devDependencies": {
70
69
  "@types/koa": "^2.15.0",
71
- "@types/koa-bodyparser": "^4.3.12",
72
- "@types/koa-mount": "^4.0.5",
73
70
  "@types/koa-router": "^7.4.8",
74
- "@types/koa-static": "^4.0.4",
75
71
  "@types/koa__cors": "^5.0.0",
76
- "@types/mime-types": "^3.0.1",
77
- "@types/uuid": "^10.0.0"
72
+ "@types/mime-types": "^3.0.1"
78
73
  },
79
74
  "bin": {
80
75
  "alemonjs": "./bin/alemonjs.js",
@@ -92,5 +87,5 @@
92
87
  "type": "git",
93
88
  "url": "https://github.com/lemonade-lab/alemonjs.git"
94
89
  },
95
- "gitHead": "c6aa5616afe091a37610dad22fbb2d2618d943b8"
96
- }
90
+ "gitHead": "f3222b96dcdca984ec726cdd26d759952ca9c705"
91
+ }