@agntk/agent-harness 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +41 -0
- package/README.md +445 -0
- package/defaults/agents/summarizer.md +49 -0
- package/defaults/instincts/lead-with-answer.md +24 -0
- package/defaults/instincts/qualify-before-recommending.md +40 -0
- package/defaults/instincts/read-before-edit.md +23 -0
- package/defaults/instincts/search-before-create.md +23 -0
- package/defaults/playbooks/ship-feature.md +31 -0
- package/defaults/rules/ask-before-assuming.md +35 -0
- package/defaults/rules/operations.md +35 -0
- package/defaults/rules/respect-the-user.md +39 -0
- package/defaults/skills/business-analyst.md +181 -0
- package/defaults/skills/content-marketer.md +184 -0
- package/defaults/skills/research.md +34 -0
- package/defaults/tools/example-web-search.md +60 -0
- package/defaults/workflows/daily-reflection.md +54 -0
- package/dist/agent-framework-K4GUIICH.js +344 -0
- package/dist/agent-framework-K4GUIICH.js.map +1 -0
- package/dist/analytics-RPT73WNM.js +12 -0
- package/dist/analytics-RPT73WNM.js.map +1 -0
- package/dist/auto-processor-OLE45UI3.js +13 -0
- package/dist/auto-processor-OLE45UI3.js.map +1 -0
- package/dist/chunk-274RV3YO.js +162 -0
- package/dist/chunk-274RV3YO.js.map +1 -0
- package/dist/chunk-4CWAGBNS.js +168 -0
- package/dist/chunk-4CWAGBNS.js.map +1 -0
- package/dist/chunk-4FDUOGSZ.js +69 -0
- package/dist/chunk-4FDUOGSZ.js.map +1 -0
- package/dist/chunk-5H34JPMB.js +199 -0
- package/dist/chunk-5H34JPMB.js.map +1 -0
- package/dist/chunk-6EMOEYGU.js +102 -0
- package/dist/chunk-6EMOEYGU.js.map +1 -0
- package/dist/chunk-A7BJPQQ6.js +236 -0
- package/dist/chunk-A7BJPQQ6.js.map +1 -0
- package/dist/chunk-AGAAFJEO.js +76 -0
- package/dist/chunk-AGAAFJEO.js.map +1 -0
- package/dist/chunk-BSKDOFRT.js +65 -0
- package/dist/chunk-BSKDOFRT.js.map +1 -0
- package/dist/chunk-CHJ5GNZC.js +100 -0
- package/dist/chunk-CHJ5GNZC.js.map +1 -0
- package/dist/chunk-CSL3ERUI.js +307 -0
- package/dist/chunk-CSL3ERUI.js.map +1 -0
- package/dist/chunk-DA7IKHC4.js +229 -0
- package/dist/chunk-DA7IKHC4.js.map +1 -0
- package/dist/chunk-DGUM43GV.js +11 -0
- package/dist/chunk-DGUM43GV.js.map +1 -0
- package/dist/chunk-DTTXPHFW.js +211 -0
- package/dist/chunk-DTTXPHFW.js.map +1 -0
- package/dist/chunk-FD55B3IO.js +204 -0
- package/dist/chunk-FD55B3IO.js.map +1 -0
- package/dist/chunk-FLZU44SV.js +230 -0
- package/dist/chunk-FLZU44SV.js.map +1 -0
- package/dist/chunk-GJNNR2RA.js +200 -0
- package/dist/chunk-GJNNR2RA.js.map +1 -0
- package/dist/chunk-GNUSHD2Y.js +111 -0
- package/dist/chunk-GNUSHD2Y.js.map +1 -0
- package/dist/chunk-GUJTBGVS.js +2212 -0
- package/dist/chunk-GUJTBGVS.js.map +1 -0
- package/dist/chunk-IZ6UZ3ZL.js +207 -0
- package/dist/chunk-IZ6UZ3ZL.js.map +1 -0
- package/dist/chunk-JKMGYWXB.js +197 -0
- package/dist/chunk-JKMGYWXB.js.map +1 -0
- package/dist/chunk-KFX54TQM.js +165 -0
- package/dist/chunk-KFX54TQM.js.map +1 -0
- package/dist/chunk-M7NXUK55.js +199 -0
- package/dist/chunk-M7NXUK55.js.map +1 -0
- package/dist/chunk-MPZ3BPUI.js +374 -0
- package/dist/chunk-MPZ3BPUI.js.map +1 -0
- package/dist/chunk-OC6YSTDX.js +119 -0
- package/dist/chunk-OC6YSTDX.js.map +1 -0
- package/dist/chunk-RC6MEZB6.js +469 -0
- package/dist/chunk-RC6MEZB6.js.map +1 -0
- package/dist/chunk-RY3ZFII7.js +3440 -0
- package/dist/chunk-RY3ZFII7.js.map +1 -0
- package/dist/chunk-TAT6JU3X.js +167 -0
- package/dist/chunk-TAT6JU3X.js.map +1 -0
- package/dist/chunk-UDZIS2AQ.js +79 -0
- package/dist/chunk-UDZIS2AQ.js.map +1 -0
- package/dist/chunk-UPLBF4RZ.js +115 -0
- package/dist/chunk-UPLBF4RZ.js.map +1 -0
- package/dist/chunk-UWQTZMNI.js +154 -0
- package/dist/chunk-UWQTZMNI.js.map +1 -0
- package/dist/chunk-W4T7PGI2.js +346 -0
- package/dist/chunk-W4T7PGI2.js.map +1 -0
- package/dist/chunk-XTBKL5BI.js +111 -0
- package/dist/chunk-XTBKL5BI.js.map +1 -0
- package/dist/chunk-YIJY5DBV.js +399 -0
- package/dist/chunk-YIJY5DBV.js.map +1 -0
- package/dist/chunk-YUFNYN2H.js +242 -0
- package/dist/chunk-YUFNYN2H.js.map +1 -0
- package/dist/chunk-Z2PUCXTZ.js +94 -0
- package/dist/chunk-Z2PUCXTZ.js.map +1 -0
- package/dist/chunk-ZZJOFKAT.js +13 -0
- package/dist/chunk-ZZJOFKAT.js.map +1 -0
- package/dist/cli/index.js +3661 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/config-WVMRUOCA.js +13 -0
- package/dist/config-WVMRUOCA.js.map +1 -0
- package/dist/context-loader-3ORBPMHJ.js +13 -0
- package/dist/context-loader-3ORBPMHJ.js.map +1 -0
- package/dist/conversation-QDEIDQPH.js +22 -0
- package/dist/conversation-QDEIDQPH.js.map +1 -0
- package/dist/cost-tracker-RS3W7SVY.js +24 -0
- package/dist/cost-tracker-RS3W7SVY.js.map +1 -0
- package/dist/delegate-VJCJLYEK.js +29 -0
- package/dist/delegate-VJCJLYEK.js.map +1 -0
- package/dist/emotional-state-VQVRA6ED.js +206 -0
- package/dist/emotional-state-VQVRA6ED.js.map +1 -0
- package/dist/env-discovery-2BLVMAIM.js +251 -0
- package/dist/env-discovery-2BLVMAIM.js.map +1 -0
- package/dist/export-6GCYHEHQ.js +165 -0
- package/dist/export-6GCYHEHQ.js.map +1 -0
- package/dist/graph-YUIPOSOO.js +14 -0
- package/dist/graph-YUIPOSOO.js.map +1 -0
- package/dist/harness-LCHA3DWP.js +10 -0
- package/dist/harness-LCHA3DWP.js.map +1 -0
- package/dist/harness-WE4SLCML.js +26 -0
- package/dist/harness-WE4SLCML.js.map +1 -0
- package/dist/health-NZ6WNIMV.js +23 -0
- package/dist/health-NZ6WNIMV.js.map +1 -0
- package/dist/index.d.ts +3612 -0
- package/dist/index.js +13501 -0
- package/dist/index.js.map +1 -0
- package/dist/indexer-LONANRRM.js +16 -0
- package/dist/indexer-LONANRRM.js.map +1 -0
- package/dist/instinct-learner-SRM72DHF.js +20 -0
- package/dist/instinct-learner-SRM72DHF.js.map +1 -0
- package/dist/intake-4M3HNU43.js +21 -0
- package/dist/intake-4M3HNU43.js.map +1 -0
- package/dist/intelligence-HJOCA4SJ.js +1081 -0
- package/dist/intelligence-HJOCA4SJ.js.map +1 -0
- package/dist/journal-WANJL3MI.js +24 -0
- package/dist/journal-WANJL3MI.js.map +1 -0
- package/dist/loader-C3TKIKZR.js +23 -0
- package/dist/loader-C3TKIKZR.js.map +1 -0
- package/dist/mcp-WTQJJZAO.js +15 -0
- package/dist/mcp-WTQJJZAO.js.map +1 -0
- package/dist/mcp-discovery-WPAQFL6S.js +377 -0
- package/dist/mcp-discovery-WPAQFL6S.js.map +1 -0
- package/dist/mcp-installer-6O2XXD3V.js +394 -0
- package/dist/mcp-installer-6O2XXD3V.js.map +1 -0
- package/dist/metrics-KXGNFAAB.js +20 -0
- package/dist/metrics-KXGNFAAB.js.map +1 -0
- package/dist/primitive-registry-I6VTIR4W.js +512 -0
- package/dist/primitive-registry-I6VTIR4W.js.map +1 -0
- package/dist/project-discovery-C4UMD7JI.js +246 -0
- package/dist/project-discovery-C4UMD7JI.js.map +1 -0
- package/dist/provider-LQHQX7Z7.js +26 -0
- package/dist/provider-LQHQX7Z7.js.map +1 -0
- package/dist/provider-SXPQZ74H.js +28 -0
- package/dist/provider-SXPQZ74H.js.map +1 -0
- package/dist/rate-limiter-RLRVM325.js +22 -0
- package/dist/rate-limiter-RLRVM325.js.map +1 -0
- package/dist/rule-engine-YGQ3RYZM.js +182 -0
- package/dist/rule-engine-YGQ3RYZM.js.map +1 -0
- package/dist/scaffold-A3VRRCBV.js +347 -0
- package/dist/scaffold-A3VRRCBV.js.map +1 -0
- package/dist/scheduler-XHHIVHRI.js +397 -0
- package/dist/scheduler-XHHIVHRI.js.map +1 -0
- package/dist/search-V3W5JMJG.js +75 -0
- package/dist/search-V3W5JMJG.js.map +1 -0
- package/dist/semantic-search-2DTOO5UX.js +241 -0
- package/dist/semantic-search-2DTOO5UX.js.map +1 -0
- package/dist/serve-DTQ3HENY.js +291 -0
- package/dist/serve-DTQ3HENY.js.map +1 -0
- package/dist/sessions-CZGVXKQE.js +21 -0
- package/dist/sessions-CZGVXKQE.js.map +1 -0
- package/dist/sources-RW5DT56F.js +32 -0
- package/dist/sources-RW5DT56F.js.map +1 -0
- package/dist/starter-packs-76YUVHEU.js +893 -0
- package/dist/starter-packs-76YUVHEU.js.map +1 -0
- package/dist/state-GMXILIHW.js +13 -0
- package/dist/state-GMXILIHW.js.map +1 -0
- package/dist/state-merge-NKO5FRBA.js +174 -0
- package/dist/state-merge-NKO5FRBA.js.map +1 -0
- package/dist/telemetry-UC6PBXC7.js +22 -0
- package/dist/telemetry-UC6PBXC7.js.map +1 -0
- package/dist/tool-executor-MJ7IG7PQ.js +28 -0
- package/dist/tool-executor-MJ7IG7PQ.js.map +1 -0
- package/dist/tools-DZ4KETET.js +20 -0
- package/dist/tools-DZ4KETET.js.map +1 -0
- package/dist/types-EW7AIB3R.js +18 -0
- package/dist/types-EW7AIB3R.js.map +1 -0
- package/dist/types-WGDLSPO6.js +16 -0
- package/dist/types-WGDLSPO6.js.map +1 -0
- package/dist/universal-installer-QGS4SJGX.js +578 -0
- package/dist/universal-installer-QGS4SJGX.js.map +1 -0
- package/dist/validator-7WXMDIHH.js +22 -0
- package/dist/validator-7WXMDIHH.js.map +1 -0
- package/dist/verification-gate-FYXUX6LH.js +246 -0
- package/dist/verification-gate-FYXUX6LH.js.map +1 -0
- package/dist/versioning-Z3XNE2Q2.js +271 -0
- package/dist/versioning-Z3XNE2Q2.js.map +1 -0
- package/dist/watcher-ISJC7YKL.js +109 -0
- package/dist/watcher-ISJC7YKL.js.map +1 -0
- package/dist/web-server-DD7ZOP46.js +28 -0
- package/dist/web-server-DD7ZOP46.js.map +1 -0
- package/package.json +76 -0
- package/sources.yaml +121 -0
- package/templates/assistant/CORE.md +24 -0
- package/templates/assistant/SYSTEM.md +24 -0
- package/templates/assistant/config.yaml +51 -0
- package/templates/base/CORE.md +17 -0
- package/templates/base/SYSTEM.md +24 -0
- package/templates/base/config.yaml +51 -0
- package/templates/claude-opus/config.yaml +51 -0
- package/templates/code-reviewer/CORE.md +25 -0
- package/templates/code-reviewer/SYSTEM.md +30 -0
- package/templates/code-reviewer/config.yaml +51 -0
- package/templates/gpt4/config.yaml +51 -0
- package/templates/local/config.yaml +51 -0
|
@@ -0,0 +1,3440 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
collectSnapshot
|
|
5
|
+
} from "./chunk-A7BJPQQ6.js";
|
|
6
|
+
import {
|
|
7
|
+
validateMcpConfig
|
|
8
|
+
} from "./chunk-5H34JPMB.js";
|
|
9
|
+
import {
|
|
10
|
+
Conversation
|
|
11
|
+
} from "./chunk-MPZ3BPUI.js";
|
|
12
|
+
import {
|
|
13
|
+
loadState,
|
|
14
|
+
saveState
|
|
15
|
+
} from "./chunk-UDZIS2AQ.js";
|
|
16
|
+
import {
|
|
17
|
+
listSessions
|
|
18
|
+
} from "./chunk-DTTXPHFW.js";
|
|
19
|
+
import {
|
|
20
|
+
loadAllPrimitives,
|
|
21
|
+
loadDirectory,
|
|
22
|
+
parseHarnessDocument
|
|
23
|
+
} from "./chunk-UPLBF4RZ.js";
|
|
24
|
+
import {
|
|
25
|
+
log
|
|
26
|
+
} from "./chunk-BSKDOFRT.js";
|
|
27
|
+
import {
|
|
28
|
+
loadConfig
|
|
29
|
+
} from "./chunk-CHJ5GNZC.js";
|
|
30
|
+
import {
|
|
31
|
+
CORE_PRIMITIVE_DIRS
|
|
32
|
+
} from "./chunk-4CWAGBNS.js";
|
|
33
|
+
|
|
34
|
+
// node_modules/hono/dist/compose.js
|
|
35
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
36
|
+
return (context, next) => {
|
|
37
|
+
let index = -1;
|
|
38
|
+
return dispatch(0);
|
|
39
|
+
async function dispatch(i) {
|
|
40
|
+
if (i <= index) {
|
|
41
|
+
throw new Error("next() called multiple times");
|
|
42
|
+
}
|
|
43
|
+
index = i;
|
|
44
|
+
let res;
|
|
45
|
+
let isError = false;
|
|
46
|
+
let handler;
|
|
47
|
+
if (middleware[i]) {
|
|
48
|
+
handler = middleware[i][0][0];
|
|
49
|
+
context.req.routeIndex = i;
|
|
50
|
+
} else {
|
|
51
|
+
handler = i === middleware.length && next || void 0;
|
|
52
|
+
}
|
|
53
|
+
if (handler) {
|
|
54
|
+
try {
|
|
55
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
56
|
+
} catch (err) {
|
|
57
|
+
if (err instanceof Error && onError) {
|
|
58
|
+
context.error = err;
|
|
59
|
+
res = await onError(err, context);
|
|
60
|
+
isError = true;
|
|
61
|
+
} else {
|
|
62
|
+
throw err;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
if (context.finalized === false && onNotFound) {
|
|
67
|
+
res = await onNotFound(context);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (res && (context.finalized === false || isError)) {
|
|
71
|
+
context.res = res;
|
|
72
|
+
}
|
|
73
|
+
return context;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// node_modules/hono/dist/request/constants.js
|
|
79
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
80
|
+
|
|
81
|
+
// node_modules/hono/dist/utils/body.js
|
|
82
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
83
|
+
const { all = false, dot = false } = options;
|
|
84
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
85
|
+
const contentType = headers.get("Content-Type");
|
|
86
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
87
|
+
return parseFormData(request, { all, dot });
|
|
88
|
+
}
|
|
89
|
+
return {};
|
|
90
|
+
};
|
|
91
|
+
async function parseFormData(request, options) {
|
|
92
|
+
const formData = await request.formData();
|
|
93
|
+
if (formData) {
|
|
94
|
+
return convertFormDataToBodyData(formData, options);
|
|
95
|
+
}
|
|
96
|
+
return {};
|
|
97
|
+
}
|
|
98
|
+
function convertFormDataToBodyData(formData, options) {
|
|
99
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
100
|
+
formData.forEach((value, key) => {
|
|
101
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
102
|
+
if (!shouldParseAllValues) {
|
|
103
|
+
form[key] = value;
|
|
104
|
+
} else {
|
|
105
|
+
handleParsingAllValues(form, key, value);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
if (options.dot) {
|
|
109
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
110
|
+
const shouldParseDotValues = key.includes(".");
|
|
111
|
+
if (shouldParseDotValues) {
|
|
112
|
+
handleParsingNestedValues(form, key, value);
|
|
113
|
+
delete form[key];
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return form;
|
|
118
|
+
}
|
|
119
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
120
|
+
if (form[key] !== void 0) {
|
|
121
|
+
if (Array.isArray(form[key])) {
|
|
122
|
+
;
|
|
123
|
+
form[key].push(value);
|
|
124
|
+
} else {
|
|
125
|
+
form[key] = [form[key], value];
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
if (!key.endsWith("[]")) {
|
|
129
|
+
form[key] = value;
|
|
130
|
+
} else {
|
|
131
|
+
form[key] = [value];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
136
|
+
if (/(?:^|\.)__proto__\./.test(key)) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
let nestedForm = form;
|
|
140
|
+
const keys = key.split(".");
|
|
141
|
+
keys.forEach((key2, index) => {
|
|
142
|
+
if (index === keys.length - 1) {
|
|
143
|
+
nestedForm[key2] = value;
|
|
144
|
+
} else {
|
|
145
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
146
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
147
|
+
}
|
|
148
|
+
nestedForm = nestedForm[key2];
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// node_modules/hono/dist/utils/url.js
|
|
154
|
+
var splitPath = (path) => {
|
|
155
|
+
const paths = path.split("/");
|
|
156
|
+
if (paths[0] === "") {
|
|
157
|
+
paths.shift();
|
|
158
|
+
}
|
|
159
|
+
return paths;
|
|
160
|
+
};
|
|
161
|
+
var splitRoutingPath = (routePath) => {
|
|
162
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
163
|
+
const paths = splitPath(path);
|
|
164
|
+
return replaceGroupMarks(paths, groups);
|
|
165
|
+
};
|
|
166
|
+
var extractGroupsFromPath = (path) => {
|
|
167
|
+
const groups = [];
|
|
168
|
+
path = path.replace(/\{[^}]+\}/g, (match2, index) => {
|
|
169
|
+
const mark = `@${index}`;
|
|
170
|
+
groups.push([mark, match2]);
|
|
171
|
+
return mark;
|
|
172
|
+
});
|
|
173
|
+
return { groups, path };
|
|
174
|
+
};
|
|
175
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
176
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
177
|
+
const [mark] = groups[i];
|
|
178
|
+
for (let j = paths.length - 1; j >= 0; j--) {
|
|
179
|
+
if (paths[j].includes(mark)) {
|
|
180
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return paths;
|
|
186
|
+
};
|
|
187
|
+
var patternCache = {};
|
|
188
|
+
var getPattern = (label, next) => {
|
|
189
|
+
if (label === "*") {
|
|
190
|
+
return "*";
|
|
191
|
+
}
|
|
192
|
+
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
193
|
+
if (match2) {
|
|
194
|
+
const cacheKey2 = `${label}#${next}`;
|
|
195
|
+
if (!patternCache[cacheKey2]) {
|
|
196
|
+
if (match2[2]) {
|
|
197
|
+
patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
|
|
198
|
+
} else {
|
|
199
|
+
patternCache[cacheKey2] = [label, match2[1], true];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return patternCache[cacheKey2];
|
|
203
|
+
}
|
|
204
|
+
return null;
|
|
205
|
+
};
|
|
206
|
+
var tryDecode = (str, decoder) => {
|
|
207
|
+
try {
|
|
208
|
+
return decoder(str);
|
|
209
|
+
} catch {
|
|
210
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
211
|
+
try {
|
|
212
|
+
return decoder(match2);
|
|
213
|
+
} catch {
|
|
214
|
+
return match2;
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
220
|
+
var getPath = (request) => {
|
|
221
|
+
const url = request.url;
|
|
222
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
223
|
+
let i = start;
|
|
224
|
+
for (; i < url.length; i++) {
|
|
225
|
+
const charCode = url.charCodeAt(i);
|
|
226
|
+
if (charCode === 37) {
|
|
227
|
+
const queryIndex = url.indexOf("?", i);
|
|
228
|
+
const hashIndex = url.indexOf("#", i);
|
|
229
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
230
|
+
const path = url.slice(start, end);
|
|
231
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
232
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return url.slice(start, i);
|
|
237
|
+
};
|
|
238
|
+
var getPathNoStrict = (request) => {
|
|
239
|
+
const result = getPath(request);
|
|
240
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
241
|
+
};
|
|
242
|
+
var mergePath = (base, sub, ...rest) => {
|
|
243
|
+
if (rest.length) {
|
|
244
|
+
sub = mergePath(sub, ...rest);
|
|
245
|
+
}
|
|
246
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
247
|
+
};
|
|
248
|
+
var checkOptionalParameter = (path) => {
|
|
249
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
const segments = path.split("/");
|
|
253
|
+
const results = [];
|
|
254
|
+
let basePath = "";
|
|
255
|
+
segments.forEach((segment) => {
|
|
256
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
257
|
+
basePath += "/" + segment;
|
|
258
|
+
} else if (/\:/.test(segment)) {
|
|
259
|
+
if (/\?/.test(segment)) {
|
|
260
|
+
if (results.length === 0 && basePath === "") {
|
|
261
|
+
results.push("/");
|
|
262
|
+
} else {
|
|
263
|
+
results.push(basePath);
|
|
264
|
+
}
|
|
265
|
+
const optionalSegment = segment.replace("?", "");
|
|
266
|
+
basePath += "/" + optionalSegment;
|
|
267
|
+
results.push(basePath);
|
|
268
|
+
} else {
|
|
269
|
+
basePath += "/" + segment;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
274
|
+
};
|
|
275
|
+
var _decodeURI = (value) => {
|
|
276
|
+
if (!/[%+]/.test(value)) {
|
|
277
|
+
return value;
|
|
278
|
+
}
|
|
279
|
+
if (value.indexOf("+") !== -1) {
|
|
280
|
+
value = value.replace(/\+/g, " ");
|
|
281
|
+
}
|
|
282
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
283
|
+
};
|
|
284
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
285
|
+
let encoded;
|
|
286
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
287
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
288
|
+
if (keyIndex2 === -1) {
|
|
289
|
+
return void 0;
|
|
290
|
+
}
|
|
291
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
292
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
293
|
+
}
|
|
294
|
+
while (keyIndex2 !== -1) {
|
|
295
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
296
|
+
if (trailingKeyCode === 61) {
|
|
297
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
298
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
299
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
300
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
301
|
+
return "";
|
|
302
|
+
}
|
|
303
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
304
|
+
}
|
|
305
|
+
encoded = /[%+]/.test(url);
|
|
306
|
+
if (!encoded) {
|
|
307
|
+
return void 0;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const results = {};
|
|
311
|
+
encoded ??= /[%+]/.test(url);
|
|
312
|
+
let keyIndex = url.indexOf("?", 8);
|
|
313
|
+
while (keyIndex !== -1) {
|
|
314
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
315
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
316
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
317
|
+
valueIndex = -1;
|
|
318
|
+
}
|
|
319
|
+
let name = url.slice(
|
|
320
|
+
keyIndex + 1,
|
|
321
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
322
|
+
);
|
|
323
|
+
if (encoded) {
|
|
324
|
+
name = _decodeURI(name);
|
|
325
|
+
}
|
|
326
|
+
keyIndex = nextKeyIndex;
|
|
327
|
+
if (name === "") {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
let value;
|
|
331
|
+
if (valueIndex === -1) {
|
|
332
|
+
value = "";
|
|
333
|
+
} else {
|
|
334
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
335
|
+
if (encoded) {
|
|
336
|
+
value = _decodeURI(value);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (multiple) {
|
|
340
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
341
|
+
results[name] = [];
|
|
342
|
+
}
|
|
343
|
+
;
|
|
344
|
+
results[name].push(value);
|
|
345
|
+
} else {
|
|
346
|
+
results[name] ??= value;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return key ? results[key] : results;
|
|
350
|
+
};
|
|
351
|
+
var getQueryParam = _getQueryParam;
|
|
352
|
+
var getQueryParams = (url, key) => {
|
|
353
|
+
return _getQueryParam(url, key, true);
|
|
354
|
+
};
|
|
355
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
356
|
+
|
|
357
|
+
// node_modules/hono/dist/request.js
|
|
358
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
359
|
+
var HonoRequest = class {
|
|
360
|
+
/**
|
|
361
|
+
* `.raw` can get the raw Request object.
|
|
362
|
+
*
|
|
363
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
364
|
+
*
|
|
365
|
+
* @example
|
|
366
|
+
* ```ts
|
|
367
|
+
* // For Cloudflare Workers
|
|
368
|
+
* app.post('/', async (c) => {
|
|
369
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
370
|
+
* ...
|
|
371
|
+
* })
|
|
372
|
+
* ```
|
|
373
|
+
*/
|
|
374
|
+
raw;
|
|
375
|
+
#validatedData;
|
|
376
|
+
// Short name of validatedData
|
|
377
|
+
#matchResult;
|
|
378
|
+
routeIndex = 0;
|
|
379
|
+
/**
|
|
380
|
+
* `.path` can get the pathname of the request.
|
|
381
|
+
*
|
|
382
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
383
|
+
*
|
|
384
|
+
* @example
|
|
385
|
+
* ```ts
|
|
386
|
+
* app.get('/about/me', (c) => {
|
|
387
|
+
* const pathname = c.req.path // `/about/me`
|
|
388
|
+
* })
|
|
389
|
+
* ```
|
|
390
|
+
*/
|
|
391
|
+
path;
|
|
392
|
+
bodyCache = {};
|
|
393
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
394
|
+
this.raw = request;
|
|
395
|
+
this.path = path;
|
|
396
|
+
this.#matchResult = matchResult;
|
|
397
|
+
this.#validatedData = {};
|
|
398
|
+
}
|
|
399
|
+
param(key) {
|
|
400
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
401
|
+
}
|
|
402
|
+
#getDecodedParam(key) {
|
|
403
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
404
|
+
const param = this.#getParamValue(paramKey);
|
|
405
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
406
|
+
}
|
|
407
|
+
#getAllDecodedParams() {
|
|
408
|
+
const decoded = {};
|
|
409
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
410
|
+
for (const key of keys) {
|
|
411
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
412
|
+
if (value !== void 0) {
|
|
413
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return decoded;
|
|
417
|
+
}
|
|
418
|
+
#getParamValue(paramKey) {
|
|
419
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
420
|
+
}
|
|
421
|
+
query(key) {
|
|
422
|
+
return getQueryParam(this.url, key);
|
|
423
|
+
}
|
|
424
|
+
queries(key) {
|
|
425
|
+
return getQueryParams(this.url, key);
|
|
426
|
+
}
|
|
427
|
+
header(name) {
|
|
428
|
+
if (name) {
|
|
429
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
430
|
+
}
|
|
431
|
+
const headerData = {};
|
|
432
|
+
this.raw.headers.forEach((value, key) => {
|
|
433
|
+
headerData[key] = value;
|
|
434
|
+
});
|
|
435
|
+
return headerData;
|
|
436
|
+
}
|
|
437
|
+
async parseBody(options) {
|
|
438
|
+
return parseBody(this, options);
|
|
439
|
+
}
|
|
440
|
+
#cachedBody = (key) => {
|
|
441
|
+
const { bodyCache, raw: raw2 } = this;
|
|
442
|
+
const cachedBody = bodyCache[key];
|
|
443
|
+
if (cachedBody) {
|
|
444
|
+
return cachedBody;
|
|
445
|
+
}
|
|
446
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
447
|
+
if (anyCachedKey) {
|
|
448
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
449
|
+
if (anyCachedKey === "json") {
|
|
450
|
+
body = JSON.stringify(body);
|
|
451
|
+
}
|
|
452
|
+
return new Response(body)[key]();
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
return bodyCache[key] = raw2[key]();
|
|
456
|
+
};
|
|
457
|
+
/**
|
|
458
|
+
* `.json()` can parse Request body of type `application/json`
|
|
459
|
+
*
|
|
460
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
461
|
+
*
|
|
462
|
+
* @example
|
|
463
|
+
* ```ts
|
|
464
|
+
* app.post('/entry', async (c) => {
|
|
465
|
+
* const body = await c.req.json()
|
|
466
|
+
* })
|
|
467
|
+
* ```
|
|
468
|
+
*/
|
|
469
|
+
json() {
|
|
470
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
474
|
+
*
|
|
475
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
476
|
+
*
|
|
477
|
+
* @example
|
|
478
|
+
* ```ts
|
|
479
|
+
* app.post('/entry', async (c) => {
|
|
480
|
+
* const body = await c.req.text()
|
|
481
|
+
* })
|
|
482
|
+
* ```
|
|
483
|
+
*/
|
|
484
|
+
text() {
|
|
485
|
+
return this.#cachedBody("text");
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
489
|
+
*
|
|
490
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
491
|
+
*
|
|
492
|
+
* @example
|
|
493
|
+
* ```ts
|
|
494
|
+
* app.post('/entry', async (c) => {
|
|
495
|
+
* const body = await c.req.arrayBuffer()
|
|
496
|
+
* })
|
|
497
|
+
* ```
|
|
498
|
+
*/
|
|
499
|
+
arrayBuffer() {
|
|
500
|
+
return this.#cachedBody("arrayBuffer");
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Parses the request body as a `Blob`.
|
|
504
|
+
* @example
|
|
505
|
+
* ```ts
|
|
506
|
+
* app.post('/entry', async (c) => {
|
|
507
|
+
* const body = await c.req.blob();
|
|
508
|
+
* });
|
|
509
|
+
* ```
|
|
510
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
511
|
+
*/
|
|
512
|
+
blob() {
|
|
513
|
+
return this.#cachedBody("blob");
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Parses the request body as `FormData`.
|
|
517
|
+
* @example
|
|
518
|
+
* ```ts
|
|
519
|
+
* app.post('/entry', async (c) => {
|
|
520
|
+
* const body = await c.req.formData();
|
|
521
|
+
* });
|
|
522
|
+
* ```
|
|
523
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
524
|
+
*/
|
|
525
|
+
formData() {
|
|
526
|
+
return this.#cachedBody("formData");
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Adds validated data to the request.
|
|
530
|
+
*
|
|
531
|
+
* @param target - The target of the validation.
|
|
532
|
+
* @param data - The validated data to add.
|
|
533
|
+
*/
|
|
534
|
+
addValidatedData(target, data) {
|
|
535
|
+
this.#validatedData[target] = data;
|
|
536
|
+
}
|
|
537
|
+
valid(target) {
|
|
538
|
+
return this.#validatedData[target];
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* `.url()` can get the request url strings.
|
|
542
|
+
*
|
|
543
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
544
|
+
*
|
|
545
|
+
* @example
|
|
546
|
+
* ```ts
|
|
547
|
+
* app.get('/about/me', (c) => {
|
|
548
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
549
|
+
* ...
|
|
550
|
+
* })
|
|
551
|
+
* ```
|
|
552
|
+
*/
|
|
553
|
+
get url() {
|
|
554
|
+
return this.raw.url;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* `.method()` can get the method name of the request.
|
|
558
|
+
*
|
|
559
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
560
|
+
*
|
|
561
|
+
* @example
|
|
562
|
+
* ```ts
|
|
563
|
+
* app.get('/about/me', (c) => {
|
|
564
|
+
* const method = c.req.method // `GET`
|
|
565
|
+
* })
|
|
566
|
+
* ```
|
|
567
|
+
*/
|
|
568
|
+
get method() {
|
|
569
|
+
return this.raw.method;
|
|
570
|
+
}
|
|
571
|
+
get [GET_MATCH_RESULT]() {
|
|
572
|
+
return this.#matchResult;
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
576
|
+
*
|
|
577
|
+
* @deprecated
|
|
578
|
+
*
|
|
579
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
580
|
+
*
|
|
581
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
582
|
+
*
|
|
583
|
+
* @example
|
|
584
|
+
* ```ts
|
|
585
|
+
* app.use('*', async function logger(c, next) {
|
|
586
|
+
* await next()
|
|
587
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
588
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
589
|
+
* console.log(
|
|
590
|
+
* method,
|
|
591
|
+
* ' ',
|
|
592
|
+
* path,
|
|
593
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
594
|
+
* name,
|
|
595
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
596
|
+
* )
|
|
597
|
+
* })
|
|
598
|
+
* })
|
|
599
|
+
* ```
|
|
600
|
+
*/
|
|
601
|
+
get matchedRoutes() {
|
|
602
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
606
|
+
*
|
|
607
|
+
* @deprecated
|
|
608
|
+
*
|
|
609
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
610
|
+
*
|
|
611
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
612
|
+
*
|
|
613
|
+
* @example
|
|
614
|
+
* ```ts
|
|
615
|
+
* app.get('/posts/:id', (c) => {
|
|
616
|
+
* return c.json({ path: c.req.routePath })
|
|
617
|
+
* })
|
|
618
|
+
* ```
|
|
619
|
+
*/
|
|
620
|
+
get routePath() {
|
|
621
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
|
|
625
|
+
// node_modules/hono/dist/utils/html.js
|
|
626
|
+
var HtmlEscapedCallbackPhase = {
|
|
627
|
+
Stringify: 1,
|
|
628
|
+
BeforeStream: 2,
|
|
629
|
+
Stream: 3
|
|
630
|
+
};
|
|
631
|
+
var raw = (value, callbacks) => {
|
|
632
|
+
const escapedString = new String(value);
|
|
633
|
+
escapedString.isEscaped = true;
|
|
634
|
+
escapedString.callbacks = callbacks;
|
|
635
|
+
return escapedString;
|
|
636
|
+
};
|
|
637
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
638
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
639
|
+
if (!(str instanceof Promise)) {
|
|
640
|
+
str = str.toString();
|
|
641
|
+
}
|
|
642
|
+
if (str instanceof Promise) {
|
|
643
|
+
str = await str;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
const callbacks = str.callbacks;
|
|
647
|
+
if (!callbacks?.length) {
|
|
648
|
+
return Promise.resolve(str);
|
|
649
|
+
}
|
|
650
|
+
if (buffer) {
|
|
651
|
+
buffer[0] += str;
|
|
652
|
+
} else {
|
|
653
|
+
buffer = [str];
|
|
654
|
+
}
|
|
655
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
656
|
+
(res) => Promise.all(
|
|
657
|
+
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
658
|
+
).then(() => buffer[0])
|
|
659
|
+
);
|
|
660
|
+
if (preserveCallbacks) {
|
|
661
|
+
return raw(await resStr, callbacks);
|
|
662
|
+
} else {
|
|
663
|
+
return resStr;
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
// node_modules/hono/dist/context.js
|
|
668
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
669
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
670
|
+
return {
|
|
671
|
+
"Content-Type": contentType,
|
|
672
|
+
...headers
|
|
673
|
+
};
|
|
674
|
+
};
|
|
675
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
676
|
+
var Context = class {
|
|
677
|
+
#rawRequest;
|
|
678
|
+
#req;
|
|
679
|
+
/**
|
|
680
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
681
|
+
*
|
|
682
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
683
|
+
*
|
|
684
|
+
* @example
|
|
685
|
+
* ```ts
|
|
686
|
+
* // Environment object for Cloudflare Workers
|
|
687
|
+
* app.get('*', async c => {
|
|
688
|
+
* const counter = c.env.COUNTER
|
|
689
|
+
* })
|
|
690
|
+
* ```
|
|
691
|
+
*/
|
|
692
|
+
env = {};
|
|
693
|
+
#var;
|
|
694
|
+
finalized = false;
|
|
695
|
+
/**
|
|
696
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
697
|
+
*
|
|
698
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
699
|
+
*
|
|
700
|
+
* @example
|
|
701
|
+
* ```ts
|
|
702
|
+
* app.use('*', async (c, next) => {
|
|
703
|
+
* await next()
|
|
704
|
+
* if (c.error) {
|
|
705
|
+
* // do something...
|
|
706
|
+
* }
|
|
707
|
+
* })
|
|
708
|
+
* ```
|
|
709
|
+
*/
|
|
710
|
+
error;
|
|
711
|
+
#status;
|
|
712
|
+
#executionCtx;
|
|
713
|
+
#res;
|
|
714
|
+
#layout;
|
|
715
|
+
#renderer;
|
|
716
|
+
#notFoundHandler;
|
|
717
|
+
#preparedHeaders;
|
|
718
|
+
#matchResult;
|
|
719
|
+
#path;
|
|
720
|
+
/**
|
|
721
|
+
* Creates an instance of the Context class.
|
|
722
|
+
*
|
|
723
|
+
* @param req - The Request object.
|
|
724
|
+
* @param options - Optional configuration options for the context.
|
|
725
|
+
*/
|
|
726
|
+
constructor(req, options) {
|
|
727
|
+
this.#rawRequest = req;
|
|
728
|
+
if (options) {
|
|
729
|
+
this.#executionCtx = options.executionCtx;
|
|
730
|
+
this.env = options.env;
|
|
731
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
732
|
+
this.#path = options.path;
|
|
733
|
+
this.#matchResult = options.matchResult;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
738
|
+
*/
|
|
739
|
+
get req() {
|
|
740
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
741
|
+
return this.#req;
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
745
|
+
* The FetchEvent associated with the current request.
|
|
746
|
+
*
|
|
747
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
748
|
+
*/
|
|
749
|
+
get event() {
|
|
750
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
751
|
+
return this.#executionCtx;
|
|
752
|
+
} else {
|
|
753
|
+
throw Error("This context has no FetchEvent");
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
758
|
+
* The ExecutionContext associated with the current request.
|
|
759
|
+
*
|
|
760
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
761
|
+
*/
|
|
762
|
+
get executionCtx() {
|
|
763
|
+
if (this.#executionCtx) {
|
|
764
|
+
return this.#executionCtx;
|
|
765
|
+
} else {
|
|
766
|
+
throw Error("This context has no ExecutionContext");
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
771
|
+
* The Response object for the current request.
|
|
772
|
+
*/
|
|
773
|
+
get res() {
|
|
774
|
+
return this.#res ||= createResponseInstance(null, {
|
|
775
|
+
headers: this.#preparedHeaders ??= new Headers()
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Sets the Response object for the current request.
|
|
780
|
+
*
|
|
781
|
+
* @param _res - The Response object to set.
|
|
782
|
+
*/
|
|
783
|
+
set res(_res) {
|
|
784
|
+
if (this.#res && _res) {
|
|
785
|
+
_res = createResponseInstance(_res.body, _res);
|
|
786
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
787
|
+
if (k === "content-type") {
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
if (k === "set-cookie") {
|
|
791
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
792
|
+
_res.headers.delete("set-cookie");
|
|
793
|
+
for (const cookie of cookies) {
|
|
794
|
+
_res.headers.append("set-cookie", cookie);
|
|
795
|
+
}
|
|
796
|
+
} else {
|
|
797
|
+
_res.headers.set(k, v);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
this.#res = _res;
|
|
802
|
+
this.finalized = true;
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* `.render()` can create a response within a layout.
|
|
806
|
+
*
|
|
807
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
808
|
+
*
|
|
809
|
+
* @example
|
|
810
|
+
* ```ts
|
|
811
|
+
* app.get('/', (c) => {
|
|
812
|
+
* return c.render('Hello!')
|
|
813
|
+
* })
|
|
814
|
+
* ```
|
|
815
|
+
*/
|
|
816
|
+
render = (...args) => {
|
|
817
|
+
this.#renderer ??= (content) => this.html(content);
|
|
818
|
+
return this.#renderer(...args);
|
|
819
|
+
};
|
|
820
|
+
/**
|
|
821
|
+
* Sets the layout for the response.
|
|
822
|
+
*
|
|
823
|
+
* @param layout - The layout to set.
|
|
824
|
+
* @returns The layout function.
|
|
825
|
+
*/
|
|
826
|
+
setLayout = (layout) => this.#layout = layout;
|
|
827
|
+
/**
|
|
828
|
+
* Gets the current layout for the response.
|
|
829
|
+
*
|
|
830
|
+
* @returns The current layout function.
|
|
831
|
+
*/
|
|
832
|
+
getLayout = () => this.#layout;
|
|
833
|
+
/**
|
|
834
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
835
|
+
*
|
|
836
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
837
|
+
*
|
|
838
|
+
* @example
|
|
839
|
+
* ```tsx
|
|
840
|
+
* app.use('*', async (c, next) => {
|
|
841
|
+
* c.setRenderer((content) => {
|
|
842
|
+
* return c.html(
|
|
843
|
+
* <html>
|
|
844
|
+
* <body>
|
|
845
|
+
* <p>{content}</p>
|
|
846
|
+
* </body>
|
|
847
|
+
* </html>
|
|
848
|
+
* )
|
|
849
|
+
* })
|
|
850
|
+
* await next()
|
|
851
|
+
* })
|
|
852
|
+
* ```
|
|
853
|
+
*/
|
|
854
|
+
setRenderer = (renderer) => {
|
|
855
|
+
this.#renderer = renderer;
|
|
856
|
+
};
|
|
857
|
+
/**
|
|
858
|
+
* `.header()` can set headers.
|
|
859
|
+
*
|
|
860
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
861
|
+
*
|
|
862
|
+
* @example
|
|
863
|
+
* ```ts
|
|
864
|
+
* app.get('/welcome', (c) => {
|
|
865
|
+
* // Set headers
|
|
866
|
+
* c.header('X-Message', 'Hello!')
|
|
867
|
+
* c.header('Content-Type', 'text/plain')
|
|
868
|
+
*
|
|
869
|
+
* return c.body('Thank you for coming')
|
|
870
|
+
* })
|
|
871
|
+
* ```
|
|
872
|
+
*/
|
|
873
|
+
header = (name, value, options) => {
|
|
874
|
+
if (this.finalized) {
|
|
875
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
876
|
+
}
|
|
877
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
878
|
+
if (value === void 0) {
|
|
879
|
+
headers.delete(name);
|
|
880
|
+
} else if (options?.append) {
|
|
881
|
+
headers.append(name, value);
|
|
882
|
+
} else {
|
|
883
|
+
headers.set(name, value);
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
status = (status) => {
|
|
887
|
+
this.#status = status;
|
|
888
|
+
};
|
|
889
|
+
/**
|
|
890
|
+
* `.set()` can set the value specified by the key.
|
|
891
|
+
*
|
|
892
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
893
|
+
*
|
|
894
|
+
* @example
|
|
895
|
+
* ```ts
|
|
896
|
+
* app.use('*', async (c, next) => {
|
|
897
|
+
* c.set('message', 'Hono is hot!!')
|
|
898
|
+
* await next()
|
|
899
|
+
* })
|
|
900
|
+
* ```
|
|
901
|
+
*/
|
|
902
|
+
set = (key, value) => {
|
|
903
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
904
|
+
this.#var.set(key, value);
|
|
905
|
+
};
|
|
906
|
+
/**
|
|
907
|
+
* `.get()` can use the value specified by the key.
|
|
908
|
+
*
|
|
909
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
910
|
+
*
|
|
911
|
+
* @example
|
|
912
|
+
* ```ts
|
|
913
|
+
* app.get('/', (c) => {
|
|
914
|
+
* const message = c.get('message')
|
|
915
|
+
* return c.text(`The message is "${message}"`)
|
|
916
|
+
* })
|
|
917
|
+
* ```
|
|
918
|
+
*/
|
|
919
|
+
get = (key) => {
|
|
920
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
921
|
+
};
|
|
922
|
+
/**
|
|
923
|
+
* `.var` can access the value of a variable.
|
|
924
|
+
*
|
|
925
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
926
|
+
*
|
|
927
|
+
* @example
|
|
928
|
+
* ```ts
|
|
929
|
+
* const result = c.var.client.oneMethod()
|
|
930
|
+
* ```
|
|
931
|
+
*/
|
|
932
|
+
// c.var.propName is a read-only
|
|
933
|
+
get var() {
|
|
934
|
+
if (!this.#var) {
|
|
935
|
+
return {};
|
|
936
|
+
}
|
|
937
|
+
return Object.fromEntries(this.#var);
|
|
938
|
+
}
|
|
939
|
+
#newResponse(data, arg, headers) {
|
|
940
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
941
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
942
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
943
|
+
for (const [key, value] of argHeaders) {
|
|
944
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
945
|
+
responseHeaders.append(key, value);
|
|
946
|
+
} else {
|
|
947
|
+
responseHeaders.set(key, value);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
if (headers) {
|
|
952
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
953
|
+
if (typeof v === "string") {
|
|
954
|
+
responseHeaders.set(k, v);
|
|
955
|
+
} else {
|
|
956
|
+
responseHeaders.delete(k);
|
|
957
|
+
for (const v2 of v) {
|
|
958
|
+
responseHeaders.append(k, v2);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
964
|
+
return createResponseInstance(data, { status, headers: responseHeaders });
|
|
965
|
+
}
|
|
966
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
967
|
+
/**
|
|
968
|
+
* `.body()` can return the HTTP response.
|
|
969
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
970
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
971
|
+
*
|
|
972
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
973
|
+
*
|
|
974
|
+
* @example
|
|
975
|
+
* ```ts
|
|
976
|
+
* app.get('/welcome', (c) => {
|
|
977
|
+
* // Set headers
|
|
978
|
+
* c.header('X-Message', 'Hello!')
|
|
979
|
+
* c.header('Content-Type', 'text/plain')
|
|
980
|
+
* // Set HTTP status code
|
|
981
|
+
* c.status(201)
|
|
982
|
+
*
|
|
983
|
+
* // Return the response body
|
|
984
|
+
* return c.body('Thank you for coming')
|
|
985
|
+
* })
|
|
986
|
+
* ```
|
|
987
|
+
*/
|
|
988
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
989
|
+
/**
|
|
990
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
991
|
+
*
|
|
992
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
993
|
+
*
|
|
994
|
+
* @example
|
|
995
|
+
* ```ts
|
|
996
|
+
* app.get('/say', (c) => {
|
|
997
|
+
* return c.text('Hello!')
|
|
998
|
+
* })
|
|
999
|
+
* ```
|
|
1000
|
+
*/
|
|
1001
|
+
text = (text, arg, headers) => {
|
|
1002
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
1003
|
+
text,
|
|
1004
|
+
arg,
|
|
1005
|
+
setDefaultContentType(TEXT_PLAIN, headers)
|
|
1006
|
+
);
|
|
1007
|
+
};
|
|
1008
|
+
/**
|
|
1009
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
1010
|
+
*
|
|
1011
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
1012
|
+
*
|
|
1013
|
+
* @example
|
|
1014
|
+
* ```ts
|
|
1015
|
+
* app.get('/api', (c) => {
|
|
1016
|
+
* return c.json({ message: 'Hello!' })
|
|
1017
|
+
* })
|
|
1018
|
+
* ```
|
|
1019
|
+
*/
|
|
1020
|
+
json = (object, arg, headers) => {
|
|
1021
|
+
return this.#newResponse(
|
|
1022
|
+
JSON.stringify(object),
|
|
1023
|
+
arg,
|
|
1024
|
+
setDefaultContentType("application/json", headers)
|
|
1025
|
+
);
|
|
1026
|
+
};
|
|
1027
|
+
html = (html, arg, headers) => {
|
|
1028
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
1029
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
1030
|
+
};
|
|
1031
|
+
/**
|
|
1032
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
1033
|
+
*
|
|
1034
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
1035
|
+
*
|
|
1036
|
+
* @example
|
|
1037
|
+
* ```ts
|
|
1038
|
+
* app.get('/redirect', (c) => {
|
|
1039
|
+
* return c.redirect('/')
|
|
1040
|
+
* })
|
|
1041
|
+
* app.get('/redirect-permanently', (c) => {
|
|
1042
|
+
* return c.redirect('/', 301)
|
|
1043
|
+
* })
|
|
1044
|
+
* ```
|
|
1045
|
+
*/
|
|
1046
|
+
redirect = (location, status) => {
|
|
1047
|
+
const locationString = String(location);
|
|
1048
|
+
this.header(
|
|
1049
|
+
"Location",
|
|
1050
|
+
// Multibyes should be encoded
|
|
1051
|
+
// eslint-disable-next-line no-control-regex
|
|
1052
|
+
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
1053
|
+
);
|
|
1054
|
+
return this.newResponse(null, status ?? 302);
|
|
1055
|
+
};
|
|
1056
|
+
/**
|
|
1057
|
+
* `.notFound()` can return the Not Found Response.
|
|
1058
|
+
*
|
|
1059
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
1060
|
+
*
|
|
1061
|
+
* @example
|
|
1062
|
+
* ```ts
|
|
1063
|
+
* app.get('/notfound', (c) => {
|
|
1064
|
+
* return c.notFound()
|
|
1065
|
+
* })
|
|
1066
|
+
* ```
|
|
1067
|
+
*/
|
|
1068
|
+
notFound = () => {
|
|
1069
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
1070
|
+
return this.#notFoundHandler(this);
|
|
1071
|
+
};
|
|
1072
|
+
};
|
|
1073
|
+
|
|
1074
|
+
// node_modules/hono/dist/router.js
|
|
1075
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1076
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1077
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
1078
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1079
|
+
var UnsupportedPathError = class extends Error {
|
|
1080
|
+
};
|
|
1081
|
+
|
|
1082
|
+
// node_modules/hono/dist/utils/constants.js
|
|
1083
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1084
|
+
|
|
1085
|
+
// node_modules/hono/dist/hono-base.js
|
|
1086
|
+
var notFoundHandler = (c) => {
|
|
1087
|
+
return c.text("404 Not Found", 404);
|
|
1088
|
+
};
|
|
1089
|
+
var errorHandler = (err, c) => {
|
|
1090
|
+
if ("getResponse" in err) {
|
|
1091
|
+
const res = err.getResponse();
|
|
1092
|
+
return c.newResponse(res.body, res);
|
|
1093
|
+
}
|
|
1094
|
+
console.error(err);
|
|
1095
|
+
return c.text("Internal Server Error", 500);
|
|
1096
|
+
};
|
|
1097
|
+
var Hono = class _Hono {
|
|
1098
|
+
get;
|
|
1099
|
+
post;
|
|
1100
|
+
put;
|
|
1101
|
+
delete;
|
|
1102
|
+
options;
|
|
1103
|
+
patch;
|
|
1104
|
+
all;
|
|
1105
|
+
on;
|
|
1106
|
+
use;
|
|
1107
|
+
/*
|
|
1108
|
+
This class is like an abstract class and does not have a router.
|
|
1109
|
+
To use it, inherit the class and implement router in the constructor.
|
|
1110
|
+
*/
|
|
1111
|
+
router;
|
|
1112
|
+
getPath;
|
|
1113
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1114
|
+
_basePath = "/";
|
|
1115
|
+
#path = "/";
|
|
1116
|
+
routes = [];
|
|
1117
|
+
constructor(options = {}) {
|
|
1118
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
1119
|
+
allMethods.forEach((method) => {
|
|
1120
|
+
this[method] = (args1, ...args) => {
|
|
1121
|
+
if (typeof args1 === "string") {
|
|
1122
|
+
this.#path = args1;
|
|
1123
|
+
} else {
|
|
1124
|
+
this.#addRoute(method, this.#path, args1);
|
|
1125
|
+
}
|
|
1126
|
+
args.forEach((handler) => {
|
|
1127
|
+
this.#addRoute(method, this.#path, handler);
|
|
1128
|
+
});
|
|
1129
|
+
return this;
|
|
1130
|
+
};
|
|
1131
|
+
});
|
|
1132
|
+
this.on = (method, path, ...handlers) => {
|
|
1133
|
+
for (const p of [path].flat()) {
|
|
1134
|
+
this.#path = p;
|
|
1135
|
+
for (const m of [method].flat()) {
|
|
1136
|
+
handlers.map((handler) => {
|
|
1137
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
return this;
|
|
1142
|
+
};
|
|
1143
|
+
this.use = (arg1, ...handlers) => {
|
|
1144
|
+
if (typeof arg1 === "string") {
|
|
1145
|
+
this.#path = arg1;
|
|
1146
|
+
} else {
|
|
1147
|
+
this.#path = "*";
|
|
1148
|
+
handlers.unshift(arg1);
|
|
1149
|
+
}
|
|
1150
|
+
handlers.forEach((handler) => {
|
|
1151
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
1152
|
+
});
|
|
1153
|
+
return this;
|
|
1154
|
+
};
|
|
1155
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
1156
|
+
Object.assign(this, optionsWithoutStrict);
|
|
1157
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
1158
|
+
}
|
|
1159
|
+
#clone() {
|
|
1160
|
+
const clone = new _Hono({
|
|
1161
|
+
router: this.router,
|
|
1162
|
+
getPath: this.getPath
|
|
1163
|
+
});
|
|
1164
|
+
clone.errorHandler = this.errorHandler;
|
|
1165
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
1166
|
+
clone.routes = this.routes;
|
|
1167
|
+
return clone;
|
|
1168
|
+
}
|
|
1169
|
+
#notFoundHandler = notFoundHandler;
|
|
1170
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1171
|
+
errorHandler = errorHandler;
|
|
1172
|
+
/**
|
|
1173
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
1174
|
+
*
|
|
1175
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
1176
|
+
*
|
|
1177
|
+
* @param {string} path - base Path
|
|
1178
|
+
* @param {Hono} app - other Hono instance
|
|
1179
|
+
* @returns {Hono} routed Hono instance
|
|
1180
|
+
*
|
|
1181
|
+
* @example
|
|
1182
|
+
* ```ts
|
|
1183
|
+
* const app = new Hono()
|
|
1184
|
+
* const app2 = new Hono()
|
|
1185
|
+
*
|
|
1186
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
1187
|
+
* app.route("/api", app2) // GET /api/user
|
|
1188
|
+
* ```
|
|
1189
|
+
*/
|
|
1190
|
+
route(path, app) {
|
|
1191
|
+
const subApp = this.basePath(path);
|
|
1192
|
+
app.routes.map((r) => {
|
|
1193
|
+
let handler;
|
|
1194
|
+
if (app.errorHandler === errorHandler) {
|
|
1195
|
+
handler = r.handler;
|
|
1196
|
+
} else {
|
|
1197
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
1198
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
1199
|
+
}
|
|
1200
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
1201
|
+
});
|
|
1202
|
+
return this;
|
|
1203
|
+
}
|
|
1204
|
+
/**
|
|
1205
|
+
* `.basePath()` allows base paths to be specified.
|
|
1206
|
+
*
|
|
1207
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
1208
|
+
*
|
|
1209
|
+
* @param {string} path - base Path
|
|
1210
|
+
* @returns {Hono} changed Hono instance
|
|
1211
|
+
*
|
|
1212
|
+
* @example
|
|
1213
|
+
* ```ts
|
|
1214
|
+
* const api = new Hono().basePath('/api')
|
|
1215
|
+
* ```
|
|
1216
|
+
*/
|
|
1217
|
+
basePath(path) {
|
|
1218
|
+
const subApp = this.#clone();
|
|
1219
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
1220
|
+
return subApp;
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
1224
|
+
*
|
|
1225
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
1226
|
+
*
|
|
1227
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
1228
|
+
* @returns {Hono} changed Hono instance
|
|
1229
|
+
*
|
|
1230
|
+
* @example
|
|
1231
|
+
* ```ts
|
|
1232
|
+
* app.onError((err, c) => {
|
|
1233
|
+
* console.error(`${err}`)
|
|
1234
|
+
* return c.text('Custom Error Message', 500)
|
|
1235
|
+
* })
|
|
1236
|
+
* ```
|
|
1237
|
+
*/
|
|
1238
|
+
onError = (handler) => {
|
|
1239
|
+
this.errorHandler = handler;
|
|
1240
|
+
return this;
|
|
1241
|
+
};
|
|
1242
|
+
/**
|
|
1243
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
1244
|
+
*
|
|
1245
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
1246
|
+
*
|
|
1247
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
1248
|
+
* @returns {Hono} changed Hono instance
|
|
1249
|
+
*
|
|
1250
|
+
* @example
|
|
1251
|
+
* ```ts
|
|
1252
|
+
* app.notFound((c) => {
|
|
1253
|
+
* return c.text('Custom 404 Message', 404)
|
|
1254
|
+
* })
|
|
1255
|
+
* ```
|
|
1256
|
+
*/
|
|
1257
|
+
notFound = (handler) => {
|
|
1258
|
+
this.#notFoundHandler = handler;
|
|
1259
|
+
return this;
|
|
1260
|
+
};
|
|
1261
|
+
/**
|
|
1262
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
1263
|
+
*
|
|
1264
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
1265
|
+
*
|
|
1266
|
+
* @param {string} path - base Path
|
|
1267
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
1268
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
1269
|
+
* @returns {Hono} mounted Hono instance
|
|
1270
|
+
*
|
|
1271
|
+
* @example
|
|
1272
|
+
* ```ts
|
|
1273
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
1274
|
+
* import { Hono } from 'hono'
|
|
1275
|
+
* // Create itty-router application
|
|
1276
|
+
* const ittyRouter = IttyRouter()
|
|
1277
|
+
* // GET /itty-router/hello
|
|
1278
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
1279
|
+
*
|
|
1280
|
+
* const app = new Hono()
|
|
1281
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
1282
|
+
* ```
|
|
1283
|
+
*
|
|
1284
|
+
* @example
|
|
1285
|
+
* ```ts
|
|
1286
|
+
* const app = new Hono()
|
|
1287
|
+
* // Send the request to another application without modification.
|
|
1288
|
+
* app.mount('/app', anotherApp, {
|
|
1289
|
+
* replaceRequest: (req) => req,
|
|
1290
|
+
* })
|
|
1291
|
+
* ```
|
|
1292
|
+
*/
|
|
1293
|
+
mount(path, applicationHandler, options) {
|
|
1294
|
+
let replaceRequest;
|
|
1295
|
+
let optionHandler;
|
|
1296
|
+
if (options) {
|
|
1297
|
+
if (typeof options === "function") {
|
|
1298
|
+
optionHandler = options;
|
|
1299
|
+
} else {
|
|
1300
|
+
optionHandler = options.optionHandler;
|
|
1301
|
+
if (options.replaceRequest === false) {
|
|
1302
|
+
replaceRequest = (request) => request;
|
|
1303
|
+
} else {
|
|
1304
|
+
replaceRequest = options.replaceRequest;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
const getOptions = optionHandler ? (c) => {
|
|
1309
|
+
const options2 = optionHandler(c);
|
|
1310
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
1311
|
+
} : (c) => {
|
|
1312
|
+
let executionContext = void 0;
|
|
1313
|
+
try {
|
|
1314
|
+
executionContext = c.executionCtx;
|
|
1315
|
+
} catch {
|
|
1316
|
+
}
|
|
1317
|
+
return [c.env, executionContext];
|
|
1318
|
+
};
|
|
1319
|
+
replaceRequest ||= (() => {
|
|
1320
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
1321
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
1322
|
+
return (request) => {
|
|
1323
|
+
const url = new URL(request.url);
|
|
1324
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
1325
|
+
return new Request(url, request);
|
|
1326
|
+
};
|
|
1327
|
+
})();
|
|
1328
|
+
const handler = async (c, next) => {
|
|
1329
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
1330
|
+
if (res) {
|
|
1331
|
+
return res;
|
|
1332
|
+
}
|
|
1333
|
+
await next();
|
|
1334
|
+
};
|
|
1335
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
1336
|
+
return this;
|
|
1337
|
+
}
|
|
1338
|
+
#addRoute(method, path, handler) {
|
|
1339
|
+
method = method.toUpperCase();
|
|
1340
|
+
path = mergePath(this._basePath, path);
|
|
1341
|
+
const r = { basePath: this._basePath, path, method, handler };
|
|
1342
|
+
this.router.add(method, path, [handler, r]);
|
|
1343
|
+
this.routes.push(r);
|
|
1344
|
+
}
|
|
1345
|
+
#handleError(err, c) {
|
|
1346
|
+
if (err instanceof Error) {
|
|
1347
|
+
return this.errorHandler(err, c);
|
|
1348
|
+
}
|
|
1349
|
+
throw err;
|
|
1350
|
+
}
|
|
1351
|
+
#dispatch(request, executionCtx, env, method) {
|
|
1352
|
+
if (method === "HEAD") {
|
|
1353
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
1354
|
+
}
|
|
1355
|
+
const path = this.getPath(request, { env });
|
|
1356
|
+
const matchResult = this.router.match(method, path);
|
|
1357
|
+
const c = new Context(request, {
|
|
1358
|
+
path,
|
|
1359
|
+
matchResult,
|
|
1360
|
+
env,
|
|
1361
|
+
executionCtx,
|
|
1362
|
+
notFoundHandler: this.#notFoundHandler
|
|
1363
|
+
});
|
|
1364
|
+
if (matchResult[0].length === 1) {
|
|
1365
|
+
let res;
|
|
1366
|
+
try {
|
|
1367
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
1368
|
+
c.res = await this.#notFoundHandler(c);
|
|
1369
|
+
});
|
|
1370
|
+
} catch (err) {
|
|
1371
|
+
return this.#handleError(err, c);
|
|
1372
|
+
}
|
|
1373
|
+
return res instanceof Promise ? res.then(
|
|
1374
|
+
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
1375
|
+
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
1376
|
+
}
|
|
1377
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
1378
|
+
return (async () => {
|
|
1379
|
+
try {
|
|
1380
|
+
const context = await composed(c);
|
|
1381
|
+
if (!context.finalized) {
|
|
1382
|
+
throw new Error(
|
|
1383
|
+
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
1384
|
+
);
|
|
1385
|
+
}
|
|
1386
|
+
return context.res;
|
|
1387
|
+
} catch (err) {
|
|
1388
|
+
return this.#handleError(err, c);
|
|
1389
|
+
}
|
|
1390
|
+
})();
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* `.fetch()` will be entry point of your app.
|
|
1394
|
+
*
|
|
1395
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
1396
|
+
*
|
|
1397
|
+
* @param {Request} request - request Object of request
|
|
1398
|
+
* @param {Env} Env - env Object
|
|
1399
|
+
* @param {ExecutionContext} - context of execution
|
|
1400
|
+
* @returns {Response | Promise<Response>} response of request
|
|
1401
|
+
*
|
|
1402
|
+
*/
|
|
1403
|
+
fetch = (request, ...rest) => {
|
|
1404
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
1405
|
+
};
|
|
1406
|
+
/**
|
|
1407
|
+
* `.request()` is a useful method for testing.
|
|
1408
|
+
* You can pass a URL or pathname to send a GET request.
|
|
1409
|
+
* app will return a Response object.
|
|
1410
|
+
* ```ts
|
|
1411
|
+
* test('GET /hello is ok', async () => {
|
|
1412
|
+
* const res = await app.request('/hello')
|
|
1413
|
+
* expect(res.status).toBe(200)
|
|
1414
|
+
* })
|
|
1415
|
+
* ```
|
|
1416
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
1417
|
+
*/
|
|
1418
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
1419
|
+
if (input instanceof Request) {
|
|
1420
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
1421
|
+
}
|
|
1422
|
+
input = input.toString();
|
|
1423
|
+
return this.fetch(
|
|
1424
|
+
new Request(
|
|
1425
|
+
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
1426
|
+
requestInit
|
|
1427
|
+
),
|
|
1428
|
+
Env,
|
|
1429
|
+
executionCtx
|
|
1430
|
+
);
|
|
1431
|
+
};
|
|
1432
|
+
/**
|
|
1433
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
1434
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
1435
|
+
* @deprecated
|
|
1436
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
1437
|
+
* ```ts
|
|
1438
|
+
* import { Hono } from 'hono'
|
|
1439
|
+
* import { fire } from 'hono/service-worker'
|
|
1440
|
+
*
|
|
1441
|
+
* const app = new Hono()
|
|
1442
|
+
* // ...
|
|
1443
|
+
* fire(app)
|
|
1444
|
+
* ```
|
|
1445
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
1446
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
1447
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
1448
|
+
*/
|
|
1449
|
+
fire = () => {
|
|
1450
|
+
addEventListener("fetch", (event) => {
|
|
1451
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
1452
|
+
});
|
|
1453
|
+
};
|
|
1454
|
+
};
|
|
1455
|
+
|
|
1456
|
+
// node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
1457
|
+
var emptyParam = [];
|
|
1458
|
+
function match(method, path) {
|
|
1459
|
+
const matchers = this.buildAllMatchers();
|
|
1460
|
+
const match2 = ((method2, path2) => {
|
|
1461
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
1462
|
+
const staticMatch = matcher[2][path2];
|
|
1463
|
+
if (staticMatch) {
|
|
1464
|
+
return staticMatch;
|
|
1465
|
+
}
|
|
1466
|
+
const match3 = path2.match(matcher[0]);
|
|
1467
|
+
if (!match3) {
|
|
1468
|
+
return [[], emptyParam];
|
|
1469
|
+
}
|
|
1470
|
+
const index = match3.indexOf("", 1);
|
|
1471
|
+
return [matcher[1][index], match3];
|
|
1472
|
+
});
|
|
1473
|
+
this.match = match2;
|
|
1474
|
+
return match2(method, path);
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// node_modules/hono/dist/router/reg-exp-router/node.js
|
|
1478
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
1479
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
1480
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
1481
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
1482
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
1483
|
+
function compareKey(a, b) {
|
|
1484
|
+
if (a.length === 1) {
|
|
1485
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
1486
|
+
}
|
|
1487
|
+
if (b.length === 1) {
|
|
1488
|
+
return 1;
|
|
1489
|
+
}
|
|
1490
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1491
|
+
return 1;
|
|
1492
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1493
|
+
return -1;
|
|
1494
|
+
}
|
|
1495
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
1496
|
+
return 1;
|
|
1497
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
1498
|
+
return -1;
|
|
1499
|
+
}
|
|
1500
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
1501
|
+
}
|
|
1502
|
+
var Node = class _Node {
|
|
1503
|
+
#index;
|
|
1504
|
+
#varIndex;
|
|
1505
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
1506
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
1507
|
+
if (tokens.length === 0) {
|
|
1508
|
+
if (this.#index !== void 0) {
|
|
1509
|
+
throw PATH_ERROR;
|
|
1510
|
+
}
|
|
1511
|
+
if (pathErrorCheckOnly) {
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
this.#index = index;
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
const [token, ...restTokens] = tokens;
|
|
1518
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
1519
|
+
let node;
|
|
1520
|
+
if (pattern) {
|
|
1521
|
+
const name = pattern[1];
|
|
1522
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
1523
|
+
if (name && pattern[2]) {
|
|
1524
|
+
if (regexpStr === ".*") {
|
|
1525
|
+
throw PATH_ERROR;
|
|
1526
|
+
}
|
|
1527
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
1528
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
1529
|
+
throw PATH_ERROR;
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
node = this.#children[regexpStr];
|
|
1533
|
+
if (!node) {
|
|
1534
|
+
if (Object.keys(this.#children).some(
|
|
1535
|
+
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
1536
|
+
)) {
|
|
1537
|
+
throw PATH_ERROR;
|
|
1538
|
+
}
|
|
1539
|
+
if (pathErrorCheckOnly) {
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
node = this.#children[regexpStr] = new _Node();
|
|
1543
|
+
if (name !== "") {
|
|
1544
|
+
node.#varIndex = context.varIndex++;
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
1548
|
+
paramMap.push([name, node.#varIndex]);
|
|
1549
|
+
}
|
|
1550
|
+
} else {
|
|
1551
|
+
node = this.#children[token];
|
|
1552
|
+
if (!node) {
|
|
1553
|
+
if (Object.keys(this.#children).some(
|
|
1554
|
+
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
1555
|
+
)) {
|
|
1556
|
+
throw PATH_ERROR;
|
|
1557
|
+
}
|
|
1558
|
+
if (pathErrorCheckOnly) {
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
node = this.#children[token] = new _Node();
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
1565
|
+
}
|
|
1566
|
+
buildRegExpStr() {
|
|
1567
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
1568
|
+
const strList = childKeys.map((k) => {
|
|
1569
|
+
const c = this.#children[k];
|
|
1570
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
1571
|
+
});
|
|
1572
|
+
if (typeof this.#index === "number") {
|
|
1573
|
+
strList.unshift(`#${this.#index}`);
|
|
1574
|
+
}
|
|
1575
|
+
if (strList.length === 0) {
|
|
1576
|
+
return "";
|
|
1577
|
+
}
|
|
1578
|
+
if (strList.length === 1) {
|
|
1579
|
+
return strList[0];
|
|
1580
|
+
}
|
|
1581
|
+
return "(?:" + strList.join("|") + ")";
|
|
1582
|
+
}
|
|
1583
|
+
};
|
|
1584
|
+
|
|
1585
|
+
// node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
1586
|
+
var Trie = class {
|
|
1587
|
+
#context = { varIndex: 0 };
|
|
1588
|
+
#root = new Node();
|
|
1589
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
1590
|
+
const paramAssoc = [];
|
|
1591
|
+
const groups = [];
|
|
1592
|
+
for (let i = 0; ; ) {
|
|
1593
|
+
let replaced = false;
|
|
1594
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
1595
|
+
const mark = `@\\${i}`;
|
|
1596
|
+
groups[i] = [mark, m];
|
|
1597
|
+
i++;
|
|
1598
|
+
replaced = true;
|
|
1599
|
+
return mark;
|
|
1600
|
+
});
|
|
1601
|
+
if (!replaced) {
|
|
1602
|
+
break;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
1606
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
1607
|
+
const [mark] = groups[i];
|
|
1608
|
+
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
1609
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
1610
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
1611
|
+
break;
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
1616
|
+
return paramAssoc;
|
|
1617
|
+
}
|
|
1618
|
+
buildRegExp() {
|
|
1619
|
+
let regexp = this.#root.buildRegExpStr();
|
|
1620
|
+
if (regexp === "") {
|
|
1621
|
+
return [/^$/, [], []];
|
|
1622
|
+
}
|
|
1623
|
+
let captureIndex = 0;
|
|
1624
|
+
const indexReplacementMap = [];
|
|
1625
|
+
const paramReplacementMap = [];
|
|
1626
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
1627
|
+
if (handlerIndex !== void 0) {
|
|
1628
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
1629
|
+
return "$()";
|
|
1630
|
+
}
|
|
1631
|
+
if (paramIndex !== void 0) {
|
|
1632
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
1633
|
+
return "";
|
|
1634
|
+
}
|
|
1635
|
+
return "";
|
|
1636
|
+
});
|
|
1637
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
1638
|
+
}
|
|
1639
|
+
};
|
|
1640
|
+
|
|
1641
|
+
// node_modules/hono/dist/router/reg-exp-router/router.js
|
|
1642
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
1643
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1644
|
+
function buildWildcardRegExp(path) {
|
|
1645
|
+
return wildcardRegExpCache[path] ??= new RegExp(
|
|
1646
|
+
path === "*" ? "" : `^${path.replace(
|
|
1647
|
+
/\/\*$|([.\\+*[^\]$()])/g,
|
|
1648
|
+
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
|
|
1649
|
+
)}$`
|
|
1650
|
+
);
|
|
1651
|
+
}
|
|
1652
|
+
function clearWildcardRegExpCache() {
|
|
1653
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1654
|
+
}
|
|
1655
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
1656
|
+
const trie = new Trie();
|
|
1657
|
+
const handlerData = [];
|
|
1658
|
+
if (routes.length === 0) {
|
|
1659
|
+
return nullMatcher;
|
|
1660
|
+
}
|
|
1661
|
+
const routesWithStaticPathFlag = routes.map(
|
|
1662
|
+
(route) => [!/\*|\/:/.test(route[0]), ...route]
|
|
1663
|
+
).sort(
|
|
1664
|
+
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
|
|
1665
|
+
);
|
|
1666
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
1667
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
1668
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
1669
|
+
if (pathErrorCheckOnly) {
|
|
1670
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
1671
|
+
} else {
|
|
1672
|
+
j++;
|
|
1673
|
+
}
|
|
1674
|
+
let paramAssoc;
|
|
1675
|
+
try {
|
|
1676
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
1677
|
+
} catch (e) {
|
|
1678
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
1679
|
+
}
|
|
1680
|
+
if (pathErrorCheckOnly) {
|
|
1681
|
+
continue;
|
|
1682
|
+
}
|
|
1683
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
1684
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
1685
|
+
paramCount -= 1;
|
|
1686
|
+
for (; paramCount >= 0; paramCount--) {
|
|
1687
|
+
const [key, value] = paramAssoc[paramCount];
|
|
1688
|
+
paramIndexMap[key] = value;
|
|
1689
|
+
}
|
|
1690
|
+
return [h, paramIndexMap];
|
|
1691
|
+
});
|
|
1692
|
+
}
|
|
1693
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
1694
|
+
for (let i = 0, len = handlerData.length; i < len; i++) {
|
|
1695
|
+
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
1696
|
+
const map = handlerData[i][j]?.[1];
|
|
1697
|
+
if (!map) {
|
|
1698
|
+
continue;
|
|
1699
|
+
}
|
|
1700
|
+
const keys = Object.keys(map);
|
|
1701
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) {
|
|
1702
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
const handlerMap = [];
|
|
1707
|
+
for (const i in indexReplacementMap) {
|
|
1708
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
1709
|
+
}
|
|
1710
|
+
return [regexp, handlerMap, staticMap];
|
|
1711
|
+
}
|
|
1712
|
+
function findMiddleware(middleware, path) {
|
|
1713
|
+
if (!middleware) {
|
|
1714
|
+
return void 0;
|
|
1715
|
+
}
|
|
1716
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
1717
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
1718
|
+
return [...middleware[k]];
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
return void 0;
|
|
1722
|
+
}
|
|
1723
|
+
var RegExpRouter = class {
|
|
1724
|
+
name = "RegExpRouter";
|
|
1725
|
+
#middleware;
|
|
1726
|
+
#routes;
|
|
1727
|
+
constructor() {
|
|
1728
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1729
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1730
|
+
}
|
|
1731
|
+
add(method, path, handler) {
|
|
1732
|
+
const middleware = this.#middleware;
|
|
1733
|
+
const routes = this.#routes;
|
|
1734
|
+
if (!middleware || !routes) {
|
|
1735
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1736
|
+
}
|
|
1737
|
+
if (!middleware[method]) {
|
|
1738
|
+
;
|
|
1739
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
1740
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
1741
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
1742
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
1743
|
+
});
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
if (path === "/*") {
|
|
1747
|
+
path = "*";
|
|
1748
|
+
}
|
|
1749
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
1750
|
+
if (/\*$/.test(path)) {
|
|
1751
|
+
const re = buildWildcardRegExp(path);
|
|
1752
|
+
if (method === METHOD_NAME_ALL) {
|
|
1753
|
+
Object.keys(middleware).forEach((m) => {
|
|
1754
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1755
|
+
});
|
|
1756
|
+
} else {
|
|
1757
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1758
|
+
}
|
|
1759
|
+
Object.keys(middleware).forEach((m) => {
|
|
1760
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1761
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
1762
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1765
|
+
});
|
|
1766
|
+
Object.keys(routes).forEach((m) => {
|
|
1767
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1768
|
+
Object.keys(routes[m]).forEach(
|
|
1769
|
+
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
|
|
1770
|
+
);
|
|
1771
|
+
}
|
|
1772
|
+
});
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
1776
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
1777
|
+
const path2 = paths[i];
|
|
1778
|
+
Object.keys(routes).forEach((m) => {
|
|
1779
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1780
|
+
routes[m][path2] ||= [
|
|
1781
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
1782
|
+
];
|
|
1783
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
1784
|
+
}
|
|
1785
|
+
});
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
match = match;
|
|
1789
|
+
buildAllMatchers() {
|
|
1790
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
1791
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
1792
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
1793
|
+
});
|
|
1794
|
+
this.#middleware = this.#routes = void 0;
|
|
1795
|
+
clearWildcardRegExpCache();
|
|
1796
|
+
return matchers;
|
|
1797
|
+
}
|
|
1798
|
+
#buildMatcher(method) {
|
|
1799
|
+
const routes = [];
|
|
1800
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
1801
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
1802
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
1803
|
+
if (ownRoute.length !== 0) {
|
|
1804
|
+
hasOwnRoute ||= true;
|
|
1805
|
+
routes.push(...ownRoute);
|
|
1806
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
1807
|
+
routes.push(
|
|
1808
|
+
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
|
|
1809
|
+
);
|
|
1810
|
+
}
|
|
1811
|
+
});
|
|
1812
|
+
if (!hasOwnRoute) {
|
|
1813
|
+
return null;
|
|
1814
|
+
} else {
|
|
1815
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
};
|
|
1819
|
+
|
|
1820
|
+
// node_modules/hono/dist/router/smart-router/router.js
|
|
1821
|
+
var SmartRouter = class {
|
|
1822
|
+
name = "SmartRouter";
|
|
1823
|
+
#routers = [];
|
|
1824
|
+
#routes = [];
|
|
1825
|
+
constructor(init) {
|
|
1826
|
+
this.#routers = init.routers;
|
|
1827
|
+
}
|
|
1828
|
+
add(method, path, handler) {
|
|
1829
|
+
if (!this.#routes) {
|
|
1830
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1831
|
+
}
|
|
1832
|
+
this.#routes.push([method, path, handler]);
|
|
1833
|
+
}
|
|
1834
|
+
match(method, path) {
|
|
1835
|
+
if (!this.#routes) {
|
|
1836
|
+
throw new Error("Fatal error");
|
|
1837
|
+
}
|
|
1838
|
+
const routers = this.#routers;
|
|
1839
|
+
const routes = this.#routes;
|
|
1840
|
+
const len = routers.length;
|
|
1841
|
+
let i = 0;
|
|
1842
|
+
let res;
|
|
1843
|
+
for (; i < len; i++) {
|
|
1844
|
+
const router = routers[i];
|
|
1845
|
+
try {
|
|
1846
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
1847
|
+
router.add(...routes[i2]);
|
|
1848
|
+
}
|
|
1849
|
+
res = router.match(method, path);
|
|
1850
|
+
} catch (e) {
|
|
1851
|
+
if (e instanceof UnsupportedPathError) {
|
|
1852
|
+
continue;
|
|
1853
|
+
}
|
|
1854
|
+
throw e;
|
|
1855
|
+
}
|
|
1856
|
+
this.match = router.match.bind(router);
|
|
1857
|
+
this.#routers = [router];
|
|
1858
|
+
this.#routes = void 0;
|
|
1859
|
+
break;
|
|
1860
|
+
}
|
|
1861
|
+
if (i === len) {
|
|
1862
|
+
throw new Error("Fatal error");
|
|
1863
|
+
}
|
|
1864
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
1865
|
+
return res;
|
|
1866
|
+
}
|
|
1867
|
+
get activeRouter() {
|
|
1868
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
1869
|
+
throw new Error("No active router has been determined yet.");
|
|
1870
|
+
}
|
|
1871
|
+
return this.#routers[0];
|
|
1872
|
+
}
|
|
1873
|
+
};
|
|
1874
|
+
|
|
1875
|
+
// node_modules/hono/dist/router/trie-router/node.js
|
|
1876
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
1877
|
+
var hasChildren = (children) => {
|
|
1878
|
+
for (const _ in children) {
|
|
1879
|
+
return true;
|
|
1880
|
+
}
|
|
1881
|
+
return false;
|
|
1882
|
+
};
|
|
1883
|
+
var Node2 = class _Node2 {
|
|
1884
|
+
#methods;
|
|
1885
|
+
#children;
|
|
1886
|
+
#patterns;
|
|
1887
|
+
#order = 0;
|
|
1888
|
+
#params = emptyParams;
|
|
1889
|
+
constructor(method, handler, children) {
|
|
1890
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
1891
|
+
this.#methods = [];
|
|
1892
|
+
if (method && handler) {
|
|
1893
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
1894
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
1895
|
+
this.#methods = [m];
|
|
1896
|
+
}
|
|
1897
|
+
this.#patterns = [];
|
|
1898
|
+
}
|
|
1899
|
+
insert(method, path, handler) {
|
|
1900
|
+
this.#order = ++this.#order;
|
|
1901
|
+
let curNode = this;
|
|
1902
|
+
const parts = splitRoutingPath(path);
|
|
1903
|
+
const possibleKeys = [];
|
|
1904
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
1905
|
+
const p = parts[i];
|
|
1906
|
+
const nextP = parts[i + 1];
|
|
1907
|
+
const pattern = getPattern(p, nextP);
|
|
1908
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
1909
|
+
if (key in curNode.#children) {
|
|
1910
|
+
curNode = curNode.#children[key];
|
|
1911
|
+
if (pattern) {
|
|
1912
|
+
possibleKeys.push(pattern[1]);
|
|
1913
|
+
}
|
|
1914
|
+
continue;
|
|
1915
|
+
}
|
|
1916
|
+
curNode.#children[key] = new _Node2();
|
|
1917
|
+
if (pattern) {
|
|
1918
|
+
curNode.#patterns.push(pattern);
|
|
1919
|
+
possibleKeys.push(pattern[1]);
|
|
1920
|
+
}
|
|
1921
|
+
curNode = curNode.#children[key];
|
|
1922
|
+
}
|
|
1923
|
+
curNode.#methods.push({
|
|
1924
|
+
[method]: {
|
|
1925
|
+
handler,
|
|
1926
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
1927
|
+
score: this.#order
|
|
1928
|
+
}
|
|
1929
|
+
});
|
|
1930
|
+
return curNode;
|
|
1931
|
+
}
|
|
1932
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
1933
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
1934
|
+
const m = node.#methods[i];
|
|
1935
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
1936
|
+
const processedSet = {};
|
|
1937
|
+
if (handlerSet !== void 0) {
|
|
1938
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
1939
|
+
handlerSets.push(handlerSet);
|
|
1940
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
1941
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
1942
|
+
const key = handlerSet.possibleKeys[i2];
|
|
1943
|
+
const processed = processedSet[handlerSet.score];
|
|
1944
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
1945
|
+
processedSet[handlerSet.score] = true;
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
search(method, path) {
|
|
1952
|
+
const handlerSets = [];
|
|
1953
|
+
this.#params = emptyParams;
|
|
1954
|
+
const curNode = this;
|
|
1955
|
+
let curNodes = [curNode];
|
|
1956
|
+
const parts = splitPath(path);
|
|
1957
|
+
const curNodesQueue = [];
|
|
1958
|
+
const len = parts.length;
|
|
1959
|
+
let partOffsets = null;
|
|
1960
|
+
for (let i = 0; i < len; i++) {
|
|
1961
|
+
const part = parts[i];
|
|
1962
|
+
const isLast = i === len - 1;
|
|
1963
|
+
const tempNodes = [];
|
|
1964
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
1965
|
+
const node = curNodes[j];
|
|
1966
|
+
const nextNode = node.#children[part];
|
|
1967
|
+
if (nextNode) {
|
|
1968
|
+
nextNode.#params = node.#params;
|
|
1969
|
+
if (isLast) {
|
|
1970
|
+
if (nextNode.#children["*"]) {
|
|
1971
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
1972
|
+
}
|
|
1973
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
1974
|
+
} else {
|
|
1975
|
+
tempNodes.push(nextNode);
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
1979
|
+
const pattern = node.#patterns[k];
|
|
1980
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
1981
|
+
if (pattern === "*") {
|
|
1982
|
+
const astNode = node.#children["*"];
|
|
1983
|
+
if (astNode) {
|
|
1984
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
1985
|
+
astNode.#params = params;
|
|
1986
|
+
tempNodes.push(astNode);
|
|
1987
|
+
}
|
|
1988
|
+
continue;
|
|
1989
|
+
}
|
|
1990
|
+
const [key, name, matcher] = pattern;
|
|
1991
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
1992
|
+
continue;
|
|
1993
|
+
}
|
|
1994
|
+
const child = node.#children[key];
|
|
1995
|
+
if (matcher instanceof RegExp) {
|
|
1996
|
+
if (partOffsets === null) {
|
|
1997
|
+
partOffsets = new Array(len);
|
|
1998
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
1999
|
+
for (let p = 0; p < len; p++) {
|
|
2000
|
+
partOffsets[p] = offset;
|
|
2001
|
+
offset += parts[p].length + 1;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
2005
|
+
const m = matcher.exec(restPathString);
|
|
2006
|
+
if (m) {
|
|
2007
|
+
params[name] = m[0];
|
|
2008
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
2009
|
+
if (hasChildren(child.#children)) {
|
|
2010
|
+
child.#params = params;
|
|
2011
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
2012
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
2013
|
+
targetCurNodes.push(child);
|
|
2014
|
+
}
|
|
2015
|
+
continue;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
if (matcher === true || matcher.test(part)) {
|
|
2019
|
+
params[name] = part;
|
|
2020
|
+
if (isLast) {
|
|
2021
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
2022
|
+
if (child.#children["*"]) {
|
|
2023
|
+
this.#pushHandlerSets(
|
|
2024
|
+
handlerSets,
|
|
2025
|
+
child.#children["*"],
|
|
2026
|
+
method,
|
|
2027
|
+
params,
|
|
2028
|
+
node.#params
|
|
2029
|
+
);
|
|
2030
|
+
}
|
|
2031
|
+
} else {
|
|
2032
|
+
child.#params = params;
|
|
2033
|
+
tempNodes.push(child);
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
const shifted = curNodesQueue.shift();
|
|
2039
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
2040
|
+
}
|
|
2041
|
+
if (handlerSets.length > 1) {
|
|
2042
|
+
handlerSets.sort((a, b) => {
|
|
2043
|
+
return a.score - b.score;
|
|
2044
|
+
});
|
|
2045
|
+
}
|
|
2046
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2047
|
+
}
|
|
2048
|
+
};
|
|
2049
|
+
|
|
2050
|
+
// node_modules/hono/dist/router/trie-router/router.js
|
|
2051
|
+
var TrieRouter = class {
|
|
2052
|
+
name = "TrieRouter";
|
|
2053
|
+
#node;
|
|
2054
|
+
constructor() {
|
|
2055
|
+
this.#node = new Node2();
|
|
2056
|
+
}
|
|
2057
|
+
add(method, path, handler) {
|
|
2058
|
+
const results = checkOptionalParameter(path);
|
|
2059
|
+
if (results) {
|
|
2060
|
+
for (let i = 0, len = results.length; i < len; i++) {
|
|
2061
|
+
this.#node.insert(method, results[i], handler);
|
|
2062
|
+
}
|
|
2063
|
+
return;
|
|
2064
|
+
}
|
|
2065
|
+
this.#node.insert(method, path, handler);
|
|
2066
|
+
}
|
|
2067
|
+
match(method, path) {
|
|
2068
|
+
return this.#node.search(method, path);
|
|
2069
|
+
}
|
|
2070
|
+
};
|
|
2071
|
+
|
|
2072
|
+
// node_modules/hono/dist/hono.js
|
|
2073
|
+
var Hono2 = class extends Hono {
|
|
2074
|
+
/**
|
|
2075
|
+
* Creates an instance of the Hono class.
|
|
2076
|
+
*
|
|
2077
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
2078
|
+
*/
|
|
2079
|
+
constructor(options = {}) {
|
|
2080
|
+
super(options);
|
|
2081
|
+
this.router = options.router ?? new SmartRouter({
|
|
2082
|
+
routers: [new RegExpRouter(), new TrieRouter()]
|
|
2083
|
+
});
|
|
2084
|
+
}
|
|
2085
|
+
};
|
|
2086
|
+
|
|
2087
|
+
// node_modules/hono/dist/middleware/cors/index.js
|
|
2088
|
+
var cors = (options) => {
|
|
2089
|
+
const defaults = {
|
|
2090
|
+
origin: "*",
|
|
2091
|
+
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
|
2092
|
+
allowHeaders: [],
|
|
2093
|
+
exposeHeaders: []
|
|
2094
|
+
};
|
|
2095
|
+
const opts = {
|
|
2096
|
+
...defaults,
|
|
2097
|
+
...options
|
|
2098
|
+
};
|
|
2099
|
+
const findAllowOrigin = ((optsOrigin) => {
|
|
2100
|
+
if (typeof optsOrigin === "string") {
|
|
2101
|
+
if (optsOrigin === "*") {
|
|
2102
|
+
if (opts.credentials) {
|
|
2103
|
+
return (origin) => origin || null;
|
|
2104
|
+
}
|
|
2105
|
+
return () => optsOrigin;
|
|
2106
|
+
} else {
|
|
2107
|
+
return (origin) => optsOrigin === origin ? origin : null;
|
|
2108
|
+
}
|
|
2109
|
+
} else if (typeof optsOrigin === "function") {
|
|
2110
|
+
return optsOrigin;
|
|
2111
|
+
} else {
|
|
2112
|
+
return (origin) => optsOrigin.includes(origin) ? origin : null;
|
|
2113
|
+
}
|
|
2114
|
+
})(opts.origin);
|
|
2115
|
+
const findAllowMethods = ((optsAllowMethods) => {
|
|
2116
|
+
if (typeof optsAllowMethods === "function") {
|
|
2117
|
+
return optsAllowMethods;
|
|
2118
|
+
} else if (Array.isArray(optsAllowMethods)) {
|
|
2119
|
+
return () => optsAllowMethods;
|
|
2120
|
+
} else {
|
|
2121
|
+
return () => [];
|
|
2122
|
+
}
|
|
2123
|
+
})(opts.allowMethods);
|
|
2124
|
+
return async function cors2(c, next) {
|
|
2125
|
+
function set(key, value) {
|
|
2126
|
+
c.res.headers.set(key, value);
|
|
2127
|
+
}
|
|
2128
|
+
const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
|
|
2129
|
+
if (allowOrigin) {
|
|
2130
|
+
set("Access-Control-Allow-Origin", allowOrigin);
|
|
2131
|
+
}
|
|
2132
|
+
if (opts.credentials) {
|
|
2133
|
+
set("Access-Control-Allow-Credentials", "true");
|
|
2134
|
+
}
|
|
2135
|
+
if (opts.exposeHeaders?.length) {
|
|
2136
|
+
set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
|
|
2137
|
+
}
|
|
2138
|
+
if (c.req.method === "OPTIONS") {
|
|
2139
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
2140
|
+
set("Vary", "Origin");
|
|
2141
|
+
}
|
|
2142
|
+
if (opts.maxAge != null) {
|
|
2143
|
+
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
2144
|
+
}
|
|
2145
|
+
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
2146
|
+
if (allowMethods.length) {
|
|
2147
|
+
set("Access-Control-Allow-Methods", allowMethods.join(","));
|
|
2148
|
+
}
|
|
2149
|
+
let headers = opts.allowHeaders;
|
|
2150
|
+
if (!headers?.length) {
|
|
2151
|
+
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
2152
|
+
if (requestHeaders) {
|
|
2153
|
+
headers = requestHeaders.split(/\s*,\s*/);
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
if (headers?.length) {
|
|
2157
|
+
set("Access-Control-Allow-Headers", headers.join(","));
|
|
2158
|
+
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
2159
|
+
}
|
|
2160
|
+
c.res.headers.delete("Content-Length");
|
|
2161
|
+
c.res.headers.delete("Content-Type");
|
|
2162
|
+
return new Response(null, {
|
|
2163
|
+
headers: c.res.headers,
|
|
2164
|
+
status: 204,
|
|
2165
|
+
statusText: "No Content"
|
|
2166
|
+
});
|
|
2167
|
+
}
|
|
2168
|
+
await next();
|
|
2169
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
2170
|
+
c.header("Vary", "Origin", { append: true });
|
|
2171
|
+
}
|
|
2172
|
+
};
|
|
2173
|
+
};
|
|
2174
|
+
|
|
2175
|
+
// node_modules/@hono/node-server/dist/index.mjs
|
|
2176
|
+
import { createServer as createServerHTTP } from "http";
|
|
2177
|
+
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
|
2178
|
+
import { Http2ServerRequest } from "http2";
|
|
2179
|
+
import { Readable } from "stream";
|
|
2180
|
+
import crypto from "crypto";
|
|
2181
|
+
var RequestError = class extends Error {
|
|
2182
|
+
constructor(message, options) {
|
|
2183
|
+
super(message, options);
|
|
2184
|
+
this.name = "RequestError";
|
|
2185
|
+
}
|
|
2186
|
+
};
|
|
2187
|
+
var toRequestError = (e) => {
|
|
2188
|
+
if (e instanceof RequestError) {
|
|
2189
|
+
return e;
|
|
2190
|
+
}
|
|
2191
|
+
return new RequestError(e.message, { cause: e });
|
|
2192
|
+
};
|
|
2193
|
+
var GlobalRequest = global.Request;
|
|
2194
|
+
var Request2 = class extends GlobalRequest {
|
|
2195
|
+
constructor(input, options) {
|
|
2196
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
2197
|
+
input = input[getRequestCache]();
|
|
2198
|
+
}
|
|
2199
|
+
if (typeof options?.body?.getReader !== "undefined") {
|
|
2200
|
+
;
|
|
2201
|
+
options.duplex ??= "half";
|
|
2202
|
+
}
|
|
2203
|
+
super(input, options);
|
|
2204
|
+
}
|
|
2205
|
+
};
|
|
2206
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
2207
|
+
const headerRecord = [];
|
|
2208
|
+
const rawHeaders = incoming.rawHeaders;
|
|
2209
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
2210
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
2211
|
+
if (key.charCodeAt(0) !== /*:*/
|
|
2212
|
+
58) {
|
|
2213
|
+
headerRecord.push([key, value]);
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
return new Headers(headerRecord);
|
|
2217
|
+
};
|
|
2218
|
+
var wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
|
|
2219
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
2220
|
+
const init = {
|
|
2221
|
+
method,
|
|
2222
|
+
headers,
|
|
2223
|
+
signal: abortController.signal
|
|
2224
|
+
};
|
|
2225
|
+
if (method === "TRACE") {
|
|
2226
|
+
init.method = "GET";
|
|
2227
|
+
const req = new Request2(url, init);
|
|
2228
|
+
Object.defineProperty(req, "method", {
|
|
2229
|
+
get() {
|
|
2230
|
+
return "TRACE";
|
|
2231
|
+
}
|
|
2232
|
+
});
|
|
2233
|
+
return req;
|
|
2234
|
+
}
|
|
2235
|
+
if (!(method === "GET" || method === "HEAD")) {
|
|
2236
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
|
2237
|
+
init.body = new ReadableStream({
|
|
2238
|
+
start(controller) {
|
|
2239
|
+
controller.enqueue(incoming.rawBody);
|
|
2240
|
+
controller.close();
|
|
2241
|
+
}
|
|
2242
|
+
});
|
|
2243
|
+
} else if (incoming[wrapBodyStream]) {
|
|
2244
|
+
let reader;
|
|
2245
|
+
init.body = new ReadableStream({
|
|
2246
|
+
async pull(controller) {
|
|
2247
|
+
try {
|
|
2248
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
2249
|
+
const { done, value } = await reader.read();
|
|
2250
|
+
if (done) {
|
|
2251
|
+
controller.close();
|
|
2252
|
+
} else {
|
|
2253
|
+
controller.enqueue(value);
|
|
2254
|
+
}
|
|
2255
|
+
} catch (error) {
|
|
2256
|
+
controller.error(error);
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
});
|
|
2260
|
+
} else {
|
|
2261
|
+
init.body = Readable.toWeb(incoming);
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
return new Request2(url, init);
|
|
2265
|
+
};
|
|
2266
|
+
var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
|
|
2267
|
+
var requestCache = /* @__PURE__ */ Symbol("requestCache");
|
|
2268
|
+
var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
|
|
2269
|
+
var urlKey = /* @__PURE__ */ Symbol("urlKey");
|
|
2270
|
+
var headersKey = /* @__PURE__ */ Symbol("headersKey");
|
|
2271
|
+
var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
|
|
2272
|
+
var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
|
|
2273
|
+
var requestPrototype = {
|
|
2274
|
+
get method() {
|
|
2275
|
+
return this[incomingKey].method || "GET";
|
|
2276
|
+
},
|
|
2277
|
+
get url() {
|
|
2278
|
+
return this[urlKey];
|
|
2279
|
+
},
|
|
2280
|
+
get headers() {
|
|
2281
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
2282
|
+
},
|
|
2283
|
+
[getAbortController]() {
|
|
2284
|
+
this[getRequestCache]();
|
|
2285
|
+
return this[abortControllerKey];
|
|
2286
|
+
},
|
|
2287
|
+
[getRequestCache]() {
|
|
2288
|
+
this[abortControllerKey] ||= new AbortController();
|
|
2289
|
+
return this[requestCache] ||= newRequestFromIncoming(
|
|
2290
|
+
this.method,
|
|
2291
|
+
this[urlKey],
|
|
2292
|
+
this.headers,
|
|
2293
|
+
this[incomingKey],
|
|
2294
|
+
this[abortControllerKey]
|
|
2295
|
+
);
|
|
2296
|
+
}
|
|
2297
|
+
};
|
|
2298
|
+
[
|
|
2299
|
+
"body",
|
|
2300
|
+
"bodyUsed",
|
|
2301
|
+
"cache",
|
|
2302
|
+
"credentials",
|
|
2303
|
+
"destination",
|
|
2304
|
+
"integrity",
|
|
2305
|
+
"mode",
|
|
2306
|
+
"redirect",
|
|
2307
|
+
"referrer",
|
|
2308
|
+
"referrerPolicy",
|
|
2309
|
+
"signal",
|
|
2310
|
+
"keepalive"
|
|
2311
|
+
].forEach((k) => {
|
|
2312
|
+
Object.defineProperty(requestPrototype, k, {
|
|
2313
|
+
get() {
|
|
2314
|
+
return this[getRequestCache]()[k];
|
|
2315
|
+
}
|
|
2316
|
+
});
|
|
2317
|
+
});
|
|
2318
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
2319
|
+
Object.defineProperty(requestPrototype, k, {
|
|
2320
|
+
value: function() {
|
|
2321
|
+
return this[getRequestCache]()[k]();
|
|
2322
|
+
}
|
|
2323
|
+
});
|
|
2324
|
+
});
|
|
2325
|
+
Object.setPrototypeOf(requestPrototype, Request2.prototype);
|
|
2326
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
2327
|
+
const req = Object.create(requestPrototype);
|
|
2328
|
+
req[incomingKey] = incoming;
|
|
2329
|
+
const incomingUrl = incoming.url || "";
|
|
2330
|
+
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
|
2331
|
+
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
2332
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
2333
|
+
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
2334
|
+
}
|
|
2335
|
+
try {
|
|
2336
|
+
const url2 = new URL(incomingUrl);
|
|
2337
|
+
req[urlKey] = url2.href;
|
|
2338
|
+
} catch (e) {
|
|
2339
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
2340
|
+
}
|
|
2341
|
+
return req;
|
|
2342
|
+
}
|
|
2343
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
2344
|
+
if (!host) {
|
|
2345
|
+
throw new RequestError("Missing host header");
|
|
2346
|
+
}
|
|
2347
|
+
let scheme;
|
|
2348
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
2349
|
+
scheme = incoming.scheme;
|
|
2350
|
+
if (!(scheme === "http" || scheme === "https")) {
|
|
2351
|
+
throw new RequestError("Unsupported scheme");
|
|
2352
|
+
}
|
|
2353
|
+
} else {
|
|
2354
|
+
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
2355
|
+
}
|
|
2356
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
2357
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
|
2358
|
+
throw new RequestError("Invalid host header");
|
|
2359
|
+
}
|
|
2360
|
+
req[urlKey] = url.href;
|
|
2361
|
+
return req;
|
|
2362
|
+
};
|
|
2363
|
+
var responseCache = /* @__PURE__ */ Symbol("responseCache");
|
|
2364
|
+
var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
|
|
2365
|
+
var cacheKey = /* @__PURE__ */ Symbol("cache");
|
|
2366
|
+
var GlobalResponse = global.Response;
|
|
2367
|
+
var Response2 = class _Response {
|
|
2368
|
+
#body;
|
|
2369
|
+
#init;
|
|
2370
|
+
[getResponseCache]() {
|
|
2371
|
+
delete this[cacheKey];
|
|
2372
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
2373
|
+
}
|
|
2374
|
+
constructor(body, init) {
|
|
2375
|
+
let headers;
|
|
2376
|
+
this.#body = body;
|
|
2377
|
+
if (init instanceof _Response) {
|
|
2378
|
+
const cachedGlobalResponse = init[responseCache];
|
|
2379
|
+
if (cachedGlobalResponse) {
|
|
2380
|
+
this.#init = cachedGlobalResponse;
|
|
2381
|
+
this[getResponseCache]();
|
|
2382
|
+
return;
|
|
2383
|
+
} else {
|
|
2384
|
+
this.#init = init.#init;
|
|
2385
|
+
headers = new Headers(init.#init.headers);
|
|
2386
|
+
}
|
|
2387
|
+
} else {
|
|
2388
|
+
this.#init = init;
|
|
2389
|
+
}
|
|
2390
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
|
2391
|
+
;
|
|
2392
|
+
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
get headers() {
|
|
2396
|
+
const cache = this[cacheKey];
|
|
2397
|
+
if (cache) {
|
|
2398
|
+
if (!(cache[2] instanceof Headers)) {
|
|
2399
|
+
cache[2] = new Headers(
|
|
2400
|
+
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
|
2401
|
+
);
|
|
2402
|
+
}
|
|
2403
|
+
return cache[2];
|
|
2404
|
+
}
|
|
2405
|
+
return this[getResponseCache]().headers;
|
|
2406
|
+
}
|
|
2407
|
+
get status() {
|
|
2408
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
2409
|
+
}
|
|
2410
|
+
get ok() {
|
|
2411
|
+
const status = this.status;
|
|
2412
|
+
return status >= 200 && status < 300;
|
|
2413
|
+
}
|
|
2414
|
+
};
|
|
2415
|
+
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
|
2416
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
2417
|
+
get() {
|
|
2418
|
+
return this[getResponseCache]()[k];
|
|
2419
|
+
}
|
|
2420
|
+
});
|
|
2421
|
+
});
|
|
2422
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
2423
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
2424
|
+
value: function() {
|
|
2425
|
+
return this[getResponseCache]()[k]();
|
|
2426
|
+
}
|
|
2427
|
+
});
|
|
2428
|
+
});
|
|
2429
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
2430
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
2431
|
+
async function readWithoutBlocking(readPromise) {
|
|
2432
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
2433
|
+
}
|
|
2434
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
2435
|
+
const cancel = (error) => {
|
|
2436
|
+
reader.cancel(error).catch(() => {
|
|
2437
|
+
});
|
|
2438
|
+
};
|
|
2439
|
+
writable.on("close", cancel);
|
|
2440
|
+
writable.on("error", cancel);
|
|
2441
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
2442
|
+
return reader.closed.finally(() => {
|
|
2443
|
+
writable.off("close", cancel);
|
|
2444
|
+
writable.off("error", cancel);
|
|
2445
|
+
});
|
|
2446
|
+
function handleStreamError(error) {
|
|
2447
|
+
if (error) {
|
|
2448
|
+
writable.destroy(error);
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
function onDrain() {
|
|
2452
|
+
reader.read().then(flow, handleStreamError);
|
|
2453
|
+
}
|
|
2454
|
+
function flow({ done, value }) {
|
|
2455
|
+
try {
|
|
2456
|
+
if (done) {
|
|
2457
|
+
writable.end();
|
|
2458
|
+
} else if (!writable.write(value)) {
|
|
2459
|
+
writable.once("drain", onDrain);
|
|
2460
|
+
} else {
|
|
2461
|
+
return reader.read().then(flow, handleStreamError);
|
|
2462
|
+
}
|
|
2463
|
+
} catch (e) {
|
|
2464
|
+
handleStreamError(e);
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
function writeFromReadableStream(stream, writable) {
|
|
2469
|
+
if (stream.locked) {
|
|
2470
|
+
throw new TypeError("ReadableStream is locked.");
|
|
2471
|
+
} else if (writable.destroyed) {
|
|
2472
|
+
return;
|
|
2473
|
+
}
|
|
2474
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
2475
|
+
}
|
|
2476
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
2477
|
+
const res = {};
|
|
2478
|
+
if (!(headers instanceof Headers)) {
|
|
2479
|
+
headers = new Headers(headers ?? void 0);
|
|
2480
|
+
}
|
|
2481
|
+
const cookies = [];
|
|
2482
|
+
for (const [k, v] of headers) {
|
|
2483
|
+
if (k === "set-cookie") {
|
|
2484
|
+
cookies.push(v);
|
|
2485
|
+
} else {
|
|
2486
|
+
res[k] = v;
|
|
2487
|
+
}
|
|
2488
|
+
}
|
|
2489
|
+
if (cookies.length > 0) {
|
|
2490
|
+
res["set-cookie"] = cookies;
|
|
2491
|
+
}
|
|
2492
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
2493
|
+
return res;
|
|
2494
|
+
};
|
|
2495
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
2496
|
+
if (typeof global.crypto === "undefined") {
|
|
2497
|
+
global.crypto = crypto;
|
|
2498
|
+
}
|
|
2499
|
+
var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
|
|
2500
|
+
var incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
|
|
2501
|
+
var DRAIN_TIMEOUT_MS = 500;
|
|
2502
|
+
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
2503
|
+
var drainIncoming = (incoming) => {
|
|
2504
|
+
const incomingWithDrainState = incoming;
|
|
2505
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
|
2506
|
+
return;
|
|
2507
|
+
}
|
|
2508
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
2509
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
2510
|
+
try {
|
|
2511
|
+
;
|
|
2512
|
+
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
|
2513
|
+
} catch {
|
|
2514
|
+
}
|
|
2515
|
+
return;
|
|
2516
|
+
}
|
|
2517
|
+
let bytesRead = 0;
|
|
2518
|
+
const cleanup = () => {
|
|
2519
|
+
clearTimeout(timer);
|
|
2520
|
+
incoming.off("data", onData);
|
|
2521
|
+
incoming.off("end", cleanup);
|
|
2522
|
+
incoming.off("error", cleanup);
|
|
2523
|
+
};
|
|
2524
|
+
const forceClose = () => {
|
|
2525
|
+
cleanup();
|
|
2526
|
+
const socket = incoming.socket;
|
|
2527
|
+
if (socket && !socket.destroyed) {
|
|
2528
|
+
socket.destroySoon();
|
|
2529
|
+
}
|
|
2530
|
+
};
|
|
2531
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
2532
|
+
timer.unref?.();
|
|
2533
|
+
const onData = (chunk) => {
|
|
2534
|
+
bytesRead += chunk.length;
|
|
2535
|
+
if (bytesRead > MAX_DRAIN_BYTES) {
|
|
2536
|
+
forceClose();
|
|
2537
|
+
}
|
|
2538
|
+
};
|
|
2539
|
+
incoming.on("data", onData);
|
|
2540
|
+
incoming.on("end", cleanup);
|
|
2541
|
+
incoming.on("error", cleanup);
|
|
2542
|
+
incoming.resume();
|
|
2543
|
+
};
|
|
2544
|
+
var handleRequestError = () => new Response(null, {
|
|
2545
|
+
status: 400
|
|
2546
|
+
});
|
|
2547
|
+
var handleFetchError = (e) => new Response(null, {
|
|
2548
|
+
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
|
2549
|
+
});
|
|
2550
|
+
var handleResponseError = (e, outgoing) => {
|
|
2551
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
2552
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
2553
|
+
console.info("The user aborted a request.");
|
|
2554
|
+
} else {
|
|
2555
|
+
console.error(e);
|
|
2556
|
+
if (!outgoing.headersSent) {
|
|
2557
|
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
2558
|
+
}
|
|
2559
|
+
outgoing.end(`Error: ${err.message}`);
|
|
2560
|
+
outgoing.destroy(err);
|
|
2561
|
+
}
|
|
2562
|
+
};
|
|
2563
|
+
var flushHeaders = (outgoing) => {
|
|
2564
|
+
if ("flushHeaders" in outgoing && outgoing.writable) {
|
|
2565
|
+
outgoing.flushHeaders();
|
|
2566
|
+
}
|
|
2567
|
+
};
|
|
2568
|
+
var responseViaCache = async (res, outgoing) => {
|
|
2569
|
+
let [status, body, header] = res[cacheKey];
|
|
2570
|
+
let hasContentLength = false;
|
|
2571
|
+
if (!header) {
|
|
2572
|
+
header = { "content-type": "text/plain; charset=UTF-8" };
|
|
2573
|
+
} else if (header instanceof Headers) {
|
|
2574
|
+
hasContentLength = header.has("content-length");
|
|
2575
|
+
header = buildOutgoingHttpHeaders(header);
|
|
2576
|
+
} else if (Array.isArray(header)) {
|
|
2577
|
+
const headerObj = new Headers(header);
|
|
2578
|
+
hasContentLength = headerObj.has("content-length");
|
|
2579
|
+
header = buildOutgoingHttpHeaders(headerObj);
|
|
2580
|
+
} else {
|
|
2581
|
+
for (const key in header) {
|
|
2582
|
+
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
2583
|
+
hasContentLength = true;
|
|
2584
|
+
break;
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
if (!hasContentLength) {
|
|
2589
|
+
if (typeof body === "string") {
|
|
2590
|
+
header["Content-Length"] = Buffer.byteLength(body);
|
|
2591
|
+
} else if (body instanceof Uint8Array) {
|
|
2592
|
+
header["Content-Length"] = body.byteLength;
|
|
2593
|
+
} else if (body instanceof Blob) {
|
|
2594
|
+
header["Content-Length"] = body.size;
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
outgoing.writeHead(status, header);
|
|
2598
|
+
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
2599
|
+
outgoing.end(body);
|
|
2600
|
+
} else if (body instanceof Blob) {
|
|
2601
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
2602
|
+
} else {
|
|
2603
|
+
flushHeaders(outgoing);
|
|
2604
|
+
await writeFromReadableStream(body, outgoing)?.catch(
|
|
2605
|
+
(e) => handleResponseError(e, outgoing)
|
|
2606
|
+
);
|
|
2607
|
+
}
|
|
2608
|
+
;
|
|
2609
|
+
outgoing[outgoingEnded]?.();
|
|
2610
|
+
};
|
|
2611
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
2612
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
2613
|
+
if (isPromise(res)) {
|
|
2614
|
+
if (options.errorHandler) {
|
|
2615
|
+
try {
|
|
2616
|
+
res = await res;
|
|
2617
|
+
} catch (err) {
|
|
2618
|
+
const errRes = await options.errorHandler(err);
|
|
2619
|
+
if (!errRes) {
|
|
2620
|
+
return;
|
|
2621
|
+
}
|
|
2622
|
+
res = errRes;
|
|
2623
|
+
}
|
|
2624
|
+
} else {
|
|
2625
|
+
res = await res.catch(handleFetchError);
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
if (cacheKey in res) {
|
|
2629
|
+
return responseViaCache(res, outgoing);
|
|
2630
|
+
}
|
|
2631
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
2632
|
+
if (res.body) {
|
|
2633
|
+
const reader = res.body.getReader();
|
|
2634
|
+
const values = [];
|
|
2635
|
+
let done = false;
|
|
2636
|
+
let currentReadPromise = void 0;
|
|
2637
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
2638
|
+
let maxReadCount = 2;
|
|
2639
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
2640
|
+
currentReadPromise ||= reader.read();
|
|
2641
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
2642
|
+
console.error(e);
|
|
2643
|
+
done = true;
|
|
2644
|
+
});
|
|
2645
|
+
if (!chunk) {
|
|
2646
|
+
if (i === 1) {
|
|
2647
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
2648
|
+
maxReadCount = 3;
|
|
2649
|
+
continue;
|
|
2650
|
+
}
|
|
2651
|
+
break;
|
|
2652
|
+
}
|
|
2653
|
+
currentReadPromise = void 0;
|
|
2654
|
+
if (chunk.value) {
|
|
2655
|
+
values.push(chunk.value);
|
|
2656
|
+
}
|
|
2657
|
+
if (chunk.done) {
|
|
2658
|
+
done = true;
|
|
2659
|
+
break;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
if (done && !("content-length" in resHeaderRecord)) {
|
|
2663
|
+
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
2667
|
+
values.forEach((value) => {
|
|
2668
|
+
;
|
|
2669
|
+
outgoing.write(value);
|
|
2670
|
+
});
|
|
2671
|
+
if (done) {
|
|
2672
|
+
outgoing.end();
|
|
2673
|
+
} else {
|
|
2674
|
+
if (values.length === 0) {
|
|
2675
|
+
flushHeaders(outgoing);
|
|
2676
|
+
}
|
|
2677
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
2678
|
+
}
|
|
2679
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
|
2680
|
+
} else {
|
|
2681
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
2682
|
+
outgoing.end();
|
|
2683
|
+
}
|
|
2684
|
+
;
|
|
2685
|
+
outgoing[outgoingEnded]?.();
|
|
2686
|
+
};
|
|
2687
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
2688
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
2689
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
|
|
2690
|
+
Object.defineProperty(global, "Request", {
|
|
2691
|
+
value: Request2
|
|
2692
|
+
});
|
|
2693
|
+
Object.defineProperty(global, "Response", {
|
|
2694
|
+
value: Response2
|
|
2695
|
+
});
|
|
2696
|
+
}
|
|
2697
|
+
return async (incoming, outgoing) => {
|
|
2698
|
+
let res, req;
|
|
2699
|
+
try {
|
|
2700
|
+
req = newRequest(incoming, options.hostname);
|
|
2701
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
2702
|
+
if (!incomingEnded) {
|
|
2703
|
+
;
|
|
2704
|
+
incoming[wrapBodyStream] = true;
|
|
2705
|
+
incoming.on("end", () => {
|
|
2706
|
+
incomingEnded = true;
|
|
2707
|
+
});
|
|
2708
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
2709
|
+
;
|
|
2710
|
+
outgoing[outgoingEnded] = () => {
|
|
2711
|
+
if (!incomingEnded) {
|
|
2712
|
+
setTimeout(() => {
|
|
2713
|
+
if (!incomingEnded) {
|
|
2714
|
+
setTimeout(() => {
|
|
2715
|
+
drainIncoming(incoming);
|
|
2716
|
+
});
|
|
2717
|
+
}
|
|
2718
|
+
});
|
|
2719
|
+
}
|
|
2720
|
+
};
|
|
2721
|
+
}
|
|
2722
|
+
outgoing.on("finish", () => {
|
|
2723
|
+
if (!incomingEnded) {
|
|
2724
|
+
drainIncoming(incoming);
|
|
2725
|
+
}
|
|
2726
|
+
});
|
|
2727
|
+
}
|
|
2728
|
+
outgoing.on("close", () => {
|
|
2729
|
+
const abortController = req[abortControllerKey];
|
|
2730
|
+
if (abortController) {
|
|
2731
|
+
if (incoming.errored) {
|
|
2732
|
+
req[abortControllerKey].abort(incoming.errored.toString());
|
|
2733
|
+
} else if (!outgoing.writableFinished) {
|
|
2734
|
+
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
if (!incomingEnded) {
|
|
2738
|
+
setTimeout(() => {
|
|
2739
|
+
if (!incomingEnded) {
|
|
2740
|
+
setTimeout(() => {
|
|
2741
|
+
drainIncoming(incoming);
|
|
2742
|
+
});
|
|
2743
|
+
}
|
|
2744
|
+
});
|
|
2745
|
+
}
|
|
2746
|
+
});
|
|
2747
|
+
res = fetchCallback(req, { incoming, outgoing });
|
|
2748
|
+
if (cacheKey in res) {
|
|
2749
|
+
return responseViaCache(res, outgoing);
|
|
2750
|
+
}
|
|
2751
|
+
} catch (e) {
|
|
2752
|
+
if (!res) {
|
|
2753
|
+
if (options.errorHandler) {
|
|
2754
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
2755
|
+
if (!res) {
|
|
2756
|
+
return;
|
|
2757
|
+
}
|
|
2758
|
+
} else if (!req) {
|
|
2759
|
+
res = handleRequestError();
|
|
2760
|
+
} else {
|
|
2761
|
+
res = handleFetchError(e);
|
|
2762
|
+
}
|
|
2763
|
+
} else {
|
|
2764
|
+
return handleResponseError(e, outgoing);
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
try {
|
|
2768
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
2769
|
+
} catch (e) {
|
|
2770
|
+
return handleResponseError(e, outgoing);
|
|
2771
|
+
}
|
|
2772
|
+
};
|
|
2773
|
+
};
|
|
2774
|
+
var createAdaptorServer = (options) => {
|
|
2775
|
+
const fetchCallback = options.fetch;
|
|
2776
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
2777
|
+
hostname: options.hostname,
|
|
2778
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
2779
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
2780
|
+
});
|
|
2781
|
+
const createServer = options.createServer || createServerHTTP;
|
|
2782
|
+
const server = createServer(options.serverOptions || {}, requestListener);
|
|
2783
|
+
return server;
|
|
2784
|
+
};
|
|
2785
|
+
var serve = (options, listeningListener) => {
|
|
2786
|
+
const server = createAdaptorServer(options);
|
|
2787
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
2788
|
+
const serverInfo = server.address();
|
|
2789
|
+
listeningListener && listeningListener(serverInfo);
|
|
2790
|
+
});
|
|
2791
|
+
return server;
|
|
2792
|
+
};
|
|
2793
|
+
|
|
2794
|
+
// src/runtime/web-server.ts
|
|
2795
|
+
import { readFileSync, existsSync, writeFileSync, readdirSync, statSync } from "fs";
|
|
2796
|
+
import { join, basename, relative } from "path";
|
|
2797
|
+
var SSEBroadcaster = class {
|
|
2798
|
+
clients = [];
|
|
2799
|
+
nextId = 0;
|
|
2800
|
+
addClient(controller) {
|
|
2801
|
+
const id = String(this.nextId++);
|
|
2802
|
+
this.clients.push({ id, controller });
|
|
2803
|
+
return id;
|
|
2804
|
+
}
|
|
2805
|
+
removeClient(id) {
|
|
2806
|
+
this.clients = this.clients.filter((c) => c.id !== id);
|
|
2807
|
+
}
|
|
2808
|
+
broadcast(event) {
|
|
2809
|
+
const message = `event: ${event.type}
|
|
2810
|
+
data: ${JSON.stringify(event.data)}
|
|
2811
|
+
|
|
2812
|
+
`;
|
|
2813
|
+
const encoder = new TextEncoder();
|
|
2814
|
+
const encoded = encoder.encode(message);
|
|
2815
|
+
for (const client of this.clients) {
|
|
2816
|
+
try {
|
|
2817
|
+
client.controller.enqueue(encoded);
|
|
2818
|
+
} catch {
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
get clientCount() {
|
|
2823
|
+
return this.clients.length;
|
|
2824
|
+
}
|
|
2825
|
+
};
|
|
2826
|
+
function buildFileTree(baseDir, dirPath, maxDepth = 3, depth = 0) {
|
|
2827
|
+
if (depth >= maxDepth || !existsSync(dirPath)) return [];
|
|
2828
|
+
const entries = readdirSync(dirPath);
|
|
2829
|
+
const nodes = [];
|
|
2830
|
+
for (const entry of entries) {
|
|
2831
|
+
if (entry.startsWith(".") && entry !== ".gitignore") continue;
|
|
2832
|
+
if (entry === "node_modules") continue;
|
|
2833
|
+
const fullPath = join(dirPath, entry);
|
|
2834
|
+
const relPath = relative(baseDir, fullPath);
|
|
2835
|
+
try {
|
|
2836
|
+
const stat = statSync(fullPath);
|
|
2837
|
+
if (stat.isDirectory()) {
|
|
2838
|
+
nodes.push({
|
|
2839
|
+
name: entry,
|
|
2840
|
+
path: relPath,
|
|
2841
|
+
type: "directory",
|
|
2842
|
+
children: buildFileTree(baseDir, fullPath, maxDepth, depth + 1)
|
|
2843
|
+
});
|
|
2844
|
+
} else {
|
|
2845
|
+
nodes.push({
|
|
2846
|
+
name: entry,
|
|
2847
|
+
path: relPath,
|
|
2848
|
+
type: "file",
|
|
2849
|
+
size: stat.size,
|
|
2850
|
+
modified: stat.mtime.toISOString()
|
|
2851
|
+
});
|
|
2852
|
+
}
|
|
2853
|
+
} catch {
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
return nodes.sort((a, b) => {
|
|
2857
|
+
if (a.type !== b.type) return a.type === "directory" ? -1 : 1;
|
|
2858
|
+
return a.name.localeCompare(b.name);
|
|
2859
|
+
});
|
|
2860
|
+
}
|
|
2861
|
+
function createWebApp(harnessDir, options) {
|
|
2862
|
+
const app = new Hono2();
|
|
2863
|
+
const broadcaster = new SSEBroadcaster();
|
|
2864
|
+
let conversation = null;
|
|
2865
|
+
app.use("*", cors({
|
|
2866
|
+
origin: "*",
|
|
2867
|
+
allowMethods: ["GET", "POST", "PUT"],
|
|
2868
|
+
allowHeaders: ["Content-Type"]
|
|
2869
|
+
}));
|
|
2870
|
+
app.get("/api/snapshot", (c) => {
|
|
2871
|
+
try {
|
|
2872
|
+
const snapshot = collectSnapshot(harnessDir);
|
|
2873
|
+
return c.json(snapshot);
|
|
2874
|
+
} catch (err) {
|
|
2875
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to collect snapshot" }, 500);
|
|
2876
|
+
}
|
|
2877
|
+
});
|
|
2878
|
+
app.get("/api/config", (c) => {
|
|
2879
|
+
try {
|
|
2880
|
+
const config = loadConfig(harnessDir);
|
|
2881
|
+
return c.json(config);
|
|
2882
|
+
} catch (err) {
|
|
2883
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to load config" }, 500);
|
|
2884
|
+
}
|
|
2885
|
+
});
|
|
2886
|
+
app.get("/api/state", (c) => {
|
|
2887
|
+
try {
|
|
2888
|
+
const state = loadState(harnessDir);
|
|
2889
|
+
return c.json(state);
|
|
2890
|
+
} catch (err) {
|
|
2891
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to load state" }, 500);
|
|
2892
|
+
}
|
|
2893
|
+
});
|
|
2894
|
+
app.put("/api/state", async (c) => {
|
|
2895
|
+
try {
|
|
2896
|
+
const body = await c.req.json();
|
|
2897
|
+
const current = loadState(harnessDir);
|
|
2898
|
+
const updated = { ...current, ...body };
|
|
2899
|
+
saveState(harnessDir, updated);
|
|
2900
|
+
return c.json(updated);
|
|
2901
|
+
} catch (err) {
|
|
2902
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to update state" }, 500);
|
|
2903
|
+
}
|
|
2904
|
+
});
|
|
2905
|
+
app.get("/api/primitives", (c) => {
|
|
2906
|
+
try {
|
|
2907
|
+
const config = loadConfig(harnessDir);
|
|
2908
|
+
const extDirs = config.extensions?.directories ?? [];
|
|
2909
|
+
const all = loadAllPrimitives(harnessDir, extDirs);
|
|
2910
|
+
const result = {};
|
|
2911
|
+
for (const [dir, docs] of all.entries()) {
|
|
2912
|
+
result[dir] = docs.map((doc) => ({
|
|
2913
|
+
id: doc.frontmatter.id ?? basename(doc.path, ".md"),
|
|
2914
|
+
path: doc.path,
|
|
2915
|
+
l0: doc.l0,
|
|
2916
|
+
tags: doc.frontmatter.tags ?? []
|
|
2917
|
+
}));
|
|
2918
|
+
}
|
|
2919
|
+
return c.json(result);
|
|
2920
|
+
} catch (err) {
|
|
2921
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to load primitives" }, 500);
|
|
2922
|
+
}
|
|
2923
|
+
});
|
|
2924
|
+
app.get("/api/primitives/:type", (c) => {
|
|
2925
|
+
const type = c.req.param("type");
|
|
2926
|
+
if (!CORE_PRIMITIVE_DIRS.includes(type) && type !== "intake") {
|
|
2927
|
+
return c.json({ error: `Unknown primitive type: ${type}` }, 404);
|
|
2928
|
+
}
|
|
2929
|
+
try {
|
|
2930
|
+
const dirPath = join(harnessDir, type);
|
|
2931
|
+
if (!existsSync(dirPath)) {
|
|
2932
|
+
return c.json([]);
|
|
2933
|
+
}
|
|
2934
|
+
const docs = loadDirectory(dirPath);
|
|
2935
|
+
return c.json(docs.map(serializeDoc));
|
|
2936
|
+
} catch (err) {
|
|
2937
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to load primitives" }, 500);
|
|
2938
|
+
}
|
|
2939
|
+
});
|
|
2940
|
+
app.get("/api/primitives/:type/:file", (c) => {
|
|
2941
|
+
const type = c.req.param("type");
|
|
2942
|
+
const file = c.req.param("file");
|
|
2943
|
+
const filePath = join(harnessDir, type, file.endsWith(".md") ? file : `${file}.md`);
|
|
2944
|
+
if (!existsSync(filePath)) {
|
|
2945
|
+
return c.json({ error: `Primitive not found: ${type}/${file}` }, 404);
|
|
2946
|
+
}
|
|
2947
|
+
try {
|
|
2948
|
+
const doc = parseHarnessDocument(filePath);
|
|
2949
|
+
return c.json(serializeDoc(doc));
|
|
2950
|
+
} catch (err) {
|
|
2951
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to parse primitive" }, 500);
|
|
2952
|
+
}
|
|
2953
|
+
});
|
|
2954
|
+
app.put("/api/primitives/:type/:file", async (c) => {
|
|
2955
|
+
const type = c.req.param("type");
|
|
2956
|
+
const file = c.req.param("file");
|
|
2957
|
+
const filePath = join(harnessDir, type, file.endsWith(".md") ? file : `${file}.md`);
|
|
2958
|
+
if (!existsSync(filePath)) {
|
|
2959
|
+
return c.json({ error: `Primitive not found: ${type}/${file}` }, 404);
|
|
2960
|
+
}
|
|
2961
|
+
try {
|
|
2962
|
+
const body = await c.req.json();
|
|
2963
|
+
if (typeof body.content !== "string") {
|
|
2964
|
+
return c.json({ error: 'Request body must have a "content" string field' }, 400);
|
|
2965
|
+
}
|
|
2966
|
+
writeFileSync(filePath, body.content, "utf-8");
|
|
2967
|
+
const doc = parseHarnessDocument(filePath);
|
|
2968
|
+
return c.json(serializeDoc(doc));
|
|
2969
|
+
} catch (err) {
|
|
2970
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to update primitive" }, 500);
|
|
2971
|
+
}
|
|
2972
|
+
});
|
|
2973
|
+
app.get("/api/sessions", (c) => {
|
|
2974
|
+
try {
|
|
2975
|
+
const sessions = listSessions(harnessDir);
|
|
2976
|
+
return c.json(sessions);
|
|
2977
|
+
} catch (err) {
|
|
2978
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to list sessions" }, 500);
|
|
2979
|
+
}
|
|
2980
|
+
});
|
|
2981
|
+
app.get("/api/sessions/:id", (c) => {
|
|
2982
|
+
const id = c.req.param("id");
|
|
2983
|
+
const sessionsDir = join(harnessDir, "memory", "sessions");
|
|
2984
|
+
const filePath = join(sessionsDir, `${id}.md`);
|
|
2985
|
+
if (!existsSync(filePath)) {
|
|
2986
|
+
return c.json({ error: `Session not found: ${id}` }, 404);
|
|
2987
|
+
}
|
|
2988
|
+
try {
|
|
2989
|
+
const content = readFileSync(filePath, "utf-8");
|
|
2990
|
+
return c.json({ id, content });
|
|
2991
|
+
} catch (err) {
|
|
2992
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to read session" }, 500);
|
|
2993
|
+
}
|
|
2994
|
+
});
|
|
2995
|
+
app.post("/api/chat", async (c) => {
|
|
2996
|
+
try {
|
|
2997
|
+
const body = await c.req.json();
|
|
2998
|
+
if (typeof body.message !== "string" || !body.message.trim()) {
|
|
2999
|
+
return c.json({ error: 'Request body must have a non-empty "message" string field' }, 400);
|
|
3000
|
+
}
|
|
3001
|
+
if (!conversation) {
|
|
3002
|
+
conversation = new Conversation(harnessDir, options?.apiKey);
|
|
3003
|
+
await conversation.init();
|
|
3004
|
+
}
|
|
3005
|
+
const result = await conversation.send(body.message);
|
|
3006
|
+
broadcaster.broadcast({
|
|
3007
|
+
type: "chat_response",
|
|
3008
|
+
data: { text: result.text, usage: result.usage, steps: result.steps },
|
|
3009
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
3010
|
+
});
|
|
3011
|
+
return c.json({
|
|
3012
|
+
text: result.text,
|
|
3013
|
+
usage: result.usage,
|
|
3014
|
+
steps: result.steps,
|
|
3015
|
+
toolCalls: result.toolCalls
|
|
3016
|
+
});
|
|
3017
|
+
} catch (err) {
|
|
3018
|
+
return c.json({ error: err instanceof Error ? err.message : "Chat error" }, 500);
|
|
3019
|
+
}
|
|
3020
|
+
});
|
|
3021
|
+
app.post("/api/chat/reset", (c) => {
|
|
3022
|
+
conversation = null;
|
|
3023
|
+
return c.json({ ok: true });
|
|
3024
|
+
});
|
|
3025
|
+
app.get("/api/mcp", (c) => {
|
|
3026
|
+
try {
|
|
3027
|
+
const config = loadConfig(harnessDir);
|
|
3028
|
+
const errors = validateMcpConfig(config);
|
|
3029
|
+
const errorServerNames = new Set(errors.map((e) => e.server));
|
|
3030
|
+
const servers = Object.entries(config.mcp.servers).map(([name, server]) => ({
|
|
3031
|
+
name,
|
|
3032
|
+
transport: server.transport,
|
|
3033
|
+
enabled: server.enabled,
|
|
3034
|
+
valid: !errorServerNames.has(name),
|
|
3035
|
+
command: server.command,
|
|
3036
|
+
url: server.url,
|
|
3037
|
+
error: errors.find((e) => e.server === name)?.error
|
|
3038
|
+
}));
|
|
3039
|
+
return c.json({
|
|
3040
|
+
serverCount: servers.length,
|
|
3041
|
+
enabledCount: servers.filter((s) => s.enabled).length,
|
|
3042
|
+
servers,
|
|
3043
|
+
errors
|
|
3044
|
+
});
|
|
3045
|
+
} catch (err) {
|
|
3046
|
+
return c.json({ error: err instanceof Error ? err.message : "MCP status error" }, 500);
|
|
3047
|
+
}
|
|
3048
|
+
});
|
|
3049
|
+
app.get("/api/files", (c) => {
|
|
3050
|
+
try {
|
|
3051
|
+
const tree = buildFileTree(harnessDir, harnessDir);
|
|
3052
|
+
return c.json(tree);
|
|
3053
|
+
} catch (err) {
|
|
3054
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to build file tree" }, 500);
|
|
3055
|
+
}
|
|
3056
|
+
});
|
|
3057
|
+
app.get("/api/files/*", (c) => {
|
|
3058
|
+
const relPath = c.req.path.replace("/api/files/", "");
|
|
3059
|
+
if (!relPath) {
|
|
3060
|
+
return c.json({ error: "File path required" }, 400);
|
|
3061
|
+
}
|
|
3062
|
+
const filePath = join(harnessDir, relPath);
|
|
3063
|
+
if (!filePath.startsWith(harnessDir)) {
|
|
3064
|
+
return c.json({ error: "Access denied: path traversal detected" }, 403);
|
|
3065
|
+
}
|
|
3066
|
+
if (!existsSync(filePath)) {
|
|
3067
|
+
return c.json({ error: "File not found" }, 404);
|
|
3068
|
+
}
|
|
3069
|
+
try {
|
|
3070
|
+
const stat = statSync(filePath);
|
|
3071
|
+
if (stat.isDirectory()) {
|
|
3072
|
+
return c.json({ error: "Path is a directory, not a file" }, 400);
|
|
3073
|
+
}
|
|
3074
|
+
const content = readFileSync(filePath, "utf-8");
|
|
3075
|
+
return c.json({ path: relPath, content, size: stat.size, modified: stat.mtime.toISOString() });
|
|
3076
|
+
} catch (err) {
|
|
3077
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to read file" }, 500);
|
|
3078
|
+
}
|
|
3079
|
+
});
|
|
3080
|
+
app.put("/api/files/*", async (c) => {
|
|
3081
|
+
const relPath = c.req.path.replace("/api/files/", "");
|
|
3082
|
+
if (!relPath) {
|
|
3083
|
+
return c.json({ error: "File path required" }, 400);
|
|
3084
|
+
}
|
|
3085
|
+
const filePath = join(harnessDir, relPath);
|
|
3086
|
+
if (!filePath.startsWith(harnessDir)) {
|
|
3087
|
+
return c.json({ error: "Access denied: path traversal detected" }, 403);
|
|
3088
|
+
}
|
|
3089
|
+
const allowedPrefixes = ["rules/", "instincts/", "skills/", "playbooks/", "workflows/", "tools/", "agents/"];
|
|
3090
|
+
const allowedFiles = ["CORE.md", "SYSTEM.md", "state.md", "config.yaml"];
|
|
3091
|
+
const isAllowed = allowedPrefixes.some((p) => relPath.startsWith(p)) || allowedFiles.includes(relPath);
|
|
3092
|
+
if (!isAllowed) {
|
|
3093
|
+
return c.json({ error: "Cannot edit files outside primitive directories and core files" }, 403);
|
|
3094
|
+
}
|
|
3095
|
+
try {
|
|
3096
|
+
const body = await c.req.json();
|
|
3097
|
+
if (typeof body.content !== "string") {
|
|
3098
|
+
return c.json({ error: 'Request body must have a "content" string field' }, 400);
|
|
3099
|
+
}
|
|
3100
|
+
writeFileSync(filePath, body.content, "utf-8");
|
|
3101
|
+
return c.json({ ok: true, path: relPath });
|
|
3102
|
+
} catch (err) {
|
|
3103
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to write file" }, 500);
|
|
3104
|
+
}
|
|
3105
|
+
});
|
|
3106
|
+
app.put("/api/config", async (c) => {
|
|
3107
|
+
try {
|
|
3108
|
+
const configPath = join(harnessDir, "config.yaml");
|
|
3109
|
+
const body = await c.req.json();
|
|
3110
|
+
if (typeof body.content !== "string") {
|
|
3111
|
+
return c.json({ error: 'Request body must have a "content" string field' }, 400);
|
|
3112
|
+
}
|
|
3113
|
+
writeFileSync(configPath, body.content, "utf-8");
|
|
3114
|
+
const config = loadConfig(harnessDir);
|
|
3115
|
+
broadcaster.broadcast({
|
|
3116
|
+
type: "config_change",
|
|
3117
|
+
data: { model: config.model.id },
|
|
3118
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
3119
|
+
});
|
|
3120
|
+
return c.json({ ok: true, agent: config.agent.name });
|
|
3121
|
+
} catch (err) {
|
|
3122
|
+
return c.json({ error: err instanceof Error ? err.message : "Failed to update config" }, 500);
|
|
3123
|
+
}
|
|
3124
|
+
});
|
|
3125
|
+
app.get("/api/events", (c) => {
|
|
3126
|
+
const stream = new ReadableStream({
|
|
3127
|
+
start(controller) {
|
|
3128
|
+
const clientId = broadcaster.addClient(controller);
|
|
3129
|
+
const encoder = new TextEncoder();
|
|
3130
|
+
const connectMsg = `event: connected
|
|
3131
|
+
data: ${JSON.stringify({ clientId, timestamp: (/* @__PURE__ */ new Date()).toISOString() })}
|
|
3132
|
+
|
|
3133
|
+
`;
|
|
3134
|
+
controller.enqueue(encoder.encode(connectMsg));
|
|
3135
|
+
c.req.raw.signal.addEventListener("abort", () => {
|
|
3136
|
+
broadcaster.removeClient(clientId);
|
|
3137
|
+
});
|
|
3138
|
+
},
|
|
3139
|
+
cancel() {
|
|
3140
|
+
}
|
|
3141
|
+
});
|
|
3142
|
+
return new Response(stream, {
|
|
3143
|
+
headers: {
|
|
3144
|
+
"Content-Type": "text/event-stream",
|
|
3145
|
+
"Cache-Control": "no-cache",
|
|
3146
|
+
"Connection": "keep-alive"
|
|
3147
|
+
}
|
|
3148
|
+
});
|
|
3149
|
+
});
|
|
3150
|
+
app.get("/api/events/clients", (c) => {
|
|
3151
|
+
return c.json({ count: broadcaster.clientCount });
|
|
3152
|
+
});
|
|
3153
|
+
app.get("/", (c) => {
|
|
3154
|
+
return c.html(buildDashboardHtml(harnessDir));
|
|
3155
|
+
});
|
|
3156
|
+
return { app, broadcaster };
|
|
3157
|
+
}
|
|
3158
|
+
async function startWebServer(options) {
|
|
3159
|
+
const { harnessDir, port: preferredPort = 3e3, apiKey, onStart } = options;
|
|
3160
|
+
const { app, broadcaster } = createWebApp(harnessDir, { apiKey });
|
|
3161
|
+
const maxAttempts = 10;
|
|
3162
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
3163
|
+
const port = preferredPort + attempt;
|
|
3164
|
+
try {
|
|
3165
|
+
const server = await new Promise((resolve, reject) => {
|
|
3166
|
+
const s = serve({ fetch: app.fetch, port }, () => {
|
|
3167
|
+
log.info(`Web server started on http://localhost:${port}`);
|
|
3168
|
+
onStart?.(port);
|
|
3169
|
+
resolve(s);
|
|
3170
|
+
});
|
|
3171
|
+
s.on("error", reject);
|
|
3172
|
+
});
|
|
3173
|
+
return { server, broadcaster };
|
|
3174
|
+
} catch (err) {
|
|
3175
|
+
const code = err.code;
|
|
3176
|
+
if (code === "EADDRINUSE" && attempt < maxAttempts - 1) {
|
|
3177
|
+
log.warn(`Port ${port} in use, trying ${port + 1}...`);
|
|
3178
|
+
continue;
|
|
3179
|
+
}
|
|
3180
|
+
throw err;
|
|
3181
|
+
}
|
|
3182
|
+
}
|
|
3183
|
+
throw new Error(`No available port found (tried ${preferredPort}-${preferredPort + maxAttempts - 1})`);
|
|
3184
|
+
}
|
|
3185
|
+
function serializeDoc(doc) {
|
|
3186
|
+
return {
|
|
3187
|
+
path: doc.path,
|
|
3188
|
+
frontmatter: doc.frontmatter,
|
|
3189
|
+
l0: doc.l0,
|
|
3190
|
+
l1: doc.l1,
|
|
3191
|
+
body: doc.body
|
|
3192
|
+
};
|
|
3193
|
+
}
|
|
3194
|
+
function buildDashboardHtml(harnessDir) {
|
|
3195
|
+
let agentName = "Agent";
|
|
3196
|
+
try {
|
|
3197
|
+
const config = loadConfig(harnessDir);
|
|
3198
|
+
agentName = config.agent.name;
|
|
3199
|
+
} catch {
|
|
3200
|
+
}
|
|
3201
|
+
return `<!DOCTYPE html>
|
|
3202
|
+
<html lang="en">
|
|
3203
|
+
<head>
|
|
3204
|
+
<meta charset="utf-8">
|
|
3205
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
3206
|
+
<title>${escapeHtml(agentName)} Dashboard</title>
|
|
3207
|
+
<style>
|
|
3208
|
+
:root{--bg:#0d1117;--surface:#161b22;--border:#30363d;--text:#c9d1d9;--dim:#8b949e;--accent:#58a6ff;--green:#3fb950;--red:#f85149;--yellow:#d29922;--font:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,monospace}
|
|
3209
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
3210
|
+
body{font-family:var(--font);background:var(--bg);color:var(--text);font-size:13px;line-height:1.5}
|
|
3211
|
+
.layout{display:grid;grid-template-columns:200px 1fr;grid-template-rows:44px 1fr;height:100vh}
|
|
3212
|
+
.topbar{grid-column:1/-1;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;padding:0 16px;gap:12px}
|
|
3213
|
+
.topbar h1{font-size:14px;font-weight:600;color:var(--accent)}
|
|
3214
|
+
.topbar .status{font-size:11px;color:var(--dim);display:flex;align-items:center;gap:4px}
|
|
3215
|
+
.dot{width:7px;height:7px;border-radius:50%;display:inline-block}
|
|
3216
|
+
.dot.ok{background:var(--green)}.dot.warn{background:var(--yellow)}.dot.err{background:var(--red)}
|
|
3217
|
+
.sidebar{background:var(--surface);border-right:1px solid var(--border);overflow-y:auto;padding-top:8px}
|
|
3218
|
+
.nav{display:block;padding:6px 16px;color:var(--dim);cursor:pointer;border:none;background:none;width:100%;text-align:left;font:inherit;font-size:12px}
|
|
3219
|
+
.nav:hover{background:var(--border);color:var(--text)}.nav.active{color:var(--accent);background:rgba(88,166,255,.1)}
|
|
3220
|
+
.main{overflow-y:auto;padding:16px}
|
|
3221
|
+
.panel{display:none}.panel.active{display:block}
|
|
3222
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px;margin-bottom:16px}
|
|
3223
|
+
.card{background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:12px}
|
|
3224
|
+
.card h3{font-size:10px;color:var(--dim);text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px}
|
|
3225
|
+
.m{display:flex;justify-content:space-between;padding:2px 0;font-size:12px}
|
|
3226
|
+
.m .l{color:var(--dim)}.m .v{font-weight:600}
|
|
3227
|
+
.v.g{color:var(--green)}.v.r{color:var(--red)}.v.y{color:var(--yellow)}
|
|
3228
|
+
.badge{display:inline-block;padding:1px 6px;border-radius:10px;font-size:10px;font-weight:500}
|
|
3229
|
+
.badge.g{background:rgba(63,185,80,.15);color:var(--green)}
|
|
3230
|
+
.badge.r{background:rgba(248,81,73,.15);color:var(--red)}
|
|
3231
|
+
.badge.y{background:rgba(210,153,34,.15);color:var(--yellow)}
|
|
3232
|
+
table{width:100%;border-collapse:collapse;font-size:12px}
|
|
3233
|
+
th{text-align:left;color:var(--dim);padding:4px 6px;border-bottom:1px solid var(--border);font-size:10px;text-transform:uppercase}
|
|
3234
|
+
td{padding:4px 6px;border-bottom:1px solid var(--border)}
|
|
3235
|
+
.events{max-height:180px;overflow-y:auto;font-size:11px;font-family:monospace;background:var(--bg);padding:6px;border-radius:4px;border:1px solid var(--border)}
|
|
3236
|
+
.events .ev{padding:1px 0;color:var(--dim)}.events .ev .t{color:var(--accent);margin-right:6px}
|
|
3237
|
+
.chat-wrap{display:flex;flex-direction:column;height:calc(100vh - 76px)}
|
|
3238
|
+
.chat-msgs{flex:1;overflow-y:auto;padding:8px 0}
|
|
3239
|
+
.msg{padding:6px 0}.msg .role{font-size:10px;font-weight:600;margin-bottom:1px}
|
|
3240
|
+
.msg .role.user{color:var(--accent)}.msg .role.assistant{color:var(--green)}
|
|
3241
|
+
.msg .body{white-space:pre-wrap;word-wrap:break-word}.msg .meta{font-size:10px;color:var(--dim);margin-top:2px}
|
|
3242
|
+
.chat-bar{display:flex;gap:6px;padding:8px 0;border-top:1px solid var(--border)}
|
|
3243
|
+
.chat-bar input{flex:1;background:var(--surface);border:1px solid var(--border);border-radius:4px;padding:8px 10px;color:var(--text);font:inherit;outline:none}
|
|
3244
|
+
.chat-bar input:focus{border-color:var(--accent)}
|
|
3245
|
+
.chat-bar button{background:var(--accent);color:#fff;border:none;border-radius:4px;padding:8px 16px;cursor:pointer;font:inherit;font-weight:600}
|
|
3246
|
+
.chat-bar button:disabled{opacity:.5;cursor:not-allowed}
|
|
3247
|
+
.editor-wrap{display:grid;grid-template-columns:220px 1fr;gap:12px;height:calc(100vh - 76px)}
|
|
3248
|
+
.tree{font-size:11px;overflow-y:auto}
|
|
3249
|
+
.tree .d{cursor:pointer;padding:2px 0}.tree .d::before{content:'\\25b8 ';color:var(--dim)}.tree .d.open::before{content:'\\25be '}
|
|
3250
|
+
.tree .f{padding:2px 0 2px 14px;cursor:pointer;color:var(--dim)}.tree .f:hover{color:var(--accent)}
|
|
3251
|
+
.tree .ch{padding-left:14px;display:none}.tree .d.open+.ch{display:block}
|
|
3252
|
+
.ed-area{display:flex;flex-direction:column}
|
|
3253
|
+
.ed-head{padding:6px 0;font-size:11px;color:var(--dim);border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center}
|
|
3254
|
+
.ed-ta{flex:1;background:var(--surface);border:1px solid var(--border);border-radius:4px;padding:10px;color:var(--text);font:inherit;font-size:11px;resize:none;outline:none;tab-size:2}
|
|
3255
|
+
.ed-ta:focus{border-color:var(--accent)}
|
|
3256
|
+
.save-btn{background:var(--green);color:var(--bg);border:none;border-radius:3px;padding:3px 10px;cursor:pointer;font:inherit;font-size:10px;font-weight:600}
|
|
3257
|
+
.config-block{background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:12px;white-space:pre-wrap;font-size:11px;font-family:monospace;overflow-x:auto;min-height:200px}
|
|
3258
|
+
.toast-box{position:fixed;bottom:16px;right:16px;z-index:1000}
|
|
3259
|
+
.toast{background:var(--surface);border:1px solid var(--border);border-radius:4px;padding:8px 12px;margin-top:6px;font-size:11px}
|
|
3260
|
+
</style>
|
|
3261
|
+
</head>
|
|
3262
|
+
<body>
|
|
3263
|
+
<div class="layout">
|
|
3264
|
+
<div class="topbar">
|
|
3265
|
+
<h1 id="title">${escapeHtml(agentName)}</h1>
|
|
3266
|
+
<div class="status"><span class="dot warn" id="sdot"></span><span id="stxt">connecting</span></div>
|
|
3267
|
+
<div style="flex:1"></div>
|
|
3268
|
+
<div class="status"><span class="dot ok" style="animation:pulse 2s infinite"></span>live</div>
|
|
3269
|
+
</div>
|
|
3270
|
+
<div class="sidebar">
|
|
3271
|
+
<button class="nav active" data-p="dashboard">Dashboard</button>
|
|
3272
|
+
<button class="nav" data-p="chat">Chat</button>
|
|
3273
|
+
<button class="nav" data-p="files">Files</button>
|
|
3274
|
+
<button class="nav" data-p="mcp">MCP Servers</button>
|
|
3275
|
+
<button class="nav" data-p="settings">Settings</button>
|
|
3276
|
+
</div>
|
|
3277
|
+
<div class="main">
|
|
3278
|
+
|
|
3279
|
+
<!-- Dashboard -->
|
|
3280
|
+
<div class="panel active" id="p-dashboard">
|
|
3281
|
+
<div class="grid" id="dash-cards"></div>
|
|
3282
|
+
<div class="grid">
|
|
3283
|
+
<div class="card"><h3>Health Checks</h3><div id="dash-health"></div></div>
|
|
3284
|
+
<div class="card"><h3>MCP Servers</h3><div id="dash-mcp"></div></div>
|
|
3285
|
+
<div class="card"><h3>Live Events</h3><div class="events" id="evlog"></div></div>
|
|
3286
|
+
</div>
|
|
3287
|
+
</div>
|
|
3288
|
+
|
|
3289
|
+
<!-- Chat -->
|
|
3290
|
+
<div class="panel" id="p-chat">
|
|
3291
|
+
<div class="chat-wrap">
|
|
3292
|
+
<div style="display:flex;justify-content:space-between;align-items:center;padding-bottom:6px">
|
|
3293
|
+
<strong>Chat</strong>
|
|
3294
|
+
<button class="save-btn" onclick="resetChat()">Reset</button>
|
|
3295
|
+
</div>
|
|
3296
|
+
<div class="chat-msgs" id="chat-msgs"></div>
|
|
3297
|
+
<div class="chat-bar">
|
|
3298
|
+
<input type="text" id="chat-in" placeholder="Type a message..." autocomplete="off">
|
|
3299
|
+
<button id="chat-btn">Send</button>
|
|
3300
|
+
</div>
|
|
3301
|
+
</div>
|
|
3302
|
+
</div>
|
|
3303
|
+
|
|
3304
|
+
<!-- Files -->
|
|
3305
|
+
<div class="panel" id="p-files">
|
|
3306
|
+
<div class="editor-wrap">
|
|
3307
|
+
<div class="tree" id="ftree"></div>
|
|
3308
|
+
<div class="ed-area">
|
|
3309
|
+
<div class="ed-head"><span id="ed-path">Select a file</span><button class="save-btn" id="ed-save" style="display:none" onclick="saveFile()">Save</button></div>
|
|
3310
|
+
<textarea class="ed-ta" id="ed-ta" disabled placeholder="Select a file..."></textarea>
|
|
3311
|
+
</div>
|
|
3312
|
+
</div>
|
|
3313
|
+
</div>
|
|
3314
|
+
|
|
3315
|
+
<!-- MCP -->
|
|
3316
|
+
<div class="panel" id="p-mcp">
|
|
3317
|
+
<h2 style="margin-bottom:12px">MCP Servers</h2>
|
|
3318
|
+
<div id="mcp-detail"></div>
|
|
3319
|
+
</div>
|
|
3320
|
+
|
|
3321
|
+
<!-- Settings -->
|
|
3322
|
+
<div class="panel" id="p-settings">
|
|
3323
|
+
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
|
|
3324
|
+
<h2>config.yaml</h2>
|
|
3325
|
+
<button class="save-btn" onclick="saveConfig()">Save Config</button>
|
|
3326
|
+
</div>
|
|
3327
|
+
<textarea class="config-block" id="cfg-ta" style="width:100%;min-height:400px;resize:vertical"></textarea>
|
|
3328
|
+
</div>
|
|
3329
|
+
|
|
3330
|
+
</div>
|
|
3331
|
+
</div>
|
|
3332
|
+
<div class="toast-box" id="toasts"></div>
|
|
3333
|
+
<style>@keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}</style>
|
|
3334
|
+
<script>
|
|
3335
|
+
(function(){
|
|
3336
|
+
let curPanel='dashboard',curFile=null,sending=false;
|
|
3337
|
+
|
|
3338
|
+
// Nav
|
|
3339
|
+
document.querySelectorAll('.nav').forEach(b=>{b.addEventListener('click',()=>{
|
|
3340
|
+
document.querySelectorAll('.nav').forEach(n=>n.classList.remove('active'));b.classList.add('active');
|
|
3341
|
+
document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
|
|
3342
|
+
const p=b.dataset.p;document.getElementById('p-'+p).classList.add('active');curPanel=p;
|
|
3343
|
+
if(p==='dashboard')loadDash();if(p==='files')loadTree();if(p==='mcp')loadMcp();if(p==='settings')loadCfg();
|
|
3344
|
+
})});
|
|
3345
|
+
|
|
3346
|
+
// Helpers
|
|
3347
|
+
async function api(path,opts){const r=await fetch('/api/'+path,opts);if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||r.statusText)}return r.json()}
|
|
3348
|
+
function toast(m){const e=document.createElement('div');e.className='toast';e.textContent=m;document.getElementById('toasts').appendChild(e);setTimeout(()=>e.remove(),4000)}
|
|
3349
|
+
function esc(s){const d=document.createElement('div');d.textContent=s;return d.innerHTML}
|
|
3350
|
+
function mt(l,v,c){return '<div class="m"><span class="l">'+esc(l)+'</span><span class="v'+(c?' '+c:'')+'">'+v+'</span></div>'}
|
|
3351
|
+
function bg(t,c){return '<span class="badge '+c+'">'+esc(t)+'</span>'}
|
|
3352
|
+
function f$(v){return '$'+(v||0).toFixed(2)}
|
|
3353
|
+
|
|
3354
|
+
// Dashboard
|
|
3355
|
+
async function loadDash(){try{
|
|
3356
|
+
const s=await api('snapshot');
|
|
3357
|
+
document.getElementById('title').textContent=s.agent.name;document.title=s.agent.name+' Dashboard';
|
|
3358
|
+
const c=document.getElementById('dash-cards');c.innerHTML='';
|
|
3359
|
+
function card(l,v,sub){c.innerHTML+='<div class="card"><h3>'+esc(l)+'</h3><div style="font-size:18px;font-weight:700">'+esc(String(v))+'</div>'+(sub?'<div style="font-size:10px;color:var(--dim);margin-top:2px">'+esc(sub)+'</div>':'')+'</div>'}
|
|
3360
|
+
card('Status',s.health.status,s.agent.mode);
|
|
3361
|
+
card('Sessions',s.sessions.total,s.sessions.totalTokens.toLocaleString()+' tokens');
|
|
3362
|
+
card('Today',f$(s.spending.today.total_cost_usd),s.spending.today.entries+' calls');
|
|
3363
|
+
card('Monthly',f$(s.spending.thisMonth.total_cost_usd));
|
|
3364
|
+
card('Workflows',s.workflows.totalRuns+' runs',s.workflows.overallSuccessRate.toFixed(0)+'% success');
|
|
3365
|
+
card('Primitives',s.storage.primitiveCount,s.storage.sessionCount+' sessions');
|
|
3366
|
+
card('MCP',s.mcp.enabledCount+'/'+s.mcp.serverCount+' servers');
|
|
3367
|
+
card('Last Active',s.agent.lastInteraction==='never'?'never':new Date(s.agent.lastInteraction).toLocaleString());
|
|
3368
|
+
// Health dot
|
|
3369
|
+
const dot=document.getElementById('sdot');const txt=document.getElementById('stxt');
|
|
3370
|
+
dot.className='dot '+(s.health.status==='healthy'?'ok':s.health.status==='degraded'?'warn':'err');
|
|
3371
|
+
txt.textContent=s.health.status;
|
|
3372
|
+
// Health checks
|
|
3373
|
+
const hh=document.getElementById('dash-health');
|
|
3374
|
+
hh.innerHTML=s.health.checks.length===0?'<span style="color:var(--dim)">No checks</span>':
|
|
3375
|
+
'<table><tr><th>Check</th><th>Status</th><th>Message</th></tr>'+s.health.checks.map(c=>'<tr><td>'+esc(c.name)+'</td><td>'+bg(c.status,c.status==='pass'?'g':c.status==='warn'?'y':'r')+'</td><td>'+esc(c.message)+'</td></tr>').join('')+'</table>';
|
|
3376
|
+
// MCP summary
|
|
3377
|
+
const mm=document.getElementById('dash-mcp');
|
|
3378
|
+
mm.innerHTML=s.mcp.servers.length===0?'<span style="color:var(--dim)">None configured</span>':
|
|
3379
|
+
'<table><tr><th>Name</th><th>Transport</th><th>Status</th></tr>'+s.mcp.servers.map(s=>'<tr><td>'+esc(s.name)+'</td><td>'+esc(s.transport)+'</td><td>'+(s.enabled?(s.valid?bg('ok','g'):bg('error','r')):bg('disabled','y'))+'</td></tr>').join('')+'</table>';
|
|
3380
|
+
}catch(e){toast('Dashboard: '+e.message)}}
|
|
3381
|
+
|
|
3382
|
+
// Chat
|
|
3383
|
+
const chatIn=document.getElementById('chat-in'),chatBtn=document.getElementById('chat-btn'),chatMsgs=document.getElementById('chat-msgs');
|
|
3384
|
+
function addMsg(role,text,meta){const d=document.createElement('div');d.className='msg';d.innerHTML='<div class="role '+role+'">'+role+'</div><div class="body">'+esc(text)+'</div>'+(meta?'<div class="meta">'+esc(meta)+'</div>':'');chatMsgs.appendChild(d);chatMsgs.scrollTop=chatMsgs.scrollHeight}
|
|
3385
|
+
async function sendChat(){const m=chatIn.value.trim();if(!m||sending)return;sending=true;chatBtn.disabled=true;chatIn.value='';addMsg('user',m);
|
|
3386
|
+
try{const r=await api('chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({message:m})});addMsg('assistant',r.text,r.usage?r.usage.totalTokens+' tokens, '+r.steps+' step(s)':'');if(r.toolCalls&&r.toolCalls.length>0)addMsg('assistant','Tools: '+r.toolCalls.map(t=>t.toolName).join(', '))}catch(e){addMsg('assistant','Error: '+e.message)}
|
|
3387
|
+
sending=false;chatBtn.disabled=false;chatIn.focus()}
|
|
3388
|
+
chatBtn.addEventListener('click',sendChat);chatIn.addEventListener('keydown',e=>{if(e.key==='Enter')sendChat()});
|
|
3389
|
+
async function resetChat(){try{await api('chat/reset',{method:'POST'});chatMsgs.innerHTML='';toast('Chat reset')}catch(e){toast('Reset error: '+e.message)}}
|
|
3390
|
+
window.resetChat=resetChat;
|
|
3391
|
+
|
|
3392
|
+
// Files
|
|
3393
|
+
async function loadTree(){try{const tree=await api('files');const el=document.getElementById('ftree');el.innerHTML=renderTree(tree);bindTree(el)}catch(e){toast('File tree: '+e.message)}}
|
|
3394
|
+
function renderTree(nodes){return nodes.map(n=>{if(n.type==='directory')return '<div class="d" data-p="'+esc(n.path)+'">'+esc(n.name)+'</div><div class="ch">'+renderTree(n.children||[])+'</div>';return '<div class="f" data-p="'+esc(n.path)+'">'+esc(n.name)+'</div>'}).join('')}
|
|
3395
|
+
function bindTree(el){el.querySelectorAll('.d').forEach(d=>d.addEventListener('click',()=>d.classList.toggle('open')));el.querySelectorAll('.f').forEach(f=>f.addEventListener('click',()=>openFile(f.dataset.p)))}
|
|
3396
|
+
async function openFile(path){try{const f=await api('files/'+path);curFile=path;document.getElementById('ed-path').textContent=path;document.getElementById('ed-ta').value=f.content;document.getElementById('ed-ta').disabled=false;document.getElementById('ed-save').style.display='inline-block'}catch(e){toast('Open: '+e.message)}}
|
|
3397
|
+
async function saveFile(){if(!curFile)return;try{await api('files/'+curFile,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({content:document.getElementById('ed-ta').value})});toast('Saved: '+curFile)}catch(e){toast('Save: '+e.message)}}
|
|
3398
|
+
window.saveFile=saveFile;
|
|
3399
|
+
|
|
3400
|
+
// MCP
|
|
3401
|
+
async function loadMcp(){try{const d=await api('mcp');const el=document.getElementById('mcp-detail');
|
|
3402
|
+
if(d.servers.length===0){el.innerHTML='<p style="color:var(--dim)">No MCP servers configured.</p>';return}
|
|
3403
|
+
el.innerHTML='<table><tr><th>Name</th><th>Transport</th><th>Enabled</th><th>Valid</th><th>Details</th></tr>'+d.servers.map(s=>'<tr><td>'+esc(s.name)+'</td><td>'+esc(s.transport)+'</td><td>'+(s.enabled?bg('yes','g'):bg('no','y'))+'</td><td>'+(s.valid?bg('valid','g'):bg('invalid','r'))+'</td><td style="font-size:10px;color:var(--dim)">'+esc(s.command||s.url||'')+'</td></tr>').join('')+'</table>';
|
|
3404
|
+
if(d.errors.length>0)el.innerHTML+='<h3 style="margin:12px 0 6px;color:var(--red)">Errors</h3><ul>'+d.errors.map(e=>'<li style="color:var(--red);font-size:11px">'+esc(e.server+': '+e.error)+'</li>').join('')+'</ul>'}catch(e){toast('MCP: '+e.message)}}
|
|
3405
|
+
|
|
3406
|
+
// Settings
|
|
3407
|
+
async function loadCfg(){try{const f=await api('files/config.yaml');document.getElementById('cfg-ta').value=f.content}catch(e){toast('Config: '+e.message)}}
|
|
3408
|
+
async function saveConfig(){try{await api('config',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({content:document.getElementById('cfg-ta').value})});toast('Config saved and reloaded')}catch(e){toast('Config save: '+e.message)}}
|
|
3409
|
+
window.saveConfig=saveConfig;
|
|
3410
|
+
|
|
3411
|
+
// SSE
|
|
3412
|
+
const evlog=document.getElementById('evlog');
|
|
3413
|
+
function addEv(type,data){const t=new Date().toLocaleTimeString();const e=document.createElement('div');e.className='ev';e.innerHTML='<span style="color:var(--dim);opacity:.6;margin-right:4px">'+t+'</span><span class="t">'+type+'</span>'+esc(typeof data==='string'?data:JSON.stringify(data));evlog.prepend(e);while(evlog.children.length>50)evlog.removeChild(evlog.lastChild)}
|
|
3414
|
+
function connectSSE(){const es=new EventSource('/api/events');
|
|
3415
|
+
es.addEventListener('connected',()=>{document.getElementById('sdot').className='dot ok';document.getElementById('stxt').textContent='connected';addEv('connected','SSE established');loadDash()});
|
|
3416
|
+
es.addEventListener('file_change',e=>{const d=JSON.parse(e.data);addEv('file_change',d.path+' ('+d.event+')');if(curPanel==='dashboard')loadDash();if(curPanel==='files')loadTree()});
|
|
3417
|
+
es.addEventListener('index_rebuild',e=>{addEv('index_rebuild',JSON.parse(e.data).directory)});
|
|
3418
|
+
es.addEventListener('auto_process',e=>{const d=JSON.parse(e.data);addEv('auto_process',d.path+': '+(d.fixes||[]).join(', '))});
|
|
3419
|
+
es.addEventListener('config_change',()=>{addEv('config_change','reloaded');if(curPanel==='dashboard')loadDash();if(curPanel==='settings')loadCfg()});
|
|
3420
|
+
es.addEventListener('chat_response',e=>{addEv('chat',JSON.parse(e.data).text?.slice(0,60)||'...')});
|
|
3421
|
+
es.onerror=()=>{document.getElementById('sdot').className='dot err';document.getElementById('stxt').textContent='disconnected'}}
|
|
3422
|
+
|
|
3423
|
+
loadDash();connectSSE();setInterval(()=>{if(curPanel==='dashboard')loadDash()},30000);
|
|
3424
|
+
})();
|
|
3425
|
+
</script>
|
|
3426
|
+
</body>
|
|
3427
|
+
</html>`;
|
|
3428
|
+
}
|
|
3429
|
+
function escapeHtml(s) {
|
|
3430
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
3431
|
+
}
|
|
3432
|
+
|
|
3433
|
+
export {
|
|
3434
|
+
Hono2 as Hono,
|
|
3435
|
+
cors,
|
|
3436
|
+
serve,
|
|
3437
|
+
createWebApp,
|
|
3438
|
+
startWebServer
|
|
3439
|
+
};
|
|
3440
|
+
//# sourceMappingURL=chunk-RY3ZFII7.js.map
|