miqro.js 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -0
- package/dist/cli.js +3164 -0
- package/dist/index.js +3033 -0
- package/package.json +34 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3164 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
9
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
10
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
11
|
+
for (let key of __getOwnPropNames(mod))
|
|
12
|
+
if (!__hasOwnProp.call(to, key))
|
|
13
|
+
__defProp(to, key, {
|
|
14
|
+
get: () => mod[key],
|
|
15
|
+
enumerable: true
|
|
16
|
+
});
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
20
|
+
var __require = import.meta.require;
|
|
21
|
+
|
|
22
|
+
// node_modules/node-cron/dist/esm/create-id.js
|
|
23
|
+
var require_create_id = __commonJS((exports) => {
|
|
24
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
25
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
26
|
+
};
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.createID = createID;
|
|
29
|
+
var node_crypto_1 = __importDefault(__require("crypto"));
|
|
30
|
+
function createID(prefix = "", length = 16) {
|
|
31
|
+
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
32
|
+
const values = node_crypto_1.default.randomBytes(length);
|
|
33
|
+
const id = Array.from(values, (v) => charset[v % charset.length]).join("");
|
|
34
|
+
return prefix ? `${prefix}-${id}` : id;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// node_modules/node-cron/dist/esm/logger.js
|
|
39
|
+
var require_logger = __commonJS((exports) => {
|
|
40
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
41
|
+
var levelColors = {
|
|
42
|
+
INFO: "\x1B[36m",
|
|
43
|
+
WARN: "\x1B[33m",
|
|
44
|
+
ERROR: "\x1B[31m",
|
|
45
|
+
DEBUG: "\x1B[35m"
|
|
46
|
+
};
|
|
47
|
+
var GREEN = "\x1B[32m";
|
|
48
|
+
var RESET = "\x1B[0m";
|
|
49
|
+
function log2(level, message, extra) {
|
|
50
|
+
const timestamp = new Date().toISOString();
|
|
51
|
+
const color = levelColors[level] ?? "";
|
|
52
|
+
const prefix = `[${timestamp}] [PID: ${process.pid}] ${GREEN}[NODE-CRON]${GREEN} ${color}[${level}]${RESET}`;
|
|
53
|
+
const output = `${prefix} ${message}`;
|
|
54
|
+
switch (level) {
|
|
55
|
+
case "ERROR":
|
|
56
|
+
console.error(output, extra ?? "");
|
|
57
|
+
break;
|
|
58
|
+
case "DEBUG":
|
|
59
|
+
console.debug(output, extra ?? "");
|
|
60
|
+
break;
|
|
61
|
+
case "WARN":
|
|
62
|
+
console.warn(output);
|
|
63
|
+
break;
|
|
64
|
+
case "INFO":
|
|
65
|
+
default:
|
|
66
|
+
console.info(output);
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
var logger2 = {
|
|
71
|
+
info(message) {
|
|
72
|
+
log2("INFO", message);
|
|
73
|
+
},
|
|
74
|
+
warn(message) {
|
|
75
|
+
log2("WARN", message);
|
|
76
|
+
},
|
|
77
|
+
error(message, err) {
|
|
78
|
+
if (message instanceof Error) {
|
|
79
|
+
log2("ERROR", message.message, message);
|
|
80
|
+
} else {
|
|
81
|
+
log2("ERROR", message, err);
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
debug(message, err) {
|
|
85
|
+
if (message instanceof Error) {
|
|
86
|
+
log2("DEBUG", message.message, message);
|
|
87
|
+
} else {
|
|
88
|
+
log2("DEBUG", message, err);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
exports.default = logger2;
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// node_modules/node-cron/dist/esm/promise/tracked-promise.js
|
|
96
|
+
var require_tracked_promise = __commonJS((exports) => {
|
|
97
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
98
|
+
exports.TrackedPromise = undefined;
|
|
99
|
+
|
|
100
|
+
class TrackedPromise {
|
|
101
|
+
promise;
|
|
102
|
+
error;
|
|
103
|
+
state;
|
|
104
|
+
value;
|
|
105
|
+
constructor(executor) {
|
|
106
|
+
this.state = "pending";
|
|
107
|
+
this.promise = new Promise((resolve, reject) => {
|
|
108
|
+
executor((value) => {
|
|
109
|
+
this.state = "fulfilled";
|
|
110
|
+
this.value = value;
|
|
111
|
+
resolve(value);
|
|
112
|
+
}, (error) => {
|
|
113
|
+
this.state = "rejected";
|
|
114
|
+
this.error = error;
|
|
115
|
+
reject(error);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
getPromise() {
|
|
120
|
+
return this.promise;
|
|
121
|
+
}
|
|
122
|
+
getState() {
|
|
123
|
+
return this.state;
|
|
124
|
+
}
|
|
125
|
+
isPending() {
|
|
126
|
+
return this.state === "pending";
|
|
127
|
+
}
|
|
128
|
+
isFulfilled() {
|
|
129
|
+
return this.state === "fulfilled";
|
|
130
|
+
}
|
|
131
|
+
isRejected() {
|
|
132
|
+
return this.state === "rejected";
|
|
133
|
+
}
|
|
134
|
+
getValue() {
|
|
135
|
+
return this.value;
|
|
136
|
+
}
|
|
137
|
+
getError() {
|
|
138
|
+
return this.error;
|
|
139
|
+
}
|
|
140
|
+
then(onfulfilled, onrejected) {
|
|
141
|
+
return this.promise.then(onfulfilled, onrejected);
|
|
142
|
+
}
|
|
143
|
+
catch(onrejected) {
|
|
144
|
+
return this.promise.catch(onrejected);
|
|
145
|
+
}
|
|
146
|
+
finally(onfinally) {
|
|
147
|
+
return this.promise.finally(onfinally);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.TrackedPromise = TrackedPromise;
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// node_modules/node-cron/dist/esm/scheduler/runner.js
|
|
154
|
+
var require_runner = __commonJS((exports) => {
|
|
155
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
156
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
157
|
+
};
|
|
158
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
159
|
+
exports.Runner = undefined;
|
|
160
|
+
var create_id_1 = require_create_id();
|
|
161
|
+
var logger_1 = __importDefault(require_logger());
|
|
162
|
+
var tracked_promise_1 = require_tracked_promise();
|
|
163
|
+
function emptyOnFn() {}
|
|
164
|
+
function emptyHookFn() {
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
function defaultOnError(date, error) {
|
|
168
|
+
logger_1.default.error("Task failed with error!", error);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
class Runner {
|
|
172
|
+
timeMatcher;
|
|
173
|
+
onMatch;
|
|
174
|
+
noOverlap;
|
|
175
|
+
maxExecutions;
|
|
176
|
+
maxRandomDelay;
|
|
177
|
+
runCount;
|
|
178
|
+
running;
|
|
179
|
+
heartBeatTimeout;
|
|
180
|
+
onMissedExecution;
|
|
181
|
+
onOverlap;
|
|
182
|
+
onError;
|
|
183
|
+
beforeRun;
|
|
184
|
+
onFinished;
|
|
185
|
+
onMaxExecutions;
|
|
186
|
+
constructor(timeMatcher, onMatch, options) {
|
|
187
|
+
this.timeMatcher = timeMatcher;
|
|
188
|
+
this.onMatch = onMatch;
|
|
189
|
+
this.noOverlap = options == undefined || options.noOverlap === undefined ? false : options.noOverlap;
|
|
190
|
+
this.maxExecutions = options?.maxExecutions;
|
|
191
|
+
this.maxRandomDelay = options?.maxRandomDelay || 0;
|
|
192
|
+
this.onMissedExecution = options?.onMissedExecution || emptyOnFn;
|
|
193
|
+
this.onOverlap = options?.onOverlap || emptyOnFn;
|
|
194
|
+
this.onError = options?.onError || defaultOnError;
|
|
195
|
+
this.onFinished = options?.onFinished || emptyHookFn;
|
|
196
|
+
this.beforeRun = options?.beforeRun || emptyHookFn;
|
|
197
|
+
this.onMaxExecutions = options?.onMaxExecutions || emptyOnFn;
|
|
198
|
+
this.runCount = 0;
|
|
199
|
+
this.running = false;
|
|
200
|
+
}
|
|
201
|
+
start() {
|
|
202
|
+
this.running = true;
|
|
203
|
+
let lastExecution;
|
|
204
|
+
let expectedNextExecution;
|
|
205
|
+
const scheduleNextHeartBeat = (currentDate) => {
|
|
206
|
+
if (this.running) {
|
|
207
|
+
clearTimeout(this.heartBeatTimeout);
|
|
208
|
+
this.heartBeatTimeout = setTimeout(heartBeat, getDelay(this.timeMatcher, currentDate));
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
const runTask = (date) => {
|
|
212
|
+
return new Promise(async (resolve) => {
|
|
213
|
+
const execution = {
|
|
214
|
+
id: (0, create_id_1.createID)("exec"),
|
|
215
|
+
reason: "scheduled"
|
|
216
|
+
};
|
|
217
|
+
const shouldExecute = await this.beforeRun(date, execution);
|
|
218
|
+
const randomDelay = Math.floor(Math.random() * this.maxRandomDelay);
|
|
219
|
+
if (shouldExecute) {
|
|
220
|
+
setTimeout(async () => {
|
|
221
|
+
try {
|
|
222
|
+
this.runCount++;
|
|
223
|
+
execution.startedAt = new Date;
|
|
224
|
+
const result = await this.onMatch(date, execution);
|
|
225
|
+
execution.finishedAt = new Date;
|
|
226
|
+
execution.result = result;
|
|
227
|
+
this.onFinished(date, execution);
|
|
228
|
+
if (this.maxExecutions && this.runCount >= this.maxExecutions) {
|
|
229
|
+
this.onMaxExecutions(date);
|
|
230
|
+
this.stop();
|
|
231
|
+
}
|
|
232
|
+
} catch (error) {
|
|
233
|
+
execution.finishedAt = new Date;
|
|
234
|
+
execution.error = error;
|
|
235
|
+
this.onError(date, error, execution);
|
|
236
|
+
}
|
|
237
|
+
resolve(true);
|
|
238
|
+
}, randomDelay);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
const checkAndRun = (date) => {
|
|
243
|
+
return new tracked_promise_1.TrackedPromise(async (resolve, reject) => {
|
|
244
|
+
try {
|
|
245
|
+
if (this.timeMatcher.match(date)) {
|
|
246
|
+
await runTask(date);
|
|
247
|
+
}
|
|
248
|
+
resolve(true);
|
|
249
|
+
} catch (err) {
|
|
250
|
+
reject(err);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
};
|
|
254
|
+
const heartBeat = async () => {
|
|
255
|
+
const currentDate = nowWithoutMs();
|
|
256
|
+
if (expectedNextExecution && expectedNextExecution.getTime() < currentDate.getTime()) {
|
|
257
|
+
while (expectedNextExecution.getTime() < currentDate.getTime()) {
|
|
258
|
+
logger_1.default.warn(`missed execution at ${expectedNextExecution}! Possible blocking IO or high CPU user at the same process used by node-cron.`);
|
|
259
|
+
expectedNextExecution = this.timeMatcher.getNextMatch(expectedNextExecution);
|
|
260
|
+
runAsync(this.onMissedExecution, expectedNextExecution, defaultOnError);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (lastExecution && lastExecution.getState() === "pending") {
|
|
264
|
+
runAsync(this.onOverlap, currentDate, defaultOnError);
|
|
265
|
+
if (this.noOverlap) {
|
|
266
|
+
logger_1.default.warn("task still running, new execution blocked by overlap prevention!");
|
|
267
|
+
expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
|
|
268
|
+
scheduleNextHeartBeat(currentDate);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
lastExecution = checkAndRun(currentDate);
|
|
273
|
+
expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
|
|
274
|
+
scheduleNextHeartBeat(currentDate);
|
|
275
|
+
};
|
|
276
|
+
this.heartBeatTimeout = setTimeout(() => {
|
|
277
|
+
heartBeat();
|
|
278
|
+
}, getDelay(this.timeMatcher, nowWithoutMs()));
|
|
279
|
+
}
|
|
280
|
+
nextRun() {
|
|
281
|
+
return this.timeMatcher.getNextMatch(new Date);
|
|
282
|
+
}
|
|
283
|
+
stop() {
|
|
284
|
+
this.running = false;
|
|
285
|
+
if (this.heartBeatTimeout) {
|
|
286
|
+
clearTimeout(this.heartBeatTimeout);
|
|
287
|
+
this.heartBeatTimeout = undefined;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
isStarted() {
|
|
291
|
+
return !!this.heartBeatTimeout && this.running;
|
|
292
|
+
}
|
|
293
|
+
isStopped() {
|
|
294
|
+
return !this.isStarted();
|
|
295
|
+
}
|
|
296
|
+
async execute() {
|
|
297
|
+
const date = new Date;
|
|
298
|
+
const execution = {
|
|
299
|
+
id: (0, create_id_1.createID)("exec"),
|
|
300
|
+
reason: "invoked"
|
|
301
|
+
};
|
|
302
|
+
try {
|
|
303
|
+
const shouldExecute = await this.beforeRun(date, execution);
|
|
304
|
+
if (shouldExecute) {
|
|
305
|
+
this.runCount++;
|
|
306
|
+
execution.startedAt = new Date;
|
|
307
|
+
const result = await this.onMatch(date, execution);
|
|
308
|
+
execution.finishedAt = new Date;
|
|
309
|
+
execution.result = result;
|
|
310
|
+
this.onFinished(date, execution);
|
|
311
|
+
}
|
|
312
|
+
} catch (error) {
|
|
313
|
+
execution.finishedAt = new Date;
|
|
314
|
+
execution.error = error;
|
|
315
|
+
this.onError(date, error, execution);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
exports.Runner = Runner;
|
|
320
|
+
async function runAsync(fn, date, onError) {
|
|
321
|
+
try {
|
|
322
|
+
await fn(date);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
onError(date, error);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function getDelay(timeMatcher, currentDate) {
|
|
328
|
+
const maxDelay = 86400000;
|
|
329
|
+
const nextRun = timeMatcher.getNextMatch(currentDate);
|
|
330
|
+
const now = new Date;
|
|
331
|
+
const delay = nextRun.getTime() - now.getTime();
|
|
332
|
+
if (delay > maxDelay) {
|
|
333
|
+
return maxDelay;
|
|
334
|
+
}
|
|
335
|
+
return Math.max(0, delay);
|
|
336
|
+
}
|
|
337
|
+
function nowWithoutMs() {
|
|
338
|
+
const date = new Date;
|
|
339
|
+
date.setMilliseconds(0);
|
|
340
|
+
return date;
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// node_modules/node-cron/dist/esm/pattern/convertion/month-names-conversion.js
|
|
345
|
+
var require_month_names_conversion = __commonJS((exports) => {
|
|
346
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
347
|
+
exports.default = (() => {
|
|
348
|
+
const months = [
|
|
349
|
+
"january",
|
|
350
|
+
"february",
|
|
351
|
+
"march",
|
|
352
|
+
"april",
|
|
353
|
+
"may",
|
|
354
|
+
"june",
|
|
355
|
+
"july",
|
|
356
|
+
"august",
|
|
357
|
+
"september",
|
|
358
|
+
"october",
|
|
359
|
+
"november",
|
|
360
|
+
"december"
|
|
361
|
+
];
|
|
362
|
+
const shortMonths = [
|
|
363
|
+
"jan",
|
|
364
|
+
"feb",
|
|
365
|
+
"mar",
|
|
366
|
+
"apr",
|
|
367
|
+
"may",
|
|
368
|
+
"jun",
|
|
369
|
+
"jul",
|
|
370
|
+
"aug",
|
|
371
|
+
"sep",
|
|
372
|
+
"oct",
|
|
373
|
+
"nov",
|
|
374
|
+
"dec"
|
|
375
|
+
];
|
|
376
|
+
function convertMonthName(expression, items) {
|
|
377
|
+
for (let i = 0;i < items.length; i++) {
|
|
378
|
+
expression = expression.replace(new RegExp(items[i], "gi"), i + 1);
|
|
379
|
+
}
|
|
380
|
+
return expression;
|
|
381
|
+
}
|
|
382
|
+
function interprete(monthExpression) {
|
|
383
|
+
monthExpression = convertMonthName(monthExpression, months);
|
|
384
|
+
monthExpression = convertMonthName(monthExpression, shortMonths);
|
|
385
|
+
return monthExpression;
|
|
386
|
+
}
|
|
387
|
+
return interprete;
|
|
388
|
+
})();
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
// node_modules/node-cron/dist/esm/pattern/convertion/week-day-names-conversion.js
|
|
392
|
+
var require_week_day_names_conversion = __commonJS((exports) => {
|
|
393
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
394
|
+
exports.default = (() => {
|
|
395
|
+
const weekDays = [
|
|
396
|
+
"sunday",
|
|
397
|
+
"monday",
|
|
398
|
+
"tuesday",
|
|
399
|
+
"wednesday",
|
|
400
|
+
"thursday",
|
|
401
|
+
"friday",
|
|
402
|
+
"saturday"
|
|
403
|
+
];
|
|
404
|
+
const shortWeekDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
405
|
+
function convertWeekDayName(expression, items) {
|
|
406
|
+
for (let i = 0;i < items.length; i++) {
|
|
407
|
+
expression = expression.replace(new RegExp(items[i], "gi"), i);
|
|
408
|
+
}
|
|
409
|
+
return expression;
|
|
410
|
+
}
|
|
411
|
+
function convertWeekDays(expression) {
|
|
412
|
+
expression = expression.replace("7", "0");
|
|
413
|
+
expression = convertWeekDayName(expression, weekDays);
|
|
414
|
+
return convertWeekDayName(expression, shortWeekDays);
|
|
415
|
+
}
|
|
416
|
+
return convertWeekDays;
|
|
417
|
+
})();
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
// node_modules/node-cron/dist/esm/pattern/convertion/asterisk-to-range-conversion.js
|
|
421
|
+
var require_asterisk_to_range_conversion = __commonJS((exports) => {
|
|
422
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
423
|
+
exports.default = (() => {
|
|
424
|
+
function convertAsterisk(expression, replecement) {
|
|
425
|
+
if (expression.indexOf("*") !== -1) {
|
|
426
|
+
return expression.replace("*", replecement);
|
|
427
|
+
}
|
|
428
|
+
return expression;
|
|
429
|
+
}
|
|
430
|
+
function convertAsterisksToRanges(expressions) {
|
|
431
|
+
expressions[0] = convertAsterisk(expressions[0], "0-59");
|
|
432
|
+
expressions[1] = convertAsterisk(expressions[1], "0-59");
|
|
433
|
+
expressions[2] = convertAsterisk(expressions[2], "0-23");
|
|
434
|
+
expressions[3] = convertAsterisk(expressions[3], "1-31");
|
|
435
|
+
expressions[4] = convertAsterisk(expressions[4], "1-12");
|
|
436
|
+
expressions[5] = convertAsterisk(expressions[5], "0-6");
|
|
437
|
+
return expressions;
|
|
438
|
+
}
|
|
439
|
+
return convertAsterisksToRanges;
|
|
440
|
+
})();
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
// node_modules/node-cron/dist/esm/pattern/convertion/range-conversion.js
|
|
444
|
+
var require_range_conversion = __commonJS((exports) => {
|
|
445
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
446
|
+
exports.default = (() => {
|
|
447
|
+
function replaceWithRange(expression, text, init, end, stepTxt) {
|
|
448
|
+
const step = parseInt(stepTxt);
|
|
449
|
+
const numbers = [];
|
|
450
|
+
let last = parseInt(end);
|
|
451
|
+
let first = parseInt(init);
|
|
452
|
+
if (first > last) {
|
|
453
|
+
last = parseInt(init);
|
|
454
|
+
first = parseInt(end);
|
|
455
|
+
}
|
|
456
|
+
for (let i = first;i <= last; i += step) {
|
|
457
|
+
numbers.push(i);
|
|
458
|
+
}
|
|
459
|
+
return expression.replace(new RegExp(text, "i"), numbers.join());
|
|
460
|
+
}
|
|
461
|
+
function convertRange(expression) {
|
|
462
|
+
const rangeRegEx = /(\d+)-(\d+)(\/(\d+)|)/;
|
|
463
|
+
let match2 = rangeRegEx.exec(expression);
|
|
464
|
+
while (match2 !== null && match2.length > 0) {
|
|
465
|
+
expression = replaceWithRange(expression, match2[0], match2[1], match2[2], match2[4] || "1");
|
|
466
|
+
match2 = rangeRegEx.exec(expression);
|
|
467
|
+
}
|
|
468
|
+
return expression;
|
|
469
|
+
}
|
|
470
|
+
function convertAllRanges(expressions) {
|
|
471
|
+
for (let i = 0;i < expressions.length; i++) {
|
|
472
|
+
expressions[i] = convertRange(expressions[i]);
|
|
473
|
+
}
|
|
474
|
+
return expressions;
|
|
475
|
+
}
|
|
476
|
+
return convertAllRanges;
|
|
477
|
+
})();
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
// node_modules/node-cron/dist/esm/pattern/convertion/index.js
|
|
481
|
+
var require_convertion = __commonJS((exports) => {
|
|
482
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
483
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
484
|
+
};
|
|
485
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
486
|
+
var month_names_conversion_1 = __importDefault(require_month_names_conversion());
|
|
487
|
+
var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
|
|
488
|
+
var asterisk_to_range_conversion_1 = __importDefault(require_asterisk_to_range_conversion());
|
|
489
|
+
var range_conversion_1 = __importDefault(require_range_conversion());
|
|
490
|
+
exports.default = (() => {
|
|
491
|
+
function appendSeccondExpression(expressions) {
|
|
492
|
+
if (expressions.length === 5) {
|
|
493
|
+
return ["0"].concat(expressions);
|
|
494
|
+
}
|
|
495
|
+
return expressions;
|
|
496
|
+
}
|
|
497
|
+
function removeSpaces(str) {
|
|
498
|
+
return str.replace(/\s{2,}/g, " ").trim();
|
|
499
|
+
}
|
|
500
|
+
function normalizeIntegers(expressions) {
|
|
501
|
+
for (let i = 0;i < expressions.length; i++) {
|
|
502
|
+
const numbers = expressions[i].split(",");
|
|
503
|
+
for (let j = 0;j < numbers.length; j++) {
|
|
504
|
+
numbers[j] = parseInt(numbers[j]);
|
|
505
|
+
}
|
|
506
|
+
expressions[i] = numbers;
|
|
507
|
+
}
|
|
508
|
+
return expressions;
|
|
509
|
+
}
|
|
510
|
+
function interprete(expression) {
|
|
511
|
+
let expressions = removeSpaces(`${expression}`).split(" ");
|
|
512
|
+
expressions = appendSeccondExpression(expressions);
|
|
513
|
+
expressions[4] = (0, month_names_conversion_1.default)(expressions[4]);
|
|
514
|
+
expressions[5] = (0, week_day_names_conversion_1.default)(expressions[5]);
|
|
515
|
+
expressions = (0, asterisk_to_range_conversion_1.default)(expressions);
|
|
516
|
+
expressions = (0, range_conversion_1.default)(expressions);
|
|
517
|
+
expressions = normalizeIntegers(expressions);
|
|
518
|
+
return expressions;
|
|
519
|
+
}
|
|
520
|
+
return interprete;
|
|
521
|
+
})();
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
// node_modules/node-cron/dist/esm/time/localized-time.js
|
|
525
|
+
var require_localized_time = __commonJS((exports) => {
|
|
526
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
527
|
+
exports.LocalizedTime = undefined;
|
|
528
|
+
|
|
529
|
+
class LocalizedTime {
|
|
530
|
+
timestamp;
|
|
531
|
+
parts;
|
|
532
|
+
timezone;
|
|
533
|
+
constructor(date, timezone) {
|
|
534
|
+
this.timestamp = date.getTime();
|
|
535
|
+
this.timezone = timezone;
|
|
536
|
+
this.parts = buildDateParts(date, timezone);
|
|
537
|
+
}
|
|
538
|
+
toDate() {
|
|
539
|
+
return new Date(this.timestamp);
|
|
540
|
+
}
|
|
541
|
+
toISO() {
|
|
542
|
+
const gmt = this.parts.gmt.replace(/^GMT/, "");
|
|
543
|
+
const offset = gmt ? gmt : "Z";
|
|
544
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
545
|
+
return `${this.parts.year}-${pad(this.parts.month)}-${pad(this.parts.day)}` + `T${pad(this.parts.hour)}:${pad(this.parts.minute)}:${pad(this.parts.second)}` + `.${String(this.parts.milisecond).padStart(3, "0")}` + offset;
|
|
546
|
+
}
|
|
547
|
+
getParts() {
|
|
548
|
+
return this.parts;
|
|
549
|
+
}
|
|
550
|
+
set(field, value) {
|
|
551
|
+
this.parts[field] = value;
|
|
552
|
+
const newDate = new Date(this.toISO());
|
|
553
|
+
this.timestamp = newDate.getTime();
|
|
554
|
+
this.parts = buildDateParts(newDate, this.timezone);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
exports.LocalizedTime = LocalizedTime;
|
|
558
|
+
function buildDateParts(date, timezone) {
|
|
559
|
+
const dftOptions = {
|
|
560
|
+
year: "numeric",
|
|
561
|
+
month: "2-digit",
|
|
562
|
+
day: "2-digit",
|
|
563
|
+
hour: "2-digit",
|
|
564
|
+
minute: "2-digit",
|
|
565
|
+
second: "2-digit",
|
|
566
|
+
weekday: "short",
|
|
567
|
+
hour12: false
|
|
568
|
+
};
|
|
569
|
+
if (timezone) {
|
|
570
|
+
dftOptions.timeZone = timezone;
|
|
571
|
+
}
|
|
572
|
+
const dateFormat = new Intl.DateTimeFormat("en-US", dftOptions);
|
|
573
|
+
const parts = dateFormat.formatToParts(date).filter((part) => {
|
|
574
|
+
return part.type !== "literal";
|
|
575
|
+
}).reduce((acc, part) => {
|
|
576
|
+
acc[part.type] = part.value;
|
|
577
|
+
return acc;
|
|
578
|
+
}, {});
|
|
579
|
+
return {
|
|
580
|
+
day: parseInt(parts.day),
|
|
581
|
+
month: parseInt(parts.month),
|
|
582
|
+
year: parseInt(parts.year),
|
|
583
|
+
hour: parts.hour === "24" ? 0 : parseInt(parts.hour),
|
|
584
|
+
minute: parseInt(parts.minute),
|
|
585
|
+
second: parseInt(parts.second),
|
|
586
|
+
milisecond: date.getMilliseconds(),
|
|
587
|
+
weekday: parts.weekday,
|
|
588
|
+
gmt: getTimezoneGMT(date, timezone)
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
function getTimezoneGMT(date, timezone) {
|
|
592
|
+
const utcDate = new Date(date.toLocaleString("en-US", { timeZone: "UTC" }));
|
|
593
|
+
const tzDate = new Date(date.toLocaleString("en-US", { timeZone: timezone }));
|
|
594
|
+
let offsetInMinutes = (utcDate.getTime() - tzDate.getTime()) / 60000;
|
|
595
|
+
const sign = offsetInMinutes <= 0 ? "+" : "-";
|
|
596
|
+
offsetInMinutes = Math.abs(offsetInMinutes);
|
|
597
|
+
if (offsetInMinutes === 0)
|
|
598
|
+
return "Z";
|
|
599
|
+
const hours = Math.floor(offsetInMinutes / 60).toString().padStart(2, "0");
|
|
600
|
+
const minutes = Math.floor(offsetInMinutes % 60).toString().padStart(2, "0");
|
|
601
|
+
return `GMT${sign}${hours}:${minutes}`;
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
// node_modules/node-cron/dist/esm/time/matcher-walker.js
|
|
606
|
+
var require_matcher_walker = __commonJS((exports) => {
|
|
607
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
608
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
609
|
+
};
|
|
610
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
611
|
+
exports.MatcherWalker = undefined;
|
|
612
|
+
var convertion_1 = __importDefault(require_convertion());
|
|
613
|
+
var localized_time_1 = require_localized_time();
|
|
614
|
+
var time_matcher_1 = require_time_matcher();
|
|
615
|
+
var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
|
|
616
|
+
|
|
617
|
+
class MatcherWalker {
|
|
618
|
+
cronExpression;
|
|
619
|
+
baseDate;
|
|
620
|
+
pattern;
|
|
621
|
+
expressions;
|
|
622
|
+
timeMatcher;
|
|
623
|
+
timezone;
|
|
624
|
+
constructor(cronExpression, baseDate, timezone) {
|
|
625
|
+
this.cronExpression = cronExpression;
|
|
626
|
+
this.baseDate = baseDate;
|
|
627
|
+
this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, timezone);
|
|
628
|
+
this.timezone = timezone;
|
|
629
|
+
this.expressions = (0, convertion_1.default)(cronExpression);
|
|
630
|
+
}
|
|
631
|
+
isMatching() {
|
|
632
|
+
return this.timeMatcher.match(this.baseDate);
|
|
633
|
+
}
|
|
634
|
+
matchNext() {
|
|
635
|
+
const findNextDateIgnoringWeekday = () => {
|
|
636
|
+
const baseDate = new Date(this.baseDate.getTime());
|
|
637
|
+
baseDate.setMilliseconds(0);
|
|
638
|
+
const localTime = new localized_time_1.LocalizedTime(baseDate, this.timezone);
|
|
639
|
+
const dateParts = localTime.getParts();
|
|
640
|
+
const date2 = new localized_time_1.LocalizedTime(localTime.toDate(), this.timezone);
|
|
641
|
+
const seconds = this.expressions[0];
|
|
642
|
+
const nextSecond = availableValue(seconds, dateParts.second);
|
|
643
|
+
if (nextSecond) {
|
|
644
|
+
date2.set("second", nextSecond);
|
|
645
|
+
if (this.timeMatcher.match(date2.toDate())) {
|
|
646
|
+
return date2;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
date2.set("second", seconds[0]);
|
|
650
|
+
const minutes = this.expressions[1];
|
|
651
|
+
const nextMinute = availableValue(minutes, dateParts.minute);
|
|
652
|
+
if (nextMinute) {
|
|
653
|
+
date2.set("minute", nextMinute);
|
|
654
|
+
if (this.timeMatcher.match(date2.toDate())) {
|
|
655
|
+
return date2;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
date2.set("minute", minutes[0]);
|
|
659
|
+
const hours = this.expressions[2];
|
|
660
|
+
const nextHour = availableValue(hours, dateParts.hour);
|
|
661
|
+
if (nextHour) {
|
|
662
|
+
date2.set("hour", nextHour);
|
|
663
|
+
if (this.timeMatcher.match(date2.toDate())) {
|
|
664
|
+
return date2;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
date2.set("hour", hours[0]);
|
|
668
|
+
const days = this.expressions[3];
|
|
669
|
+
const nextDay = availableValue(days, dateParts.day);
|
|
670
|
+
if (nextDay) {
|
|
671
|
+
date2.set("day", nextDay);
|
|
672
|
+
if (this.timeMatcher.match(date2.toDate())) {
|
|
673
|
+
return date2;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
date2.set("day", days[0]);
|
|
677
|
+
const months = this.expressions[4];
|
|
678
|
+
const nextMonth = availableValue(months, dateParts.month);
|
|
679
|
+
if (nextMonth) {
|
|
680
|
+
date2.set("month", nextMonth);
|
|
681
|
+
if (this.timeMatcher.match(date2.toDate())) {
|
|
682
|
+
return date2;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
date2.set("year", date2.getParts().year + 1);
|
|
686
|
+
date2.set("month", months[0]);
|
|
687
|
+
return date2;
|
|
688
|
+
};
|
|
689
|
+
const date = findNextDateIgnoringWeekday();
|
|
690
|
+
const weekdays = this.expressions[5];
|
|
691
|
+
let currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
|
|
692
|
+
while (!(weekdays.indexOf(currentWeekday) > -1)) {
|
|
693
|
+
date.set("year", date.getParts().year + 1);
|
|
694
|
+
currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
|
|
695
|
+
}
|
|
696
|
+
return date;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
exports.MatcherWalker = MatcherWalker;
|
|
700
|
+
function availableValue(values, currentValue) {
|
|
701
|
+
const availableValues = values.sort((a, b) => a - b).filter((s) => s > currentValue);
|
|
702
|
+
if (availableValues.length > 0)
|
|
703
|
+
return availableValues[0];
|
|
704
|
+
return false;
|
|
705
|
+
}
|
|
706
|
+
});
|
|
707
|
+
|
|
708
|
+
// node_modules/node-cron/dist/esm/time/time-matcher.js
|
|
709
|
+
var require_time_matcher = __commonJS((exports) => {
|
|
710
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
711
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
712
|
+
};
|
|
713
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
714
|
+
exports.TimeMatcher = undefined;
|
|
715
|
+
var index_1 = __importDefault(require_convertion());
|
|
716
|
+
var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
|
|
717
|
+
var localized_time_1 = require_localized_time();
|
|
718
|
+
var matcher_walker_1 = require_matcher_walker();
|
|
719
|
+
function matchValue(allowedValues, value) {
|
|
720
|
+
return allowedValues.indexOf(value) !== -1;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
class TimeMatcher {
|
|
724
|
+
timezone;
|
|
725
|
+
pattern;
|
|
726
|
+
expressions;
|
|
727
|
+
constructor(pattern, timezone) {
|
|
728
|
+
this.timezone = timezone;
|
|
729
|
+
this.pattern = pattern;
|
|
730
|
+
this.expressions = (0, index_1.default)(pattern);
|
|
731
|
+
}
|
|
732
|
+
match(date) {
|
|
733
|
+
const localizedTime = new localized_time_1.LocalizedTime(date, this.timezone);
|
|
734
|
+
const parts = localizedTime.getParts();
|
|
735
|
+
const runOnSecond = matchValue(this.expressions[0], parts.second);
|
|
736
|
+
const runOnMinute = matchValue(this.expressions[1], parts.minute);
|
|
737
|
+
const runOnHour = matchValue(this.expressions[2], parts.hour);
|
|
738
|
+
const runOnDay = matchValue(this.expressions[3], parts.day);
|
|
739
|
+
const runOnMonth = matchValue(this.expressions[4], parts.month);
|
|
740
|
+
const runOnWeekDay = matchValue(this.expressions[5], parseInt((0, week_day_names_conversion_1.default)(parts.weekday)));
|
|
741
|
+
return runOnSecond && runOnMinute && runOnHour && runOnDay && runOnMonth && runOnWeekDay;
|
|
742
|
+
}
|
|
743
|
+
getNextMatch(date) {
|
|
744
|
+
const walker = new matcher_walker_1.MatcherWalker(this.pattern, date, this.timezone);
|
|
745
|
+
const next = walker.matchNext();
|
|
746
|
+
return next.toDate();
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
exports.TimeMatcher = TimeMatcher;
|
|
750
|
+
});
|
|
751
|
+
|
|
752
|
+
// node_modules/node-cron/dist/esm/tasks/state-machine.js
|
|
753
|
+
var require_state_machine = __commonJS((exports) => {
|
|
754
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
755
|
+
exports.StateMachine = undefined;
|
|
756
|
+
var allowedTransitions = {
|
|
757
|
+
stopped: ["stopped", "idle", "destroyed"],
|
|
758
|
+
idle: ["idle", "running", "stopped", "destroyed"],
|
|
759
|
+
running: ["running", "idle", "stopped", "destroyed"],
|
|
760
|
+
destroyed: ["destroyed"]
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
class StateMachine {
|
|
764
|
+
state;
|
|
765
|
+
constructor(initial = "stopped") {
|
|
766
|
+
this.state = initial;
|
|
767
|
+
}
|
|
768
|
+
changeState(state) {
|
|
769
|
+
if (allowedTransitions[this.state].includes(state)) {
|
|
770
|
+
this.state = state;
|
|
771
|
+
} else {
|
|
772
|
+
throw new Error(`invalid transition from ${this.state} to ${state}`);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
exports.StateMachine = StateMachine;
|
|
777
|
+
});
|
|
778
|
+
|
|
779
|
+
// node_modules/node-cron/dist/esm/tasks/inline-scheduled-task.js
|
|
780
|
+
var require_inline_scheduled_task = __commonJS((exports) => {
|
|
781
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
782
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
783
|
+
};
|
|
784
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
785
|
+
exports.InlineScheduledTask = undefined;
|
|
786
|
+
var events_1 = __importDefault(__require("events"));
|
|
787
|
+
var runner_1 = require_runner();
|
|
788
|
+
var time_matcher_1 = require_time_matcher();
|
|
789
|
+
var create_id_1 = require_create_id();
|
|
790
|
+
var state_machine_1 = require_state_machine();
|
|
791
|
+
var logger_1 = __importDefault(require_logger());
|
|
792
|
+
var localized_time_1 = require_localized_time();
|
|
793
|
+
|
|
794
|
+
class TaskEmitter extends events_1.default {
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
class InlineScheduledTask {
|
|
798
|
+
emitter;
|
|
799
|
+
cronExpression;
|
|
800
|
+
timeMatcher;
|
|
801
|
+
runner;
|
|
802
|
+
id;
|
|
803
|
+
name;
|
|
804
|
+
stateMachine;
|
|
805
|
+
timezone;
|
|
806
|
+
constructor(cronExpression, taskFn, options) {
|
|
807
|
+
this.emitter = new TaskEmitter;
|
|
808
|
+
this.cronExpression = cronExpression;
|
|
809
|
+
this.id = (0, create_id_1.createID)("task", 12);
|
|
810
|
+
this.name = options?.name || this.id;
|
|
811
|
+
this.timezone = options?.timezone;
|
|
812
|
+
this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, options?.timezone);
|
|
813
|
+
this.stateMachine = new state_machine_1.StateMachine;
|
|
814
|
+
const runnerOptions = {
|
|
815
|
+
timezone: options?.timezone,
|
|
816
|
+
noOverlap: options?.noOverlap,
|
|
817
|
+
maxExecutions: options?.maxExecutions,
|
|
818
|
+
maxRandomDelay: options?.maxRandomDelay,
|
|
819
|
+
beforeRun: (date, execution) => {
|
|
820
|
+
if (execution.reason === "scheduled") {
|
|
821
|
+
this.changeState("running");
|
|
822
|
+
}
|
|
823
|
+
this.emitter.emit("execution:started", this.createContext(date, execution));
|
|
824
|
+
return true;
|
|
825
|
+
},
|
|
826
|
+
onFinished: (date, execution) => {
|
|
827
|
+
if (execution.reason === "scheduled") {
|
|
828
|
+
this.changeState("idle");
|
|
829
|
+
}
|
|
830
|
+
this.emitter.emit("execution:finished", this.createContext(date, execution));
|
|
831
|
+
return true;
|
|
832
|
+
},
|
|
833
|
+
onError: (date, error, execution) => {
|
|
834
|
+
logger_1.default.error(error);
|
|
835
|
+
this.emitter.emit("execution:failed", this.createContext(date, execution));
|
|
836
|
+
this.changeState("idle");
|
|
837
|
+
},
|
|
838
|
+
onOverlap: (date) => {
|
|
839
|
+
this.emitter.emit("execution:overlap", this.createContext(date));
|
|
840
|
+
},
|
|
841
|
+
onMissedExecution: (date) => {
|
|
842
|
+
this.emitter.emit("execution:missed", this.createContext(date));
|
|
843
|
+
},
|
|
844
|
+
onMaxExecutions: (date) => {
|
|
845
|
+
this.emitter.emit("execution:maxReached", this.createContext(date));
|
|
846
|
+
this.destroy();
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
this.runner = new runner_1.Runner(this.timeMatcher, (date, execution) => {
|
|
850
|
+
return taskFn(this.createContext(date, execution));
|
|
851
|
+
}, runnerOptions);
|
|
852
|
+
}
|
|
853
|
+
getNextRun() {
|
|
854
|
+
if (this.stateMachine.state !== "stopped") {
|
|
855
|
+
return this.runner.nextRun();
|
|
856
|
+
}
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
changeState(state) {
|
|
860
|
+
if (this.runner.isStarted()) {
|
|
861
|
+
this.stateMachine.changeState(state);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
start() {
|
|
865
|
+
if (this.runner.isStopped()) {
|
|
866
|
+
this.runner.start();
|
|
867
|
+
this.stateMachine.changeState("idle");
|
|
868
|
+
this.emitter.emit("task:started", this.createContext(new Date));
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
stop() {
|
|
872
|
+
if (this.runner.isStarted()) {
|
|
873
|
+
this.runner.stop();
|
|
874
|
+
this.stateMachine.changeState("stopped");
|
|
875
|
+
this.emitter.emit("task:stopped", this.createContext(new Date));
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
getStatus() {
|
|
879
|
+
return this.stateMachine.state;
|
|
880
|
+
}
|
|
881
|
+
destroy() {
|
|
882
|
+
if (this.stateMachine.state === "destroyed")
|
|
883
|
+
return;
|
|
884
|
+
this.stop();
|
|
885
|
+
this.stateMachine.changeState("destroyed");
|
|
886
|
+
this.emitter.emit("task:destroyed", this.createContext(new Date));
|
|
887
|
+
}
|
|
888
|
+
execute() {
|
|
889
|
+
return new Promise((resolve, reject) => {
|
|
890
|
+
const onFail = (context) => {
|
|
891
|
+
this.off("execution:finished", onFail);
|
|
892
|
+
reject(context.execution?.error);
|
|
893
|
+
};
|
|
894
|
+
const onFinished = (context) => {
|
|
895
|
+
this.off("execution:failed", onFail);
|
|
896
|
+
resolve(context.execution?.result);
|
|
897
|
+
};
|
|
898
|
+
this.once("execution:finished", onFinished);
|
|
899
|
+
this.once("execution:failed", onFail);
|
|
900
|
+
this.runner.execute();
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
on(event, fun) {
|
|
904
|
+
this.emitter.on(event, fun);
|
|
905
|
+
}
|
|
906
|
+
off(event, fun) {
|
|
907
|
+
this.emitter.off(event, fun);
|
|
908
|
+
}
|
|
909
|
+
once(event, fun) {
|
|
910
|
+
this.emitter.once(event, fun);
|
|
911
|
+
}
|
|
912
|
+
createContext(executionDate, execution) {
|
|
913
|
+
const localTime = new localized_time_1.LocalizedTime(executionDate, this.timezone);
|
|
914
|
+
const ctx = {
|
|
915
|
+
date: localTime.toDate(),
|
|
916
|
+
dateLocalIso: localTime.toISO(),
|
|
917
|
+
triggeredAt: new Date,
|
|
918
|
+
task: this,
|
|
919
|
+
execution
|
|
920
|
+
};
|
|
921
|
+
return ctx;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
exports.InlineScheduledTask = InlineScheduledTask;
|
|
925
|
+
});
|
|
926
|
+
|
|
927
|
+
// node_modules/node-cron/dist/esm/task-registry.js
|
|
928
|
+
var require_task_registry = __commonJS((exports) => {
|
|
929
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
930
|
+
exports.TaskRegistry = undefined;
|
|
931
|
+
var tasks = new Map;
|
|
932
|
+
|
|
933
|
+
class TaskRegistry {
|
|
934
|
+
add(task) {
|
|
935
|
+
if (this.has(task.id)) {
|
|
936
|
+
throw Error(`task ${task.id} already registred!`);
|
|
937
|
+
}
|
|
938
|
+
tasks.set(task.id, task);
|
|
939
|
+
task.on("task:destroyed", () => {
|
|
940
|
+
this.remove(task);
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
get(taskId) {
|
|
944
|
+
return tasks.get(taskId);
|
|
945
|
+
}
|
|
946
|
+
remove(task) {
|
|
947
|
+
if (this.has(task.id)) {
|
|
948
|
+
task?.destroy();
|
|
949
|
+
tasks.delete(task.id);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
all() {
|
|
953
|
+
return tasks;
|
|
954
|
+
}
|
|
955
|
+
has(taskId) {
|
|
956
|
+
return tasks.has(taskId);
|
|
957
|
+
}
|
|
958
|
+
killAll() {
|
|
959
|
+
tasks.forEach((id) => this.remove(id));
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
exports.TaskRegistry = TaskRegistry;
|
|
963
|
+
});
|
|
964
|
+
|
|
965
|
+
// node_modules/node-cron/dist/esm/pattern/validation/pattern-validation.js
|
|
966
|
+
var require_pattern_validation = __commonJS((exports) => {
|
|
967
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
968
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
969
|
+
};
|
|
970
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
971
|
+
var index_1 = __importDefault(require_convertion());
|
|
972
|
+
var validationRegex = /^(?:\d+|\*|\*\/\d+)$/;
|
|
973
|
+
function isValidExpression(expression, min, max) {
|
|
974
|
+
const options = expression;
|
|
975
|
+
for (const option of options) {
|
|
976
|
+
const optionAsInt = parseInt(option, 10);
|
|
977
|
+
if (!Number.isNaN(optionAsInt) && (optionAsInt < min || optionAsInt > max) || !validationRegex.test(option))
|
|
978
|
+
return false;
|
|
979
|
+
}
|
|
980
|
+
return true;
|
|
981
|
+
}
|
|
982
|
+
function isInvalidSecond(expression) {
|
|
983
|
+
return !isValidExpression(expression, 0, 59);
|
|
984
|
+
}
|
|
985
|
+
function isInvalidMinute(expression) {
|
|
986
|
+
return !isValidExpression(expression, 0, 59);
|
|
987
|
+
}
|
|
988
|
+
function isInvalidHour(expression) {
|
|
989
|
+
return !isValidExpression(expression, 0, 23);
|
|
990
|
+
}
|
|
991
|
+
function isInvalidDayOfMonth(expression) {
|
|
992
|
+
return !isValidExpression(expression, 1, 31);
|
|
993
|
+
}
|
|
994
|
+
function isInvalidMonth(expression) {
|
|
995
|
+
return !isValidExpression(expression, 1, 12);
|
|
996
|
+
}
|
|
997
|
+
function isInvalidWeekDay(expression) {
|
|
998
|
+
return !isValidExpression(expression, 0, 7);
|
|
999
|
+
}
|
|
1000
|
+
function validateFields(patterns, executablePatterns) {
|
|
1001
|
+
if (isInvalidSecond(executablePatterns[0]))
|
|
1002
|
+
throw new Error(`${patterns[0]} is a invalid expression for second`);
|
|
1003
|
+
if (isInvalidMinute(executablePatterns[1]))
|
|
1004
|
+
throw new Error(`${patterns[1]} is a invalid expression for minute`);
|
|
1005
|
+
if (isInvalidHour(executablePatterns[2]))
|
|
1006
|
+
throw new Error(`${patterns[2]} is a invalid expression for hour`);
|
|
1007
|
+
if (isInvalidDayOfMonth(executablePatterns[3]))
|
|
1008
|
+
throw new Error(`${patterns[3]} is a invalid expression for day of month`);
|
|
1009
|
+
if (isInvalidMonth(executablePatterns[4]))
|
|
1010
|
+
throw new Error(`${patterns[4]} is a invalid expression for month`);
|
|
1011
|
+
if (isInvalidWeekDay(executablePatterns[5]))
|
|
1012
|
+
throw new Error(`${patterns[5]} is a invalid expression for week day`);
|
|
1013
|
+
}
|
|
1014
|
+
function validate(pattern) {
|
|
1015
|
+
if (typeof pattern !== "string")
|
|
1016
|
+
throw new TypeError("pattern must be a string!");
|
|
1017
|
+
const patterns = pattern.split(" ");
|
|
1018
|
+
const executablePatterns = (0, index_1.default)(pattern);
|
|
1019
|
+
if (patterns.length === 5)
|
|
1020
|
+
patterns.unshift("0");
|
|
1021
|
+
validateFields(patterns, executablePatterns);
|
|
1022
|
+
}
|
|
1023
|
+
exports.default = validate;
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
// node_modules/node-cron/dist/esm/tasks/background-scheduled-task/background-scheduled-task.js
|
|
1027
|
+
var require_background_scheduled_task = __commonJS((exports) => {
|
|
1028
|
+
var __dirname = "/Users/antonwerschinin/Code/miqro/node_modules/node-cron/dist/esm/tasks/background-scheduled-task";
|
|
1029
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
1030
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
1031
|
+
};
|
|
1032
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1033
|
+
var path_1 = __require("path");
|
|
1034
|
+
var child_process_1 = __require("child_process");
|
|
1035
|
+
var create_id_1 = require_create_id();
|
|
1036
|
+
var stream_1 = __require("stream");
|
|
1037
|
+
var state_machine_1 = require_state_machine();
|
|
1038
|
+
var localized_time_1 = require_localized_time();
|
|
1039
|
+
var logger_1 = __importDefault(require_logger());
|
|
1040
|
+
var time_matcher_1 = require_time_matcher();
|
|
1041
|
+
var daemonPath = (0, path_1.resolve)(__dirname, "daemon.js");
|
|
1042
|
+
|
|
1043
|
+
class TaskEmitter extends stream_1.EventEmitter {
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
class BackgroundScheduledTask {
|
|
1047
|
+
emitter;
|
|
1048
|
+
id;
|
|
1049
|
+
name;
|
|
1050
|
+
cronExpression;
|
|
1051
|
+
taskPath;
|
|
1052
|
+
options;
|
|
1053
|
+
forkProcess;
|
|
1054
|
+
stateMachine;
|
|
1055
|
+
constructor(cronExpression, taskPath, options) {
|
|
1056
|
+
this.cronExpression = cronExpression;
|
|
1057
|
+
this.taskPath = taskPath;
|
|
1058
|
+
this.options = options;
|
|
1059
|
+
this.id = (0, create_id_1.createID)("task");
|
|
1060
|
+
this.name = options?.name || this.id;
|
|
1061
|
+
this.emitter = new TaskEmitter;
|
|
1062
|
+
this.stateMachine = new state_machine_1.StateMachine("stopped");
|
|
1063
|
+
this.on("task:stopped", () => {
|
|
1064
|
+
this.forkProcess?.kill();
|
|
1065
|
+
this.forkProcess = undefined;
|
|
1066
|
+
this.stateMachine.changeState("stopped");
|
|
1067
|
+
});
|
|
1068
|
+
this.on("task:destroyed", () => {
|
|
1069
|
+
this.forkProcess?.kill();
|
|
1070
|
+
this.forkProcess = undefined;
|
|
1071
|
+
this.stateMachine.changeState("destroyed");
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
getNextRun() {
|
|
1075
|
+
if (this.stateMachine.state !== "stopped") {
|
|
1076
|
+
const timeMatcher = new time_matcher_1.TimeMatcher(this.cronExpression, this.options?.timezone);
|
|
1077
|
+
return timeMatcher.getNextMatch(new Date);
|
|
1078
|
+
}
|
|
1079
|
+
return null;
|
|
1080
|
+
}
|
|
1081
|
+
start() {
|
|
1082
|
+
return new Promise((resolve, reject) => {
|
|
1083
|
+
if (this.forkProcess) {
|
|
1084
|
+
return resolve(undefined);
|
|
1085
|
+
}
|
|
1086
|
+
const timeout = setTimeout(() => {
|
|
1087
|
+
reject(new Error("Start operation timed out"));
|
|
1088
|
+
}, 5000);
|
|
1089
|
+
try {
|
|
1090
|
+
this.forkProcess = (0, child_process_1.fork)(daemonPath);
|
|
1091
|
+
this.forkProcess.on("error", (err) => {
|
|
1092
|
+
clearTimeout(timeout);
|
|
1093
|
+
reject(new Error(`Error on daemon: ${err.message}`));
|
|
1094
|
+
});
|
|
1095
|
+
this.forkProcess.on("exit", (code, signal) => {
|
|
1096
|
+
if (code !== 0 && signal !== "SIGTERM") {
|
|
1097
|
+
const erro = new Error(`node-cron daemon exited with code ${code || signal}`);
|
|
1098
|
+
logger_1.default.error(erro);
|
|
1099
|
+
clearTimeout(timeout);
|
|
1100
|
+
reject(erro);
|
|
1101
|
+
}
|
|
1102
|
+
});
|
|
1103
|
+
this.forkProcess.on("message", (message) => {
|
|
1104
|
+
if (message.jsonError) {
|
|
1105
|
+
if (message.context?.execution) {
|
|
1106
|
+
message.context.execution.error = deserializeError(message.jsonError);
|
|
1107
|
+
delete message.jsonError;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
if (message.context?.task?.state) {
|
|
1111
|
+
this.stateMachine.changeState(message.context?.task?.state);
|
|
1112
|
+
}
|
|
1113
|
+
if (message.context) {
|
|
1114
|
+
const execution = message.context?.execution;
|
|
1115
|
+
delete execution?.hasError;
|
|
1116
|
+
const context = this.createContext(new Date(message.context.date), execution);
|
|
1117
|
+
this.emitter.emit(message.event, context);
|
|
1118
|
+
}
|
|
1119
|
+
});
|
|
1120
|
+
this.once("task:started", () => {
|
|
1121
|
+
this.stateMachine.changeState("idle");
|
|
1122
|
+
clearTimeout(timeout);
|
|
1123
|
+
resolve(undefined);
|
|
1124
|
+
});
|
|
1125
|
+
this.forkProcess.send({
|
|
1126
|
+
command: "task:start",
|
|
1127
|
+
path: this.taskPath,
|
|
1128
|
+
cron: this.cronExpression,
|
|
1129
|
+
options: this.options
|
|
1130
|
+
});
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
reject(error);
|
|
1133
|
+
}
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
stop() {
|
|
1137
|
+
return new Promise((resolve, reject) => {
|
|
1138
|
+
if (!this.forkProcess) {
|
|
1139
|
+
return resolve(undefined);
|
|
1140
|
+
}
|
|
1141
|
+
const timeoutId = setTimeout(() => {
|
|
1142
|
+
clearTimeout(timeoutId);
|
|
1143
|
+
reject(new Error("Stop operation timed out"));
|
|
1144
|
+
}, 5000);
|
|
1145
|
+
const cleanupAndResolve = () => {
|
|
1146
|
+
clearTimeout(timeoutId);
|
|
1147
|
+
this.off("task:stopped", onStopped);
|
|
1148
|
+
this.forkProcess = undefined;
|
|
1149
|
+
resolve(undefined);
|
|
1150
|
+
};
|
|
1151
|
+
const onStopped = () => {
|
|
1152
|
+
cleanupAndResolve();
|
|
1153
|
+
};
|
|
1154
|
+
this.once("task:stopped", onStopped);
|
|
1155
|
+
this.forkProcess.send({
|
|
1156
|
+
command: "task:stop"
|
|
1157
|
+
});
|
|
1158
|
+
});
|
|
1159
|
+
}
|
|
1160
|
+
getStatus() {
|
|
1161
|
+
return this.stateMachine.state;
|
|
1162
|
+
}
|
|
1163
|
+
destroy() {
|
|
1164
|
+
return new Promise((resolve, reject) => {
|
|
1165
|
+
if (!this.forkProcess) {
|
|
1166
|
+
return resolve(undefined);
|
|
1167
|
+
}
|
|
1168
|
+
const timeoutId = setTimeout(() => {
|
|
1169
|
+
clearTimeout(timeoutId);
|
|
1170
|
+
reject(new Error("Destroy operation timed out"));
|
|
1171
|
+
}, 5000);
|
|
1172
|
+
const onDestroy = () => {
|
|
1173
|
+
clearTimeout(timeoutId);
|
|
1174
|
+
this.off("task:destroyed", onDestroy);
|
|
1175
|
+
resolve(undefined);
|
|
1176
|
+
};
|
|
1177
|
+
this.once("task:destroyed", onDestroy);
|
|
1178
|
+
this.forkProcess.send({
|
|
1179
|
+
command: "task:destroy"
|
|
1180
|
+
});
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
execute() {
|
|
1184
|
+
return new Promise((resolve, reject) => {
|
|
1185
|
+
if (!this.forkProcess) {
|
|
1186
|
+
return reject(new Error("Cannot execute background task because it hasn't been started yet. Please initialize the task using the start() method before attempting to execute it."));
|
|
1187
|
+
}
|
|
1188
|
+
const timeoutId = setTimeout(() => {
|
|
1189
|
+
cleanupListeners();
|
|
1190
|
+
reject(new Error("Execution timeout exceeded"));
|
|
1191
|
+
}, 5000);
|
|
1192
|
+
const cleanupListeners = () => {
|
|
1193
|
+
clearTimeout(timeoutId);
|
|
1194
|
+
this.off("execution:finished", onFinished);
|
|
1195
|
+
this.off("execution:failed", onFail);
|
|
1196
|
+
};
|
|
1197
|
+
const onFinished = (context) => {
|
|
1198
|
+
cleanupListeners();
|
|
1199
|
+
resolve(context.execution?.result);
|
|
1200
|
+
};
|
|
1201
|
+
const onFail = (context) => {
|
|
1202
|
+
cleanupListeners();
|
|
1203
|
+
reject(context.execution?.error || new Error("Execution failed without specific error"));
|
|
1204
|
+
};
|
|
1205
|
+
this.once("execution:finished", onFinished);
|
|
1206
|
+
this.once("execution:failed", onFail);
|
|
1207
|
+
this.forkProcess.send({
|
|
1208
|
+
command: "task:execute"
|
|
1209
|
+
});
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
on(event, fun) {
|
|
1213
|
+
this.emitter.on(event, fun);
|
|
1214
|
+
}
|
|
1215
|
+
off(event, fun) {
|
|
1216
|
+
this.emitter.off(event, fun);
|
|
1217
|
+
}
|
|
1218
|
+
once(event, fun) {
|
|
1219
|
+
this.emitter.once(event, fun);
|
|
1220
|
+
}
|
|
1221
|
+
createContext(executionDate, execution) {
|
|
1222
|
+
const localTime = new localized_time_1.LocalizedTime(executionDate, this.options?.timezone);
|
|
1223
|
+
const ctx = {
|
|
1224
|
+
date: localTime.toDate(),
|
|
1225
|
+
dateLocalIso: localTime.toISO(),
|
|
1226
|
+
triggeredAt: new Date,
|
|
1227
|
+
task: this,
|
|
1228
|
+
execution
|
|
1229
|
+
};
|
|
1230
|
+
return ctx;
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
function deserializeError(str) {
|
|
1234
|
+
const data = JSON.parse(str);
|
|
1235
|
+
const Err = globalThis[data.name] || Error;
|
|
1236
|
+
const err = new Err(data.message);
|
|
1237
|
+
if (data.stack) {
|
|
1238
|
+
err.stack = data.stack;
|
|
1239
|
+
}
|
|
1240
|
+
Object.keys(data).forEach((key) => {
|
|
1241
|
+
if (!["name", "message", "stack"].includes(key)) {
|
|
1242
|
+
err[key] = data[key];
|
|
1243
|
+
}
|
|
1244
|
+
});
|
|
1245
|
+
return err;
|
|
1246
|
+
}
|
|
1247
|
+
exports.default = BackgroundScheduledTask;
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1250
|
+
// node_modules/node-cron/dist/esm/node-cron.js
|
|
1251
|
+
var require_node_cron = __commonJS((exports) => {
|
|
1252
|
+
var __filename = "/Users/antonwerschinin/Code/miqro/node_modules/node-cron/dist/esm/node-cron.js";
|
|
1253
|
+
var __importDefault = exports && exports.__importDefault || function(mod) {
|
|
1254
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
1255
|
+
};
|
|
1256
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1257
|
+
exports.nodeCron = exports.getTask = exports.getTasks = undefined;
|
|
1258
|
+
exports.schedule = schedule;
|
|
1259
|
+
exports.createTask = createTask;
|
|
1260
|
+
exports.solvePath = solvePath;
|
|
1261
|
+
exports.validate = validate;
|
|
1262
|
+
var inline_scheduled_task_1 = require_inline_scheduled_task();
|
|
1263
|
+
var task_registry_1 = require_task_registry();
|
|
1264
|
+
var pattern_validation_1 = __importDefault(require_pattern_validation());
|
|
1265
|
+
var background_scheduled_task_1 = __importDefault(require_background_scheduled_task());
|
|
1266
|
+
var path_1 = __importDefault(__require("path"));
|
|
1267
|
+
var url_1 = __require("url");
|
|
1268
|
+
var registry = new task_registry_1.TaskRegistry;
|
|
1269
|
+
function schedule(expression, func, options) {
|
|
1270
|
+
const task = createTask(expression, func, options);
|
|
1271
|
+
task.start();
|
|
1272
|
+
return task;
|
|
1273
|
+
}
|
|
1274
|
+
function createTask(expression, func, options) {
|
|
1275
|
+
let task;
|
|
1276
|
+
if (func instanceof Function) {
|
|
1277
|
+
task = new inline_scheduled_task_1.InlineScheduledTask(expression, func, options);
|
|
1278
|
+
} else {
|
|
1279
|
+
const taskPath = solvePath(func);
|
|
1280
|
+
task = new background_scheduled_task_1.default(expression, taskPath, options);
|
|
1281
|
+
}
|
|
1282
|
+
registry.add(task);
|
|
1283
|
+
return task;
|
|
1284
|
+
}
|
|
1285
|
+
function solvePath(filePath) {
|
|
1286
|
+
if (path_1.default.isAbsolute(filePath))
|
|
1287
|
+
return (0, url_1.pathToFileURL)(filePath).href;
|
|
1288
|
+
if (filePath.startsWith("file://"))
|
|
1289
|
+
return filePath;
|
|
1290
|
+
const stackLines = new Error().stack?.split(`
|
|
1291
|
+
`);
|
|
1292
|
+
if (stackLines) {
|
|
1293
|
+
stackLines?.shift();
|
|
1294
|
+
const callerLine = stackLines?.find((line) => {
|
|
1295
|
+
return line.indexOf(__filename) === -1;
|
|
1296
|
+
});
|
|
1297
|
+
const match2 = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
|
|
1298
|
+
if (match2) {
|
|
1299
|
+
const dir = `${match2[5] ?? ""}${path_1.default.dirname(match2[6])}`;
|
|
1300
|
+
return (0, url_1.pathToFileURL)(path_1.default.resolve(dir, filePath)).href;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
throw new Error(`Could not locate task file ${filePath}`);
|
|
1304
|
+
}
|
|
1305
|
+
function validate(expression) {
|
|
1306
|
+
try {
|
|
1307
|
+
(0, pattern_validation_1.default)(expression);
|
|
1308
|
+
return true;
|
|
1309
|
+
} catch (e) {
|
|
1310
|
+
return false;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
exports.getTasks = registry.all;
|
|
1314
|
+
exports.getTask = registry.get;
|
|
1315
|
+
exports.nodeCron = {
|
|
1316
|
+
schedule,
|
|
1317
|
+
createTask,
|
|
1318
|
+
validate,
|
|
1319
|
+
getTasks: exports.getTasks,
|
|
1320
|
+
getTask: exports.getTask
|
|
1321
|
+
};
|
|
1322
|
+
exports.default = exports.nodeCron;
|
|
1323
|
+
});
|
|
1324
|
+
|
|
1325
|
+
// src/index.ts
|
|
1326
|
+
import { readdir } from "fs/promises";
|
|
1327
|
+
import { join } from "path";
|
|
1328
|
+
|
|
1329
|
+
// node_modules/hono/dist/compose.js
|
|
1330
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
1331
|
+
return (context, next) => {
|
|
1332
|
+
let index = -1;
|
|
1333
|
+
return dispatch(0);
|
|
1334
|
+
async function dispatch(i) {
|
|
1335
|
+
if (i <= index) {
|
|
1336
|
+
throw new Error("next() called multiple times");
|
|
1337
|
+
}
|
|
1338
|
+
index = i;
|
|
1339
|
+
let res;
|
|
1340
|
+
let isError = false;
|
|
1341
|
+
let handler;
|
|
1342
|
+
if (middleware[i]) {
|
|
1343
|
+
handler = middleware[i][0][0];
|
|
1344
|
+
context.req.routeIndex = i;
|
|
1345
|
+
} else {
|
|
1346
|
+
handler = i === middleware.length && next || undefined;
|
|
1347
|
+
}
|
|
1348
|
+
if (handler) {
|
|
1349
|
+
try {
|
|
1350
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
1351
|
+
} catch (err) {
|
|
1352
|
+
if (err instanceof Error && onError) {
|
|
1353
|
+
context.error = err;
|
|
1354
|
+
res = await onError(err, context);
|
|
1355
|
+
isError = true;
|
|
1356
|
+
} else {
|
|
1357
|
+
throw err;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
} else {
|
|
1361
|
+
if (context.finalized === false && onNotFound) {
|
|
1362
|
+
res = await onNotFound(context);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
if (res && (context.finalized === false || isError)) {
|
|
1366
|
+
context.res = res;
|
|
1367
|
+
}
|
|
1368
|
+
return context;
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
};
|
|
1372
|
+
|
|
1373
|
+
// node_modules/hono/dist/request/constants.js
|
|
1374
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
1375
|
+
|
|
1376
|
+
// node_modules/hono/dist/utils/body.js
|
|
1377
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
1378
|
+
const { all = false, dot = false } = options;
|
|
1379
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
1380
|
+
const contentType = headers.get("Content-Type");
|
|
1381
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
1382
|
+
return parseFormData(request, { all, dot });
|
|
1383
|
+
}
|
|
1384
|
+
return {};
|
|
1385
|
+
};
|
|
1386
|
+
async function parseFormData(request, options) {
|
|
1387
|
+
const formData = await request.formData();
|
|
1388
|
+
if (formData) {
|
|
1389
|
+
return convertFormDataToBodyData(formData, options);
|
|
1390
|
+
}
|
|
1391
|
+
return {};
|
|
1392
|
+
}
|
|
1393
|
+
function convertFormDataToBodyData(formData, options) {
|
|
1394
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
1395
|
+
formData.forEach((value, key) => {
|
|
1396
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
1397
|
+
if (!shouldParseAllValues) {
|
|
1398
|
+
form[key] = value;
|
|
1399
|
+
} else {
|
|
1400
|
+
handleParsingAllValues(form, key, value);
|
|
1401
|
+
}
|
|
1402
|
+
});
|
|
1403
|
+
if (options.dot) {
|
|
1404
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
1405
|
+
const shouldParseDotValues = key.includes(".");
|
|
1406
|
+
if (shouldParseDotValues) {
|
|
1407
|
+
handleParsingNestedValues(form, key, value);
|
|
1408
|
+
delete form[key];
|
|
1409
|
+
}
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
return form;
|
|
1413
|
+
}
|
|
1414
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
1415
|
+
if (form[key] !== undefined) {
|
|
1416
|
+
if (Array.isArray(form[key])) {
|
|
1417
|
+
form[key].push(value);
|
|
1418
|
+
} else {
|
|
1419
|
+
form[key] = [form[key], value];
|
|
1420
|
+
}
|
|
1421
|
+
} else {
|
|
1422
|
+
if (!key.endsWith("[]")) {
|
|
1423
|
+
form[key] = value;
|
|
1424
|
+
} else {
|
|
1425
|
+
form[key] = [value];
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
};
|
|
1429
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
1430
|
+
let nestedForm = form;
|
|
1431
|
+
const keys = key.split(".");
|
|
1432
|
+
keys.forEach((key2, index) => {
|
|
1433
|
+
if (index === keys.length - 1) {
|
|
1434
|
+
nestedForm[key2] = value;
|
|
1435
|
+
} else {
|
|
1436
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
1437
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
1438
|
+
}
|
|
1439
|
+
nestedForm = nestedForm[key2];
|
|
1440
|
+
}
|
|
1441
|
+
});
|
|
1442
|
+
};
|
|
1443
|
+
|
|
1444
|
+
// node_modules/hono/dist/utils/url.js
|
|
1445
|
+
var splitPath = (path) => {
|
|
1446
|
+
const paths = path.split("/");
|
|
1447
|
+
if (paths[0] === "") {
|
|
1448
|
+
paths.shift();
|
|
1449
|
+
}
|
|
1450
|
+
return paths;
|
|
1451
|
+
};
|
|
1452
|
+
var splitRoutingPath = (routePath) => {
|
|
1453
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
1454
|
+
const paths = splitPath(path);
|
|
1455
|
+
return replaceGroupMarks(paths, groups);
|
|
1456
|
+
};
|
|
1457
|
+
var extractGroupsFromPath = (path) => {
|
|
1458
|
+
const groups = [];
|
|
1459
|
+
path = path.replace(/\{[^}]+\}/g, (match, index) => {
|
|
1460
|
+
const mark = `@${index}`;
|
|
1461
|
+
groups.push([mark, match]);
|
|
1462
|
+
return mark;
|
|
1463
|
+
});
|
|
1464
|
+
return { groups, path };
|
|
1465
|
+
};
|
|
1466
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
1467
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
1468
|
+
const [mark] = groups[i];
|
|
1469
|
+
for (let j = paths.length - 1;j >= 0; j--) {
|
|
1470
|
+
if (paths[j].includes(mark)) {
|
|
1471
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
1472
|
+
break;
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
return paths;
|
|
1477
|
+
};
|
|
1478
|
+
var patternCache = {};
|
|
1479
|
+
var getPattern = (label, next) => {
|
|
1480
|
+
if (label === "*") {
|
|
1481
|
+
return "*";
|
|
1482
|
+
}
|
|
1483
|
+
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
1484
|
+
if (match) {
|
|
1485
|
+
const cacheKey = `${label}#${next}`;
|
|
1486
|
+
if (!patternCache[cacheKey]) {
|
|
1487
|
+
if (match[2]) {
|
|
1488
|
+
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
|
|
1489
|
+
} else {
|
|
1490
|
+
patternCache[cacheKey] = [label, match[1], true];
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
return patternCache[cacheKey];
|
|
1494
|
+
}
|
|
1495
|
+
return null;
|
|
1496
|
+
};
|
|
1497
|
+
var tryDecode = (str, decoder) => {
|
|
1498
|
+
try {
|
|
1499
|
+
return decoder(str);
|
|
1500
|
+
} catch {
|
|
1501
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
1502
|
+
try {
|
|
1503
|
+
return decoder(match);
|
|
1504
|
+
} catch {
|
|
1505
|
+
return match;
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
}
|
|
1509
|
+
};
|
|
1510
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
1511
|
+
var getPath = (request) => {
|
|
1512
|
+
const url = request.url;
|
|
1513
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
1514
|
+
let i = start;
|
|
1515
|
+
for (;i < url.length; i++) {
|
|
1516
|
+
const charCode = url.charCodeAt(i);
|
|
1517
|
+
if (charCode === 37) {
|
|
1518
|
+
const queryIndex = url.indexOf("?", i);
|
|
1519
|
+
const hashIndex = url.indexOf("#", i);
|
|
1520
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
1521
|
+
const path = url.slice(start, end);
|
|
1522
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
1523
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
1524
|
+
break;
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
return url.slice(start, i);
|
|
1528
|
+
};
|
|
1529
|
+
var getPathNoStrict = (request) => {
|
|
1530
|
+
const result = getPath(request);
|
|
1531
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
1532
|
+
};
|
|
1533
|
+
var mergePath = (base, sub, ...rest) => {
|
|
1534
|
+
if (rest.length) {
|
|
1535
|
+
sub = mergePath(sub, ...rest);
|
|
1536
|
+
}
|
|
1537
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
1538
|
+
};
|
|
1539
|
+
var checkOptionalParameter = (path) => {
|
|
1540
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
1541
|
+
return null;
|
|
1542
|
+
}
|
|
1543
|
+
const segments = path.split("/");
|
|
1544
|
+
const results = [];
|
|
1545
|
+
let basePath = "";
|
|
1546
|
+
segments.forEach((segment) => {
|
|
1547
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
1548
|
+
basePath += "/" + segment;
|
|
1549
|
+
} else if (/\:/.test(segment)) {
|
|
1550
|
+
if (/\?/.test(segment)) {
|
|
1551
|
+
if (results.length === 0 && basePath === "") {
|
|
1552
|
+
results.push("/");
|
|
1553
|
+
} else {
|
|
1554
|
+
results.push(basePath);
|
|
1555
|
+
}
|
|
1556
|
+
const optionalSegment = segment.replace("?", "");
|
|
1557
|
+
basePath += "/" + optionalSegment;
|
|
1558
|
+
results.push(basePath);
|
|
1559
|
+
} else {
|
|
1560
|
+
basePath += "/" + segment;
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
});
|
|
1564
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
1565
|
+
};
|
|
1566
|
+
var _decodeURI = (value) => {
|
|
1567
|
+
if (!/[%+]/.test(value)) {
|
|
1568
|
+
return value;
|
|
1569
|
+
}
|
|
1570
|
+
if (value.indexOf("+") !== -1) {
|
|
1571
|
+
value = value.replace(/\+/g, " ");
|
|
1572
|
+
}
|
|
1573
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
1574
|
+
};
|
|
1575
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
1576
|
+
let encoded;
|
|
1577
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
1578
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
1579
|
+
if (keyIndex2 === -1) {
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
1583
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1584
|
+
}
|
|
1585
|
+
while (keyIndex2 !== -1) {
|
|
1586
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
1587
|
+
if (trailingKeyCode === 61) {
|
|
1588
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
1589
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
1590
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
|
|
1591
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
1592
|
+
return "";
|
|
1593
|
+
}
|
|
1594
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1595
|
+
}
|
|
1596
|
+
encoded = /[%+]/.test(url);
|
|
1597
|
+
if (!encoded) {
|
|
1598
|
+
return;
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
const results = {};
|
|
1602
|
+
encoded ??= /[%+]/.test(url);
|
|
1603
|
+
let keyIndex = url.indexOf("?", 8);
|
|
1604
|
+
while (keyIndex !== -1) {
|
|
1605
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
1606
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
1607
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
1608
|
+
valueIndex = -1;
|
|
1609
|
+
}
|
|
1610
|
+
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
|
|
1611
|
+
if (encoded) {
|
|
1612
|
+
name = _decodeURI(name);
|
|
1613
|
+
}
|
|
1614
|
+
keyIndex = nextKeyIndex;
|
|
1615
|
+
if (name === "") {
|
|
1616
|
+
continue;
|
|
1617
|
+
}
|
|
1618
|
+
let value;
|
|
1619
|
+
if (valueIndex === -1) {
|
|
1620
|
+
value = "";
|
|
1621
|
+
} else {
|
|
1622
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
|
|
1623
|
+
if (encoded) {
|
|
1624
|
+
value = _decodeURI(value);
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
if (multiple) {
|
|
1628
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
1629
|
+
results[name] = [];
|
|
1630
|
+
}
|
|
1631
|
+
results[name].push(value);
|
|
1632
|
+
} else {
|
|
1633
|
+
results[name] ??= value;
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
return key ? results[key] : results;
|
|
1637
|
+
};
|
|
1638
|
+
var getQueryParam = _getQueryParam;
|
|
1639
|
+
var getQueryParams = (url, key) => {
|
|
1640
|
+
return _getQueryParam(url, key, true);
|
|
1641
|
+
};
|
|
1642
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
1643
|
+
|
|
1644
|
+
// node_modules/hono/dist/request.js
|
|
1645
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
1646
|
+
var HonoRequest = class {
|
|
1647
|
+
raw;
|
|
1648
|
+
#validatedData;
|
|
1649
|
+
#matchResult;
|
|
1650
|
+
routeIndex = 0;
|
|
1651
|
+
path;
|
|
1652
|
+
bodyCache = {};
|
|
1653
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
1654
|
+
this.raw = request;
|
|
1655
|
+
this.path = path;
|
|
1656
|
+
this.#matchResult = matchResult;
|
|
1657
|
+
this.#validatedData = {};
|
|
1658
|
+
}
|
|
1659
|
+
param(key) {
|
|
1660
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1661
|
+
}
|
|
1662
|
+
#getDecodedParam(key) {
|
|
1663
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
1664
|
+
const param = this.#getParamValue(paramKey);
|
|
1665
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
1666
|
+
}
|
|
1667
|
+
#getAllDecodedParams() {
|
|
1668
|
+
const decoded = {};
|
|
1669
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
1670
|
+
for (const key of keys) {
|
|
1671
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1672
|
+
if (value !== undefined) {
|
|
1673
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
return decoded;
|
|
1677
|
+
}
|
|
1678
|
+
#getParamValue(paramKey) {
|
|
1679
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1680
|
+
}
|
|
1681
|
+
query(key) {
|
|
1682
|
+
return getQueryParam(this.url, key);
|
|
1683
|
+
}
|
|
1684
|
+
queries(key) {
|
|
1685
|
+
return getQueryParams(this.url, key);
|
|
1686
|
+
}
|
|
1687
|
+
header(name) {
|
|
1688
|
+
if (name) {
|
|
1689
|
+
return this.raw.headers.get(name) ?? undefined;
|
|
1690
|
+
}
|
|
1691
|
+
const headerData = {};
|
|
1692
|
+
this.raw.headers.forEach((value, key) => {
|
|
1693
|
+
headerData[key] = value;
|
|
1694
|
+
});
|
|
1695
|
+
return headerData;
|
|
1696
|
+
}
|
|
1697
|
+
async parseBody(options) {
|
|
1698
|
+
return this.bodyCache.parsedBody ??= await parseBody(this, options);
|
|
1699
|
+
}
|
|
1700
|
+
#cachedBody = (key) => {
|
|
1701
|
+
const { bodyCache, raw } = this;
|
|
1702
|
+
const cachedBody = bodyCache[key];
|
|
1703
|
+
if (cachedBody) {
|
|
1704
|
+
return cachedBody;
|
|
1705
|
+
}
|
|
1706
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
1707
|
+
if (anyCachedKey) {
|
|
1708
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1709
|
+
if (anyCachedKey === "json") {
|
|
1710
|
+
body = JSON.stringify(body);
|
|
1711
|
+
}
|
|
1712
|
+
return new Response(body)[key]();
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
return bodyCache[key] = raw[key]();
|
|
1716
|
+
};
|
|
1717
|
+
json() {
|
|
1718
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1719
|
+
}
|
|
1720
|
+
text() {
|
|
1721
|
+
return this.#cachedBody("text");
|
|
1722
|
+
}
|
|
1723
|
+
arrayBuffer() {
|
|
1724
|
+
return this.#cachedBody("arrayBuffer");
|
|
1725
|
+
}
|
|
1726
|
+
blob() {
|
|
1727
|
+
return this.#cachedBody("blob");
|
|
1728
|
+
}
|
|
1729
|
+
formData() {
|
|
1730
|
+
return this.#cachedBody("formData");
|
|
1731
|
+
}
|
|
1732
|
+
addValidatedData(target, data) {
|
|
1733
|
+
this.#validatedData[target] = data;
|
|
1734
|
+
}
|
|
1735
|
+
valid(target) {
|
|
1736
|
+
return this.#validatedData[target];
|
|
1737
|
+
}
|
|
1738
|
+
get url() {
|
|
1739
|
+
return this.raw.url;
|
|
1740
|
+
}
|
|
1741
|
+
get method() {
|
|
1742
|
+
return this.raw.method;
|
|
1743
|
+
}
|
|
1744
|
+
get [GET_MATCH_RESULT]() {
|
|
1745
|
+
return this.#matchResult;
|
|
1746
|
+
}
|
|
1747
|
+
get matchedRoutes() {
|
|
1748
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
1749
|
+
}
|
|
1750
|
+
get routePath() {
|
|
1751
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
|
|
1755
|
+
// node_modules/hono/dist/utils/html.js
|
|
1756
|
+
var HtmlEscapedCallbackPhase = {
|
|
1757
|
+
Stringify: 1,
|
|
1758
|
+
BeforeStream: 2,
|
|
1759
|
+
Stream: 3
|
|
1760
|
+
};
|
|
1761
|
+
var raw = (value, callbacks) => {
|
|
1762
|
+
const escapedString = new String(value);
|
|
1763
|
+
escapedString.isEscaped = true;
|
|
1764
|
+
escapedString.callbacks = callbacks;
|
|
1765
|
+
return escapedString;
|
|
1766
|
+
};
|
|
1767
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
1768
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
1769
|
+
if (!(str instanceof Promise)) {
|
|
1770
|
+
str = str.toString();
|
|
1771
|
+
}
|
|
1772
|
+
if (str instanceof Promise) {
|
|
1773
|
+
str = await str;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
const callbacks = str.callbacks;
|
|
1777
|
+
if (!callbacks?.length) {
|
|
1778
|
+
return Promise.resolve(str);
|
|
1779
|
+
}
|
|
1780
|
+
if (buffer) {
|
|
1781
|
+
buffer[0] += str;
|
|
1782
|
+
} else {
|
|
1783
|
+
buffer = [str];
|
|
1784
|
+
}
|
|
1785
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
|
|
1786
|
+
if (preserveCallbacks) {
|
|
1787
|
+
return raw(await resStr, callbacks);
|
|
1788
|
+
} else {
|
|
1789
|
+
return resStr;
|
|
1790
|
+
}
|
|
1791
|
+
};
|
|
1792
|
+
|
|
1793
|
+
// node_modules/hono/dist/context.js
|
|
1794
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
1795
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
1796
|
+
return {
|
|
1797
|
+
"Content-Type": contentType,
|
|
1798
|
+
...headers
|
|
1799
|
+
};
|
|
1800
|
+
};
|
|
1801
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
1802
|
+
var Context = class {
|
|
1803
|
+
#rawRequest;
|
|
1804
|
+
#req;
|
|
1805
|
+
env = {};
|
|
1806
|
+
#var;
|
|
1807
|
+
finalized = false;
|
|
1808
|
+
error;
|
|
1809
|
+
#status;
|
|
1810
|
+
#executionCtx;
|
|
1811
|
+
#res;
|
|
1812
|
+
#layout;
|
|
1813
|
+
#renderer;
|
|
1814
|
+
#notFoundHandler;
|
|
1815
|
+
#preparedHeaders;
|
|
1816
|
+
#matchResult;
|
|
1817
|
+
#path;
|
|
1818
|
+
constructor(req, options) {
|
|
1819
|
+
this.#rawRequest = req;
|
|
1820
|
+
if (options) {
|
|
1821
|
+
this.#executionCtx = options.executionCtx;
|
|
1822
|
+
this.env = options.env;
|
|
1823
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
1824
|
+
this.#path = options.path;
|
|
1825
|
+
this.#matchResult = options.matchResult;
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
get req() {
|
|
1829
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
1830
|
+
return this.#req;
|
|
1831
|
+
}
|
|
1832
|
+
get event() {
|
|
1833
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
1834
|
+
return this.#executionCtx;
|
|
1835
|
+
} else {
|
|
1836
|
+
throw Error("This context has no FetchEvent");
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
get executionCtx() {
|
|
1840
|
+
if (this.#executionCtx) {
|
|
1841
|
+
return this.#executionCtx;
|
|
1842
|
+
} else {
|
|
1843
|
+
throw Error("This context has no ExecutionContext");
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
get res() {
|
|
1847
|
+
return this.#res ||= createResponseInstance(null, {
|
|
1848
|
+
headers: this.#preparedHeaders ??= new Headers
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
set res(_res) {
|
|
1852
|
+
if (this.#res && _res) {
|
|
1853
|
+
_res = createResponseInstance(_res.body, _res);
|
|
1854
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
1855
|
+
if (k === "content-type") {
|
|
1856
|
+
continue;
|
|
1857
|
+
}
|
|
1858
|
+
if (k === "set-cookie") {
|
|
1859
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
1860
|
+
_res.headers.delete("set-cookie");
|
|
1861
|
+
for (const cookie of cookies) {
|
|
1862
|
+
_res.headers.append("set-cookie", cookie);
|
|
1863
|
+
}
|
|
1864
|
+
} else {
|
|
1865
|
+
_res.headers.set(k, v);
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
this.#res = _res;
|
|
1870
|
+
this.finalized = true;
|
|
1871
|
+
}
|
|
1872
|
+
render = (...args) => {
|
|
1873
|
+
this.#renderer ??= (content) => this.html(content);
|
|
1874
|
+
return this.#renderer(...args);
|
|
1875
|
+
};
|
|
1876
|
+
setLayout = (layout) => this.#layout = layout;
|
|
1877
|
+
getLayout = () => this.#layout;
|
|
1878
|
+
setRenderer = (renderer) => {
|
|
1879
|
+
this.#renderer = renderer;
|
|
1880
|
+
};
|
|
1881
|
+
header = (name, value, options) => {
|
|
1882
|
+
if (this.finalized) {
|
|
1883
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
1884
|
+
}
|
|
1885
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
|
|
1886
|
+
if (value === undefined) {
|
|
1887
|
+
headers.delete(name);
|
|
1888
|
+
} else if (options?.append) {
|
|
1889
|
+
headers.append(name, value);
|
|
1890
|
+
} else {
|
|
1891
|
+
headers.set(name, value);
|
|
1892
|
+
}
|
|
1893
|
+
};
|
|
1894
|
+
status = (status) => {
|
|
1895
|
+
this.#status = status;
|
|
1896
|
+
};
|
|
1897
|
+
set = (key, value) => {
|
|
1898
|
+
this.#var ??= /* @__PURE__ */ new Map;
|
|
1899
|
+
this.#var.set(key, value);
|
|
1900
|
+
};
|
|
1901
|
+
get = (key) => {
|
|
1902
|
+
return this.#var ? this.#var.get(key) : undefined;
|
|
1903
|
+
};
|
|
1904
|
+
get var() {
|
|
1905
|
+
if (!this.#var) {
|
|
1906
|
+
return {};
|
|
1907
|
+
}
|
|
1908
|
+
return Object.fromEntries(this.#var);
|
|
1909
|
+
}
|
|
1910
|
+
#newResponse(data, arg, headers) {
|
|
1911
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
|
|
1912
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
1913
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
1914
|
+
for (const [key, value] of argHeaders) {
|
|
1915
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
1916
|
+
responseHeaders.append(key, value);
|
|
1917
|
+
} else {
|
|
1918
|
+
responseHeaders.set(key, value);
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
if (headers) {
|
|
1923
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
1924
|
+
if (typeof v === "string") {
|
|
1925
|
+
responseHeaders.set(k, v);
|
|
1926
|
+
} else {
|
|
1927
|
+
responseHeaders.delete(k);
|
|
1928
|
+
for (const v2 of v) {
|
|
1929
|
+
responseHeaders.append(k, v2);
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
1935
|
+
return createResponseInstance(data, { status, headers: responseHeaders });
|
|
1936
|
+
}
|
|
1937
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
1938
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
1939
|
+
text = (text, arg, headers) => {
|
|
1940
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
|
|
1941
|
+
};
|
|
1942
|
+
json = (object, arg, headers) => {
|
|
1943
|
+
return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
|
|
1944
|
+
};
|
|
1945
|
+
html = (html, arg, headers) => {
|
|
1946
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
1947
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
1948
|
+
};
|
|
1949
|
+
redirect = (location, status) => {
|
|
1950
|
+
const locationString = String(location);
|
|
1951
|
+
this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
|
|
1952
|
+
return this.newResponse(null, status ?? 302);
|
|
1953
|
+
};
|
|
1954
|
+
notFound = () => {
|
|
1955
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
1956
|
+
return this.#notFoundHandler(this);
|
|
1957
|
+
};
|
|
1958
|
+
};
|
|
1959
|
+
|
|
1960
|
+
// node_modules/hono/dist/router.js
|
|
1961
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1962
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1963
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
1964
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1965
|
+
var UnsupportedPathError = class extends Error {
|
|
1966
|
+
};
|
|
1967
|
+
|
|
1968
|
+
// node_modules/hono/dist/utils/constants.js
|
|
1969
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1970
|
+
|
|
1971
|
+
// node_modules/hono/dist/hono-base.js
|
|
1972
|
+
var notFoundHandler = (c) => {
|
|
1973
|
+
return c.text("404 Not Found", 404);
|
|
1974
|
+
};
|
|
1975
|
+
var errorHandler = (err, c) => {
|
|
1976
|
+
if ("getResponse" in err) {
|
|
1977
|
+
const res = err.getResponse();
|
|
1978
|
+
return c.newResponse(res.body, res);
|
|
1979
|
+
}
|
|
1980
|
+
console.error(err);
|
|
1981
|
+
return c.text("Internal Server Error", 500);
|
|
1982
|
+
};
|
|
1983
|
+
var Hono = class _Hono {
|
|
1984
|
+
get;
|
|
1985
|
+
post;
|
|
1986
|
+
put;
|
|
1987
|
+
delete;
|
|
1988
|
+
options;
|
|
1989
|
+
patch;
|
|
1990
|
+
all;
|
|
1991
|
+
on;
|
|
1992
|
+
use;
|
|
1993
|
+
router;
|
|
1994
|
+
getPath;
|
|
1995
|
+
_basePath = "/";
|
|
1996
|
+
#path = "/";
|
|
1997
|
+
routes = [];
|
|
1998
|
+
constructor(options = {}) {
|
|
1999
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
2000
|
+
allMethods.forEach((method) => {
|
|
2001
|
+
this[method] = (args1, ...args) => {
|
|
2002
|
+
if (typeof args1 === "string") {
|
|
2003
|
+
this.#path = args1;
|
|
2004
|
+
} else {
|
|
2005
|
+
this.#addRoute(method, this.#path, args1);
|
|
2006
|
+
}
|
|
2007
|
+
args.forEach((handler) => {
|
|
2008
|
+
this.#addRoute(method, this.#path, handler);
|
|
2009
|
+
});
|
|
2010
|
+
return this;
|
|
2011
|
+
};
|
|
2012
|
+
});
|
|
2013
|
+
this.on = (method, path, ...handlers) => {
|
|
2014
|
+
for (const p of [path].flat()) {
|
|
2015
|
+
this.#path = p;
|
|
2016
|
+
for (const m of [method].flat()) {
|
|
2017
|
+
handlers.map((handler) => {
|
|
2018
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
2019
|
+
});
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
return this;
|
|
2023
|
+
};
|
|
2024
|
+
this.use = (arg1, ...handlers) => {
|
|
2025
|
+
if (typeof arg1 === "string") {
|
|
2026
|
+
this.#path = arg1;
|
|
2027
|
+
} else {
|
|
2028
|
+
this.#path = "*";
|
|
2029
|
+
handlers.unshift(arg1);
|
|
2030
|
+
}
|
|
2031
|
+
handlers.forEach((handler) => {
|
|
2032
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
2033
|
+
});
|
|
2034
|
+
return this;
|
|
2035
|
+
};
|
|
2036
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
2037
|
+
Object.assign(this, optionsWithoutStrict);
|
|
2038
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
2039
|
+
}
|
|
2040
|
+
#clone() {
|
|
2041
|
+
const clone = new _Hono({
|
|
2042
|
+
router: this.router,
|
|
2043
|
+
getPath: this.getPath
|
|
2044
|
+
});
|
|
2045
|
+
clone.errorHandler = this.errorHandler;
|
|
2046
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
2047
|
+
clone.routes = this.routes;
|
|
2048
|
+
return clone;
|
|
2049
|
+
}
|
|
2050
|
+
#notFoundHandler = notFoundHandler;
|
|
2051
|
+
errorHandler = errorHandler;
|
|
2052
|
+
route(path, app) {
|
|
2053
|
+
const subApp = this.basePath(path);
|
|
2054
|
+
app.routes.map((r) => {
|
|
2055
|
+
let handler;
|
|
2056
|
+
if (app.errorHandler === errorHandler) {
|
|
2057
|
+
handler = r.handler;
|
|
2058
|
+
} else {
|
|
2059
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
2060
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
2061
|
+
}
|
|
2062
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
2063
|
+
});
|
|
2064
|
+
return this;
|
|
2065
|
+
}
|
|
2066
|
+
basePath(path) {
|
|
2067
|
+
const subApp = this.#clone();
|
|
2068
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
2069
|
+
return subApp;
|
|
2070
|
+
}
|
|
2071
|
+
onError = (handler) => {
|
|
2072
|
+
this.errorHandler = handler;
|
|
2073
|
+
return this;
|
|
2074
|
+
};
|
|
2075
|
+
notFound = (handler) => {
|
|
2076
|
+
this.#notFoundHandler = handler;
|
|
2077
|
+
return this;
|
|
2078
|
+
};
|
|
2079
|
+
mount(path, applicationHandler, options) {
|
|
2080
|
+
let replaceRequest;
|
|
2081
|
+
let optionHandler;
|
|
2082
|
+
if (options) {
|
|
2083
|
+
if (typeof options === "function") {
|
|
2084
|
+
optionHandler = options;
|
|
2085
|
+
} else {
|
|
2086
|
+
optionHandler = options.optionHandler;
|
|
2087
|
+
if (options.replaceRequest === false) {
|
|
2088
|
+
replaceRequest = (request) => request;
|
|
2089
|
+
} else {
|
|
2090
|
+
replaceRequest = options.replaceRequest;
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
const getOptions = optionHandler ? (c) => {
|
|
2095
|
+
const options2 = optionHandler(c);
|
|
2096
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
2097
|
+
} : (c) => {
|
|
2098
|
+
let executionContext = undefined;
|
|
2099
|
+
try {
|
|
2100
|
+
executionContext = c.executionCtx;
|
|
2101
|
+
} catch {}
|
|
2102
|
+
return [c.env, executionContext];
|
|
2103
|
+
};
|
|
2104
|
+
replaceRequest ||= (() => {
|
|
2105
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
2106
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
2107
|
+
return (request) => {
|
|
2108
|
+
const url = new URL(request.url);
|
|
2109
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
2110
|
+
return new Request(url, request);
|
|
2111
|
+
};
|
|
2112
|
+
})();
|
|
2113
|
+
const handler = async (c, next) => {
|
|
2114
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
2115
|
+
if (res) {
|
|
2116
|
+
return res;
|
|
2117
|
+
}
|
|
2118
|
+
await next();
|
|
2119
|
+
};
|
|
2120
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
2121
|
+
return this;
|
|
2122
|
+
}
|
|
2123
|
+
#addRoute(method, path, handler) {
|
|
2124
|
+
method = method.toUpperCase();
|
|
2125
|
+
path = mergePath(this._basePath, path);
|
|
2126
|
+
const r = { basePath: this._basePath, path, method, handler };
|
|
2127
|
+
this.router.add(method, path, [handler, r]);
|
|
2128
|
+
this.routes.push(r);
|
|
2129
|
+
}
|
|
2130
|
+
#handleError(err, c) {
|
|
2131
|
+
if (err instanceof Error) {
|
|
2132
|
+
return this.errorHandler(err, c);
|
|
2133
|
+
}
|
|
2134
|
+
throw err;
|
|
2135
|
+
}
|
|
2136
|
+
#dispatch(request, executionCtx, env, method) {
|
|
2137
|
+
if (method === "HEAD") {
|
|
2138
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
2139
|
+
}
|
|
2140
|
+
const path = this.getPath(request, { env });
|
|
2141
|
+
const matchResult = this.router.match(method, path);
|
|
2142
|
+
const c = new Context(request, {
|
|
2143
|
+
path,
|
|
2144
|
+
matchResult,
|
|
2145
|
+
env,
|
|
2146
|
+
executionCtx,
|
|
2147
|
+
notFoundHandler: this.#notFoundHandler
|
|
2148
|
+
});
|
|
2149
|
+
if (matchResult[0].length === 1) {
|
|
2150
|
+
let res;
|
|
2151
|
+
try {
|
|
2152
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
2153
|
+
c.res = await this.#notFoundHandler(c);
|
|
2154
|
+
});
|
|
2155
|
+
} catch (err) {
|
|
2156
|
+
return this.#handleError(err, c);
|
|
2157
|
+
}
|
|
2158
|
+
return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
2159
|
+
}
|
|
2160
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
2161
|
+
return (async () => {
|
|
2162
|
+
try {
|
|
2163
|
+
const context = await composed(c);
|
|
2164
|
+
if (!context.finalized) {
|
|
2165
|
+
throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
|
|
2166
|
+
}
|
|
2167
|
+
return context.res;
|
|
2168
|
+
} catch (err) {
|
|
2169
|
+
return this.#handleError(err, c);
|
|
2170
|
+
}
|
|
2171
|
+
})();
|
|
2172
|
+
}
|
|
2173
|
+
fetch = (request, ...rest) => {
|
|
2174
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
2175
|
+
};
|
|
2176
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
2177
|
+
if (input instanceof Request) {
|
|
2178
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
2179
|
+
}
|
|
2180
|
+
input = input.toString();
|
|
2181
|
+
return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
|
|
2182
|
+
};
|
|
2183
|
+
fire = () => {
|
|
2184
|
+
addEventListener("fetch", (event) => {
|
|
2185
|
+
event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
|
|
2186
|
+
});
|
|
2187
|
+
};
|
|
2188
|
+
};
|
|
2189
|
+
|
|
2190
|
+
// node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
2191
|
+
var emptyParam = [];
|
|
2192
|
+
function match(method, path) {
|
|
2193
|
+
const matchers = this.buildAllMatchers();
|
|
2194
|
+
const match2 = (method2, path2) => {
|
|
2195
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
2196
|
+
const staticMatch = matcher[2][path2];
|
|
2197
|
+
if (staticMatch) {
|
|
2198
|
+
return staticMatch;
|
|
2199
|
+
}
|
|
2200
|
+
const match3 = path2.match(matcher[0]);
|
|
2201
|
+
if (!match3) {
|
|
2202
|
+
return [[], emptyParam];
|
|
2203
|
+
}
|
|
2204
|
+
const index = match3.indexOf("", 1);
|
|
2205
|
+
return [matcher[1][index], match3];
|
|
2206
|
+
};
|
|
2207
|
+
this.match = match2;
|
|
2208
|
+
return match2(method, path);
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
// node_modules/hono/dist/router/reg-exp-router/node.js
|
|
2212
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
2213
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
2214
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
2215
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
2216
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
2217
|
+
function compareKey(a, b) {
|
|
2218
|
+
if (a.length === 1) {
|
|
2219
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
2220
|
+
}
|
|
2221
|
+
if (b.length === 1) {
|
|
2222
|
+
return 1;
|
|
2223
|
+
}
|
|
2224
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2225
|
+
return 1;
|
|
2226
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2227
|
+
return -1;
|
|
2228
|
+
}
|
|
2229
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
2230
|
+
return 1;
|
|
2231
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
2232
|
+
return -1;
|
|
2233
|
+
}
|
|
2234
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
2235
|
+
}
|
|
2236
|
+
var Node = class _Node {
|
|
2237
|
+
#index;
|
|
2238
|
+
#varIndex;
|
|
2239
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
2240
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
2241
|
+
if (tokens.length === 0) {
|
|
2242
|
+
if (this.#index !== undefined) {
|
|
2243
|
+
throw PATH_ERROR;
|
|
2244
|
+
}
|
|
2245
|
+
if (pathErrorCheckOnly) {
|
|
2246
|
+
return;
|
|
2247
|
+
}
|
|
2248
|
+
this.#index = index;
|
|
2249
|
+
return;
|
|
2250
|
+
}
|
|
2251
|
+
const [token, ...restTokens] = tokens;
|
|
2252
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
2253
|
+
let node;
|
|
2254
|
+
if (pattern) {
|
|
2255
|
+
const name = pattern[1];
|
|
2256
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
2257
|
+
if (name && pattern[2]) {
|
|
2258
|
+
if (regexpStr === ".*") {
|
|
2259
|
+
throw PATH_ERROR;
|
|
2260
|
+
}
|
|
2261
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
2262
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
2263
|
+
throw PATH_ERROR;
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
node = this.#children[regexpStr];
|
|
2267
|
+
if (!node) {
|
|
2268
|
+
if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
2269
|
+
throw PATH_ERROR;
|
|
2270
|
+
}
|
|
2271
|
+
if (pathErrorCheckOnly) {
|
|
2272
|
+
return;
|
|
2273
|
+
}
|
|
2274
|
+
node = this.#children[regexpStr] = new _Node;
|
|
2275
|
+
if (name !== "") {
|
|
2276
|
+
node.#varIndex = context.varIndex++;
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
2280
|
+
paramMap.push([name, node.#varIndex]);
|
|
2281
|
+
}
|
|
2282
|
+
} else {
|
|
2283
|
+
node = this.#children[token];
|
|
2284
|
+
if (!node) {
|
|
2285
|
+
if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
2286
|
+
throw PATH_ERROR;
|
|
2287
|
+
}
|
|
2288
|
+
if (pathErrorCheckOnly) {
|
|
2289
|
+
return;
|
|
2290
|
+
}
|
|
2291
|
+
node = this.#children[token] = new _Node;
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
2295
|
+
}
|
|
2296
|
+
buildRegExpStr() {
|
|
2297
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
2298
|
+
const strList = childKeys.map((k) => {
|
|
2299
|
+
const c = this.#children[k];
|
|
2300
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
2301
|
+
});
|
|
2302
|
+
if (typeof this.#index === "number") {
|
|
2303
|
+
strList.unshift(`#${this.#index}`);
|
|
2304
|
+
}
|
|
2305
|
+
if (strList.length === 0) {
|
|
2306
|
+
return "";
|
|
2307
|
+
}
|
|
2308
|
+
if (strList.length === 1) {
|
|
2309
|
+
return strList[0];
|
|
2310
|
+
}
|
|
2311
|
+
return "(?:" + strList.join("|") + ")";
|
|
2312
|
+
}
|
|
2313
|
+
};
|
|
2314
|
+
|
|
2315
|
+
// node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
2316
|
+
var Trie = class {
|
|
2317
|
+
#context = { varIndex: 0 };
|
|
2318
|
+
#root = new Node;
|
|
2319
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
2320
|
+
const paramAssoc = [];
|
|
2321
|
+
const groups = [];
|
|
2322
|
+
for (let i = 0;; ) {
|
|
2323
|
+
let replaced = false;
|
|
2324
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
2325
|
+
const mark = `@\\${i}`;
|
|
2326
|
+
groups[i] = [mark, m];
|
|
2327
|
+
i++;
|
|
2328
|
+
replaced = true;
|
|
2329
|
+
return mark;
|
|
2330
|
+
});
|
|
2331
|
+
if (!replaced) {
|
|
2332
|
+
break;
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
2336
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
2337
|
+
const [mark] = groups[i];
|
|
2338
|
+
for (let j = tokens.length - 1;j >= 0; j--) {
|
|
2339
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
2340
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
2341
|
+
break;
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
2346
|
+
return paramAssoc;
|
|
2347
|
+
}
|
|
2348
|
+
buildRegExp() {
|
|
2349
|
+
let regexp = this.#root.buildRegExpStr();
|
|
2350
|
+
if (regexp === "") {
|
|
2351
|
+
return [/^$/, [], []];
|
|
2352
|
+
}
|
|
2353
|
+
let captureIndex = 0;
|
|
2354
|
+
const indexReplacementMap = [];
|
|
2355
|
+
const paramReplacementMap = [];
|
|
2356
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
2357
|
+
if (handlerIndex !== undefined) {
|
|
2358
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
2359
|
+
return "$()";
|
|
2360
|
+
}
|
|
2361
|
+
if (paramIndex !== undefined) {
|
|
2362
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
2363
|
+
return "";
|
|
2364
|
+
}
|
|
2365
|
+
return "";
|
|
2366
|
+
});
|
|
2367
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
2368
|
+
}
|
|
2369
|
+
};
|
|
2370
|
+
|
|
2371
|
+
// node_modules/hono/dist/router/reg-exp-router/router.js
|
|
2372
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
2373
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2374
|
+
function buildWildcardRegExp(path) {
|
|
2375
|
+
return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
|
|
2376
|
+
}
|
|
2377
|
+
function clearWildcardRegExpCache() {
|
|
2378
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2379
|
+
}
|
|
2380
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
2381
|
+
const trie = new Trie;
|
|
2382
|
+
const handlerData = [];
|
|
2383
|
+
if (routes.length === 0) {
|
|
2384
|
+
return nullMatcher;
|
|
2385
|
+
}
|
|
2386
|
+
const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
|
|
2387
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
2388
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
|
|
2389
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
2390
|
+
if (pathErrorCheckOnly) {
|
|
2391
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
2392
|
+
} else {
|
|
2393
|
+
j++;
|
|
2394
|
+
}
|
|
2395
|
+
let paramAssoc;
|
|
2396
|
+
try {
|
|
2397
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
2398
|
+
} catch (e) {
|
|
2399
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
2400
|
+
}
|
|
2401
|
+
if (pathErrorCheckOnly) {
|
|
2402
|
+
continue;
|
|
2403
|
+
}
|
|
2404
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
2405
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
2406
|
+
paramCount -= 1;
|
|
2407
|
+
for (;paramCount >= 0; paramCount--) {
|
|
2408
|
+
const [key, value] = paramAssoc[paramCount];
|
|
2409
|
+
paramIndexMap[key] = value;
|
|
2410
|
+
}
|
|
2411
|
+
return [h, paramIndexMap];
|
|
2412
|
+
});
|
|
2413
|
+
}
|
|
2414
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
2415
|
+
for (let i = 0, len = handlerData.length;i < len; i++) {
|
|
2416
|
+
for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
|
|
2417
|
+
const map = handlerData[i][j]?.[1];
|
|
2418
|
+
if (!map) {
|
|
2419
|
+
continue;
|
|
2420
|
+
}
|
|
2421
|
+
const keys = Object.keys(map);
|
|
2422
|
+
for (let k = 0, len3 = keys.length;k < len3; k++) {
|
|
2423
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
const handlerMap = [];
|
|
2428
|
+
for (const i in indexReplacementMap) {
|
|
2429
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
2430
|
+
}
|
|
2431
|
+
return [regexp, handlerMap, staticMap];
|
|
2432
|
+
}
|
|
2433
|
+
function findMiddleware(middleware, path) {
|
|
2434
|
+
if (!middleware) {
|
|
2435
|
+
return;
|
|
2436
|
+
}
|
|
2437
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
2438
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
2439
|
+
return [...middleware[k]];
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
return;
|
|
2443
|
+
}
|
|
2444
|
+
var RegExpRouter = class {
|
|
2445
|
+
name = "RegExpRouter";
|
|
2446
|
+
#middleware;
|
|
2447
|
+
#routes;
|
|
2448
|
+
constructor() {
|
|
2449
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2450
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2451
|
+
}
|
|
2452
|
+
add(method, path, handler) {
|
|
2453
|
+
const middleware = this.#middleware;
|
|
2454
|
+
const routes = this.#routes;
|
|
2455
|
+
if (!middleware || !routes) {
|
|
2456
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2457
|
+
}
|
|
2458
|
+
if (!middleware[method]) {
|
|
2459
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
2460
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
2461
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
2462
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
2463
|
+
});
|
|
2464
|
+
});
|
|
2465
|
+
}
|
|
2466
|
+
if (path === "/*") {
|
|
2467
|
+
path = "*";
|
|
2468
|
+
}
|
|
2469
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
2470
|
+
if (/\*$/.test(path)) {
|
|
2471
|
+
const re = buildWildcardRegExp(path);
|
|
2472
|
+
if (method === METHOD_NAME_ALL) {
|
|
2473
|
+
Object.keys(middleware).forEach((m) => {
|
|
2474
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
2475
|
+
});
|
|
2476
|
+
} else {
|
|
2477
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
2478
|
+
}
|
|
2479
|
+
Object.keys(middleware).forEach((m) => {
|
|
2480
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2481
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
2482
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
});
|
|
2486
|
+
Object.keys(routes).forEach((m) => {
|
|
2487
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2488
|
+
Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
|
|
2489
|
+
}
|
|
2490
|
+
});
|
|
2491
|
+
return;
|
|
2492
|
+
}
|
|
2493
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
2494
|
+
for (let i = 0, len = paths.length;i < len; i++) {
|
|
2495
|
+
const path2 = paths[i];
|
|
2496
|
+
Object.keys(routes).forEach((m) => {
|
|
2497
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2498
|
+
routes[m][path2] ||= [
|
|
2499
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
2500
|
+
];
|
|
2501
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
2502
|
+
}
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
match = match;
|
|
2507
|
+
buildAllMatchers() {
|
|
2508
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
2509
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
2510
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
2511
|
+
});
|
|
2512
|
+
this.#middleware = this.#routes = undefined;
|
|
2513
|
+
clearWildcardRegExpCache();
|
|
2514
|
+
return matchers;
|
|
2515
|
+
}
|
|
2516
|
+
#buildMatcher(method) {
|
|
2517
|
+
const routes = [];
|
|
2518
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
2519
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
2520
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
2521
|
+
if (ownRoute.length !== 0) {
|
|
2522
|
+
hasOwnRoute ||= true;
|
|
2523
|
+
routes.push(...ownRoute);
|
|
2524
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
2525
|
+
routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
|
|
2526
|
+
}
|
|
2527
|
+
});
|
|
2528
|
+
if (!hasOwnRoute) {
|
|
2529
|
+
return null;
|
|
2530
|
+
} else {
|
|
2531
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
};
|
|
2535
|
+
|
|
2536
|
+
// node_modules/hono/dist/router/reg-exp-router/prepared-router.js
|
|
2537
|
+
var PreparedRegExpRouter = class {
|
|
2538
|
+
name = "PreparedRegExpRouter";
|
|
2539
|
+
#matchers;
|
|
2540
|
+
#relocateMap;
|
|
2541
|
+
constructor(matchers, relocateMap) {
|
|
2542
|
+
this.#matchers = matchers;
|
|
2543
|
+
this.#relocateMap = relocateMap;
|
|
2544
|
+
}
|
|
2545
|
+
#addWildcard(method, handlerData) {
|
|
2546
|
+
const matcher = this.#matchers[method];
|
|
2547
|
+
matcher[1].forEach((list) => list && list.push(handlerData));
|
|
2548
|
+
Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
|
|
2549
|
+
}
|
|
2550
|
+
#addPath(method, path, handler, indexes, map) {
|
|
2551
|
+
const matcher = this.#matchers[method];
|
|
2552
|
+
if (!map) {
|
|
2553
|
+
matcher[2][path][0].push([handler, {}]);
|
|
2554
|
+
} else {
|
|
2555
|
+
indexes.forEach((index) => {
|
|
2556
|
+
if (typeof index === "number") {
|
|
2557
|
+
matcher[1][index].push([handler, map]);
|
|
2558
|
+
} else {
|
|
2559
|
+
matcher[2][index || path][0].push([handler, map]);
|
|
2560
|
+
}
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
add(method, path, handler) {
|
|
2565
|
+
if (!this.#matchers[method]) {
|
|
2566
|
+
const all = this.#matchers[METHOD_NAME_ALL];
|
|
2567
|
+
const staticMap = {};
|
|
2568
|
+
for (const key in all[2]) {
|
|
2569
|
+
staticMap[key] = [all[2][key][0].slice(), emptyParam];
|
|
2570
|
+
}
|
|
2571
|
+
this.#matchers[method] = [
|
|
2572
|
+
all[0],
|
|
2573
|
+
all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
|
|
2574
|
+
staticMap
|
|
2575
|
+
];
|
|
2576
|
+
}
|
|
2577
|
+
if (path === "/*" || path === "*") {
|
|
2578
|
+
const handlerData = [handler, {}];
|
|
2579
|
+
if (method === METHOD_NAME_ALL) {
|
|
2580
|
+
for (const m in this.#matchers) {
|
|
2581
|
+
this.#addWildcard(m, handlerData);
|
|
2582
|
+
}
|
|
2583
|
+
} else {
|
|
2584
|
+
this.#addWildcard(method, handlerData);
|
|
2585
|
+
}
|
|
2586
|
+
return;
|
|
2587
|
+
}
|
|
2588
|
+
const data = this.#relocateMap[path];
|
|
2589
|
+
if (!data) {
|
|
2590
|
+
throw new Error(`Path ${path} is not registered`);
|
|
2591
|
+
}
|
|
2592
|
+
for (const [indexes, map] of data) {
|
|
2593
|
+
if (method === METHOD_NAME_ALL) {
|
|
2594
|
+
for (const m in this.#matchers) {
|
|
2595
|
+
this.#addPath(m, path, handler, indexes, map);
|
|
2596
|
+
}
|
|
2597
|
+
} else {
|
|
2598
|
+
this.#addPath(method, path, handler, indexes, map);
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
buildAllMatchers() {
|
|
2603
|
+
return this.#matchers;
|
|
2604
|
+
}
|
|
2605
|
+
match = match;
|
|
2606
|
+
};
|
|
2607
|
+
|
|
2608
|
+
// node_modules/hono/dist/router/smart-router/router.js
|
|
2609
|
+
var SmartRouter = class {
|
|
2610
|
+
name = "SmartRouter";
|
|
2611
|
+
#routers = [];
|
|
2612
|
+
#routes = [];
|
|
2613
|
+
constructor(init) {
|
|
2614
|
+
this.#routers = init.routers;
|
|
2615
|
+
}
|
|
2616
|
+
add(method, path, handler) {
|
|
2617
|
+
if (!this.#routes) {
|
|
2618
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2619
|
+
}
|
|
2620
|
+
this.#routes.push([method, path, handler]);
|
|
2621
|
+
}
|
|
2622
|
+
match(method, path) {
|
|
2623
|
+
if (!this.#routes) {
|
|
2624
|
+
throw new Error("Fatal error");
|
|
2625
|
+
}
|
|
2626
|
+
const routers = this.#routers;
|
|
2627
|
+
const routes = this.#routes;
|
|
2628
|
+
const len = routers.length;
|
|
2629
|
+
let i = 0;
|
|
2630
|
+
let res;
|
|
2631
|
+
for (;i < len; i++) {
|
|
2632
|
+
const router = routers[i];
|
|
2633
|
+
try {
|
|
2634
|
+
for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
|
|
2635
|
+
router.add(...routes[i2]);
|
|
2636
|
+
}
|
|
2637
|
+
res = router.match(method, path);
|
|
2638
|
+
} catch (e) {
|
|
2639
|
+
if (e instanceof UnsupportedPathError) {
|
|
2640
|
+
continue;
|
|
2641
|
+
}
|
|
2642
|
+
throw e;
|
|
2643
|
+
}
|
|
2644
|
+
this.match = router.match.bind(router);
|
|
2645
|
+
this.#routers = [router];
|
|
2646
|
+
this.#routes = undefined;
|
|
2647
|
+
break;
|
|
2648
|
+
}
|
|
2649
|
+
if (i === len) {
|
|
2650
|
+
throw new Error("Fatal error");
|
|
2651
|
+
}
|
|
2652
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
2653
|
+
return res;
|
|
2654
|
+
}
|
|
2655
|
+
get activeRouter() {
|
|
2656
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
2657
|
+
throw new Error("No active router has been determined yet.");
|
|
2658
|
+
}
|
|
2659
|
+
return this.#routers[0];
|
|
2660
|
+
}
|
|
2661
|
+
};
|
|
2662
|
+
|
|
2663
|
+
// node_modules/hono/dist/router/trie-router/node.js
|
|
2664
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
2665
|
+
var hasChildren = (children) => {
|
|
2666
|
+
for (const _ in children) {
|
|
2667
|
+
return true;
|
|
2668
|
+
}
|
|
2669
|
+
return false;
|
|
2670
|
+
};
|
|
2671
|
+
var Node2 = class _Node2 {
|
|
2672
|
+
#methods;
|
|
2673
|
+
#children;
|
|
2674
|
+
#patterns;
|
|
2675
|
+
#order = 0;
|
|
2676
|
+
#params = emptyParams;
|
|
2677
|
+
constructor(method, handler, children) {
|
|
2678
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
2679
|
+
this.#methods = [];
|
|
2680
|
+
if (method && handler) {
|
|
2681
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
2682
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
2683
|
+
this.#methods = [m];
|
|
2684
|
+
}
|
|
2685
|
+
this.#patterns = [];
|
|
2686
|
+
}
|
|
2687
|
+
insert(method, path, handler) {
|
|
2688
|
+
this.#order = ++this.#order;
|
|
2689
|
+
let curNode = this;
|
|
2690
|
+
const parts = splitRoutingPath(path);
|
|
2691
|
+
const possibleKeys = [];
|
|
2692
|
+
for (let i = 0, len = parts.length;i < len; i++) {
|
|
2693
|
+
const p = parts[i];
|
|
2694
|
+
const nextP = parts[i + 1];
|
|
2695
|
+
const pattern = getPattern(p, nextP);
|
|
2696
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
2697
|
+
if (key in curNode.#children) {
|
|
2698
|
+
curNode = curNode.#children[key];
|
|
2699
|
+
if (pattern) {
|
|
2700
|
+
possibleKeys.push(pattern[1]);
|
|
2701
|
+
}
|
|
2702
|
+
continue;
|
|
2703
|
+
}
|
|
2704
|
+
curNode.#children[key] = new _Node2;
|
|
2705
|
+
if (pattern) {
|
|
2706
|
+
curNode.#patterns.push(pattern);
|
|
2707
|
+
possibleKeys.push(pattern[1]);
|
|
2708
|
+
}
|
|
2709
|
+
curNode = curNode.#children[key];
|
|
2710
|
+
}
|
|
2711
|
+
curNode.#methods.push({
|
|
2712
|
+
[method]: {
|
|
2713
|
+
handler,
|
|
2714
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
2715
|
+
score: this.#order
|
|
2716
|
+
}
|
|
2717
|
+
});
|
|
2718
|
+
return curNode;
|
|
2719
|
+
}
|
|
2720
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
2721
|
+
for (let i = 0, len = node.#methods.length;i < len; i++) {
|
|
2722
|
+
const m = node.#methods[i];
|
|
2723
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
2724
|
+
const processedSet = {};
|
|
2725
|
+
if (handlerSet !== undefined) {
|
|
2726
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
2727
|
+
handlerSets.push(handlerSet);
|
|
2728
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
2729
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
|
|
2730
|
+
const key = handlerSet.possibleKeys[i2];
|
|
2731
|
+
const processed = processedSet[handlerSet.score];
|
|
2732
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
2733
|
+
processedSet[handlerSet.score] = true;
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
search(method, path) {
|
|
2740
|
+
const handlerSets = [];
|
|
2741
|
+
this.#params = emptyParams;
|
|
2742
|
+
const curNode = this;
|
|
2743
|
+
let curNodes = [curNode];
|
|
2744
|
+
const parts = splitPath(path);
|
|
2745
|
+
const curNodesQueue = [];
|
|
2746
|
+
const len = parts.length;
|
|
2747
|
+
let partOffsets = null;
|
|
2748
|
+
for (let i = 0;i < len; i++) {
|
|
2749
|
+
const part = parts[i];
|
|
2750
|
+
const isLast = i === len - 1;
|
|
2751
|
+
const tempNodes = [];
|
|
2752
|
+
for (let j = 0, len2 = curNodes.length;j < len2; j++) {
|
|
2753
|
+
const node = curNodes[j];
|
|
2754
|
+
const nextNode = node.#children[part];
|
|
2755
|
+
if (nextNode) {
|
|
2756
|
+
nextNode.#params = node.#params;
|
|
2757
|
+
if (isLast) {
|
|
2758
|
+
if (nextNode.#children["*"]) {
|
|
2759
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
2760
|
+
}
|
|
2761
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
2762
|
+
} else {
|
|
2763
|
+
tempNodes.push(nextNode);
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
|
|
2767
|
+
const pattern = node.#patterns[k];
|
|
2768
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
2769
|
+
if (pattern === "*") {
|
|
2770
|
+
const astNode = node.#children["*"];
|
|
2771
|
+
if (astNode) {
|
|
2772
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
2773
|
+
astNode.#params = params;
|
|
2774
|
+
tempNodes.push(astNode);
|
|
2775
|
+
}
|
|
2776
|
+
continue;
|
|
2777
|
+
}
|
|
2778
|
+
const [key, name, matcher] = pattern;
|
|
2779
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
2780
|
+
continue;
|
|
2781
|
+
}
|
|
2782
|
+
const child = node.#children[key];
|
|
2783
|
+
if (matcher instanceof RegExp) {
|
|
2784
|
+
if (partOffsets === null) {
|
|
2785
|
+
partOffsets = new Array(len);
|
|
2786
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
2787
|
+
for (let p = 0;p < len; p++) {
|
|
2788
|
+
partOffsets[p] = offset;
|
|
2789
|
+
offset += parts[p].length + 1;
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
2793
|
+
const m = matcher.exec(restPathString);
|
|
2794
|
+
if (m) {
|
|
2795
|
+
params[name] = m[0];
|
|
2796
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
2797
|
+
if (hasChildren(child.#children)) {
|
|
2798
|
+
child.#params = params;
|
|
2799
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
2800
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
2801
|
+
targetCurNodes.push(child);
|
|
2802
|
+
}
|
|
2803
|
+
continue;
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
if (matcher === true || matcher.test(part)) {
|
|
2807
|
+
params[name] = part;
|
|
2808
|
+
if (isLast) {
|
|
2809
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
2810
|
+
if (child.#children["*"]) {
|
|
2811
|
+
this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
|
|
2812
|
+
}
|
|
2813
|
+
} else {
|
|
2814
|
+
child.#params = params;
|
|
2815
|
+
tempNodes.push(child);
|
|
2816
|
+
}
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
const shifted = curNodesQueue.shift();
|
|
2821
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
2822
|
+
}
|
|
2823
|
+
if (handlerSets.length > 1) {
|
|
2824
|
+
handlerSets.sort((a, b) => {
|
|
2825
|
+
return a.score - b.score;
|
|
2826
|
+
});
|
|
2827
|
+
}
|
|
2828
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2829
|
+
}
|
|
2830
|
+
};
|
|
2831
|
+
|
|
2832
|
+
// node_modules/hono/dist/router/trie-router/router.js
|
|
2833
|
+
var TrieRouter = class {
|
|
2834
|
+
name = "TrieRouter";
|
|
2835
|
+
#node;
|
|
2836
|
+
constructor() {
|
|
2837
|
+
this.#node = new Node2;
|
|
2838
|
+
}
|
|
2839
|
+
add(method, path, handler) {
|
|
2840
|
+
const results = checkOptionalParameter(path);
|
|
2841
|
+
if (results) {
|
|
2842
|
+
for (let i = 0, len = results.length;i < len; i++) {
|
|
2843
|
+
this.#node.insert(method, results[i], handler);
|
|
2844
|
+
}
|
|
2845
|
+
return;
|
|
2846
|
+
}
|
|
2847
|
+
this.#node.insert(method, path, handler);
|
|
2848
|
+
}
|
|
2849
|
+
match(method, path) {
|
|
2850
|
+
return this.#node.search(method, path);
|
|
2851
|
+
}
|
|
2852
|
+
};
|
|
2853
|
+
|
|
2854
|
+
// node_modules/hono/dist/hono.js
|
|
2855
|
+
var Hono2 = class extends Hono {
|
|
2856
|
+
constructor(options = {}) {
|
|
2857
|
+
super(options);
|
|
2858
|
+
this.router = options.router ?? new SmartRouter({
|
|
2859
|
+
routers: [new RegExpRouter, new TrieRouter]
|
|
2860
|
+
});
|
|
2861
|
+
}
|
|
2862
|
+
};
|
|
2863
|
+
|
|
2864
|
+
// node_modules/hono/dist/utils/color.js
|
|
2865
|
+
function getColorEnabled() {
|
|
2866
|
+
const { process: process2, Deno } = globalThis;
|
|
2867
|
+
const isNoColor = typeof Deno?.noColor === "boolean" ? Deno.noColor : process2 !== undefined ? "NO_COLOR" in process2?.env : false;
|
|
2868
|
+
return !isNoColor;
|
|
2869
|
+
}
|
|
2870
|
+
async function getColorEnabledAsync() {
|
|
2871
|
+
const { navigator } = globalThis;
|
|
2872
|
+
const cfWorkers = "cloudflare:workers";
|
|
2873
|
+
const isNoColor = navigator !== undefined && navigator.userAgent === "Cloudflare-Workers" ? await (async () => {
|
|
2874
|
+
try {
|
|
2875
|
+
return "NO_COLOR" in ((await import(cfWorkers)).env ?? {});
|
|
2876
|
+
} catch {
|
|
2877
|
+
return false;
|
|
2878
|
+
}
|
|
2879
|
+
})() : !getColorEnabled();
|
|
2880
|
+
return !isNoColor;
|
|
2881
|
+
}
|
|
2882
|
+
|
|
2883
|
+
// node_modules/hono/dist/middleware/logger/index.js
|
|
2884
|
+
var humanize = (times) => {
|
|
2885
|
+
const [delimiter, separator] = [",", "."];
|
|
2886
|
+
const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter));
|
|
2887
|
+
return orderTimes.join(separator);
|
|
2888
|
+
};
|
|
2889
|
+
var time = (start) => {
|
|
2890
|
+
const delta = Date.now() - start;
|
|
2891
|
+
return humanize([delta < 1000 ? delta + "ms" : Math.round(delta / 1000) + "s"]);
|
|
2892
|
+
};
|
|
2893
|
+
var colorStatus = async (status) => {
|
|
2894
|
+
const colorEnabled = await getColorEnabledAsync();
|
|
2895
|
+
if (colorEnabled) {
|
|
2896
|
+
switch (status / 100 | 0) {
|
|
2897
|
+
case 5:
|
|
2898
|
+
return `\x1B[31m${status}\x1B[0m`;
|
|
2899
|
+
case 4:
|
|
2900
|
+
return `\x1B[33m${status}\x1B[0m`;
|
|
2901
|
+
case 3:
|
|
2902
|
+
return `\x1B[36m${status}\x1B[0m`;
|
|
2903
|
+
case 2:
|
|
2904
|
+
return `\x1B[32m${status}\x1B[0m`;
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
return `${status}`;
|
|
2908
|
+
};
|
|
2909
|
+
async function log(fn, prefix, method, path, status = 0, elapsed) {
|
|
2910
|
+
const out = prefix === "<--" ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`;
|
|
2911
|
+
fn(out);
|
|
2912
|
+
}
|
|
2913
|
+
var logger = (fn = console.log) => {
|
|
2914
|
+
return async function logger2(c, next) {
|
|
2915
|
+
const { method, url } = c.req;
|
|
2916
|
+
const path = url.slice(url.indexOf("/", 8));
|
|
2917
|
+
await log(fn, "<--", method, path);
|
|
2918
|
+
const start = Date.now();
|
|
2919
|
+
await next();
|
|
2920
|
+
await log(fn, "-->", method, path, c.res.status, time(start));
|
|
2921
|
+
};
|
|
2922
|
+
};
|
|
2923
|
+
|
|
2924
|
+
// src/index.ts
|
|
2925
|
+
var import_node_cron = __toESM(require_node_cron(), 1);
|
|
2926
|
+
async function loadWorkflows(workflowsDir) {
|
|
2927
|
+
const workflows = {};
|
|
2928
|
+
try {
|
|
2929
|
+
const files = await readdir(workflowsDir);
|
|
2930
|
+
for (const file of files) {
|
|
2931
|
+
if (file.endsWith(".ts") || file.endsWith(".js")) {
|
|
2932
|
+
const modulePath = join(workflowsDir, file);
|
|
2933
|
+
const importedModule = await import(modulePath);
|
|
2934
|
+
const workflow = importedModule.default;
|
|
2935
|
+
if (workflow?.config?.id) {
|
|
2936
|
+
workflows[workflow.config.id] = workflow;
|
|
2937
|
+
console.log(`[Miqro] Loaded workflow: ${workflow.config.id} (${file})`);
|
|
2938
|
+
if (workflow.config.schedule) {
|
|
2939
|
+
import_node_cron.default.schedule(workflow.config.schedule, () => {
|
|
2940
|
+
console.log(`[Cron] Executing scheduled workflow: ${workflow.config.id}`);
|
|
2941
|
+
const payload = { source: "cron", timestamp: Date.now() };
|
|
2942
|
+
workflow.execute(payload);
|
|
2943
|
+
});
|
|
2944
|
+
console.log(`[Miqro] Scheduled workflow '${workflow.config.id}' with cron: '${workflow.config.schedule}'`);
|
|
2945
|
+
}
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
} catch (error) {
|
|
2950
|
+
console.error(`[Miqro] Error loading workflows from ${workflowsDir}:`, error);
|
|
2951
|
+
}
|
|
2952
|
+
return workflows;
|
|
2953
|
+
}
|
|
2954
|
+
async function startMiqroCore(config, staticWorkflows) {
|
|
2955
|
+
const workflows = {};
|
|
2956
|
+
for (const workflow of staticWorkflows) {
|
|
2957
|
+
if (workflow?.config?.id) {
|
|
2958
|
+
workflows[workflow.config.id] = workflow;
|
|
2959
|
+
console.log(`[Miqro] Loaded workflow: ${workflow.config.id}`);
|
|
2960
|
+
if (workflow.config.schedule) {
|
|
2961
|
+
import_node_cron.default.schedule(workflow.config.schedule, () => {
|
|
2962
|
+
console.log(`[Cron] Executing scheduled workflow: ${workflow.config.id}`);
|
|
2963
|
+
const payload = { source: "cron", timestamp: Date.now() };
|
|
2964
|
+
workflow.execute(payload);
|
|
2965
|
+
});
|
|
2966
|
+
console.log(`[Miqro] Scheduled workflow '${workflow.config.id}' with cron: '${workflow.config.schedule}'`);
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
}
|
|
2970
|
+
const app = new Hono2;
|
|
2971
|
+
app.use("*", logger());
|
|
2972
|
+
app.get("/health", (c) => c.json({
|
|
2973
|
+
status: "ok",
|
|
2974
|
+
uptime: process.uptime(),
|
|
2975
|
+
loadedWorkflows: Object.keys(workflows).length
|
|
2976
|
+
}));
|
|
2977
|
+
app.post("/webhook", async (c) => {
|
|
2978
|
+
try {
|
|
2979
|
+
const payload = await c.req.json();
|
|
2980
|
+
const workflowId = c.req.query("workflowId") || payload.workflowId;
|
|
2981
|
+
if (workflowId) {
|
|
2982
|
+
const workflow = workflows[workflowId];
|
|
2983
|
+
if (!workflow) {
|
|
2984
|
+
return c.json({ error: `Workflow '${workflowId}' not found` }, 404);
|
|
2985
|
+
}
|
|
2986
|
+
const authHeader = c.req.header("Authorization");
|
|
2987
|
+
const { auth } = workflow.config;
|
|
2988
|
+
if (auth.type === "apiKey") {
|
|
2989
|
+
const apiKey = c.req.header("x-api-key") || c.req.query("apiKey");
|
|
2990
|
+
if (apiKey !== auth.key) {
|
|
2991
|
+
return c.json({ error: "Unauthorized: Invalid API Key" }, 401);
|
|
2992
|
+
}
|
|
2993
|
+
} else if (auth.type === "bearer") {
|
|
2994
|
+
if (!authHeader || !authHeader.startsWith(`Bearer ${auth.token}`)) {
|
|
2995
|
+
return c.json({ error: "Unauthorized: Invalid Bearer token" }, 401);
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
await workflow.execute(payload);
|
|
2999
|
+
return c.json({
|
|
3000
|
+
status: "success",
|
|
3001
|
+
message: `Workflow '${workflowId}' executed`
|
|
3002
|
+
});
|
|
3003
|
+
}
|
|
3004
|
+
return c.json({
|
|
3005
|
+
status: "success",
|
|
3006
|
+
message: "Payload received but no workflow triggered"
|
|
3007
|
+
});
|
|
3008
|
+
} catch (error) {
|
|
3009
|
+
console.error("[Miqro Webhook Error]", error);
|
|
3010
|
+
return c.json({ error: "Invalid JSON payload or internal error" }, 400);
|
|
3011
|
+
}
|
|
3012
|
+
});
|
|
3013
|
+
const port = config.port || process.env.PORT || 3000;
|
|
3014
|
+
console.log(`\uD83D\uDE80 Miqro started on http://localhost:${port}`);
|
|
3015
|
+
if (Object.keys(workflows).length > 0) {
|
|
3016
|
+
console.log(`Active Webhooks:
|
|
3017
|
+
${Object.keys(workflows).map((w) => ` - POST http://localhost:${port}/webhook?workflowId=${w}`).join(`
|
|
3018
|
+
`)}`);
|
|
3019
|
+
} else {
|
|
3020
|
+
console.log(`No workflows loaded.`);
|
|
3021
|
+
}
|
|
3022
|
+
return {
|
|
3023
|
+
port,
|
|
3024
|
+
fetch: app.fetch
|
|
3025
|
+
};
|
|
3026
|
+
}
|
|
3027
|
+
async function startMiqro(config) {
|
|
3028
|
+
const loadedWorkflowMap = await loadWorkflows(config.workflowsDir);
|
|
3029
|
+
return startMiqroCore(config, Object.values(loadedWorkflowMap));
|
|
3030
|
+
}
|
|
3031
|
+
|
|
3032
|
+
// src/cli.ts
|
|
3033
|
+
import { existsSync } from "fs";
|
|
3034
|
+
import { mkdir, readdir as readdir2, unlink, writeFile } from "fs/promises";
|
|
3035
|
+
import { resolve } from "path";
|
|
3036
|
+
import { parseArgs } from "util";
|
|
3037
|
+
var __dirname = "/Users/antonwerschinin/Code/miqro/src";
|
|
3038
|
+
async function main() {
|
|
3039
|
+
const { positionals } = parseArgs({
|
|
3040
|
+
args: Bun.argv.slice(2),
|
|
3041
|
+
allowPositionals: true
|
|
3042
|
+
});
|
|
3043
|
+
const command = positionals[0] || "start";
|
|
3044
|
+
if (command === "init") {
|
|
3045
|
+
const configPath2 = resolve(process.cwd(), "miqro.config.ts");
|
|
3046
|
+
if (existsSync(configPath2)) {
|
|
3047
|
+
console.error(`\u274C miqro.config.ts already exists in the current directory.`);
|
|
3048
|
+
process.exit(1);
|
|
3049
|
+
}
|
|
3050
|
+
const defaultConfig = `import type { MiqroConfig } from "miqro.js";
|
|
3051
|
+
|
|
3052
|
+
export default {
|
|
3053
|
+
port: 3000,
|
|
3054
|
+
workflowsDir: "./workflows",
|
|
3055
|
+
} satisfies MiqroConfig;
|
|
3056
|
+
`;
|
|
3057
|
+
await writeFile(configPath2, defaultConfig);
|
|
3058
|
+
const workflowsPath = resolve(process.cwd(), "workflows");
|
|
3059
|
+
if (!existsSync(workflowsPath)) {
|
|
3060
|
+
await mkdir(workflowsPath, { recursive: true });
|
|
3061
|
+
}
|
|
3062
|
+
console.log("\u2705 Created miqro.config.ts and workflows directory.");
|
|
3063
|
+
console.log("\uD83D\uDC49 Run `miqro dev` to start the development server.");
|
|
3064
|
+
process.exit(0);
|
|
3065
|
+
}
|
|
3066
|
+
const configPath = resolve(process.cwd(), "miqro.config.ts");
|
|
3067
|
+
let userConfig = {};
|
|
3068
|
+
try {
|
|
3069
|
+
const importedConfig = await import(configPath);
|
|
3070
|
+
userConfig = importedConfig.default || importedConfig;
|
|
3071
|
+
} catch (_err) {
|
|
3072
|
+
console.error(`\u274C Could not load configuration at ${configPath}.`);
|
|
3073
|
+
console.error(`Are you sure you have a miqro.config.ts in the current directory?`);
|
|
3074
|
+
process.exit(1);
|
|
3075
|
+
}
|
|
3076
|
+
if (!userConfig.workflowsDir) {
|
|
3077
|
+
console.error(`\u274C miqro.config.ts is missing 'workflowsDir'`);
|
|
3078
|
+
process.exit(1);
|
|
3079
|
+
}
|
|
3080
|
+
const absoluteWorkflowsDir = resolve(process.cwd(), userConfig.workflowsDir);
|
|
3081
|
+
userConfig.workflowsDir = absoluteWorkflowsDir;
|
|
3082
|
+
if (command === "dev") {
|
|
3083
|
+
console.log("\uD83D\uDD04 Starting Miqro in DEV mode (hot-reloading enabled)...");
|
|
3084
|
+
Bun.spawn(["bun", "--watch", Bun.argv[1], "start"], {
|
|
3085
|
+
stdout: "inherit",
|
|
3086
|
+
stderr: "inherit"
|
|
3087
|
+
});
|
|
3088
|
+
} else if (command === "start") {
|
|
3089
|
+
console.log("\uD83D\uDE80 Starting Miqro...");
|
|
3090
|
+
const app = await startMiqro(userConfig);
|
|
3091
|
+
Bun.serve(app);
|
|
3092
|
+
} else if (command === "build") {
|
|
3093
|
+
console.log("\uD83D\uDCE6 Building Miqro for production...");
|
|
3094
|
+
let files = [];
|
|
3095
|
+
try {
|
|
3096
|
+
files = await readdir2(absoluteWorkflowsDir);
|
|
3097
|
+
} catch (_err) {
|
|
3098
|
+
console.error(`\u274C Failed reading workflows directory during build: ${absoluteWorkflowsDir}`);
|
|
3099
|
+
process.exit(1);
|
|
3100
|
+
}
|
|
3101
|
+
const workflowFiles = files.filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
|
|
3102
|
+
const tempEntryPath = resolve(process.cwd(), ".miqro.entry.ts");
|
|
3103
|
+
let tempCode = `import { Hono } from 'hono';
|
|
3104
|
+
`;
|
|
3105
|
+
tempCode += `import { logger } from 'hono/logger';
|
|
3106
|
+
`;
|
|
3107
|
+
tempCode += `import cron from 'node-cron';
|
|
3108
|
+
`;
|
|
3109
|
+
tempCode += `import { startMiqroCore } from '${resolve(__dirname, "index.ts")}'; // From miqro module
|
|
3110
|
+
|
|
3111
|
+
`;
|
|
3112
|
+
workflowFiles.forEach((file, idx) => {
|
|
3113
|
+
tempCode += `import wf_${idx} from '${resolve(absoluteWorkflowsDir, file)}';
|
|
3114
|
+
`;
|
|
3115
|
+
});
|
|
3116
|
+
tempCode += `
|
|
3117
|
+
const staticWorkflowsList = [
|
|
3118
|
+
`;
|
|
3119
|
+
workflowFiles.forEach((_, idx) => {
|
|
3120
|
+
tempCode += ` wf_${idx},
|
|
3121
|
+
`;
|
|
3122
|
+
});
|
|
3123
|
+
tempCode += `];
|
|
3124
|
+
|
|
3125
|
+
`;
|
|
3126
|
+
tempCode += `const app = await startMiqroCore({
|
|
3127
|
+
`;
|
|
3128
|
+
tempCode += ` port: ${userConfig.port || 3000},
|
|
3129
|
+
`;
|
|
3130
|
+
tempCode += `}, staticWorkflowsList);
|
|
3131
|
+
|
|
3132
|
+
`;
|
|
3133
|
+
tempCode += `export default app;
|
|
3134
|
+
`;
|
|
3135
|
+
await writeFile(tempEntryPath, tempCode);
|
|
3136
|
+
const outDir = resolve(process.cwd(), "dist");
|
|
3137
|
+
const outName = "index.js";
|
|
3138
|
+
console.log(`Compiling single file artifact to ${outDir}/${outName}...`);
|
|
3139
|
+
const result = await Bun.build({
|
|
3140
|
+
entrypoints: [tempEntryPath],
|
|
3141
|
+
outdir: outDir,
|
|
3142
|
+
target: "bun",
|
|
3143
|
+
naming: outName
|
|
3144
|
+
});
|
|
3145
|
+
try {
|
|
3146
|
+
await unlink(tempEntryPath);
|
|
3147
|
+
} catch (_e) {}
|
|
3148
|
+
if (!result.success) {
|
|
3149
|
+
console.error("\u274C Build failed");
|
|
3150
|
+
console.error(result.logs);
|
|
3151
|
+
process.exit(1);
|
|
3152
|
+
} else {
|
|
3153
|
+
console.log(`\u2705 Build successful! Run it with: bun run dist/${outName}`);
|
|
3154
|
+
}
|
|
3155
|
+
} else {
|
|
3156
|
+
console.error(`Unknown command: ${command}`);
|
|
3157
|
+
console.error("Available commands: init, dev, start, build");
|
|
3158
|
+
process.exit(1);
|
|
3159
|
+
}
|
|
3160
|
+
}
|
|
3161
|
+
main().catch((err) => {
|
|
3162
|
+
console.error("Fatal exception in CLI", err);
|
|
3163
|
+
process.exit(1);
|
|
3164
|
+
});
|