@chromahq/core 0.1.15 → 0.1.16
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/dist/boot-D6U4s43p.js +1624 -0
- package/dist/boot-D6U4s43p.js.map +1 -0
- package/dist/boot-Dl66KPJQ.js +1629 -0
- package/dist/boot-Dl66KPJQ.js.map +1 -0
- package/dist/boot.cjs.js +2 -1554
- package/dist/boot.cjs.js.map +1 -1
- package/dist/boot.es.js +1 -1557
- package/dist/boot.es.js.map +1 -1
- package/dist/index.cjs.js +6 -5
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +27 -5
- package/dist/index.es.js +3 -4
- package/dist/index.es.js.map +1 -1
- package/package.json +14 -15
- package/dist/IJob-ByOJx8qA.js +0 -20
- package/dist/IJob-ByOJx8qA.js.map +0 -1
- package/dist/IJob-CoWGJUZM.js +0 -24
- package/dist/IJob-CoWGJUZM.js.map +0 -1
|
@@ -0,0 +1,1629 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var container$1 = require('@inversifyjs/container');
|
|
4
|
+
|
|
5
|
+
const container = new container$1.Container({
|
|
6
|
+
defaultScope: "Singleton"
|
|
7
|
+
});
|
|
8
|
+
container.id = Math.random().toString(36).substring(2, 15);
|
|
9
|
+
|
|
10
|
+
var JobState = /* @__PURE__ */ ((JobState2) => {
|
|
11
|
+
JobState2["SCHEDULED"] = "scheduled";
|
|
12
|
+
JobState2["RUNNING"] = "running";
|
|
13
|
+
JobState2["PAUSED"] = "paused";
|
|
14
|
+
JobState2["STOPPED"] = "stopped";
|
|
15
|
+
JobState2["COMPLETED"] = "completed";
|
|
16
|
+
JobState2["FAILED"] = "failed";
|
|
17
|
+
return JobState2;
|
|
18
|
+
})(JobState || {});
|
|
19
|
+
|
|
20
|
+
class MiddlewareRegistryClass {
|
|
21
|
+
constructor() {
|
|
22
|
+
this.global = [];
|
|
23
|
+
this.perHandler = /* @__PURE__ */ new Map();
|
|
24
|
+
}
|
|
25
|
+
registerGlobal(fn) {
|
|
26
|
+
this.global.push(fn);
|
|
27
|
+
}
|
|
28
|
+
registerForKey(key, fn) {
|
|
29
|
+
const arr = this.perHandler.get(key) ?? [];
|
|
30
|
+
arr.push(fn);
|
|
31
|
+
this.perHandler.set(key, arr);
|
|
32
|
+
}
|
|
33
|
+
pipeline(key) {
|
|
34
|
+
return [...this.global, ...this.perHandler.get(key) ?? []];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const MiddlewareRegistry = new MiddlewareRegistryClass();
|
|
38
|
+
|
|
39
|
+
const DEFAULT_PORT_NAME = "chroma-bridge";
|
|
40
|
+
|
|
41
|
+
class DefaultErrorHandler {
|
|
42
|
+
handle(error, context) {
|
|
43
|
+
return {
|
|
44
|
+
id: context.request.id,
|
|
45
|
+
error: error?.message ?? "UNKNOWN_ERROR",
|
|
46
|
+
timestamp: Date.now()
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const _BridgeRuntimeManager = class _BridgeRuntimeManager {
|
|
51
|
+
constructor(options) {
|
|
52
|
+
this.keepAliveTimer = null;
|
|
53
|
+
this.isInitialized = false;
|
|
54
|
+
this.container = options.container;
|
|
55
|
+
this.portName = options.portName ?? DEFAULT_PORT_NAME;
|
|
56
|
+
this.enableLogging = options.enableLogging ?? true;
|
|
57
|
+
this.errorHandler = options.errorHandler ?? new DefaultErrorHandler();
|
|
58
|
+
this.logger = new BridgeLogger(this.enableLogging);
|
|
59
|
+
this.keepAlive = options.keepAlive ?? false;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Initialize the bridge runtime and start listening for connections
|
|
63
|
+
*/
|
|
64
|
+
initialize() {
|
|
65
|
+
if (this.isInitialized) {
|
|
66
|
+
this.logger.warn("Bridge runtime already initialized");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
this.setupPortListener();
|
|
70
|
+
if (this.keepAlive) {
|
|
71
|
+
this.startKeepAlive();
|
|
72
|
+
}
|
|
73
|
+
this.isInitialized = true;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Setup Chrome runtime port listener
|
|
77
|
+
*/
|
|
78
|
+
setupPortListener() {
|
|
79
|
+
chrome.runtime.onConnect.addListener((port) => {
|
|
80
|
+
try {
|
|
81
|
+
if (!this.isValidPort(port)) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
this.logger.info(`\u{1F4E1} Port connected: ${port.name}`);
|
|
85
|
+
this.setupMessageHandler(port);
|
|
86
|
+
if (chrome.runtime.lastError) {
|
|
87
|
+
this.logger.warn(`Runtime error during port setup: ${chrome.runtime.lastError.message}`);
|
|
88
|
+
chrome.runtime.lastError;
|
|
89
|
+
}
|
|
90
|
+
} catch (error) {
|
|
91
|
+
this.logger.error("Error setting up port listener:", error);
|
|
92
|
+
if (chrome.runtime.lastError) {
|
|
93
|
+
this.logger.warn(`Additional runtime error: ${chrome.runtime.lastError.message}`);
|
|
94
|
+
chrome.runtime.lastError;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Validate incoming port connection
|
|
101
|
+
*/
|
|
102
|
+
isValidPort(port) {
|
|
103
|
+
if (port.name !== this.portName) {
|
|
104
|
+
this.logger.warn(`Ignoring port "${port.name}", expected "${this.portName}"`);
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
const senderId = port.sender?.id;
|
|
108
|
+
if (senderId !== chrome.runtime.id) {
|
|
109
|
+
this.logger.warn(
|
|
110
|
+
`Ignoring port from different extension (senderId: ${senderId}, expected: ${chrome.runtime.id})`
|
|
111
|
+
);
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Setup message handler for connected port
|
|
118
|
+
*/
|
|
119
|
+
setupMessageHandler(port) {
|
|
120
|
+
port.onMessage.addListener(async (request) => {
|
|
121
|
+
const context = this.createPipelineContext(request);
|
|
122
|
+
try {
|
|
123
|
+
this.logger.debug("\u{1F4E8} Received message:", {
|
|
124
|
+
key: request.key,
|
|
125
|
+
id: request.id,
|
|
126
|
+
hasPayload: !!request.payload
|
|
127
|
+
});
|
|
128
|
+
const response = await this.processMessage(context);
|
|
129
|
+
this.sendResponse(port, response);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
const errorResponse = await this.handleError(error, context);
|
|
132
|
+
this.sendResponse(port, errorResponse);
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
port.onDisconnect.addListener(() => {
|
|
136
|
+
if (chrome.runtime.lastError) {
|
|
137
|
+
this.logger.warn(`\u{1F4F4} Port disconnected with error: ${chrome.runtime.lastError.message}`);
|
|
138
|
+
chrome.runtime.lastError;
|
|
139
|
+
} else {
|
|
140
|
+
this.logger.info(`\u{1F4F4} Port disconnected: ${port.name}`);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Create pipeline context for request processing
|
|
146
|
+
*/
|
|
147
|
+
createPipelineContext(request) {
|
|
148
|
+
return {
|
|
149
|
+
request,
|
|
150
|
+
startTime: Date.now(),
|
|
151
|
+
metadata: { ...request.metadata }
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Process message through middleware pipeline and handler
|
|
156
|
+
*/
|
|
157
|
+
async processMessage(context) {
|
|
158
|
+
const { request } = context;
|
|
159
|
+
const handler = this.resolveHandler(request.key);
|
|
160
|
+
const middlewares = MiddlewareRegistry.pipeline(request.key);
|
|
161
|
+
const data = await this.runPipeline(
|
|
162
|
+
middlewares,
|
|
163
|
+
context,
|
|
164
|
+
() => handler.handle(request.payload)
|
|
165
|
+
);
|
|
166
|
+
return {
|
|
167
|
+
id: request.id,
|
|
168
|
+
data,
|
|
169
|
+
timestamp: Date.now()
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Resolve message handler from dependency injection container
|
|
174
|
+
*/
|
|
175
|
+
resolveHandler(key) {
|
|
176
|
+
try {
|
|
177
|
+
const handler = this.container.get(key);
|
|
178
|
+
if (!handler || typeof handler.handle !== "function") {
|
|
179
|
+
throw new Error(`Handler "${key}" does not implement MessageHandler interface`);
|
|
180
|
+
}
|
|
181
|
+
return handler;
|
|
182
|
+
} catch (error) {
|
|
183
|
+
throw new Error(`Failed to resolve handler "${key}": ${error.message}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Execute middleware pipeline with proper error handling
|
|
188
|
+
*/
|
|
189
|
+
async runPipeline(middlewares, context, finalHandler) {
|
|
190
|
+
let currentIndex = -1;
|
|
191
|
+
const executeNext = async () => {
|
|
192
|
+
currentIndex++;
|
|
193
|
+
if (currentIndex === middlewares.length) {
|
|
194
|
+
return finalHandler();
|
|
195
|
+
}
|
|
196
|
+
if (currentIndex > middlewares.length) {
|
|
197
|
+
throw new Error("next() called multiple times");
|
|
198
|
+
}
|
|
199
|
+
const middleware = middlewares[currentIndex];
|
|
200
|
+
return middleware(context, executeNext);
|
|
201
|
+
};
|
|
202
|
+
return executeNext();
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Handle errors during message processing
|
|
206
|
+
*/
|
|
207
|
+
async handleError(error, context) {
|
|
208
|
+
const duration = Date.now() - context.startTime;
|
|
209
|
+
this.logger.error(`\u{1F4A5} Message processing failed after ${duration}ms:`, {
|
|
210
|
+
key: context.request.key,
|
|
211
|
+
id: context.request.id,
|
|
212
|
+
error: error.message
|
|
213
|
+
});
|
|
214
|
+
return this.errorHandler.handle(error, context);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Send response back through the port
|
|
218
|
+
*/
|
|
219
|
+
sendResponse(port, response) {
|
|
220
|
+
try {
|
|
221
|
+
if (!port) {
|
|
222
|
+
this.logger.warn(`Cannot send response: port is null (ID: ${response.id})`);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
port.postMessage(response);
|
|
226
|
+
if (chrome.runtime.lastError) {
|
|
227
|
+
this.logger.warn(
|
|
228
|
+
`Chrome runtime error during postMessage: ${chrome.runtime.lastError.message} (ID: ${response.id})`
|
|
229
|
+
);
|
|
230
|
+
chrome.runtime.lastError;
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
this.logger.debug("\u{1F4E4} Response sent:", {
|
|
234
|
+
id: response.id,
|
|
235
|
+
hasData: !!response.data,
|
|
236
|
+
hasError: !!response.error,
|
|
237
|
+
data: response.data
|
|
238
|
+
});
|
|
239
|
+
} catch (error) {
|
|
240
|
+
this.logger.error("Failed to send response:", error);
|
|
241
|
+
if (chrome.runtime.lastError) {
|
|
242
|
+
this.logger.warn(`Additional Chrome runtime error: ${chrome.runtime.lastError.message}`);
|
|
243
|
+
chrome.runtime.lastError;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Get runtime statistics
|
|
249
|
+
*/
|
|
250
|
+
getStats() {
|
|
251
|
+
return {
|
|
252
|
+
portName: this.portName,
|
|
253
|
+
initialized: this.isInitialized
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Start keep-alive timer to keep service worker alive
|
|
258
|
+
*/
|
|
259
|
+
startKeepAlive() {
|
|
260
|
+
if (this.keepAliveTimer) return;
|
|
261
|
+
this.logger.info("Starting keep-alive timer to keep service worker alive");
|
|
262
|
+
this.keepAliveTimer = setInterval(() => {
|
|
263
|
+
chrome.runtime.getPlatformInfo(() => {
|
|
264
|
+
});
|
|
265
|
+
}, _BridgeRuntimeManager.KEEP_ALIVE_INTERVAL_MS);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Stop keep-alive timer
|
|
269
|
+
*/
|
|
270
|
+
stopKeepAlive() {
|
|
271
|
+
if (this.keepAliveTimer) {
|
|
272
|
+
clearInterval(this.keepAliveTimer);
|
|
273
|
+
this.keepAliveTimer = null;
|
|
274
|
+
this.logger.info("Stopped keep-alive timer");
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
_BridgeRuntimeManager.KEEP_ALIVE_INTERVAL_MS = 25e3;
|
|
279
|
+
let BridgeRuntimeManager = _BridgeRuntimeManager;
|
|
280
|
+
class BridgeLogger {
|
|
281
|
+
constructor(enabled = true) {
|
|
282
|
+
this.enabled = enabled;
|
|
283
|
+
}
|
|
284
|
+
info(message, context) {
|
|
285
|
+
if (!this.enabled) return;
|
|
286
|
+
console.log(`[Bridge] ${message}`);
|
|
287
|
+
if (context) console.log(" Context:", context);
|
|
288
|
+
}
|
|
289
|
+
success(message) {
|
|
290
|
+
if (!this.enabled) return;
|
|
291
|
+
console.log(`[Bridge] ${message}`);
|
|
292
|
+
}
|
|
293
|
+
warn(message) {
|
|
294
|
+
if (!this.enabled) return;
|
|
295
|
+
console.warn(`[Bridge] ${message}`);
|
|
296
|
+
}
|
|
297
|
+
error(message, error) {
|
|
298
|
+
if (!this.enabled) return;
|
|
299
|
+
console.error(`[Bridge] ${message}`);
|
|
300
|
+
if (error) console.error(" Error:", error);
|
|
301
|
+
}
|
|
302
|
+
debug(message, context) {
|
|
303
|
+
if (!this.enabled) return;
|
|
304
|
+
console.debug(`[Bridge] ${message}`);
|
|
305
|
+
if (context) console.debug(" Context:", context);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function bootstrap$1(options) {
|
|
309
|
+
const runtime = new BridgeRuntimeManager(options);
|
|
310
|
+
runtime.initialize();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
class AlarmAdapter {
|
|
314
|
+
constructor() {
|
|
315
|
+
this.callbacks = /* @__PURE__ */ new Map();
|
|
316
|
+
}
|
|
317
|
+
onTrigger(callback) {
|
|
318
|
+
this.triggerCallback = callback;
|
|
319
|
+
}
|
|
320
|
+
schedule(id, when) {
|
|
321
|
+
const delay = Math.max(0, when - Date.now());
|
|
322
|
+
const timeoutId = setTimeout(() => {
|
|
323
|
+
this.callbacks.delete(id);
|
|
324
|
+
this.triggerCallback?.(id);
|
|
325
|
+
}, delay);
|
|
326
|
+
this.callbacks.set(id, () => clearTimeout(timeoutId));
|
|
327
|
+
return timeoutId;
|
|
328
|
+
}
|
|
329
|
+
cancel(id) {
|
|
330
|
+
const callback = this.callbacks.get(id);
|
|
331
|
+
if (callback) {
|
|
332
|
+
callback();
|
|
333
|
+
this.callbacks.delete(id);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
class TimeoutAdapter {
|
|
339
|
+
constructor() {
|
|
340
|
+
this.callbacks = /* @__PURE__ */ new Map();
|
|
341
|
+
}
|
|
342
|
+
onTrigger(callback) {
|
|
343
|
+
this.triggerCallback = callback;
|
|
344
|
+
}
|
|
345
|
+
schedule(id, when) {
|
|
346
|
+
const delay = Math.max(0, when - Date.now());
|
|
347
|
+
const timeoutId = setTimeout(() => {
|
|
348
|
+
this.callbacks.delete(id);
|
|
349
|
+
this.triggerCallback?.(id);
|
|
350
|
+
}, delay);
|
|
351
|
+
this.callbacks.set(id, () => clearTimeout(timeoutId));
|
|
352
|
+
return timeoutId;
|
|
353
|
+
}
|
|
354
|
+
cancel(id) {
|
|
355
|
+
const callback = this.callbacks.get(id);
|
|
356
|
+
if (callback) {
|
|
357
|
+
callback();
|
|
358
|
+
this.callbacks.delete(id);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const _JobRegistry = class _JobRegistry {
|
|
364
|
+
constructor() {
|
|
365
|
+
this.jobs = /* @__PURE__ */ new Map();
|
|
366
|
+
}
|
|
367
|
+
register(id, job, options) {
|
|
368
|
+
const context = this.createJobContext(id, options);
|
|
369
|
+
this.jobs.set(id, {
|
|
370
|
+
job,
|
|
371
|
+
context,
|
|
372
|
+
options
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
resolve(id) {
|
|
376
|
+
const entry = this.jobs.get(id);
|
|
377
|
+
return entry?.job;
|
|
378
|
+
}
|
|
379
|
+
meta(id) {
|
|
380
|
+
const entry = this.jobs.get(id);
|
|
381
|
+
return entry?.options;
|
|
382
|
+
}
|
|
383
|
+
getContext(id) {
|
|
384
|
+
const entry = this.jobs.get(id);
|
|
385
|
+
return entry?.context;
|
|
386
|
+
}
|
|
387
|
+
updateState(id, state) {
|
|
388
|
+
const entry = this.jobs.get(id);
|
|
389
|
+
if (entry) {
|
|
390
|
+
entry.context.state = state;
|
|
391
|
+
entry.context.updatedAt = /* @__PURE__ */ new Date();
|
|
392
|
+
switch (state) {
|
|
393
|
+
case JobState.RUNNING:
|
|
394
|
+
entry.context.startedAt = /* @__PURE__ */ new Date();
|
|
395
|
+
break;
|
|
396
|
+
case JobState.PAUSED:
|
|
397
|
+
entry.context.pausedAt = /* @__PURE__ */ new Date();
|
|
398
|
+
break;
|
|
399
|
+
case JobState.STOPPED:
|
|
400
|
+
entry.context.stoppedAt = /* @__PURE__ */ new Date();
|
|
401
|
+
break;
|
|
402
|
+
case JobState.COMPLETED:
|
|
403
|
+
entry.context.completedAt = /* @__PURE__ */ new Date();
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
setTimeoutId(id, timeoutId) {
|
|
409
|
+
const entry = this.jobs.get(id);
|
|
410
|
+
if (entry) {
|
|
411
|
+
entry.timeoutId = timeoutId;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
setIntervalId(id, intervalId) {
|
|
415
|
+
const entry = this.jobs.get(id);
|
|
416
|
+
if (entry) {
|
|
417
|
+
entry.intervalId = intervalId;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
clearTimers(id) {
|
|
421
|
+
const entry = this.jobs.get(id);
|
|
422
|
+
if (entry) {
|
|
423
|
+
if (entry.timeoutId) {
|
|
424
|
+
clearTimeout(entry.timeoutId);
|
|
425
|
+
entry.timeoutId = void 0;
|
|
426
|
+
}
|
|
427
|
+
if (entry.intervalId) {
|
|
428
|
+
clearInterval(entry.intervalId);
|
|
429
|
+
entry.intervalId = void 0;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
pause(id) {
|
|
434
|
+
const entry = this.jobs.get(id);
|
|
435
|
+
console.log(`Pausing job ${id}`);
|
|
436
|
+
if (entry && entry.context.state === JobState.RUNNING) {
|
|
437
|
+
console.log(`paused job ${id}`);
|
|
438
|
+
this.updateState(id, JobState.PAUSED);
|
|
439
|
+
this.clearTimers(id);
|
|
440
|
+
entry.job.pause?.();
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
resume(id) {
|
|
444
|
+
const entry = this.jobs.get(id);
|
|
445
|
+
console.log(`Resuming job ${id}`);
|
|
446
|
+
if (entry && entry.context.state === JobState.PAUSED) {
|
|
447
|
+
console.log(`Resuming job ${id}`);
|
|
448
|
+
this.updateState(id, JobState.SCHEDULED);
|
|
449
|
+
entry.job.resume?.();
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
stop(id) {
|
|
453
|
+
const entry = this.jobs.get(id);
|
|
454
|
+
if (entry && entry.context.state !== JobState.STOPPED) {
|
|
455
|
+
console.log(`Stopping job ${id}`);
|
|
456
|
+
this.updateState(id, JobState.STOPPED);
|
|
457
|
+
this.clearTimers(id);
|
|
458
|
+
entry.job.stop?.();
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
createJobContext(id, options) {
|
|
462
|
+
const now = /* @__PURE__ */ new Date();
|
|
463
|
+
return {
|
|
464
|
+
id,
|
|
465
|
+
options,
|
|
466
|
+
state: JobState.SCHEDULED,
|
|
467
|
+
createdAt: now,
|
|
468
|
+
updatedAt: now,
|
|
469
|
+
retryCount: 0,
|
|
470
|
+
pause: () => this.pause(id),
|
|
471
|
+
resume: () => this.resume(id),
|
|
472
|
+
stop: () => this.stop(id),
|
|
473
|
+
complete: () => this.updateState(id, JobState.COMPLETED),
|
|
474
|
+
fail: (error) => {
|
|
475
|
+
this.updateState(id, JobState.FAILED);
|
|
476
|
+
const entry = this.jobs.get(id);
|
|
477
|
+
if (entry) entry.context.error = error;
|
|
478
|
+
},
|
|
479
|
+
retry: () => {
|
|
480
|
+
const entry = this.jobs.get(id);
|
|
481
|
+
if (entry) {
|
|
482
|
+
entry.context.retryCount = (entry.context.retryCount || 0) + 1;
|
|
483
|
+
this.updateState(id, JobState.SCHEDULED);
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
isRunning: () => this.getContext(id)?.state === JobState.RUNNING,
|
|
487
|
+
isPaused: () => this.getContext(id)?.state === JobState.PAUSED,
|
|
488
|
+
isStopped: () => this.getContext(id)?.state === JobState.STOPPED,
|
|
489
|
+
isCompleted: () => this.getContext(id)?.state === JobState.COMPLETED,
|
|
490
|
+
isFailed: () => this.getContext(id)?.state === JobState.FAILED,
|
|
491
|
+
isRetrying: () => (this.getContext(id)?.retryCount || 0) > 0,
|
|
492
|
+
isScheduled: () => this.getContext(id)?.state === JobState.SCHEDULED,
|
|
493
|
+
isDelayed: () => !!options.delay,
|
|
494
|
+
isRecurring: () => !!options.cron,
|
|
495
|
+
isCron: () => !!options.cron,
|
|
496
|
+
isTimeout: () => !!options.delay && !options.cron,
|
|
497
|
+
isAlarm: () => !!options.cron || !!options.delay && options.delay > 6e4
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
_JobRegistry.instance = new _JobRegistry();
|
|
502
|
+
let JobRegistry = _JobRegistry;
|
|
503
|
+
|
|
504
|
+
/* Extracts second, minute, hour, date, month and the weekday from a date. */
|
|
505
|
+
function extractDateElements(date) {
|
|
506
|
+
return {
|
|
507
|
+
second: date.getSeconds(),
|
|
508
|
+
minute: date.getMinutes(),
|
|
509
|
+
hour: date.getHours(),
|
|
510
|
+
day: date.getDate(),
|
|
511
|
+
month: date.getMonth(),
|
|
512
|
+
weekday: date.getDay(),
|
|
513
|
+
year: date.getFullYear(),
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
/* Gets the amount of days in the given month (indexed by 0) of the given year. */
|
|
517
|
+
function getDaysInMonth(year, month) {
|
|
518
|
+
return new Date(year, month + 1, 0).getDate();
|
|
519
|
+
}
|
|
520
|
+
/* Gets the amount of days from weekday1 to weekday2. */
|
|
521
|
+
function getDaysBetweenWeekdays(weekday1, weekday2) {
|
|
522
|
+
if (weekday1 <= weekday2) {
|
|
523
|
+
return weekday2 - weekday1;
|
|
524
|
+
}
|
|
525
|
+
return 6 - weekday1 + weekday2 + 1;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
class Cron {
|
|
529
|
+
constructor({ seconds, minutes, hours, days, months, weekdays, }) {
|
|
530
|
+
// Validate that there are values provided.
|
|
531
|
+
if (!seconds || seconds.size === 0)
|
|
532
|
+
throw new Error('There must be at least one allowed second.');
|
|
533
|
+
if (!minutes || minutes.size === 0)
|
|
534
|
+
throw new Error('There must be at least one allowed minute.');
|
|
535
|
+
if (!hours || hours.size === 0)
|
|
536
|
+
throw new Error('There must be at least one allowed hour.');
|
|
537
|
+
if (!months || months.size === 0)
|
|
538
|
+
throw new Error('There must be at least one allowed month.');
|
|
539
|
+
if ((!weekdays || weekdays.size === 0) && (!days || days.size === 0))
|
|
540
|
+
throw new Error('There must be at least one allowed day or weekday.');
|
|
541
|
+
// Convert set to array and sort in ascending order.
|
|
542
|
+
this.seconds = Array.from(seconds).sort((a, b) => a - b);
|
|
543
|
+
this.minutes = Array.from(minutes).sort((a, b) => a - b);
|
|
544
|
+
this.hours = Array.from(hours).sort((a, b) => a - b);
|
|
545
|
+
this.days = Array.from(days).sort((a, b) => a - b);
|
|
546
|
+
this.months = Array.from(months).sort((a, b) => a - b);
|
|
547
|
+
this.weekdays = Array.from(weekdays).sort((a, b) => a - b);
|
|
548
|
+
// Validate that all values are integers within the constraint.
|
|
549
|
+
const validateData = (name, data, constraint) => {
|
|
550
|
+
if (data.some((x) => typeof x !== 'number' ||
|
|
551
|
+
x % 1 !== 0 ||
|
|
552
|
+
x < constraint.min ||
|
|
553
|
+
x > constraint.max)) {
|
|
554
|
+
throw new Error(`${name} must only consist of integers which are within the range of ${constraint.min} and ${constraint.max}`);
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
validateData('seconds', this.seconds, { min: 0, max: 59 });
|
|
558
|
+
validateData('minutes', this.minutes, { min: 0, max: 59 });
|
|
559
|
+
validateData('hours', this.hours, { min: 0, max: 23 });
|
|
560
|
+
validateData('days', this.days, { min: 1, max: 31 });
|
|
561
|
+
validateData('months', this.months, { min: 0, max: 11 });
|
|
562
|
+
validateData('weekdays', this.weekdays, { min: 0, max: 6 });
|
|
563
|
+
// For each element, store a reversed copy in the reversed attribute for finding prev dates.
|
|
564
|
+
this.reversed = {
|
|
565
|
+
seconds: this.seconds.map((x) => x).reverse(),
|
|
566
|
+
minutes: this.minutes.map((x) => x).reverse(),
|
|
567
|
+
hours: this.hours.map((x) => x).reverse(),
|
|
568
|
+
days: this.days.map((x) => x).reverse(),
|
|
569
|
+
months: this.months.map((x) => x).reverse(),
|
|
570
|
+
weekdays: this.weekdays.map((x) => x).reverse(),
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Find the next or previous hour, starting from the given start hour that matches the hour constraint.
|
|
575
|
+
* startHour itself might also be allowed.
|
|
576
|
+
*/
|
|
577
|
+
findAllowedHour(dir, startHour) {
|
|
578
|
+
return dir === 'next'
|
|
579
|
+
? this.hours.find((x) => x >= startHour)
|
|
580
|
+
: this.reversed.hours.find((x) => x <= startHour);
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Find the next or previous minute, starting from the given start minute that matches the minute constraint.
|
|
584
|
+
* startMinute itself might also be allowed.
|
|
585
|
+
*/
|
|
586
|
+
findAllowedMinute(dir, startMinute) {
|
|
587
|
+
return dir === 'next'
|
|
588
|
+
? this.minutes.find((x) => x >= startMinute)
|
|
589
|
+
: this.reversed.minutes.find((x) => x <= startMinute);
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Find the next or previous second, starting from the given start second that matches the second constraint.
|
|
593
|
+
* startSecond itself IS NOT allowed.
|
|
594
|
+
*/
|
|
595
|
+
findAllowedSecond(dir, startSecond) {
|
|
596
|
+
return dir === 'next'
|
|
597
|
+
? this.seconds.find((x) => x > startSecond)
|
|
598
|
+
: this.reversed.seconds.find((x) => x < startSecond);
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Find the next or previous time, starting from the given start time that matches the hour, minute
|
|
602
|
+
* and second constraints. startTime itself might also be allowed.
|
|
603
|
+
*/
|
|
604
|
+
findAllowedTime(dir, startTime) {
|
|
605
|
+
// Try to find an allowed hour.
|
|
606
|
+
let hour = this.findAllowedHour(dir, startTime.hour);
|
|
607
|
+
if (hour !== undefined) {
|
|
608
|
+
if (hour === startTime.hour) {
|
|
609
|
+
// We found an hour that is the start hour. Try to find an allowed minute.
|
|
610
|
+
let minute = this.findAllowedMinute(dir, startTime.minute);
|
|
611
|
+
if (minute !== undefined) {
|
|
612
|
+
if (minute === startTime.minute) {
|
|
613
|
+
// We found a minute that is the start minute. Try to find an allowed second.
|
|
614
|
+
const second = this.findAllowedSecond(dir, startTime.second);
|
|
615
|
+
if (second !== undefined) {
|
|
616
|
+
// We found a second within the start hour and minute.
|
|
617
|
+
return { hour, minute, second };
|
|
618
|
+
}
|
|
619
|
+
// We did not find a valid second within the start minute. Try to find another minute.
|
|
620
|
+
minute = this.findAllowedMinute(dir, dir === 'next' ? startTime.minute + 1 : startTime.minute - 1);
|
|
621
|
+
if (minute !== undefined) {
|
|
622
|
+
// We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
|
|
623
|
+
return {
|
|
624
|
+
hour,
|
|
625
|
+
minute,
|
|
626
|
+
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
else {
|
|
631
|
+
// We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
|
|
632
|
+
return {
|
|
633
|
+
hour,
|
|
634
|
+
minute,
|
|
635
|
+
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
// We did not find an allowed minute / second combination inside the start hour. Try to find the next / previous allowed hour.
|
|
640
|
+
hour = this.findAllowedHour(dir, dir === 'next' ? startTime.hour + 1 : startTime.hour - 1);
|
|
641
|
+
if (hour !== undefined) {
|
|
642
|
+
// We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
|
|
643
|
+
return {
|
|
644
|
+
hour,
|
|
645
|
+
minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
|
|
646
|
+
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
else {
|
|
651
|
+
// We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
|
|
652
|
+
return {
|
|
653
|
+
hour,
|
|
654
|
+
minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
|
|
655
|
+
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
// No allowed time found.
|
|
660
|
+
return undefined;
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Find the next or previous day in the given month, starting from the given startDay
|
|
664
|
+
* that matches either the day or the weekday constraint. startDay itself might also be allowed.
|
|
665
|
+
*/
|
|
666
|
+
findAllowedDayInMonth(dir, year, month, startDay) {
|
|
667
|
+
var _a, _b;
|
|
668
|
+
if (startDay < 1)
|
|
669
|
+
throw new Error('startDay must not be smaller than 1.');
|
|
670
|
+
// If only days are restricted: allow day based on day constraint only.
|
|
671
|
+
// If only weekdays are restricted: allow day based on weekday constraint only.
|
|
672
|
+
// If both are restricted: allow day based on both day and weekday constraint. pick day that is closer to startDay.
|
|
673
|
+
// If none are restricted: return the day closest to startDay (respecting dir) that is allowed (or startDay itself).
|
|
674
|
+
const daysInMonth = getDaysInMonth(year, month);
|
|
675
|
+
const daysRestricted = this.days.length !== 31;
|
|
676
|
+
const weekdaysRestricted = this.weekdays.length !== 7;
|
|
677
|
+
if (!daysRestricted && !weekdaysRestricted) {
|
|
678
|
+
if (startDay > daysInMonth) {
|
|
679
|
+
return dir === 'next' ? undefined : daysInMonth;
|
|
680
|
+
}
|
|
681
|
+
return startDay;
|
|
682
|
+
}
|
|
683
|
+
// Try to find a day based on the days constraint.
|
|
684
|
+
let allowedDayByDays;
|
|
685
|
+
if (daysRestricted) {
|
|
686
|
+
allowedDayByDays =
|
|
687
|
+
dir === 'next'
|
|
688
|
+
? this.days.find((x) => x >= startDay)
|
|
689
|
+
: this.reversed.days.find((x) => x <= startDay);
|
|
690
|
+
// Make sure the day does not exceed the amount of days in month.
|
|
691
|
+
if (allowedDayByDays !== undefined && allowedDayByDays > daysInMonth) {
|
|
692
|
+
allowedDayByDays = undefined;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
// Try to find a day based on the weekday constraint.
|
|
696
|
+
let allowedDayByWeekdays;
|
|
697
|
+
if (weekdaysRestricted) {
|
|
698
|
+
const startWeekday = new Date(year, month, startDay).getDay();
|
|
699
|
+
const nearestAllowedWeekday = dir === 'next'
|
|
700
|
+
? (_a = this.weekdays.find((x) => x >= startWeekday)) !== null && _a !== void 0 ? _a : this.weekdays[0]
|
|
701
|
+
: (_b = this.reversed.weekdays.find((x) => x <= startWeekday)) !== null && _b !== void 0 ? _b : this.reversed.weekdays[0];
|
|
702
|
+
if (nearestAllowedWeekday !== undefined) {
|
|
703
|
+
const daysBetweenWeekdays = dir === 'next'
|
|
704
|
+
? getDaysBetweenWeekdays(startWeekday, nearestAllowedWeekday)
|
|
705
|
+
: getDaysBetweenWeekdays(nearestAllowedWeekday, startWeekday);
|
|
706
|
+
allowedDayByWeekdays =
|
|
707
|
+
dir === 'next'
|
|
708
|
+
? startDay + daysBetweenWeekdays
|
|
709
|
+
: startDay - daysBetweenWeekdays;
|
|
710
|
+
// Make sure the day does not exceed the month boundaries.
|
|
711
|
+
if (allowedDayByWeekdays > daysInMonth || allowedDayByWeekdays < 1) {
|
|
712
|
+
allowedDayByWeekdays = undefined;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (allowedDayByDays !== undefined && allowedDayByWeekdays !== undefined) {
|
|
717
|
+
// If a day is found both via the days and the weekdays constraint, pick the day
|
|
718
|
+
// that is closer to start date.
|
|
719
|
+
return dir === 'next'
|
|
720
|
+
? Math.min(allowedDayByDays, allowedDayByWeekdays)
|
|
721
|
+
: Math.max(allowedDayByDays, allowedDayByWeekdays);
|
|
722
|
+
}
|
|
723
|
+
if (allowedDayByDays !== undefined) {
|
|
724
|
+
return allowedDayByDays;
|
|
725
|
+
}
|
|
726
|
+
if (allowedDayByWeekdays !== undefined) {
|
|
727
|
+
return allowedDayByWeekdays;
|
|
728
|
+
}
|
|
729
|
+
return undefined;
|
|
730
|
+
}
|
|
731
|
+
/** Gets the next date starting from the given start date or now. */
|
|
732
|
+
getNextDate(startDate = new Date()) {
|
|
733
|
+
const startDateElements = extractDateElements(startDate);
|
|
734
|
+
let minYear = startDateElements.year;
|
|
735
|
+
let startIndexMonth = this.months.findIndex((x) => x >= startDateElements.month);
|
|
736
|
+
if (startIndexMonth === -1) {
|
|
737
|
+
startIndexMonth = 0;
|
|
738
|
+
minYear++;
|
|
739
|
+
}
|
|
740
|
+
// We try every month within the next 5 years to make sure that we tried to
|
|
741
|
+
// find a matching date insidde a whole leap year.
|
|
742
|
+
const maxIterations = this.months.length * 5;
|
|
743
|
+
for (let i = 0; i < maxIterations; i++) {
|
|
744
|
+
// Get the next year and month.
|
|
745
|
+
const year = minYear + Math.floor((startIndexMonth + i) / this.months.length);
|
|
746
|
+
const month = this.months[(startIndexMonth + i) % this.months.length];
|
|
747
|
+
const isStartMonth = year === startDateElements.year && month === startDateElements.month;
|
|
748
|
+
// Find the next day.
|
|
749
|
+
let day = this.findAllowedDayInMonth('next', year, month, isStartMonth ? startDateElements.day : 1);
|
|
750
|
+
let isStartDay = isStartMonth && day === startDateElements.day;
|
|
751
|
+
// If we found a day and it is the start day, try to find a valid time beginning from the start date time.
|
|
752
|
+
if (day !== undefined && isStartDay) {
|
|
753
|
+
const nextTime = this.findAllowedTime('next', startDateElements);
|
|
754
|
+
if (nextTime !== undefined) {
|
|
755
|
+
return new Date(year, month, day, nextTime.hour, nextTime.minute, nextTime.second);
|
|
756
|
+
}
|
|
757
|
+
// If no valid time has been found for the start date, try the next day.
|
|
758
|
+
day = this.findAllowedDayInMonth('next', year, month, day + 1);
|
|
759
|
+
isStartDay = false;
|
|
760
|
+
}
|
|
761
|
+
// If we found a next day and it is not the start day, just use the next day with the first allowed values
|
|
762
|
+
// for hours, minutes and seconds.
|
|
763
|
+
if (day !== undefined && !isStartDay) {
|
|
764
|
+
return new Date(year, month, day, this.hours[0], this.minutes[0], this.seconds[0]);
|
|
765
|
+
}
|
|
766
|
+
// No allowed day has been found for this month. Continue to search in next month.
|
|
767
|
+
}
|
|
768
|
+
throw new Error('No valid next date was found.');
|
|
769
|
+
}
|
|
770
|
+
/** Gets the specified amount of future dates starting from the given start date or now. */
|
|
771
|
+
getNextDates(amount, startDate) {
|
|
772
|
+
const dates = [];
|
|
773
|
+
let nextDate;
|
|
774
|
+
for (let i = 0; i < amount; i++) {
|
|
775
|
+
nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
|
|
776
|
+
dates.push(nextDate);
|
|
777
|
+
}
|
|
778
|
+
return dates;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.
|
|
782
|
+
* The iterator runs until the optional endDate is reached or forever.
|
|
783
|
+
*/
|
|
784
|
+
*getNextDatesIterator(startDate, endDate) {
|
|
785
|
+
let nextDate;
|
|
786
|
+
while (true) {
|
|
787
|
+
nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
|
|
788
|
+
if (endDate && endDate.getTime() < nextDate.getTime()) {
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
yield nextDate;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
/** Gets the previous date starting from the given start date or now. */
|
|
795
|
+
getPrevDate(startDate = new Date()) {
|
|
796
|
+
const startDateElements = extractDateElements(startDate);
|
|
797
|
+
let maxYear = startDateElements.year;
|
|
798
|
+
let startIndexMonth = this.reversed.months.findIndex((x) => x <= startDateElements.month);
|
|
799
|
+
if (startIndexMonth === -1) {
|
|
800
|
+
startIndexMonth = 0;
|
|
801
|
+
maxYear--;
|
|
802
|
+
}
|
|
803
|
+
// We try every month within the past 5 years to make sure that we tried to
|
|
804
|
+
// find a matching date inside a whole leap year.
|
|
805
|
+
const maxIterations = this.reversed.months.length * 5;
|
|
806
|
+
for (let i = 0; i < maxIterations; i++) {
|
|
807
|
+
// Get the next year and month.
|
|
808
|
+
const year = maxYear -
|
|
809
|
+
Math.floor((startIndexMonth + i) / this.reversed.months.length);
|
|
810
|
+
const month = this.reversed.months[(startIndexMonth + i) % this.reversed.months.length];
|
|
811
|
+
const isStartMonth = year === startDateElements.year && month === startDateElements.month;
|
|
812
|
+
// Find the previous day.
|
|
813
|
+
let day = this.findAllowedDayInMonth('prev', year, month, isStartMonth
|
|
814
|
+
? startDateElements.day
|
|
815
|
+
: // Start searching from the last day of the month.
|
|
816
|
+
getDaysInMonth(year, month));
|
|
817
|
+
let isStartDay = isStartMonth && day === startDateElements.day;
|
|
818
|
+
// If we found a day and it is the start day, try to find a valid time beginning from the start date time.
|
|
819
|
+
if (day !== undefined && isStartDay) {
|
|
820
|
+
const prevTime = this.findAllowedTime('prev', startDateElements);
|
|
821
|
+
if (prevTime !== undefined) {
|
|
822
|
+
return new Date(year, month, day, prevTime.hour, prevTime.minute, prevTime.second);
|
|
823
|
+
}
|
|
824
|
+
// If no valid time has been found for the start date, try the previous day.
|
|
825
|
+
if (day > 1) {
|
|
826
|
+
day = this.findAllowedDayInMonth('prev', year, month, day - 1);
|
|
827
|
+
isStartDay = false;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
// If we found a previous day and it is not the start day, just use the previous day with the first allowed values
|
|
831
|
+
// for hours, minutes and seconds (which will be the latest time due to using the reversed array).
|
|
832
|
+
if (day !== undefined && !isStartDay) {
|
|
833
|
+
return new Date(year, month, day, this.reversed.hours[0], this.reversed.minutes[0], this.reversed.seconds[0]);
|
|
834
|
+
}
|
|
835
|
+
// No allowed day has been found for this month. Continue to search in previous month.
|
|
836
|
+
}
|
|
837
|
+
throw new Error('No valid previous date was found.');
|
|
838
|
+
}
|
|
839
|
+
/** Gets the specified amount of previous dates starting from the given start date or now. */
|
|
840
|
+
getPrevDates(amount, startDate) {
|
|
841
|
+
const dates = [];
|
|
842
|
+
let prevDate;
|
|
843
|
+
for (let i = 0; i < amount; i++) {
|
|
844
|
+
prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
|
|
845
|
+
dates.push(prevDate);
|
|
846
|
+
}
|
|
847
|
+
return dates;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.
|
|
851
|
+
* The iterator runs until the optional endDate is reached or forever.
|
|
852
|
+
*/
|
|
853
|
+
*getPrevDatesIterator(startDate, endDate) {
|
|
854
|
+
let prevDate;
|
|
855
|
+
while (true) {
|
|
856
|
+
prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
|
|
857
|
+
if (endDate && endDate.getTime() > prevDate.getTime()) {
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
yield prevDate;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
/** Returns true when there is a cron date at the given date. */
|
|
864
|
+
matchDate(date) {
|
|
865
|
+
const { second, minute, hour, day, month, weekday } = extractDateElements(date);
|
|
866
|
+
if (this.seconds.indexOf(second) === -1 ||
|
|
867
|
+
this.minutes.indexOf(minute) === -1 ||
|
|
868
|
+
this.hours.indexOf(hour) === -1 ||
|
|
869
|
+
this.months.indexOf(month) === -1) {
|
|
870
|
+
return false;
|
|
871
|
+
}
|
|
872
|
+
if (this.days.length !== 31 && this.weekdays.length !== 7) {
|
|
873
|
+
return (this.days.indexOf(day) !== -1 || this.weekdays.indexOf(weekday) !== -1);
|
|
874
|
+
}
|
|
875
|
+
return (this.days.indexOf(day) !== -1 && this.weekdays.indexOf(weekday) !== -1);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
const secondConstraint = {
|
|
880
|
+
min: 0,
|
|
881
|
+
max: 59,
|
|
882
|
+
};
|
|
883
|
+
const minuteConstraint = {
|
|
884
|
+
min: 0,
|
|
885
|
+
max: 59,
|
|
886
|
+
};
|
|
887
|
+
const hourConstraint = {
|
|
888
|
+
min: 0,
|
|
889
|
+
max: 23,
|
|
890
|
+
};
|
|
891
|
+
const dayConstraint = {
|
|
892
|
+
min: 1,
|
|
893
|
+
max: 31,
|
|
894
|
+
};
|
|
895
|
+
const monthConstraint = {
|
|
896
|
+
min: 1,
|
|
897
|
+
max: 12,
|
|
898
|
+
aliases: {
|
|
899
|
+
jan: '1',
|
|
900
|
+
feb: '2',
|
|
901
|
+
mar: '3',
|
|
902
|
+
apr: '4',
|
|
903
|
+
may: '5',
|
|
904
|
+
jun: '6',
|
|
905
|
+
jul: '7',
|
|
906
|
+
aug: '8',
|
|
907
|
+
sep: '9',
|
|
908
|
+
oct: '10',
|
|
909
|
+
nov: '11',
|
|
910
|
+
dec: '12',
|
|
911
|
+
},
|
|
912
|
+
};
|
|
913
|
+
const weekdayConstraint = {
|
|
914
|
+
min: 0,
|
|
915
|
+
max: 7,
|
|
916
|
+
aliases: {
|
|
917
|
+
mon: '1',
|
|
918
|
+
tue: '2',
|
|
919
|
+
wed: '3',
|
|
920
|
+
thu: '4',
|
|
921
|
+
fri: '5',
|
|
922
|
+
sat: '6',
|
|
923
|
+
sun: '7',
|
|
924
|
+
},
|
|
925
|
+
};
|
|
926
|
+
const timeNicknames = {
|
|
927
|
+
'@yearly': '0 0 1 1 *',
|
|
928
|
+
'@annually': '0 0 1 1 *',
|
|
929
|
+
'@monthly': '0 0 1 * *',
|
|
930
|
+
'@weekly': '0 0 * * 0',
|
|
931
|
+
'@daily': '0 0 * * *',
|
|
932
|
+
'@hourly': '0 * * * *',
|
|
933
|
+
'@minutely': '* * * * *',
|
|
934
|
+
};
|
|
935
|
+
function parseElement(element, constraint) {
|
|
936
|
+
const result = new Set();
|
|
937
|
+
// If returned set of numbers is empty, the scheduler class interpretes the emtpy set of numbers as all valid values of the constraint
|
|
938
|
+
if (element === '*') {
|
|
939
|
+
for (let i = constraint.min; i <= constraint.max; i = i + 1) {
|
|
940
|
+
result.add(i);
|
|
941
|
+
}
|
|
942
|
+
return result;
|
|
943
|
+
}
|
|
944
|
+
// If the element is a list, parse each element in the list.
|
|
945
|
+
const listElements = element.split(',');
|
|
946
|
+
if (listElements.length > 1) {
|
|
947
|
+
for (const listElement of listElements) {
|
|
948
|
+
const parsedListElement = parseElement(listElement, constraint);
|
|
949
|
+
for (const x of parsedListElement) {
|
|
950
|
+
result.add(x);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return result;
|
|
954
|
+
}
|
|
955
|
+
// Helper function to parse a single element, which includes checking for alias, valid number and constraint min and max.
|
|
956
|
+
const parseSingleElement = (singleElement) => {
|
|
957
|
+
var _a, _b;
|
|
958
|
+
// biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
|
|
959
|
+
singleElement =
|
|
960
|
+
(_b = (_a = constraint.aliases) === null || _a === void 0 ? void 0 : _a[singleElement.toLowerCase()]) !== null && _b !== void 0 ? _b : singleElement;
|
|
961
|
+
const parsedElement = Number.parseInt(singleElement, 10);
|
|
962
|
+
if (Number.isNaN(parsedElement)) {
|
|
963
|
+
throw new Error(`Failed to parse ${element}: ${singleElement} is NaN.`);
|
|
964
|
+
}
|
|
965
|
+
if (parsedElement < constraint.min || parsedElement > constraint.max) {
|
|
966
|
+
throw new Error(`Failed to parse ${element}: ${singleElement} is outside of constraint range of ${constraint.min} - ${constraint.max}.`);
|
|
967
|
+
}
|
|
968
|
+
return parsedElement;
|
|
969
|
+
};
|
|
970
|
+
// Detect if the element is a range.
|
|
971
|
+
// Possible range formats: 'start-end', 'start-end/step', '*', '*/step'.
|
|
972
|
+
// Where start and end can be numbers or aliases.
|
|
973
|
+
// Capture groups: 1: start-end, 2: start, 3: end, 4: /step, 5: step.
|
|
974
|
+
const rangeSegments = /^(([0-9a-zA-Z]+)-([0-9a-zA-Z]+)|\*)(\/([0-9]+))?$/.exec(element);
|
|
975
|
+
// If not, it must be a single element.
|
|
976
|
+
if (rangeSegments === null) {
|
|
977
|
+
result.add(parseSingleElement(element));
|
|
978
|
+
return result;
|
|
979
|
+
}
|
|
980
|
+
// If it is a range, get start and end of the range.
|
|
981
|
+
let parsedStart = rangeSegments[1] === '*'
|
|
982
|
+
? constraint.min
|
|
983
|
+
: parseSingleElement(rangeSegments[2]);
|
|
984
|
+
const parsedEnd = rangeSegments[1] === '*'
|
|
985
|
+
? constraint.max
|
|
986
|
+
: parseSingleElement(rangeSegments[3]);
|
|
987
|
+
// need to catch Sunday, which gets parsed here as 7, but is also legitimate at the start of a range as 0, to avoid the out of order error
|
|
988
|
+
if (constraint === weekdayConstraint &&
|
|
989
|
+
parsedStart === 7 &&
|
|
990
|
+
// this check ensures that sun-sun is not incorrectly parsed as [0,1,2,3,4,5,6]
|
|
991
|
+
parsedEnd !== 7) {
|
|
992
|
+
parsedStart = 0;
|
|
993
|
+
}
|
|
994
|
+
if (parsedStart > parsedEnd) {
|
|
995
|
+
throw new Error(`Failed to parse ${element}: Invalid range (start: ${parsedStart}, end: ${parsedEnd}).`);
|
|
996
|
+
}
|
|
997
|
+
// Check whether there is a custom step defined for the range, defaulting to 1.
|
|
998
|
+
const step = rangeSegments[5];
|
|
999
|
+
let parsedStep = 1;
|
|
1000
|
+
if (step !== undefined) {
|
|
1001
|
+
parsedStep = Number.parseInt(step, 10);
|
|
1002
|
+
if (Number.isNaN(parsedStep)) {
|
|
1003
|
+
throw new Error(`Failed to parse step: ${step} is NaN.`);
|
|
1004
|
+
}
|
|
1005
|
+
if (parsedStep < 1) {
|
|
1006
|
+
throw new Error(`Failed to parse step: Expected ${step} to be greater than 0.`);
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
// Go from start to end of the range by the given steps.
|
|
1010
|
+
for (let i = parsedStart; i <= parsedEnd; i = i + parsedStep) {
|
|
1011
|
+
result.add(i);
|
|
1012
|
+
}
|
|
1013
|
+
return result;
|
|
1014
|
+
}
|
|
1015
|
+
/** Parses a cron expression into a Cron instance. */
|
|
1016
|
+
function parseCronExpression(cronExpression) {
|
|
1017
|
+
var _a;
|
|
1018
|
+
if (typeof cronExpression !== 'string') {
|
|
1019
|
+
throw new TypeError('Invalid cron expression: must be of type string.');
|
|
1020
|
+
}
|
|
1021
|
+
// Convert time nicknames.
|
|
1022
|
+
// biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
|
|
1023
|
+
cronExpression = (_a = timeNicknames[cronExpression.toLowerCase()]) !== null && _a !== void 0 ? _a : cronExpression;
|
|
1024
|
+
// Split the cron expression into its elements, removing empty elements (extra whitespaces).
|
|
1025
|
+
const elements = cronExpression.split(' ').filter((elem) => elem.length > 0);
|
|
1026
|
+
if (elements.length < 5 || elements.length > 6) {
|
|
1027
|
+
throw new Error('Invalid cron expression: expected 5 or 6 elements.');
|
|
1028
|
+
}
|
|
1029
|
+
const rawSeconds = elements.length === 6 ? elements[0] : '0';
|
|
1030
|
+
const rawMinutes = elements.length === 6 ? elements[1] : elements[0];
|
|
1031
|
+
const rawHours = elements.length === 6 ? elements[2] : elements[1];
|
|
1032
|
+
const rawDays = elements.length === 6 ? elements[3] : elements[2];
|
|
1033
|
+
const rawMonths = elements.length === 6 ? elements[4] : elements[3];
|
|
1034
|
+
const rawWeekdays = elements.length === 6 ? elements[5] : elements[4];
|
|
1035
|
+
return new Cron({
|
|
1036
|
+
seconds: parseElement(rawSeconds, secondConstraint),
|
|
1037
|
+
minutes: parseElement(rawMinutes, minuteConstraint),
|
|
1038
|
+
hours: parseElement(rawHours, hourConstraint),
|
|
1039
|
+
days: parseElement(rawDays, dayConstraint),
|
|
1040
|
+
// months in cron are indexed by 1, but Cron expects indexes by 0, so we need to reduce all set values by one.
|
|
1041
|
+
months: new Set(Array.from(parseElement(rawMonths, monthConstraint)).map((x) => x - 1)),
|
|
1042
|
+
weekdays: new Set(Array.from(parseElement(rawWeekdays, weekdayConstraint)).map((x) => x % 7)),
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function getNextCronDate(expr) {
|
|
1047
|
+
try {
|
|
1048
|
+
const interval = parseCronExpression(expr);
|
|
1049
|
+
return interval.getNextDate();
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
console.error("Invalid cron expression:", expr, error);
|
|
1052
|
+
throw new Error("Invalid cron expression");
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
class Scheduler {
|
|
1057
|
+
constructor() {
|
|
1058
|
+
this.registry = JobRegistry.instance;
|
|
1059
|
+
this.alarm = new AlarmAdapter();
|
|
1060
|
+
this.timeout = new TimeoutAdapter();
|
|
1061
|
+
console.log("Scheduler initialized");
|
|
1062
|
+
this.alarm.onTrigger(this.execute.bind(this));
|
|
1063
|
+
this.timeout.onTrigger(this.execute.bind(this));
|
|
1064
|
+
}
|
|
1065
|
+
schedule(id, options) {
|
|
1066
|
+
const context = this.registry.getContext(id);
|
|
1067
|
+
if (!context || context.isStopped()) {
|
|
1068
|
+
console.log(`Job ${id} is stopped, skipping schedule`);
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
console.log(`Scheduling job ${id} with options:`, options);
|
|
1072
|
+
const when = this.getScheduleTime(options);
|
|
1073
|
+
const adapter = when - Date.now() < 6e4 ? this.timeout : this.alarm;
|
|
1074
|
+
const timerId = adapter.schedule(id, when);
|
|
1075
|
+
if (adapter === this.timeout) {
|
|
1076
|
+
this.registry.setTimeoutId(id, timerId);
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
pause(id) {
|
|
1080
|
+
console.log(`Pausing job ${id}`);
|
|
1081
|
+
this.registry.pause(id);
|
|
1082
|
+
}
|
|
1083
|
+
resume(id) {
|
|
1084
|
+
console.log(`Resuming job ${id}`);
|
|
1085
|
+
this.registry.resume(id);
|
|
1086
|
+
const options = this.registry.meta(id);
|
|
1087
|
+
if (options) {
|
|
1088
|
+
this.schedule(id, options);
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
stop(id) {
|
|
1092
|
+
console.log(`Stopping job ${id}`);
|
|
1093
|
+
this.registry.stop(id);
|
|
1094
|
+
}
|
|
1095
|
+
async execute(id) {
|
|
1096
|
+
const job = this.registry.resolve(id);
|
|
1097
|
+
const context = this.registry.getContext(id);
|
|
1098
|
+
if (!job || !context) {
|
|
1099
|
+
console.log(`Job ${id} not found or no context`);
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
if (context.isPaused() || context.isStopped()) {
|
|
1103
|
+
console.log(`Job ${id} is paused or stopped, skipping execution`);
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
try {
|
|
1107
|
+
this.registry.updateState(id, JobState.RUNNING);
|
|
1108
|
+
console.log(`Executing job ${id}`);
|
|
1109
|
+
const jobInstance = container.get(id);
|
|
1110
|
+
console.log(jobInstance);
|
|
1111
|
+
await jobInstance.handle.bind(jobInstance).call(jobInstance, context);
|
|
1112
|
+
if (!context.isStopped() && !context.isPaused()) {
|
|
1113
|
+
this.registry.updateState(id, JobState.COMPLETED);
|
|
1114
|
+
const options = this.registry.meta(id);
|
|
1115
|
+
if (options?.cron) {
|
|
1116
|
+
this.registry.updateState(id, JobState.SCHEDULED);
|
|
1117
|
+
this.schedule(id, options);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
console.error(`Job ${id} execution failed:`, error);
|
|
1122
|
+
context.fail(error);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
getScheduleTime(options) {
|
|
1126
|
+
if (options.delay) return Date.now() + options.delay;
|
|
1127
|
+
if (options.cron) {
|
|
1128
|
+
const date = getNextCronDate(options.cron);
|
|
1129
|
+
if (!date) {
|
|
1130
|
+
throw new Error("Invalid cron expression");
|
|
1131
|
+
}
|
|
1132
|
+
return date.getTime();
|
|
1133
|
+
}
|
|
1134
|
+
return Date.now();
|
|
1135
|
+
}
|
|
1136
|
+
// Public API for job control
|
|
1137
|
+
getJobState(id) {
|
|
1138
|
+
return this.registry.getContext(id)?.state;
|
|
1139
|
+
}
|
|
1140
|
+
listJobs() {
|
|
1141
|
+
const jobs = [];
|
|
1142
|
+
return jobs;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
class ApplicationBootstrap {
|
|
1147
|
+
constructor() {
|
|
1148
|
+
this.serviceDependencies = /* @__PURE__ */ new Map();
|
|
1149
|
+
this.serviceRegistry = /* @__PURE__ */ new Map();
|
|
1150
|
+
this.logger = new BootstrapLogger();
|
|
1151
|
+
this.storeDefinitions = [];
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* Add a store definition to be initialized
|
|
1155
|
+
*/
|
|
1156
|
+
withStore(storeDefinition) {
|
|
1157
|
+
if (storeDefinition && storeDefinition.def && storeDefinition.store) {
|
|
1158
|
+
this.storeDefinitions.push(storeDefinition);
|
|
1159
|
+
}
|
|
1160
|
+
return this;
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Add multiple store definitions to be initialized
|
|
1164
|
+
*/
|
|
1165
|
+
withStores(storeDefinitions) {
|
|
1166
|
+
storeDefinitions.forEach((store) => this.withStore(store));
|
|
1167
|
+
return this;
|
|
1168
|
+
}
|
|
1169
|
+
/**
|
|
1170
|
+
* Create and initialize a new Chroma application instance
|
|
1171
|
+
*/
|
|
1172
|
+
async create({
|
|
1173
|
+
keepPortAlive = false,
|
|
1174
|
+
portName,
|
|
1175
|
+
enableLogs = true
|
|
1176
|
+
}) {
|
|
1177
|
+
try {
|
|
1178
|
+
this.logger = new BootstrapLogger(enableLogs);
|
|
1179
|
+
this.logger.info("\u{1F680} Starting Chroma application bootstrap...");
|
|
1180
|
+
await this.discoverAndInitializeStores();
|
|
1181
|
+
await this.discoverServices();
|
|
1182
|
+
this.analyzeDependencies();
|
|
1183
|
+
await this.registerMessages();
|
|
1184
|
+
await this.registerJobs();
|
|
1185
|
+
await this.bootMessages();
|
|
1186
|
+
await this.bootServices();
|
|
1187
|
+
this.logger.success("\u{1F389} Chroma application initialization complete!");
|
|
1188
|
+
bootstrap$1({ container, keepAlive: keepPortAlive, portName });
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
this.logger.error("\u{1F4A5} Application bootstrap failed:", error);
|
|
1191
|
+
throw error;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* Boot all registered services by calling their onBoot method if present
|
|
1196
|
+
*/
|
|
1197
|
+
async bootServices() {
|
|
1198
|
+
this.logger.info("\u{1F680} Booting services...");
|
|
1199
|
+
console.log("services", this.serviceRegistry.entries());
|
|
1200
|
+
for (const [serviceName, ServiceClass] of this.serviceRegistry.entries()) {
|
|
1201
|
+
try {
|
|
1202
|
+
const instance = container.get(ServiceClass);
|
|
1203
|
+
if (typeof instance.onBoot === "function") {
|
|
1204
|
+
await instance.onBoot();
|
|
1205
|
+
this.logger.success(`Booted service: ${serviceName}`);
|
|
1206
|
+
}
|
|
1207
|
+
} catch (error) {
|
|
1208
|
+
this.logger.error(`Failed to boot service ${serviceName}:`, error);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Discover all services in the application directory
|
|
1214
|
+
*/
|
|
1215
|
+
async discoverServices() {
|
|
1216
|
+
this.logger.info("\u{1F50D} Discovering services...");
|
|
1217
|
+
const serviceModules = undefined(
|
|
1218
|
+
"/src/app/services/**/*.service.{ts,js}",
|
|
1219
|
+
{ eager: true }
|
|
1220
|
+
);
|
|
1221
|
+
const serviceClasses = [];
|
|
1222
|
+
for (const module of Object.values(serviceModules)) {
|
|
1223
|
+
const ServiceClass = module?.default;
|
|
1224
|
+
if (ServiceClass) {
|
|
1225
|
+
serviceClasses.push(ServiceClass);
|
|
1226
|
+
this.serviceRegistry.set(ServiceClass.name, ServiceClass);
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
const circularDepsResult = this.detectCircularDependencies(serviceClasses);
|
|
1230
|
+
if (circularDepsResult.hasCircularDependencies) {
|
|
1231
|
+
this.logger.error("\u{1F4A5} Circular dependencies detected!");
|
|
1232
|
+
circularDepsResult.cycles.forEach((cycle, index) => {
|
|
1233
|
+
this.logger.error(`Cycle ${index + 1}: ${cycle.cycle.join(" \u2192 ")} \u2192 ${cycle.cycle[0]}`);
|
|
1234
|
+
});
|
|
1235
|
+
throw new Error(`Circular dependencies found. Cannot initialize services.`);
|
|
1236
|
+
}
|
|
1237
|
+
for (const ServiceClass of serviceClasses) {
|
|
1238
|
+
container.bind(ServiceClass).toSelf().inSingletonScope();
|
|
1239
|
+
this.logger.debug(`\u{1F4E6} Discovered service: ${ServiceClass.name}`);
|
|
1240
|
+
}
|
|
1241
|
+
this.logger.success(
|
|
1242
|
+
`\u2705 Registered ${serviceClasses.length} services without circular dependencies`
|
|
1243
|
+
);
|
|
1244
|
+
}
|
|
1245
|
+
/**
|
|
1246
|
+
* Detect circular dependencies in service classes using reflection
|
|
1247
|
+
* Enhanced: logs all detected dependencies for debugging
|
|
1248
|
+
*/
|
|
1249
|
+
detectCircularDependencies(serviceClasses) {
|
|
1250
|
+
const dependencyGraph = /* @__PURE__ */ new Map();
|
|
1251
|
+
for (const ServiceClass of serviceClasses) {
|
|
1252
|
+
const dependencies = this.extractDependencies(ServiceClass);
|
|
1253
|
+
this.logger.debug(`[DependencyDetection] ${ServiceClass.name} dependencies:`, {
|
|
1254
|
+
dependencies: dependencies.map(
|
|
1255
|
+
(dep) => typeof dep === "function" ? dep.name : typeof dep === "string" ? dep : dep?.toString()
|
|
1256
|
+
)
|
|
1257
|
+
});
|
|
1258
|
+
const dependencyNames = dependencies.map(
|
|
1259
|
+
(dep) => typeof dep === "function" ? dep.name : typeof dep === "string" ? dep : dep?.toString()
|
|
1260
|
+
);
|
|
1261
|
+
dependencyGraph.set(ServiceClass.name, {
|
|
1262
|
+
service: ServiceClass.name,
|
|
1263
|
+
dependencies: dependencyNames,
|
|
1264
|
+
constructor: ServiceClass
|
|
1265
|
+
});
|
|
1266
|
+
}
|
|
1267
|
+
const cycles = [];
|
|
1268
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1269
|
+
const recursionStack = /* @__PURE__ */ new Set();
|
|
1270
|
+
const currentPath = [];
|
|
1271
|
+
for (const serviceName of dependencyGraph.keys()) {
|
|
1272
|
+
if (!visited.has(serviceName)) {
|
|
1273
|
+
this.detectCycles(
|
|
1274
|
+
serviceName,
|
|
1275
|
+
dependencyGraph,
|
|
1276
|
+
visited,
|
|
1277
|
+
recursionStack,
|
|
1278
|
+
currentPath,
|
|
1279
|
+
cycles
|
|
1280
|
+
);
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
return {
|
|
1284
|
+
hasCircularDependencies: cycles.length > 0,
|
|
1285
|
+
cycles,
|
|
1286
|
+
dependencyGraph
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
/**
|
|
1290
|
+
* Extract dependencies from constructor using reflect-metadata
|
|
1291
|
+
* Fallback: parse constructor parameter names if metadata is missing
|
|
1292
|
+
*/
|
|
1293
|
+
extractDependencies(ServiceClass) {
|
|
1294
|
+
try {
|
|
1295
|
+
const paramTypes = Reflect.getMetadata("design:paramtypes", ServiceClass) || [];
|
|
1296
|
+
const injectMetadata = Reflect.getMetadata("inversify:tagged", ServiceClass) || /* @__PURE__ */ new Map();
|
|
1297
|
+
const dependencies = [];
|
|
1298
|
+
for (let i = 0; i < paramTypes.length; i++) {
|
|
1299
|
+
const paramType = paramTypes[i];
|
|
1300
|
+
const paramMetadata = injectMetadata.get(i);
|
|
1301
|
+
if (paramMetadata && paramMetadata.length > 0) {
|
|
1302
|
+
const injectTag = paramMetadata.find((tag) => tag.key === "inject");
|
|
1303
|
+
if (injectTag) {
|
|
1304
|
+
dependencies.push(injectTag.value);
|
|
1305
|
+
} else {
|
|
1306
|
+
dependencies.push(paramType);
|
|
1307
|
+
}
|
|
1308
|
+
} else {
|
|
1309
|
+
dependencies.push(paramType);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
if (dependencies.length === 0) {
|
|
1313
|
+
const paramNames = this.getConstructorParamNames(ServiceClass);
|
|
1314
|
+
this.logger.debug(
|
|
1315
|
+
`[DependencyDetection:FALLBACK] ${ServiceClass.name} constructor param names:`,
|
|
1316
|
+
{ paramNames }
|
|
1317
|
+
);
|
|
1318
|
+
return paramNames;
|
|
1319
|
+
}
|
|
1320
|
+
return dependencies.filter((dep) => dep && dep !== Object);
|
|
1321
|
+
} catch (error) {
|
|
1322
|
+
this.logger.debug(`Could not extract dependencies for ${ServiceClass.name}: ${error}`);
|
|
1323
|
+
return [];
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Fallback: Parse constructor parameter names from function source
|
|
1328
|
+
*/
|
|
1329
|
+
getConstructorParamNames(ServiceClass) {
|
|
1330
|
+
const constructor = ServiceClass.prototype.constructor;
|
|
1331
|
+
const src = constructor.toString();
|
|
1332
|
+
const match = src.match(/constructor\s*\(([^)]*)\)/);
|
|
1333
|
+
if (!match) return [];
|
|
1334
|
+
const params = match[1].split(",").map((p) => p.trim()).filter((p) => p.length > 0);
|
|
1335
|
+
return params;
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* Perform DFS to detect cycles in dependency graph
|
|
1339
|
+
*/
|
|
1340
|
+
detectCycles(serviceName, graph, visited, recursionStack, currentPath, cycles) {
|
|
1341
|
+
visited.add(serviceName);
|
|
1342
|
+
recursionStack.add(serviceName);
|
|
1343
|
+
currentPath.push(serviceName);
|
|
1344
|
+
const node = graph.get(serviceName);
|
|
1345
|
+
if (!node) {
|
|
1346
|
+
recursionStack.delete(serviceName);
|
|
1347
|
+
currentPath.pop();
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
for (const dependency of node.dependencies) {
|
|
1351
|
+
if (!graph.has(dependency)) {
|
|
1352
|
+
continue;
|
|
1353
|
+
}
|
|
1354
|
+
if (!visited.has(dependency)) {
|
|
1355
|
+
this.detectCycles(dependency, graph, visited, recursionStack, currentPath, cycles);
|
|
1356
|
+
} else if (recursionStack.has(dependency)) {
|
|
1357
|
+
const cycleStartIndex = currentPath.indexOf(dependency);
|
|
1358
|
+
const cycle = currentPath.slice(cycleStartIndex);
|
|
1359
|
+
cycles.push({
|
|
1360
|
+
cycle: [...cycle],
|
|
1361
|
+
services: [...currentPath]
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
recursionStack.delete(serviceName);
|
|
1366
|
+
currentPath.pop();
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Debug method to visualize the dependency graph
|
|
1370
|
+
*/
|
|
1371
|
+
analyzeDependencies() {
|
|
1372
|
+
const serviceClasses = Array.from(this.serviceRegistry.values());
|
|
1373
|
+
const result = this.detectCircularDependencies(serviceClasses);
|
|
1374
|
+
this.logger.info("\u{1F4CA} Dependency Analysis Report:");
|
|
1375
|
+
this.logger.info(`Total Services: ${result.dependencyGraph.size}`);
|
|
1376
|
+
if (result.hasCircularDependencies) {
|
|
1377
|
+
this.logger.error(`\u{1F504} Circular Dependencies Found: ${result.cycles.length}`);
|
|
1378
|
+
result.cycles.forEach((cycle, index) => {
|
|
1379
|
+
this.logger.error(` Cycle ${index + 1}: ${cycle.cycle.join(" \u2192 ")} \u2192 ${cycle.cycle[0]}`);
|
|
1380
|
+
});
|
|
1381
|
+
} else {
|
|
1382
|
+
this.logger.success("\u2705 No circular dependencies detected");
|
|
1383
|
+
}
|
|
1384
|
+
this.logger.info("\u{1F333} Service Dependency Tree:");
|
|
1385
|
+
for (const [serviceName, node] of result.dependencyGraph) {
|
|
1386
|
+
if (node.dependencies.length > 0) {
|
|
1387
|
+
this.logger.info(` ${serviceName} depends on:`);
|
|
1388
|
+
node.dependencies.forEach((dep) => {
|
|
1389
|
+
this.logger.info(` - ${dep}`);
|
|
1390
|
+
});
|
|
1391
|
+
} else {
|
|
1392
|
+
this.logger.info(` ${serviceName} (no dependencies)`);
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Initialize stores from provided definitions
|
|
1398
|
+
*/
|
|
1399
|
+
async discoverAndInitializeStores() {
|
|
1400
|
+
try {
|
|
1401
|
+
if (this.storeDefinitions.length === 0) {
|
|
1402
|
+
this.logger.debug("\u{1F4ED} No store definitions provided");
|
|
1403
|
+
return;
|
|
1404
|
+
}
|
|
1405
|
+
this.logger.info(`Initializing ${this.storeDefinitions.length} store(s)...`);
|
|
1406
|
+
let isFirstStore = true;
|
|
1407
|
+
for (const store of this.storeDefinitions) {
|
|
1408
|
+
const diKey = `CentralStore:${store.def.name}`;
|
|
1409
|
+
const storeInstance = store.store;
|
|
1410
|
+
const classes = store.classes;
|
|
1411
|
+
container.bind(diKey).toConstantValue(storeInstance);
|
|
1412
|
+
if (isFirstStore) {
|
|
1413
|
+
container.bind(Symbol.for("Store")).toConstantValue(storeInstance);
|
|
1414
|
+
isFirstStore = false;
|
|
1415
|
+
}
|
|
1416
|
+
this.registerMessageClass(classes.GetStoreStateMessage, `store:${store.def.name}:getState`);
|
|
1417
|
+
this.registerMessageClass(classes.SetStoreStateMessage, `store:${store.def.name}:setState`);
|
|
1418
|
+
this.registerMessageClass(
|
|
1419
|
+
classes.SubscribeToStoreMessage,
|
|
1420
|
+
`store:${store.def.name}:subscribe`
|
|
1421
|
+
);
|
|
1422
|
+
this.logger.debug(`\u2705 Initialized store: ${store.def.name}`);
|
|
1423
|
+
}
|
|
1424
|
+
this.logger.success(`\u2705 Initialized ${this.storeDefinitions.length} store(s)`);
|
|
1425
|
+
} catch (error) {
|
|
1426
|
+
this.logger.error("\u274C Failed to initialize stores:", error);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Register message handlers
|
|
1431
|
+
*/
|
|
1432
|
+
async registerMessages() {
|
|
1433
|
+
this.logger.info("\u{1F4E8} Registering messages...");
|
|
1434
|
+
const messageModules = undefined(
|
|
1435
|
+
"/src/app/messages/**/*.message.{ts,js}",
|
|
1436
|
+
{ eager: true }
|
|
1437
|
+
);
|
|
1438
|
+
const messageClasses = [];
|
|
1439
|
+
for (const module of Object.values(messageModules)) {
|
|
1440
|
+
const MessageClass = module?.default;
|
|
1441
|
+
if (MessageClass) messageClasses.push(MessageClass);
|
|
1442
|
+
}
|
|
1443
|
+
if (messageClasses.length > 0) {
|
|
1444
|
+
const circularDepsResult = this.detectCircularDependencies(messageClasses);
|
|
1445
|
+
if (circularDepsResult.hasCircularDependencies) {
|
|
1446
|
+
this.logger.error("\u{1F4A5} Circular dependencies detected in messages!");
|
|
1447
|
+
circularDepsResult.cycles.forEach((cycle, index) => {
|
|
1448
|
+
this.logger.error(
|
|
1449
|
+
`Message Cycle ${index + 1}: ${cycle.cycle.join(" \u2192 ")} \u2192 ${cycle.cycle[0]}`
|
|
1450
|
+
);
|
|
1451
|
+
});
|
|
1452
|
+
throw new Error(`Circular dependencies found in messages. Cannot register messages.`);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
for (const module of Object.values(messageModules)) {
|
|
1456
|
+
const MessageClass = module?.default;
|
|
1457
|
+
if (!MessageClass) continue;
|
|
1458
|
+
try {
|
|
1459
|
+
for (const [name, ServiceClass] of this.serviceRegistry) {
|
|
1460
|
+
if (!ServiceClass) {
|
|
1461
|
+
this.logger.warn(`\u26A0\uFE0F Service not found in registry: ${name}`);
|
|
1462
|
+
}
|
|
1463
|
+
if (!container.isBound(ServiceClass)) {
|
|
1464
|
+
this.logger.warn(`\u26A0\uFE0F Service not bound in container: ${name}`);
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
const messageMetadata = Reflect.getMetadata("name", MessageClass);
|
|
1468
|
+
const messageName = messageMetadata || MessageClass.name;
|
|
1469
|
+
container.bind(messageName).to(MessageClass).inSingletonScope();
|
|
1470
|
+
this.logger.success(`\u2705 Registered message: ${messageName}`);
|
|
1471
|
+
} catch (error) {
|
|
1472
|
+
this.logger.error(`\u274C Failed to register message ${MessageClass.name}:`, error);
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
async registerMessageClass(MessageClass, name) {
|
|
1477
|
+
container.bind(name).to(MessageClass).inSingletonScope();
|
|
1478
|
+
this.logger.success(`\u2705 Registered message: ${name}`);
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Boot all registered messages
|
|
1482
|
+
*/
|
|
1483
|
+
async bootMessages() {
|
|
1484
|
+
this.logger.info("\u{1F680} Booting messages...");
|
|
1485
|
+
const messageModules = undefined(
|
|
1486
|
+
"/src/app/messages/**/*.message.{ts,js}",
|
|
1487
|
+
{ eager: true }
|
|
1488
|
+
);
|
|
1489
|
+
for (const module of Object.values(messageModules)) {
|
|
1490
|
+
const MessageClass = module?.default;
|
|
1491
|
+
if (!MessageClass || typeof MessageClass.prototype.boot !== "function") continue;
|
|
1492
|
+
try {
|
|
1493
|
+
const messageMetadata = Reflect.getMetadata("name", MessageClass);
|
|
1494
|
+
const messageName = messageMetadata || MessageClass.name;
|
|
1495
|
+
const messageInstance = container.get(messageName);
|
|
1496
|
+
await messageInstance.boot();
|
|
1497
|
+
this.logger.success(`\u2705 Booted message: ${messageName}`);
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
this.logger.error(`\u274C Failed to boot message ${MessageClass.name}:`, error);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* Register jobs for scheduled execution
|
|
1505
|
+
*/
|
|
1506
|
+
async registerJobs() {
|
|
1507
|
+
this.logger.info("\u{1F552} Registering jobs...");
|
|
1508
|
+
const jobModules = undefined(
|
|
1509
|
+
"/src/app/jobs/**/*.job.{ts,js}",
|
|
1510
|
+
{ eager: true }
|
|
1511
|
+
);
|
|
1512
|
+
if (!container.isBound(Scheduler)) {
|
|
1513
|
+
container.bind(Scheduler).toSelf().inSingletonScope();
|
|
1514
|
+
}
|
|
1515
|
+
console.log("container isBound(Scheduler)", container.isBound(Scheduler));
|
|
1516
|
+
for (const [name, ServiceClass] of this.serviceRegistry) {
|
|
1517
|
+
if (!ServiceClass) {
|
|
1518
|
+
this.logger.warn(`\u26A0\uFE0F Service not found in registry: ${name}`);
|
|
1519
|
+
}
|
|
1520
|
+
if (!container.isBound(ServiceClass)) {
|
|
1521
|
+
this.logger.warn(`\u26A0\uFE0F Service not bound in container: ${name}`);
|
|
1522
|
+
} else {
|
|
1523
|
+
container.get(ServiceClass);
|
|
1524
|
+
console.log("got service", name);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
this.scheduler = container.get(Scheduler);
|
|
1528
|
+
for (const module of Object.values(jobModules)) {
|
|
1529
|
+
const JobClass = module?.default;
|
|
1530
|
+
if (!JobClass) continue;
|
|
1531
|
+
try {
|
|
1532
|
+
const jobMetadata = Reflect.getMetadata("name", JobClass);
|
|
1533
|
+
const jobName = jobMetadata || JobClass.name;
|
|
1534
|
+
container.bind(JobClass).toSelf().inSingletonScope();
|
|
1535
|
+
const id = `${jobName.toLowerCase()}:${JobClass.name.toLowerCase()} ${Math.random().toString(36).substring(2, 15)}`;
|
|
1536
|
+
container.bind(id).to(JobClass).inSingletonScope();
|
|
1537
|
+
const options = Reflect.getMetadata("job:options", JobClass) || {};
|
|
1538
|
+
const instance = container.get(JobClass);
|
|
1539
|
+
JobRegistry.instance.register(id, instance, options);
|
|
1540
|
+
this.scheduler.schedule(id, options);
|
|
1541
|
+
this.logger.success(`\u2705 Registered job: ${jobName}`);
|
|
1542
|
+
} catch (error) {
|
|
1543
|
+
this.logger.error(`\u274C Failed to register job ${JobClass.name}:`, error);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
class BootstrapLogger {
|
|
1549
|
+
constructor(enableLogs = true) {
|
|
1550
|
+
this.enableLogs = enableLogs;
|
|
1551
|
+
}
|
|
1552
|
+
info(message, context) {
|
|
1553
|
+
if (!this.enableLogs) return;
|
|
1554
|
+
console.log(message);
|
|
1555
|
+
if (context) console.log(" ", context);
|
|
1556
|
+
}
|
|
1557
|
+
success(message) {
|
|
1558
|
+
if (!this.enableLogs) return;
|
|
1559
|
+
console.log(message);
|
|
1560
|
+
}
|
|
1561
|
+
warn(message) {
|
|
1562
|
+
if (!this.enableLogs) return;
|
|
1563
|
+
console.warn(message);
|
|
1564
|
+
}
|
|
1565
|
+
error(message, error) {
|
|
1566
|
+
if (!this.enableLogs) return;
|
|
1567
|
+
console.error(message);
|
|
1568
|
+
if (error) console.error(" ", error);
|
|
1569
|
+
}
|
|
1570
|
+
debug(message, context) {
|
|
1571
|
+
if (!this.enableLogs) return;
|
|
1572
|
+
console.debug(message);
|
|
1573
|
+
if (context) console.debug(" ", context);
|
|
1574
|
+
}
|
|
1575
|
+
divider() {
|
|
1576
|
+
if (!this.enableLogs) return;
|
|
1577
|
+
console.log("=".repeat(50));
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
async function create({
|
|
1581
|
+
keepPortAlive = false,
|
|
1582
|
+
portName,
|
|
1583
|
+
enableLogs = true
|
|
1584
|
+
} = {}) {
|
|
1585
|
+
const bootstrap2 = new ApplicationBootstrap();
|
|
1586
|
+
await bootstrap2.create({
|
|
1587
|
+
keepPortAlive,
|
|
1588
|
+
portName,
|
|
1589
|
+
enableLogs
|
|
1590
|
+
});
|
|
1591
|
+
}
|
|
1592
|
+
function bootstrap() {
|
|
1593
|
+
return new BootstrapBuilder();
|
|
1594
|
+
}
|
|
1595
|
+
class BootstrapBuilder {
|
|
1596
|
+
constructor() {
|
|
1597
|
+
this.app = new ApplicationBootstrap();
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* Add a store definition to be initialized
|
|
1601
|
+
*/
|
|
1602
|
+
withStore(storeDefinition) {
|
|
1603
|
+
this.app.withStore(storeDefinition);
|
|
1604
|
+
return this;
|
|
1605
|
+
}
|
|
1606
|
+
/**
|
|
1607
|
+
* Add multiple store definitions to be initialized
|
|
1608
|
+
*/
|
|
1609
|
+
withStores(storeDefinitions) {
|
|
1610
|
+
this.app.withStores(storeDefinitions);
|
|
1611
|
+
return this;
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* Create and start the application
|
|
1615
|
+
*/
|
|
1616
|
+
async create({
|
|
1617
|
+
keepPortAlive = false,
|
|
1618
|
+
portName,
|
|
1619
|
+
enableLogs = true
|
|
1620
|
+
} = {}) {
|
|
1621
|
+
await this.app.create({ keepPortAlive, portName, enableLogs });
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
exports.JobState = JobState;
|
|
1626
|
+
exports.bootstrap = bootstrap;
|
|
1627
|
+
exports.container = container;
|
|
1628
|
+
exports.create = create;
|
|
1629
|
+
//# sourceMappingURL=boot-Dl66KPJQ.js.map
|