@seedvault/server 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/seedvault-server.mjs +5 -0
- package/dist/index.html +383 -0
- package/dist/server.js +2171 -0
- package/package.json +26 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,2171 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/index.ts
|
|
3
|
+
import { join as join2 } from "path";
|
|
4
|
+
import { homedir } from "os";
|
|
5
|
+
import { mkdir as mkdir2 } from "fs/promises";
|
|
6
|
+
|
|
7
|
+
// src/db.ts
|
|
8
|
+
import { Database } from "bun:sqlite";
|
|
9
|
+
import { randomUUID } from "crypto";
|
|
10
|
+
var db;
|
|
11
|
+
function getDb() {
|
|
12
|
+
if (!db)
|
|
13
|
+
throw new Error("Database not initialized. Call initDb() first.");
|
|
14
|
+
return db;
|
|
15
|
+
}
|
|
16
|
+
function initDb(dbPath) {
|
|
17
|
+
db = new Database(dbPath, { create: true });
|
|
18
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
19
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
20
|
+
db.exec(`
|
|
21
|
+
CREATE TABLE IF NOT EXISTS contributors (
|
|
22
|
+
username TEXT PRIMARY KEY,
|
|
23
|
+
is_operator BOOLEAN NOT NULL DEFAULT FALSE,
|
|
24
|
+
created_at TEXT NOT NULL
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
CREATE TABLE IF NOT EXISTS api_keys (
|
|
28
|
+
id TEXT PRIMARY KEY,
|
|
29
|
+
key_hash TEXT UNIQUE NOT NULL,
|
|
30
|
+
label TEXT NOT NULL,
|
|
31
|
+
contributor TEXT NOT NULL REFERENCES contributors(username),
|
|
32
|
+
created_at TEXT NOT NULL,
|
|
33
|
+
last_used_at TEXT
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
CREATE TABLE IF NOT EXISTS invites (
|
|
37
|
+
id TEXT PRIMARY KEY,
|
|
38
|
+
created_by TEXT NOT NULL REFERENCES contributors(username),
|
|
39
|
+
created_at TEXT NOT NULL,
|
|
40
|
+
used_at TEXT,
|
|
41
|
+
used_by TEXT REFERENCES contributors(username)
|
|
42
|
+
);
|
|
43
|
+
`);
|
|
44
|
+
return db;
|
|
45
|
+
}
|
|
46
|
+
function validateUsername(username) {
|
|
47
|
+
if (!username || username.length === 0) {
|
|
48
|
+
return "Username is required";
|
|
49
|
+
}
|
|
50
|
+
if (username.length > 63) {
|
|
51
|
+
return "Username must be 63 characters or fewer";
|
|
52
|
+
}
|
|
53
|
+
if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(username) && !/^[a-z0-9]$/.test(username)) {
|
|
54
|
+
return "Username must be lowercase alphanumeric with hyphens, starting and ending with alphanumeric";
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
function createContributor(username, isOperator) {
|
|
59
|
+
const now = new Date().toISOString();
|
|
60
|
+
getDb().prepare("INSERT INTO contributors (username, is_operator, created_at) VALUES (?, ?, ?)").run(username, isOperator ? 1 : 0, now);
|
|
61
|
+
return { username, is_operator: isOperator, created_at: now };
|
|
62
|
+
}
|
|
63
|
+
function getContributor(username) {
|
|
64
|
+
const row = getDb().prepare("SELECT username, is_operator, created_at FROM contributors WHERE username = ?").get(username);
|
|
65
|
+
if (row)
|
|
66
|
+
row.is_operator = Boolean(row.is_operator);
|
|
67
|
+
return row;
|
|
68
|
+
}
|
|
69
|
+
function listContributors() {
|
|
70
|
+
const rows = getDb().prepare("SELECT username, is_operator, created_at FROM contributors ORDER BY created_at ASC").all();
|
|
71
|
+
return rows.map((r) => ({ ...r, is_operator: Boolean(r.is_operator) }));
|
|
72
|
+
}
|
|
73
|
+
function hasAnyContributor() {
|
|
74
|
+
const row = getDb().prepare("SELECT COUNT(*) as count FROM contributors").get();
|
|
75
|
+
return row.count > 0;
|
|
76
|
+
}
|
|
77
|
+
function createApiKey(keyHash, label, contributor) {
|
|
78
|
+
const id = `key_${randomUUID().replace(/-/g, "").slice(0, 12)}`;
|
|
79
|
+
const now = new Date().toISOString();
|
|
80
|
+
getDb().prepare("INSERT INTO api_keys (id, key_hash, label, contributor, created_at) VALUES (?, ?, ?, ?, ?)").run(id, keyHash, label, contributor, now);
|
|
81
|
+
return { id, key_hash: keyHash, label, contributor, created_at: now, last_used_at: null };
|
|
82
|
+
}
|
|
83
|
+
function getApiKeyByHash(keyHash) {
|
|
84
|
+
return getDb().prepare("SELECT * FROM api_keys WHERE key_hash = ?").get(keyHash);
|
|
85
|
+
}
|
|
86
|
+
function touchApiKey(id) {
|
|
87
|
+
getDb().prepare("UPDATE api_keys SET last_used_at = ? WHERE id = ?").run(new Date().toISOString(), id);
|
|
88
|
+
}
|
|
89
|
+
function createInvite(createdBy) {
|
|
90
|
+
const id = randomUUID().replace(/-/g, "").slice(0, 12);
|
|
91
|
+
const now = new Date().toISOString();
|
|
92
|
+
getDb().prepare("INSERT INTO invites (id, created_by, created_at) VALUES (?, ?, ?)").run(id, createdBy, now);
|
|
93
|
+
return { id, created_by: createdBy, created_at: now, used_at: null, used_by: null };
|
|
94
|
+
}
|
|
95
|
+
function getInvite(id) {
|
|
96
|
+
return getDb().prepare("SELECT * FROM invites WHERE id = ?").get(id);
|
|
97
|
+
}
|
|
98
|
+
function markInviteUsed(id, usedBy) {
|
|
99
|
+
getDb().prepare("UPDATE invites SET used_at = ?, used_by = ? WHERE id = ?").run(new Date().toISOString(), usedBy, id);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/compose.js
|
|
103
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
104
|
+
return (context, next) => {
|
|
105
|
+
let index = -1;
|
|
106
|
+
return dispatch(0);
|
|
107
|
+
async function dispatch(i) {
|
|
108
|
+
if (i <= index) {
|
|
109
|
+
throw new Error("next() called multiple times");
|
|
110
|
+
}
|
|
111
|
+
index = i;
|
|
112
|
+
let res;
|
|
113
|
+
let isError = false;
|
|
114
|
+
let handler;
|
|
115
|
+
if (middleware[i]) {
|
|
116
|
+
handler = middleware[i][0][0];
|
|
117
|
+
context.req.routeIndex = i;
|
|
118
|
+
} else {
|
|
119
|
+
handler = i === middleware.length && next || undefined;
|
|
120
|
+
}
|
|
121
|
+
if (handler) {
|
|
122
|
+
try {
|
|
123
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
124
|
+
} catch (err) {
|
|
125
|
+
if (err instanceof Error && onError) {
|
|
126
|
+
context.error = err;
|
|
127
|
+
res = await onError(err, context);
|
|
128
|
+
isError = true;
|
|
129
|
+
} else {
|
|
130
|
+
throw err;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
} else {
|
|
134
|
+
if (context.finalized === false && onNotFound) {
|
|
135
|
+
res = await onNotFound(context);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (res && (context.finalized === false || isError)) {
|
|
139
|
+
context.res = res;
|
|
140
|
+
}
|
|
141
|
+
return context;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/request/constants.js
|
|
147
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
148
|
+
|
|
149
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/utils/body.js
|
|
150
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
151
|
+
const { all = false, dot = false } = options;
|
|
152
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
153
|
+
const contentType = headers.get("Content-Type");
|
|
154
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
155
|
+
return parseFormData(request, { all, dot });
|
|
156
|
+
}
|
|
157
|
+
return {};
|
|
158
|
+
};
|
|
159
|
+
async function parseFormData(request, options) {
|
|
160
|
+
const formData = await request.formData();
|
|
161
|
+
if (formData) {
|
|
162
|
+
return convertFormDataToBodyData(formData, options);
|
|
163
|
+
}
|
|
164
|
+
return {};
|
|
165
|
+
}
|
|
166
|
+
function convertFormDataToBodyData(formData, options) {
|
|
167
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
168
|
+
formData.forEach((value, key) => {
|
|
169
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
170
|
+
if (!shouldParseAllValues) {
|
|
171
|
+
form[key] = value;
|
|
172
|
+
} else {
|
|
173
|
+
handleParsingAllValues(form, key, value);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
if (options.dot) {
|
|
177
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
178
|
+
const shouldParseDotValues = key.includes(".");
|
|
179
|
+
if (shouldParseDotValues) {
|
|
180
|
+
handleParsingNestedValues(form, key, value);
|
|
181
|
+
delete form[key];
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return form;
|
|
186
|
+
}
|
|
187
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
188
|
+
if (form[key] !== undefined) {
|
|
189
|
+
if (Array.isArray(form[key])) {
|
|
190
|
+
form[key].push(value);
|
|
191
|
+
} else {
|
|
192
|
+
form[key] = [form[key], value];
|
|
193
|
+
}
|
|
194
|
+
} else {
|
|
195
|
+
if (!key.endsWith("[]")) {
|
|
196
|
+
form[key] = value;
|
|
197
|
+
} else {
|
|
198
|
+
form[key] = [value];
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
203
|
+
let nestedForm = form;
|
|
204
|
+
const keys = key.split(".");
|
|
205
|
+
keys.forEach((key2, index) => {
|
|
206
|
+
if (index === keys.length - 1) {
|
|
207
|
+
nestedForm[key2] = value;
|
|
208
|
+
} else {
|
|
209
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
210
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
211
|
+
}
|
|
212
|
+
nestedForm = nestedForm[key2];
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/utils/url.js
|
|
218
|
+
var splitPath = (path) => {
|
|
219
|
+
const paths = path.split("/");
|
|
220
|
+
if (paths[0] === "") {
|
|
221
|
+
paths.shift();
|
|
222
|
+
}
|
|
223
|
+
return paths;
|
|
224
|
+
};
|
|
225
|
+
var splitRoutingPath = (routePath) => {
|
|
226
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
227
|
+
const paths = splitPath(path);
|
|
228
|
+
return replaceGroupMarks(paths, groups);
|
|
229
|
+
};
|
|
230
|
+
var extractGroupsFromPath = (path) => {
|
|
231
|
+
const groups = [];
|
|
232
|
+
path = path.replace(/\{[^}]+\}/g, (match, index) => {
|
|
233
|
+
const mark = `@${index}`;
|
|
234
|
+
groups.push([mark, match]);
|
|
235
|
+
return mark;
|
|
236
|
+
});
|
|
237
|
+
return { groups, path };
|
|
238
|
+
};
|
|
239
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
240
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
241
|
+
const [mark] = groups[i];
|
|
242
|
+
for (let j = paths.length - 1;j >= 0; j--) {
|
|
243
|
+
if (paths[j].includes(mark)) {
|
|
244
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return paths;
|
|
250
|
+
};
|
|
251
|
+
var patternCache = {};
|
|
252
|
+
var getPattern = (label, next) => {
|
|
253
|
+
if (label === "*") {
|
|
254
|
+
return "*";
|
|
255
|
+
}
|
|
256
|
+
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
257
|
+
if (match) {
|
|
258
|
+
const cacheKey = `${label}#${next}`;
|
|
259
|
+
if (!patternCache[cacheKey]) {
|
|
260
|
+
if (match[2]) {
|
|
261
|
+
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
|
|
262
|
+
} else {
|
|
263
|
+
patternCache[cacheKey] = [label, match[1], true];
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return patternCache[cacheKey];
|
|
267
|
+
}
|
|
268
|
+
return null;
|
|
269
|
+
};
|
|
270
|
+
var tryDecode = (str, decoder) => {
|
|
271
|
+
try {
|
|
272
|
+
return decoder(str);
|
|
273
|
+
} catch {
|
|
274
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
275
|
+
try {
|
|
276
|
+
return decoder(match);
|
|
277
|
+
} catch {
|
|
278
|
+
return match;
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
284
|
+
var getPath = (request) => {
|
|
285
|
+
const url = request.url;
|
|
286
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
287
|
+
let i = start;
|
|
288
|
+
for (;i < url.length; i++) {
|
|
289
|
+
const charCode = url.charCodeAt(i);
|
|
290
|
+
if (charCode === 37) {
|
|
291
|
+
const queryIndex = url.indexOf("?", i);
|
|
292
|
+
const hashIndex = url.indexOf("#", i);
|
|
293
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
294
|
+
const path = url.slice(start, end);
|
|
295
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
296
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return url.slice(start, i);
|
|
301
|
+
};
|
|
302
|
+
var getPathNoStrict = (request) => {
|
|
303
|
+
const result = getPath(request);
|
|
304
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
305
|
+
};
|
|
306
|
+
var mergePath = (base, sub, ...rest) => {
|
|
307
|
+
if (rest.length) {
|
|
308
|
+
sub = mergePath(sub, ...rest);
|
|
309
|
+
}
|
|
310
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
311
|
+
};
|
|
312
|
+
var checkOptionalParameter = (path) => {
|
|
313
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
const segments = path.split("/");
|
|
317
|
+
const results = [];
|
|
318
|
+
let basePath = "";
|
|
319
|
+
segments.forEach((segment) => {
|
|
320
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
321
|
+
basePath += "/" + segment;
|
|
322
|
+
} else if (/\:/.test(segment)) {
|
|
323
|
+
if (/\?/.test(segment)) {
|
|
324
|
+
if (results.length === 0 && basePath === "") {
|
|
325
|
+
results.push("/");
|
|
326
|
+
} else {
|
|
327
|
+
results.push(basePath);
|
|
328
|
+
}
|
|
329
|
+
const optionalSegment = segment.replace("?", "");
|
|
330
|
+
basePath += "/" + optionalSegment;
|
|
331
|
+
results.push(basePath);
|
|
332
|
+
} else {
|
|
333
|
+
basePath += "/" + segment;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
338
|
+
};
|
|
339
|
+
var _decodeURI = (value) => {
|
|
340
|
+
if (!/[%+]/.test(value)) {
|
|
341
|
+
return value;
|
|
342
|
+
}
|
|
343
|
+
if (value.indexOf("+") !== -1) {
|
|
344
|
+
value = value.replace(/\+/g, " ");
|
|
345
|
+
}
|
|
346
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
347
|
+
};
|
|
348
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
349
|
+
let encoded;
|
|
350
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
351
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
352
|
+
if (keyIndex2 === -1) {
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
356
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
357
|
+
}
|
|
358
|
+
while (keyIndex2 !== -1) {
|
|
359
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
360
|
+
if (trailingKeyCode === 61) {
|
|
361
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
362
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
363
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
|
|
364
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
365
|
+
return "";
|
|
366
|
+
}
|
|
367
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
368
|
+
}
|
|
369
|
+
encoded = /[%+]/.test(url);
|
|
370
|
+
if (!encoded) {
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const results = {};
|
|
375
|
+
encoded ??= /[%+]/.test(url);
|
|
376
|
+
let keyIndex = url.indexOf("?", 8);
|
|
377
|
+
while (keyIndex !== -1) {
|
|
378
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
379
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
380
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
381
|
+
valueIndex = -1;
|
|
382
|
+
}
|
|
383
|
+
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
|
|
384
|
+
if (encoded) {
|
|
385
|
+
name = _decodeURI(name);
|
|
386
|
+
}
|
|
387
|
+
keyIndex = nextKeyIndex;
|
|
388
|
+
if (name === "") {
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
let value;
|
|
392
|
+
if (valueIndex === -1) {
|
|
393
|
+
value = "";
|
|
394
|
+
} else {
|
|
395
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
|
|
396
|
+
if (encoded) {
|
|
397
|
+
value = _decodeURI(value);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (multiple) {
|
|
401
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
402
|
+
results[name] = [];
|
|
403
|
+
}
|
|
404
|
+
results[name].push(value);
|
|
405
|
+
} else {
|
|
406
|
+
results[name] ??= value;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return key ? results[key] : results;
|
|
410
|
+
};
|
|
411
|
+
var getQueryParam = _getQueryParam;
|
|
412
|
+
var getQueryParams = (url, key) => {
|
|
413
|
+
return _getQueryParam(url, key, true);
|
|
414
|
+
};
|
|
415
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
416
|
+
|
|
417
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/request.js
|
|
418
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
419
|
+
var HonoRequest = class {
|
|
420
|
+
raw;
|
|
421
|
+
#validatedData;
|
|
422
|
+
#matchResult;
|
|
423
|
+
routeIndex = 0;
|
|
424
|
+
path;
|
|
425
|
+
bodyCache = {};
|
|
426
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
427
|
+
this.raw = request;
|
|
428
|
+
this.path = path;
|
|
429
|
+
this.#matchResult = matchResult;
|
|
430
|
+
this.#validatedData = {};
|
|
431
|
+
}
|
|
432
|
+
param(key) {
|
|
433
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
434
|
+
}
|
|
435
|
+
#getDecodedParam(key) {
|
|
436
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
437
|
+
const param = this.#getParamValue(paramKey);
|
|
438
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
439
|
+
}
|
|
440
|
+
#getAllDecodedParams() {
|
|
441
|
+
const decoded = {};
|
|
442
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
443
|
+
for (const key of keys) {
|
|
444
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
445
|
+
if (value !== undefined) {
|
|
446
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
return decoded;
|
|
450
|
+
}
|
|
451
|
+
#getParamValue(paramKey) {
|
|
452
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
453
|
+
}
|
|
454
|
+
query(key) {
|
|
455
|
+
return getQueryParam(this.url, key);
|
|
456
|
+
}
|
|
457
|
+
queries(key) {
|
|
458
|
+
return getQueryParams(this.url, key);
|
|
459
|
+
}
|
|
460
|
+
header(name) {
|
|
461
|
+
if (name) {
|
|
462
|
+
return this.raw.headers.get(name) ?? undefined;
|
|
463
|
+
}
|
|
464
|
+
const headerData = {};
|
|
465
|
+
this.raw.headers.forEach((value, key) => {
|
|
466
|
+
headerData[key] = value;
|
|
467
|
+
});
|
|
468
|
+
return headerData;
|
|
469
|
+
}
|
|
470
|
+
async parseBody(options) {
|
|
471
|
+
return this.bodyCache.parsedBody ??= await parseBody(this, options);
|
|
472
|
+
}
|
|
473
|
+
#cachedBody = (key) => {
|
|
474
|
+
const { bodyCache, raw } = this;
|
|
475
|
+
const cachedBody = bodyCache[key];
|
|
476
|
+
if (cachedBody) {
|
|
477
|
+
return cachedBody;
|
|
478
|
+
}
|
|
479
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
480
|
+
if (anyCachedKey) {
|
|
481
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
482
|
+
if (anyCachedKey === "json") {
|
|
483
|
+
body = JSON.stringify(body);
|
|
484
|
+
}
|
|
485
|
+
return new Response(body)[key]();
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
return bodyCache[key] = raw[key]();
|
|
489
|
+
};
|
|
490
|
+
json() {
|
|
491
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
492
|
+
}
|
|
493
|
+
text() {
|
|
494
|
+
return this.#cachedBody("text");
|
|
495
|
+
}
|
|
496
|
+
arrayBuffer() {
|
|
497
|
+
return this.#cachedBody("arrayBuffer");
|
|
498
|
+
}
|
|
499
|
+
blob() {
|
|
500
|
+
return this.#cachedBody("blob");
|
|
501
|
+
}
|
|
502
|
+
formData() {
|
|
503
|
+
return this.#cachedBody("formData");
|
|
504
|
+
}
|
|
505
|
+
addValidatedData(target, data) {
|
|
506
|
+
this.#validatedData[target] = data;
|
|
507
|
+
}
|
|
508
|
+
valid(target) {
|
|
509
|
+
return this.#validatedData[target];
|
|
510
|
+
}
|
|
511
|
+
get url() {
|
|
512
|
+
return this.raw.url;
|
|
513
|
+
}
|
|
514
|
+
get method() {
|
|
515
|
+
return this.raw.method;
|
|
516
|
+
}
|
|
517
|
+
get [GET_MATCH_RESULT]() {
|
|
518
|
+
return this.#matchResult;
|
|
519
|
+
}
|
|
520
|
+
get matchedRoutes() {
|
|
521
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
522
|
+
}
|
|
523
|
+
get routePath() {
|
|
524
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/utils/html.js
|
|
529
|
+
var HtmlEscapedCallbackPhase = {
|
|
530
|
+
Stringify: 1,
|
|
531
|
+
BeforeStream: 2,
|
|
532
|
+
Stream: 3
|
|
533
|
+
};
|
|
534
|
+
var raw = (value, callbacks) => {
|
|
535
|
+
const escapedString = new String(value);
|
|
536
|
+
escapedString.isEscaped = true;
|
|
537
|
+
escapedString.callbacks = callbacks;
|
|
538
|
+
return escapedString;
|
|
539
|
+
};
|
|
540
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
541
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
542
|
+
if (!(str instanceof Promise)) {
|
|
543
|
+
str = str.toString();
|
|
544
|
+
}
|
|
545
|
+
if (str instanceof Promise) {
|
|
546
|
+
str = await str;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
const callbacks = str.callbacks;
|
|
550
|
+
if (!callbacks?.length) {
|
|
551
|
+
return Promise.resolve(str);
|
|
552
|
+
}
|
|
553
|
+
if (buffer) {
|
|
554
|
+
buffer[0] += str;
|
|
555
|
+
} else {
|
|
556
|
+
buffer = [str];
|
|
557
|
+
}
|
|
558
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
|
|
559
|
+
if (preserveCallbacks) {
|
|
560
|
+
return raw(await resStr, callbacks);
|
|
561
|
+
} else {
|
|
562
|
+
return resStr;
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/context.js
|
|
567
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
568
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
569
|
+
return {
|
|
570
|
+
"Content-Type": contentType,
|
|
571
|
+
...headers
|
|
572
|
+
};
|
|
573
|
+
};
|
|
574
|
+
var Context = class {
|
|
575
|
+
#rawRequest;
|
|
576
|
+
#req;
|
|
577
|
+
env = {};
|
|
578
|
+
#var;
|
|
579
|
+
finalized = false;
|
|
580
|
+
error;
|
|
581
|
+
#status;
|
|
582
|
+
#executionCtx;
|
|
583
|
+
#res;
|
|
584
|
+
#layout;
|
|
585
|
+
#renderer;
|
|
586
|
+
#notFoundHandler;
|
|
587
|
+
#preparedHeaders;
|
|
588
|
+
#matchResult;
|
|
589
|
+
#path;
|
|
590
|
+
constructor(req, options) {
|
|
591
|
+
this.#rawRequest = req;
|
|
592
|
+
if (options) {
|
|
593
|
+
this.#executionCtx = options.executionCtx;
|
|
594
|
+
this.env = options.env;
|
|
595
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
596
|
+
this.#path = options.path;
|
|
597
|
+
this.#matchResult = options.matchResult;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
get req() {
|
|
601
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
602
|
+
return this.#req;
|
|
603
|
+
}
|
|
604
|
+
get event() {
|
|
605
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
606
|
+
return this.#executionCtx;
|
|
607
|
+
} else {
|
|
608
|
+
throw Error("This context has no FetchEvent");
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
get executionCtx() {
|
|
612
|
+
if (this.#executionCtx) {
|
|
613
|
+
return this.#executionCtx;
|
|
614
|
+
} else {
|
|
615
|
+
throw Error("This context has no ExecutionContext");
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
get res() {
|
|
619
|
+
return this.#res ||= new Response(null, {
|
|
620
|
+
headers: this.#preparedHeaders ??= new Headers
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
set res(_res) {
|
|
624
|
+
if (this.#res && _res) {
|
|
625
|
+
_res = new Response(_res.body, _res);
|
|
626
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
627
|
+
if (k === "content-type") {
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
if (k === "set-cookie") {
|
|
631
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
632
|
+
_res.headers.delete("set-cookie");
|
|
633
|
+
for (const cookie of cookies) {
|
|
634
|
+
_res.headers.append("set-cookie", cookie);
|
|
635
|
+
}
|
|
636
|
+
} else {
|
|
637
|
+
_res.headers.set(k, v);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
this.#res = _res;
|
|
642
|
+
this.finalized = true;
|
|
643
|
+
}
|
|
644
|
+
render = (...args) => {
|
|
645
|
+
this.#renderer ??= (content) => this.html(content);
|
|
646
|
+
return this.#renderer(...args);
|
|
647
|
+
};
|
|
648
|
+
setLayout = (layout) => this.#layout = layout;
|
|
649
|
+
getLayout = () => this.#layout;
|
|
650
|
+
setRenderer = (renderer) => {
|
|
651
|
+
this.#renderer = renderer;
|
|
652
|
+
};
|
|
653
|
+
header = (name, value, options) => {
|
|
654
|
+
if (this.finalized) {
|
|
655
|
+
this.#res = new Response(this.#res.body, this.#res);
|
|
656
|
+
}
|
|
657
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
|
|
658
|
+
if (value === undefined) {
|
|
659
|
+
headers.delete(name);
|
|
660
|
+
} else if (options?.append) {
|
|
661
|
+
headers.append(name, value);
|
|
662
|
+
} else {
|
|
663
|
+
headers.set(name, value);
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
status = (status) => {
|
|
667
|
+
this.#status = status;
|
|
668
|
+
};
|
|
669
|
+
set = (key, value) => {
|
|
670
|
+
this.#var ??= /* @__PURE__ */ new Map;
|
|
671
|
+
this.#var.set(key, value);
|
|
672
|
+
};
|
|
673
|
+
get = (key) => {
|
|
674
|
+
return this.#var ? this.#var.get(key) : undefined;
|
|
675
|
+
};
|
|
676
|
+
get var() {
|
|
677
|
+
if (!this.#var) {
|
|
678
|
+
return {};
|
|
679
|
+
}
|
|
680
|
+
return Object.fromEntries(this.#var);
|
|
681
|
+
}
|
|
682
|
+
#newResponse(data, arg, headers) {
|
|
683
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
|
|
684
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
685
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
686
|
+
for (const [key, value] of argHeaders) {
|
|
687
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
688
|
+
responseHeaders.append(key, value);
|
|
689
|
+
} else {
|
|
690
|
+
responseHeaders.set(key, value);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
if (headers) {
|
|
695
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
696
|
+
if (typeof v === "string") {
|
|
697
|
+
responseHeaders.set(k, v);
|
|
698
|
+
} else {
|
|
699
|
+
responseHeaders.delete(k);
|
|
700
|
+
for (const v2 of v) {
|
|
701
|
+
responseHeaders.append(k, v2);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
707
|
+
return new Response(data, { status, headers: responseHeaders });
|
|
708
|
+
}
|
|
709
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
710
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
711
|
+
text = (text, arg, headers) => {
|
|
712
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
|
|
713
|
+
};
|
|
714
|
+
json = (object, arg, headers) => {
|
|
715
|
+
return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
|
|
716
|
+
};
|
|
717
|
+
html = (html, arg, headers) => {
|
|
718
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
719
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
720
|
+
};
|
|
721
|
+
redirect = (location, status) => {
|
|
722
|
+
const locationString = String(location);
|
|
723
|
+
this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
|
|
724
|
+
return this.newResponse(null, status ?? 302);
|
|
725
|
+
};
|
|
726
|
+
notFound = () => {
|
|
727
|
+
this.#notFoundHandler ??= () => new Response;
|
|
728
|
+
return this.#notFoundHandler(this);
|
|
729
|
+
};
|
|
730
|
+
};
|
|
731
|
+
|
|
732
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router.js
|
|
733
|
+
var METHOD_NAME_ALL = "ALL";
|
|
734
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
735
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
736
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
737
|
+
var UnsupportedPathError = class extends Error {
|
|
738
|
+
};
|
|
739
|
+
|
|
740
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/utils/constants.js
|
|
741
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
742
|
+
|
|
743
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/hono-base.js
|
|
744
|
+
var notFoundHandler = (c) => {
|
|
745
|
+
return c.text("404 Not Found", 404);
|
|
746
|
+
};
|
|
747
|
+
var errorHandler = (err, c) => {
|
|
748
|
+
if ("getResponse" in err) {
|
|
749
|
+
const res = err.getResponse();
|
|
750
|
+
return c.newResponse(res.body, res);
|
|
751
|
+
}
|
|
752
|
+
console.error(err);
|
|
753
|
+
return c.text("Internal Server Error", 500);
|
|
754
|
+
};
|
|
755
|
+
var Hono = class _Hono {
|
|
756
|
+
get;
|
|
757
|
+
post;
|
|
758
|
+
put;
|
|
759
|
+
delete;
|
|
760
|
+
options;
|
|
761
|
+
patch;
|
|
762
|
+
all;
|
|
763
|
+
on;
|
|
764
|
+
use;
|
|
765
|
+
router;
|
|
766
|
+
getPath;
|
|
767
|
+
_basePath = "/";
|
|
768
|
+
#path = "/";
|
|
769
|
+
routes = [];
|
|
770
|
+
constructor(options = {}) {
|
|
771
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
772
|
+
allMethods.forEach((method) => {
|
|
773
|
+
this[method] = (args1, ...args) => {
|
|
774
|
+
if (typeof args1 === "string") {
|
|
775
|
+
this.#path = args1;
|
|
776
|
+
} else {
|
|
777
|
+
this.#addRoute(method, this.#path, args1);
|
|
778
|
+
}
|
|
779
|
+
args.forEach((handler) => {
|
|
780
|
+
this.#addRoute(method, this.#path, handler);
|
|
781
|
+
});
|
|
782
|
+
return this;
|
|
783
|
+
};
|
|
784
|
+
});
|
|
785
|
+
this.on = (method, path, ...handlers) => {
|
|
786
|
+
for (const p of [path].flat()) {
|
|
787
|
+
this.#path = p;
|
|
788
|
+
for (const m of [method].flat()) {
|
|
789
|
+
handlers.map((handler) => {
|
|
790
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return this;
|
|
795
|
+
};
|
|
796
|
+
this.use = (arg1, ...handlers) => {
|
|
797
|
+
if (typeof arg1 === "string") {
|
|
798
|
+
this.#path = arg1;
|
|
799
|
+
} else {
|
|
800
|
+
this.#path = "*";
|
|
801
|
+
handlers.unshift(arg1);
|
|
802
|
+
}
|
|
803
|
+
handlers.forEach((handler) => {
|
|
804
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
805
|
+
});
|
|
806
|
+
return this;
|
|
807
|
+
};
|
|
808
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
809
|
+
Object.assign(this, optionsWithoutStrict);
|
|
810
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
811
|
+
}
|
|
812
|
+
#clone() {
|
|
813
|
+
const clone = new _Hono({
|
|
814
|
+
router: this.router,
|
|
815
|
+
getPath: this.getPath
|
|
816
|
+
});
|
|
817
|
+
clone.errorHandler = this.errorHandler;
|
|
818
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
819
|
+
clone.routes = this.routes;
|
|
820
|
+
return clone;
|
|
821
|
+
}
|
|
822
|
+
#notFoundHandler = notFoundHandler;
|
|
823
|
+
errorHandler = errorHandler;
|
|
824
|
+
route(path, app) {
|
|
825
|
+
const subApp = this.basePath(path);
|
|
826
|
+
app.routes.map((r) => {
|
|
827
|
+
let handler;
|
|
828
|
+
if (app.errorHandler === errorHandler) {
|
|
829
|
+
handler = r.handler;
|
|
830
|
+
} else {
|
|
831
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
832
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
833
|
+
}
|
|
834
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
835
|
+
});
|
|
836
|
+
return this;
|
|
837
|
+
}
|
|
838
|
+
basePath(path) {
|
|
839
|
+
const subApp = this.#clone();
|
|
840
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
841
|
+
return subApp;
|
|
842
|
+
}
|
|
843
|
+
onError = (handler) => {
|
|
844
|
+
this.errorHandler = handler;
|
|
845
|
+
return this;
|
|
846
|
+
};
|
|
847
|
+
notFound = (handler) => {
|
|
848
|
+
this.#notFoundHandler = handler;
|
|
849
|
+
return this;
|
|
850
|
+
};
|
|
851
|
+
mount(path, applicationHandler, options) {
|
|
852
|
+
let replaceRequest;
|
|
853
|
+
let optionHandler;
|
|
854
|
+
if (options) {
|
|
855
|
+
if (typeof options === "function") {
|
|
856
|
+
optionHandler = options;
|
|
857
|
+
} else {
|
|
858
|
+
optionHandler = options.optionHandler;
|
|
859
|
+
if (options.replaceRequest === false) {
|
|
860
|
+
replaceRequest = (request) => request;
|
|
861
|
+
} else {
|
|
862
|
+
replaceRequest = options.replaceRequest;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
const getOptions = optionHandler ? (c) => {
|
|
867
|
+
const options2 = optionHandler(c);
|
|
868
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
869
|
+
} : (c) => {
|
|
870
|
+
let executionContext = undefined;
|
|
871
|
+
try {
|
|
872
|
+
executionContext = c.executionCtx;
|
|
873
|
+
} catch {}
|
|
874
|
+
return [c.env, executionContext];
|
|
875
|
+
};
|
|
876
|
+
replaceRequest ||= (() => {
|
|
877
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
878
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
879
|
+
return (request) => {
|
|
880
|
+
const url = new URL(request.url);
|
|
881
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
882
|
+
return new Request(url, request);
|
|
883
|
+
};
|
|
884
|
+
})();
|
|
885
|
+
const handler = async (c, next) => {
|
|
886
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
887
|
+
if (res) {
|
|
888
|
+
return res;
|
|
889
|
+
}
|
|
890
|
+
await next();
|
|
891
|
+
};
|
|
892
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
893
|
+
return this;
|
|
894
|
+
}
|
|
895
|
+
#addRoute(method, path, handler) {
|
|
896
|
+
method = method.toUpperCase();
|
|
897
|
+
path = mergePath(this._basePath, path);
|
|
898
|
+
const r = { basePath: this._basePath, path, method, handler };
|
|
899
|
+
this.router.add(method, path, [handler, r]);
|
|
900
|
+
this.routes.push(r);
|
|
901
|
+
}
|
|
902
|
+
#handleError(err, c) {
|
|
903
|
+
if (err instanceof Error) {
|
|
904
|
+
return this.errorHandler(err, c);
|
|
905
|
+
}
|
|
906
|
+
throw err;
|
|
907
|
+
}
|
|
908
|
+
#dispatch(request, executionCtx, env, method) {
|
|
909
|
+
if (method === "HEAD") {
|
|
910
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
911
|
+
}
|
|
912
|
+
const path = this.getPath(request, { env });
|
|
913
|
+
const matchResult = this.router.match(method, path);
|
|
914
|
+
const c = new Context(request, {
|
|
915
|
+
path,
|
|
916
|
+
matchResult,
|
|
917
|
+
env,
|
|
918
|
+
executionCtx,
|
|
919
|
+
notFoundHandler: this.#notFoundHandler
|
|
920
|
+
});
|
|
921
|
+
if (matchResult[0].length === 1) {
|
|
922
|
+
let res;
|
|
923
|
+
try {
|
|
924
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
925
|
+
c.res = await this.#notFoundHandler(c);
|
|
926
|
+
});
|
|
927
|
+
} catch (err) {
|
|
928
|
+
return this.#handleError(err, c);
|
|
929
|
+
}
|
|
930
|
+
return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
931
|
+
}
|
|
932
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
933
|
+
return (async () => {
|
|
934
|
+
try {
|
|
935
|
+
const context = await composed(c);
|
|
936
|
+
if (!context.finalized) {
|
|
937
|
+
throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
|
|
938
|
+
}
|
|
939
|
+
return context.res;
|
|
940
|
+
} catch (err) {
|
|
941
|
+
return this.#handleError(err, c);
|
|
942
|
+
}
|
|
943
|
+
})();
|
|
944
|
+
}
|
|
945
|
+
fetch = (request, ...rest) => {
|
|
946
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
947
|
+
};
|
|
948
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
949
|
+
if (input instanceof Request) {
|
|
950
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
951
|
+
}
|
|
952
|
+
input = input.toString();
|
|
953
|
+
return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
|
|
954
|
+
};
|
|
955
|
+
fire = () => {
|
|
956
|
+
addEventListener("fetch", (event) => {
|
|
957
|
+
event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
|
|
958
|
+
});
|
|
959
|
+
};
|
|
960
|
+
};
|
|
961
|
+
|
|
962
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
963
|
+
var emptyParam = [];
|
|
964
|
+
function match(method, path) {
|
|
965
|
+
const matchers = this.buildAllMatchers();
|
|
966
|
+
const match2 = (method2, path2) => {
|
|
967
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
968
|
+
const staticMatch = matcher[2][path2];
|
|
969
|
+
if (staticMatch) {
|
|
970
|
+
return staticMatch;
|
|
971
|
+
}
|
|
972
|
+
const match3 = path2.match(matcher[0]);
|
|
973
|
+
if (!match3) {
|
|
974
|
+
return [[], emptyParam];
|
|
975
|
+
}
|
|
976
|
+
const index = match3.indexOf("", 1);
|
|
977
|
+
return [matcher[1][index], match3];
|
|
978
|
+
};
|
|
979
|
+
this.match = match2;
|
|
980
|
+
return match2(method, path);
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/reg-exp-router/node.js
|
|
984
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
985
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
986
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
987
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
988
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
989
|
+
function compareKey(a, b) {
|
|
990
|
+
if (a.length === 1) {
|
|
991
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
992
|
+
}
|
|
993
|
+
if (b.length === 1) {
|
|
994
|
+
return 1;
|
|
995
|
+
}
|
|
996
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
997
|
+
return 1;
|
|
998
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
999
|
+
return -1;
|
|
1000
|
+
}
|
|
1001
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
1002
|
+
return 1;
|
|
1003
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
1004
|
+
return -1;
|
|
1005
|
+
}
|
|
1006
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
1007
|
+
}
|
|
1008
|
+
var Node = class _Node {
|
|
1009
|
+
#index;
|
|
1010
|
+
#varIndex;
|
|
1011
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
1012
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
1013
|
+
if (tokens.length === 0) {
|
|
1014
|
+
if (this.#index !== undefined) {
|
|
1015
|
+
throw PATH_ERROR;
|
|
1016
|
+
}
|
|
1017
|
+
if (pathErrorCheckOnly) {
|
|
1018
|
+
return;
|
|
1019
|
+
}
|
|
1020
|
+
this.#index = index;
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
const [token, ...restTokens] = tokens;
|
|
1024
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
1025
|
+
let node;
|
|
1026
|
+
if (pattern) {
|
|
1027
|
+
const name = pattern[1];
|
|
1028
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
1029
|
+
if (name && pattern[2]) {
|
|
1030
|
+
if (regexpStr === ".*") {
|
|
1031
|
+
throw PATH_ERROR;
|
|
1032
|
+
}
|
|
1033
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
1034
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
1035
|
+
throw PATH_ERROR;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
node = this.#children[regexpStr];
|
|
1039
|
+
if (!node) {
|
|
1040
|
+
if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
1041
|
+
throw PATH_ERROR;
|
|
1042
|
+
}
|
|
1043
|
+
if (pathErrorCheckOnly) {
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
node = this.#children[regexpStr] = new _Node;
|
|
1047
|
+
if (name !== "") {
|
|
1048
|
+
node.#varIndex = context.varIndex++;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
1052
|
+
paramMap.push([name, node.#varIndex]);
|
|
1053
|
+
}
|
|
1054
|
+
} else {
|
|
1055
|
+
node = this.#children[token];
|
|
1056
|
+
if (!node) {
|
|
1057
|
+
if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
1058
|
+
throw PATH_ERROR;
|
|
1059
|
+
}
|
|
1060
|
+
if (pathErrorCheckOnly) {
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
node = this.#children[token] = new _Node;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
1067
|
+
}
|
|
1068
|
+
buildRegExpStr() {
|
|
1069
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
1070
|
+
const strList = childKeys.map((k) => {
|
|
1071
|
+
const c = this.#children[k];
|
|
1072
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
1073
|
+
});
|
|
1074
|
+
if (typeof this.#index === "number") {
|
|
1075
|
+
strList.unshift(`#${this.#index}`);
|
|
1076
|
+
}
|
|
1077
|
+
if (strList.length === 0) {
|
|
1078
|
+
return "";
|
|
1079
|
+
}
|
|
1080
|
+
if (strList.length === 1) {
|
|
1081
|
+
return strList[0];
|
|
1082
|
+
}
|
|
1083
|
+
return "(?:" + strList.join("|") + ")";
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
1088
|
+
var Trie = class {
|
|
1089
|
+
#context = { varIndex: 0 };
|
|
1090
|
+
#root = new Node;
|
|
1091
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
1092
|
+
const paramAssoc = [];
|
|
1093
|
+
const groups = [];
|
|
1094
|
+
for (let i = 0;; ) {
|
|
1095
|
+
let replaced = false;
|
|
1096
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
1097
|
+
const mark = `@\\${i}`;
|
|
1098
|
+
groups[i] = [mark, m];
|
|
1099
|
+
i++;
|
|
1100
|
+
replaced = true;
|
|
1101
|
+
return mark;
|
|
1102
|
+
});
|
|
1103
|
+
if (!replaced) {
|
|
1104
|
+
break;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
1108
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
1109
|
+
const [mark] = groups[i];
|
|
1110
|
+
for (let j = tokens.length - 1;j >= 0; j--) {
|
|
1111
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
1112
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
1113
|
+
break;
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
1118
|
+
return paramAssoc;
|
|
1119
|
+
}
|
|
1120
|
+
buildRegExp() {
|
|
1121
|
+
let regexp = this.#root.buildRegExpStr();
|
|
1122
|
+
if (regexp === "") {
|
|
1123
|
+
return [/^$/, [], []];
|
|
1124
|
+
}
|
|
1125
|
+
let captureIndex = 0;
|
|
1126
|
+
const indexReplacementMap = [];
|
|
1127
|
+
const paramReplacementMap = [];
|
|
1128
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
1129
|
+
if (handlerIndex !== undefined) {
|
|
1130
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
1131
|
+
return "$()";
|
|
1132
|
+
}
|
|
1133
|
+
if (paramIndex !== undefined) {
|
|
1134
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
1135
|
+
return "";
|
|
1136
|
+
}
|
|
1137
|
+
return "";
|
|
1138
|
+
});
|
|
1139
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1143
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/reg-exp-router/router.js
|
|
1144
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
1145
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1146
|
+
function buildWildcardRegExp(path) {
|
|
1147
|
+
return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
|
|
1148
|
+
}
|
|
1149
|
+
function clearWildcardRegExpCache() {
|
|
1150
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1151
|
+
}
|
|
1152
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
1153
|
+
const trie = new Trie;
|
|
1154
|
+
const handlerData = [];
|
|
1155
|
+
if (routes.length === 0) {
|
|
1156
|
+
return nullMatcher;
|
|
1157
|
+
}
|
|
1158
|
+
const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
|
|
1159
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
1160
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
|
|
1161
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
1162
|
+
if (pathErrorCheckOnly) {
|
|
1163
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
1164
|
+
} else {
|
|
1165
|
+
j++;
|
|
1166
|
+
}
|
|
1167
|
+
let paramAssoc;
|
|
1168
|
+
try {
|
|
1169
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
1170
|
+
} catch (e) {
|
|
1171
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
1172
|
+
}
|
|
1173
|
+
if (pathErrorCheckOnly) {
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
1177
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
1178
|
+
paramCount -= 1;
|
|
1179
|
+
for (;paramCount >= 0; paramCount--) {
|
|
1180
|
+
const [key, value] = paramAssoc[paramCount];
|
|
1181
|
+
paramIndexMap[key] = value;
|
|
1182
|
+
}
|
|
1183
|
+
return [h, paramIndexMap];
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
1187
|
+
for (let i = 0, len = handlerData.length;i < len; i++) {
|
|
1188
|
+
for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
|
|
1189
|
+
const map = handlerData[i][j]?.[1];
|
|
1190
|
+
if (!map) {
|
|
1191
|
+
continue;
|
|
1192
|
+
}
|
|
1193
|
+
const keys = Object.keys(map);
|
|
1194
|
+
for (let k = 0, len3 = keys.length;k < len3; k++) {
|
|
1195
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
const handlerMap = [];
|
|
1200
|
+
for (const i in indexReplacementMap) {
|
|
1201
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
1202
|
+
}
|
|
1203
|
+
return [regexp, handlerMap, staticMap];
|
|
1204
|
+
}
|
|
1205
|
+
function findMiddleware(middleware, path) {
|
|
1206
|
+
if (!middleware) {
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
1209
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
1210
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
1211
|
+
return [...middleware[k]];
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
var RegExpRouter = class {
|
|
1217
|
+
name = "RegExpRouter";
|
|
1218
|
+
#middleware;
|
|
1219
|
+
#routes;
|
|
1220
|
+
constructor() {
|
|
1221
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1222
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1223
|
+
}
|
|
1224
|
+
add(method, path, handler) {
|
|
1225
|
+
const middleware = this.#middleware;
|
|
1226
|
+
const routes = this.#routes;
|
|
1227
|
+
if (!middleware || !routes) {
|
|
1228
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1229
|
+
}
|
|
1230
|
+
if (!middleware[method]) {
|
|
1231
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
1232
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
1233
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
1234
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
1235
|
+
});
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
if (path === "/*") {
|
|
1239
|
+
path = "*";
|
|
1240
|
+
}
|
|
1241
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
1242
|
+
if (/\*$/.test(path)) {
|
|
1243
|
+
const re = buildWildcardRegExp(path);
|
|
1244
|
+
if (method === METHOD_NAME_ALL) {
|
|
1245
|
+
Object.keys(middleware).forEach((m) => {
|
|
1246
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1247
|
+
});
|
|
1248
|
+
} else {
|
|
1249
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1250
|
+
}
|
|
1251
|
+
Object.keys(middleware).forEach((m) => {
|
|
1252
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1253
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
1254
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
});
|
|
1258
|
+
Object.keys(routes).forEach((m) => {
|
|
1259
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1260
|
+
Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
|
|
1261
|
+
}
|
|
1262
|
+
});
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
1266
|
+
for (let i = 0, len = paths.length;i < len; i++) {
|
|
1267
|
+
const path2 = paths[i];
|
|
1268
|
+
Object.keys(routes).forEach((m) => {
|
|
1269
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1270
|
+
routes[m][path2] ||= [
|
|
1271
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
1272
|
+
];
|
|
1273
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
1274
|
+
}
|
|
1275
|
+
});
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
match = match;
|
|
1279
|
+
buildAllMatchers() {
|
|
1280
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
1281
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
1282
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
1283
|
+
});
|
|
1284
|
+
this.#middleware = this.#routes = undefined;
|
|
1285
|
+
clearWildcardRegExpCache();
|
|
1286
|
+
return matchers;
|
|
1287
|
+
}
|
|
1288
|
+
#buildMatcher(method) {
|
|
1289
|
+
const routes = [];
|
|
1290
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
1291
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
1292
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
1293
|
+
if (ownRoute.length !== 0) {
|
|
1294
|
+
hasOwnRoute ||= true;
|
|
1295
|
+
routes.push(...ownRoute);
|
|
1296
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
1297
|
+
routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
|
|
1298
|
+
}
|
|
1299
|
+
});
|
|
1300
|
+
if (!hasOwnRoute) {
|
|
1301
|
+
return null;
|
|
1302
|
+
} else {
|
|
1303
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
};
|
|
1307
|
+
|
|
1308
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/reg-exp-router/prepared-router.js
|
|
1309
|
+
var PreparedRegExpRouter = class {
|
|
1310
|
+
name = "PreparedRegExpRouter";
|
|
1311
|
+
#matchers;
|
|
1312
|
+
#relocateMap;
|
|
1313
|
+
constructor(matchers, relocateMap) {
|
|
1314
|
+
this.#matchers = matchers;
|
|
1315
|
+
this.#relocateMap = relocateMap;
|
|
1316
|
+
}
|
|
1317
|
+
#addWildcard(method, handlerData) {
|
|
1318
|
+
const matcher = this.#matchers[method];
|
|
1319
|
+
matcher[1].forEach((list) => list && list.push(handlerData));
|
|
1320
|
+
Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
|
|
1321
|
+
}
|
|
1322
|
+
#addPath(method, path, handler, indexes, map) {
|
|
1323
|
+
const matcher = this.#matchers[method];
|
|
1324
|
+
if (!map) {
|
|
1325
|
+
matcher[2][path][0].push([handler, {}]);
|
|
1326
|
+
} else {
|
|
1327
|
+
indexes.forEach((index) => {
|
|
1328
|
+
if (typeof index === "number") {
|
|
1329
|
+
matcher[1][index].push([handler, map]);
|
|
1330
|
+
} else {
|
|
1331
|
+
matcher[2][index || path][0].push([handler, map]);
|
|
1332
|
+
}
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
add(method, path, handler) {
|
|
1337
|
+
if (!this.#matchers[method]) {
|
|
1338
|
+
const all = this.#matchers[METHOD_NAME_ALL];
|
|
1339
|
+
const staticMap = {};
|
|
1340
|
+
for (const key in all[2]) {
|
|
1341
|
+
staticMap[key] = [all[2][key][0].slice(), emptyParam];
|
|
1342
|
+
}
|
|
1343
|
+
this.#matchers[method] = [
|
|
1344
|
+
all[0],
|
|
1345
|
+
all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
|
|
1346
|
+
staticMap
|
|
1347
|
+
];
|
|
1348
|
+
}
|
|
1349
|
+
if (path === "/*" || path === "*") {
|
|
1350
|
+
const handlerData = [handler, {}];
|
|
1351
|
+
if (method === METHOD_NAME_ALL) {
|
|
1352
|
+
for (const m in this.#matchers) {
|
|
1353
|
+
this.#addWildcard(m, handlerData);
|
|
1354
|
+
}
|
|
1355
|
+
} else {
|
|
1356
|
+
this.#addWildcard(method, handlerData);
|
|
1357
|
+
}
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
const data = this.#relocateMap[path];
|
|
1361
|
+
if (!data) {
|
|
1362
|
+
throw new Error(`Path ${path} is not registered`);
|
|
1363
|
+
}
|
|
1364
|
+
for (const [indexes, map] of data) {
|
|
1365
|
+
if (method === METHOD_NAME_ALL) {
|
|
1366
|
+
for (const m in this.#matchers) {
|
|
1367
|
+
this.#addPath(m, path, handler, indexes, map);
|
|
1368
|
+
}
|
|
1369
|
+
} else {
|
|
1370
|
+
this.#addPath(method, path, handler, indexes, map);
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
buildAllMatchers() {
|
|
1375
|
+
return this.#matchers;
|
|
1376
|
+
}
|
|
1377
|
+
match = match;
|
|
1378
|
+
};
|
|
1379
|
+
|
|
1380
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/smart-router/router.js
|
|
1381
|
+
var SmartRouter = class {
|
|
1382
|
+
name = "SmartRouter";
|
|
1383
|
+
#routers = [];
|
|
1384
|
+
#routes = [];
|
|
1385
|
+
constructor(init) {
|
|
1386
|
+
this.#routers = init.routers;
|
|
1387
|
+
}
|
|
1388
|
+
add(method, path, handler) {
|
|
1389
|
+
if (!this.#routes) {
|
|
1390
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1391
|
+
}
|
|
1392
|
+
this.#routes.push([method, path, handler]);
|
|
1393
|
+
}
|
|
1394
|
+
match(method, path) {
|
|
1395
|
+
if (!this.#routes) {
|
|
1396
|
+
throw new Error("Fatal error");
|
|
1397
|
+
}
|
|
1398
|
+
const routers = this.#routers;
|
|
1399
|
+
const routes = this.#routes;
|
|
1400
|
+
const len = routers.length;
|
|
1401
|
+
let i = 0;
|
|
1402
|
+
let res;
|
|
1403
|
+
for (;i < len; i++) {
|
|
1404
|
+
const router = routers[i];
|
|
1405
|
+
try {
|
|
1406
|
+
for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
|
|
1407
|
+
router.add(...routes[i2]);
|
|
1408
|
+
}
|
|
1409
|
+
res = router.match(method, path);
|
|
1410
|
+
} catch (e) {
|
|
1411
|
+
if (e instanceof UnsupportedPathError) {
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
throw e;
|
|
1415
|
+
}
|
|
1416
|
+
this.match = router.match.bind(router);
|
|
1417
|
+
this.#routers = [router];
|
|
1418
|
+
this.#routes = undefined;
|
|
1419
|
+
break;
|
|
1420
|
+
}
|
|
1421
|
+
if (i === len) {
|
|
1422
|
+
throw new Error("Fatal error");
|
|
1423
|
+
}
|
|
1424
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
1425
|
+
return res;
|
|
1426
|
+
}
|
|
1427
|
+
get activeRouter() {
|
|
1428
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
1429
|
+
throw new Error("No active router has been determined yet.");
|
|
1430
|
+
}
|
|
1431
|
+
return this.#routers[0];
|
|
1432
|
+
}
|
|
1433
|
+
};
|
|
1434
|
+
|
|
1435
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/trie-router/node.js
|
|
1436
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
1437
|
+
var Node2 = class _Node2 {
|
|
1438
|
+
#methods;
|
|
1439
|
+
#children;
|
|
1440
|
+
#patterns;
|
|
1441
|
+
#order = 0;
|
|
1442
|
+
#params = emptyParams;
|
|
1443
|
+
constructor(method, handler, children) {
|
|
1444
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
1445
|
+
this.#methods = [];
|
|
1446
|
+
if (method && handler) {
|
|
1447
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
1448
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
1449
|
+
this.#methods = [m];
|
|
1450
|
+
}
|
|
1451
|
+
this.#patterns = [];
|
|
1452
|
+
}
|
|
1453
|
+
insert(method, path, handler) {
|
|
1454
|
+
this.#order = ++this.#order;
|
|
1455
|
+
let curNode = this;
|
|
1456
|
+
const parts = splitRoutingPath(path);
|
|
1457
|
+
const possibleKeys = [];
|
|
1458
|
+
for (let i = 0, len = parts.length;i < len; i++) {
|
|
1459
|
+
const p = parts[i];
|
|
1460
|
+
const nextP = parts[i + 1];
|
|
1461
|
+
const pattern = getPattern(p, nextP);
|
|
1462
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
1463
|
+
if (key in curNode.#children) {
|
|
1464
|
+
curNode = curNode.#children[key];
|
|
1465
|
+
if (pattern) {
|
|
1466
|
+
possibleKeys.push(pattern[1]);
|
|
1467
|
+
}
|
|
1468
|
+
continue;
|
|
1469
|
+
}
|
|
1470
|
+
curNode.#children[key] = new _Node2;
|
|
1471
|
+
if (pattern) {
|
|
1472
|
+
curNode.#patterns.push(pattern);
|
|
1473
|
+
possibleKeys.push(pattern[1]);
|
|
1474
|
+
}
|
|
1475
|
+
curNode = curNode.#children[key];
|
|
1476
|
+
}
|
|
1477
|
+
curNode.#methods.push({
|
|
1478
|
+
[method]: {
|
|
1479
|
+
handler,
|
|
1480
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
1481
|
+
score: this.#order
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
return curNode;
|
|
1485
|
+
}
|
|
1486
|
+
#getHandlerSets(node, method, nodeParams, params) {
|
|
1487
|
+
const handlerSets = [];
|
|
1488
|
+
for (let i = 0, len = node.#methods.length;i < len; i++) {
|
|
1489
|
+
const m = node.#methods[i];
|
|
1490
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
1491
|
+
const processedSet = {};
|
|
1492
|
+
if (handlerSet !== undefined) {
|
|
1493
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
1494
|
+
handlerSets.push(handlerSet);
|
|
1495
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
1496
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
|
|
1497
|
+
const key = handlerSet.possibleKeys[i2];
|
|
1498
|
+
const processed = processedSet[handlerSet.score];
|
|
1499
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
1500
|
+
processedSet[handlerSet.score] = true;
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
return handlerSets;
|
|
1506
|
+
}
|
|
1507
|
+
search(method, path) {
|
|
1508
|
+
const handlerSets = [];
|
|
1509
|
+
this.#params = emptyParams;
|
|
1510
|
+
const curNode = this;
|
|
1511
|
+
let curNodes = [curNode];
|
|
1512
|
+
const parts = splitPath(path);
|
|
1513
|
+
const curNodesQueue = [];
|
|
1514
|
+
for (let i = 0, len = parts.length;i < len; i++) {
|
|
1515
|
+
const part = parts[i];
|
|
1516
|
+
const isLast = i === len - 1;
|
|
1517
|
+
const tempNodes = [];
|
|
1518
|
+
for (let j = 0, len2 = curNodes.length;j < len2; j++) {
|
|
1519
|
+
const node = curNodes[j];
|
|
1520
|
+
const nextNode = node.#children[part];
|
|
1521
|
+
if (nextNode) {
|
|
1522
|
+
nextNode.#params = node.#params;
|
|
1523
|
+
if (isLast) {
|
|
1524
|
+
if (nextNode.#children["*"]) {
|
|
1525
|
+
handlerSets.push(...this.#getHandlerSets(nextNode.#children["*"], method, node.#params));
|
|
1526
|
+
}
|
|
1527
|
+
handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
|
|
1528
|
+
} else {
|
|
1529
|
+
tempNodes.push(nextNode);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
|
|
1533
|
+
const pattern = node.#patterns[k];
|
|
1534
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
1535
|
+
if (pattern === "*") {
|
|
1536
|
+
const astNode = node.#children["*"];
|
|
1537
|
+
if (astNode) {
|
|
1538
|
+
handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
|
|
1539
|
+
astNode.#params = params;
|
|
1540
|
+
tempNodes.push(astNode);
|
|
1541
|
+
}
|
|
1542
|
+
continue;
|
|
1543
|
+
}
|
|
1544
|
+
const [key, name, matcher] = pattern;
|
|
1545
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
1546
|
+
continue;
|
|
1547
|
+
}
|
|
1548
|
+
const child = node.#children[key];
|
|
1549
|
+
const restPathString = parts.slice(i).join("/");
|
|
1550
|
+
if (matcher instanceof RegExp) {
|
|
1551
|
+
const m = matcher.exec(restPathString);
|
|
1552
|
+
if (m) {
|
|
1553
|
+
params[name] = m[0];
|
|
1554
|
+
handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
|
|
1555
|
+
if (Object.keys(child.#children).length) {
|
|
1556
|
+
child.#params = params;
|
|
1557
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
1558
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
1559
|
+
targetCurNodes.push(child);
|
|
1560
|
+
}
|
|
1561
|
+
continue;
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
if (matcher === true || matcher.test(part)) {
|
|
1565
|
+
params[name] = part;
|
|
1566
|
+
if (isLast) {
|
|
1567
|
+
handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
|
|
1568
|
+
if (child.#children["*"]) {
|
|
1569
|
+
handlerSets.push(...this.#getHandlerSets(child.#children["*"], method, params, node.#params));
|
|
1570
|
+
}
|
|
1571
|
+
} else {
|
|
1572
|
+
child.#params = params;
|
|
1573
|
+
tempNodes.push(child);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
|
|
1579
|
+
}
|
|
1580
|
+
if (handlerSets.length > 1) {
|
|
1581
|
+
handlerSets.sort((a, b) => {
|
|
1582
|
+
return a.score - b.score;
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
|
|
1589
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/trie-router/router.js
|
|
1590
|
+
var TrieRouter = class {
|
|
1591
|
+
name = "TrieRouter";
|
|
1592
|
+
#node;
|
|
1593
|
+
constructor() {
|
|
1594
|
+
this.#node = new Node2;
|
|
1595
|
+
}
|
|
1596
|
+
add(method, path, handler) {
|
|
1597
|
+
const results = checkOptionalParameter(path);
|
|
1598
|
+
if (results) {
|
|
1599
|
+
for (let i = 0, len = results.length;i < len; i++) {
|
|
1600
|
+
this.#node.insert(method, results[i], handler);
|
|
1601
|
+
}
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
this.#node.insert(method, path, handler);
|
|
1605
|
+
}
|
|
1606
|
+
match(method, path) {
|
|
1607
|
+
return this.#node.search(method, path);
|
|
1608
|
+
}
|
|
1609
|
+
};
|
|
1610
|
+
|
|
1611
|
+
// ../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/hono.js
|
|
1612
|
+
var Hono2 = class extends Hono {
|
|
1613
|
+
constructor(options = {}) {
|
|
1614
|
+
super(options);
|
|
1615
|
+
this.router = options.router ?? new SmartRouter({
|
|
1616
|
+
routers: [new RegExpRouter, new TrieRouter]
|
|
1617
|
+
});
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
|
|
1621
|
+
// src/routes.ts
|
|
1622
|
+
import { readFileSync } from "fs";
|
|
1623
|
+
import { resolve } from "path";
|
|
1624
|
+
|
|
1625
|
+
// src/auth.ts
|
|
1626
|
+
import { createHash, randomBytes } from "crypto";
|
|
1627
|
+
function generateToken() {
|
|
1628
|
+
return `sv_${randomBytes(16).toString("hex")}`;
|
|
1629
|
+
}
|
|
1630
|
+
function hashToken(raw2) {
|
|
1631
|
+
return createHash("sha256").update(raw2).digest("hex");
|
|
1632
|
+
}
|
|
1633
|
+
function extractToken(c) {
|
|
1634
|
+
const header = c.req.header("Authorization");
|
|
1635
|
+
if (header) {
|
|
1636
|
+
const match2 = header.match(/^Bearer\s+(.+)$/i);
|
|
1637
|
+
if (match2)
|
|
1638
|
+
return match2[1];
|
|
1639
|
+
}
|
|
1640
|
+
return c.req.query("token") || null;
|
|
1641
|
+
}
|
|
1642
|
+
async function authMiddleware(c, next) {
|
|
1643
|
+
const raw2 = extractToken(c);
|
|
1644
|
+
if (!raw2) {
|
|
1645
|
+
return c.json({ error: "Missing or invalid Authorization header" }, 401);
|
|
1646
|
+
}
|
|
1647
|
+
const keyHash = hashToken(raw2);
|
|
1648
|
+
const apiKey = getApiKeyByHash(keyHash);
|
|
1649
|
+
if (!apiKey) {
|
|
1650
|
+
return c.json({ error: "Invalid token" }, 401);
|
|
1651
|
+
}
|
|
1652
|
+
const contributor = getContributor(apiKey.contributor);
|
|
1653
|
+
if (!contributor) {
|
|
1654
|
+
return c.json({ error: "Token references a contributor that no longer exists" }, 401);
|
|
1655
|
+
}
|
|
1656
|
+
touchApiKey(apiKey.id);
|
|
1657
|
+
c.set("authCtx", { apiKey, contributor });
|
|
1658
|
+
await next();
|
|
1659
|
+
}
|
|
1660
|
+
function getAuthCtx(c) {
|
|
1661
|
+
return c.get("authCtx");
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
// src/storage.ts
|
|
1665
|
+
import { join, dirname, relative, sep } from "path";
|
|
1666
|
+
import { mkdir, writeFile, unlink, readdir, stat, readFile, rename, rmdir } from "fs/promises";
|
|
1667
|
+
import { existsSync } from "fs";
|
|
1668
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1669
|
+
var MAX_FILE_SIZE = 10 * 1024 * 1024;
|
|
1670
|
+
function validatePath(filePath) {
|
|
1671
|
+
if (!filePath || filePath.length === 0) {
|
|
1672
|
+
return "Path cannot be empty";
|
|
1673
|
+
}
|
|
1674
|
+
if (filePath.startsWith("/")) {
|
|
1675
|
+
return "Path cannot start with /";
|
|
1676
|
+
}
|
|
1677
|
+
if (filePath.includes("\\")) {
|
|
1678
|
+
return "Path cannot contain backslashes";
|
|
1679
|
+
}
|
|
1680
|
+
if (filePath.includes("//")) {
|
|
1681
|
+
return "Path cannot contain double slashes";
|
|
1682
|
+
}
|
|
1683
|
+
if (!filePath.endsWith(".md")) {
|
|
1684
|
+
return "Path must end in .md";
|
|
1685
|
+
}
|
|
1686
|
+
const segments = filePath.split("/");
|
|
1687
|
+
for (const seg of segments) {
|
|
1688
|
+
if (seg === "." || seg === "..") {
|
|
1689
|
+
return "Path cannot contain . or .. segments";
|
|
1690
|
+
}
|
|
1691
|
+
if (seg.length === 0) {
|
|
1692
|
+
return "Path cannot contain empty segments";
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
return null;
|
|
1696
|
+
}
|
|
1697
|
+
function resolvePath(storageRoot, contributor, filePath) {
|
|
1698
|
+
return join(storageRoot, contributor, filePath);
|
|
1699
|
+
}
|
|
1700
|
+
async function ensureContributorDir(storageRoot, contributor) {
|
|
1701
|
+
const dir = join(storageRoot, contributor);
|
|
1702
|
+
await mkdir(dir, { recursive: true });
|
|
1703
|
+
}
|
|
1704
|
+
async function writeFileAtomic(storageRoot, contributor, filePath, content) {
|
|
1705
|
+
const contentBuf = typeof content === "string" ? Buffer.from(content) : content;
|
|
1706
|
+
if (contentBuf.length > MAX_FILE_SIZE) {
|
|
1707
|
+
throw new FileTooLargeError(contentBuf.length);
|
|
1708
|
+
}
|
|
1709
|
+
const absPath = resolvePath(storageRoot, contributor, filePath);
|
|
1710
|
+
const dir = dirname(absPath);
|
|
1711
|
+
await mkdir(dir, { recursive: true });
|
|
1712
|
+
const tmpPath = `${absPath}.tmp.${randomUUID2().slice(0, 8)}`;
|
|
1713
|
+
try {
|
|
1714
|
+
await writeFile(tmpPath, contentBuf);
|
|
1715
|
+
await rename(tmpPath, absPath);
|
|
1716
|
+
} catch (e) {
|
|
1717
|
+
try {
|
|
1718
|
+
await unlink(tmpPath);
|
|
1719
|
+
} catch {}
|
|
1720
|
+
throw e;
|
|
1721
|
+
}
|
|
1722
|
+
const fileStat = await stat(absPath);
|
|
1723
|
+
return {
|
|
1724
|
+
path: filePath,
|
|
1725
|
+
size: fileStat.size,
|
|
1726
|
+
modifiedAt: fileStat.mtime.toISOString()
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
async function deleteFile(storageRoot, contributor, filePath) {
|
|
1730
|
+
const absPath = resolvePath(storageRoot, contributor, filePath);
|
|
1731
|
+
if (!existsSync(absPath)) {
|
|
1732
|
+
throw new FileNotFoundError(filePath);
|
|
1733
|
+
}
|
|
1734
|
+
await unlink(absPath);
|
|
1735
|
+
const contributorRoot = join(storageRoot, contributor);
|
|
1736
|
+
let dir = dirname(absPath);
|
|
1737
|
+
while (dir !== contributorRoot && dir.startsWith(contributorRoot)) {
|
|
1738
|
+
try {
|
|
1739
|
+
await rmdir(dir);
|
|
1740
|
+
dir = dirname(dir);
|
|
1741
|
+
} catch {
|
|
1742
|
+
break;
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
async function readFileContent(storageRoot, contributor, filePath) {
|
|
1747
|
+
const absPath = resolvePath(storageRoot, contributor, filePath);
|
|
1748
|
+
if (!existsSync(absPath)) {
|
|
1749
|
+
throw new FileNotFoundError(filePath);
|
|
1750
|
+
}
|
|
1751
|
+
return await readFile(absPath, "utf-8");
|
|
1752
|
+
}
|
|
1753
|
+
async function listFiles(storageRoot, contributor, prefix) {
|
|
1754
|
+
const contributorRoot = join(storageRoot, contributor);
|
|
1755
|
+
if (!existsSync(contributorRoot)) {
|
|
1756
|
+
return [];
|
|
1757
|
+
}
|
|
1758
|
+
const files = [];
|
|
1759
|
+
await walkDir(contributorRoot, contributorRoot, prefix, files);
|
|
1760
|
+
files.sort((a, b) => b.modifiedAt.localeCompare(a.modifiedAt));
|
|
1761
|
+
return files;
|
|
1762
|
+
}
|
|
1763
|
+
async function walkDir(dir, contributorRoot, prefix, results) {
|
|
1764
|
+
let entries;
|
|
1765
|
+
try {
|
|
1766
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
1767
|
+
} catch {
|
|
1768
|
+
return;
|
|
1769
|
+
}
|
|
1770
|
+
for (const entry of entries) {
|
|
1771
|
+
const fullPath = join(dir, entry.name);
|
|
1772
|
+
if (entry.isDirectory()) {
|
|
1773
|
+
await walkDir(fullPath, contributorRoot, prefix, results);
|
|
1774
|
+
} else if (entry.isFile() && entry.name.endsWith(".md")) {
|
|
1775
|
+
const relPath = relative(contributorRoot, fullPath).split(sep).join("/");
|
|
1776
|
+
if (prefix && !relPath.startsWith(prefix)) {
|
|
1777
|
+
continue;
|
|
1778
|
+
}
|
|
1779
|
+
const fileStat = await stat(fullPath);
|
|
1780
|
+
results.push({
|
|
1781
|
+
path: relPath,
|
|
1782
|
+
size: fileStat.size,
|
|
1783
|
+
modifiedAt: fileStat.mtime.toISOString()
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
class FileNotFoundError extends Error {
|
|
1790
|
+
constructor(path) {
|
|
1791
|
+
super(`File not found: ${path}`);
|
|
1792
|
+
this.name = "FileNotFoundError";
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
class FileTooLargeError extends Error {
|
|
1797
|
+
size;
|
|
1798
|
+
constructor(size) {
|
|
1799
|
+
super(`File too large: ${size} bytes (max ${MAX_FILE_SIZE})`);
|
|
1800
|
+
this.name = "FileTooLargeError";
|
|
1801
|
+
this.size = size;
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
// src/sse.ts
|
|
1806
|
+
var clients = new Set;
|
|
1807
|
+
function addClient(controller) {
|
|
1808
|
+
clients.add(controller);
|
|
1809
|
+
}
|
|
1810
|
+
function removeClient(controller) {
|
|
1811
|
+
clients.delete(controller);
|
|
1812
|
+
}
|
|
1813
|
+
function broadcast(event, data) {
|
|
1814
|
+
const message = `event: ${event}
|
|
1815
|
+
data: ${JSON.stringify(data)}
|
|
1816
|
+
|
|
1817
|
+
`;
|
|
1818
|
+
const encoded = new TextEncoder().encode(message);
|
|
1819
|
+
for (const controller of clients) {
|
|
1820
|
+
try {
|
|
1821
|
+
controller.enqueue(encoded);
|
|
1822
|
+
} catch {
|
|
1823
|
+
clients.delete(controller);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
// src/qmd.ts
|
|
1829
|
+
async function isQmdAvailable() {
|
|
1830
|
+
try {
|
|
1831
|
+
const proc = Bun.spawn(["qmd", "status"], { stdout: "pipe", stderr: "pipe" });
|
|
1832
|
+
await proc.exited;
|
|
1833
|
+
return true;
|
|
1834
|
+
} catch {
|
|
1835
|
+
return false;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
async function addCollection(storageRoot, contributor) {
|
|
1839
|
+
const dir = `${storageRoot}/${contributor.username}`;
|
|
1840
|
+
const proc = Bun.spawn(["qmd", "collection", "add", dir, "--name", contributor.username, "--mask", "**/*.md"], { stdout: "pipe", stderr: "pipe" });
|
|
1841
|
+
const exitCode = await proc.exited;
|
|
1842
|
+
if (exitCode !== 0) {
|
|
1843
|
+
const stderr = await new Response(proc.stderr).text();
|
|
1844
|
+
if (!stderr.includes("already exists")) {
|
|
1845
|
+
console.error(`QMD collection add failed for ${contributor.username}:`, stderr);
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
var updateInFlight = false;
|
|
1850
|
+
var updateQueued = false;
|
|
1851
|
+
function triggerUpdate() {
|
|
1852
|
+
if (updateInFlight) {
|
|
1853
|
+
updateQueued = true;
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
runUpdate();
|
|
1857
|
+
}
|
|
1858
|
+
async function runUpdate() {
|
|
1859
|
+
updateInFlight = true;
|
|
1860
|
+
try {
|
|
1861
|
+
const proc = Bun.spawn(["qmd", "update"], { stdout: "pipe", stderr: "pipe" });
|
|
1862
|
+
const exitCode = await proc.exited;
|
|
1863
|
+
if (exitCode !== 0) {
|
|
1864
|
+
const stderr = await new Response(proc.stderr).text();
|
|
1865
|
+
console.error("QMD update failed:", stderr);
|
|
1866
|
+
}
|
|
1867
|
+
} catch (e) {
|
|
1868
|
+
console.error("QMD update error:", e);
|
|
1869
|
+
} finally {
|
|
1870
|
+
updateInFlight = false;
|
|
1871
|
+
if (updateQueued) {
|
|
1872
|
+
updateQueued = false;
|
|
1873
|
+
runUpdate();
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
async function search(query, options = {}) {
|
|
1878
|
+
const limit = options.limit ?? 10;
|
|
1879
|
+
const args = ["search", query, "--json", "-n", String(limit)];
|
|
1880
|
+
if (options.collection) {
|
|
1881
|
+
args.push("-c", options.collection);
|
|
1882
|
+
}
|
|
1883
|
+
try {
|
|
1884
|
+
const proc = Bun.spawn(["qmd", ...args], { stdout: "pipe", stderr: "pipe" });
|
|
1885
|
+
const stdout = await new Response(proc.stdout).text();
|
|
1886
|
+
const exitCode = await proc.exited;
|
|
1887
|
+
if (exitCode !== 0) {
|
|
1888
|
+
const stderr = await new Response(proc.stderr).text();
|
|
1889
|
+
console.error("QMD search failed:", stderr);
|
|
1890
|
+
return [];
|
|
1891
|
+
}
|
|
1892
|
+
if (!stdout.trim())
|
|
1893
|
+
return [];
|
|
1894
|
+
return JSON.parse(stdout);
|
|
1895
|
+
} catch (e) {
|
|
1896
|
+
console.error("QMD search error:", e);
|
|
1897
|
+
return [];
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
async function syncContributors(storageRoot, contributors) {
|
|
1901
|
+
for (const contributor of contributors) {
|
|
1902
|
+
await addCollection(storageRoot, contributor);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
// src/routes.ts
|
|
1907
|
+
var uiPath = resolve(import.meta.dirname, "index.html");
|
|
1908
|
+
var isDev = true;
|
|
1909
|
+
var uiHtmlCached = readFileSync(uiPath, "utf-8");
|
|
1910
|
+
function extractFilePath(reqPath, username) {
|
|
1911
|
+
const raw2 = reqPath.replace(`/v1/contributors/${username}/files/`, "");
|
|
1912
|
+
try {
|
|
1913
|
+
return decodeURIComponent(raw2);
|
|
1914
|
+
} catch {
|
|
1915
|
+
return null;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
function createApp(storageRoot) {
|
|
1919
|
+
const app = new Hono2;
|
|
1920
|
+
app.get("/", (c) => {
|
|
1921
|
+
return c.html(isDev ? readFileSync(uiPath, "utf-8") : uiHtmlCached);
|
|
1922
|
+
});
|
|
1923
|
+
app.get("/health", (c) => {
|
|
1924
|
+
return c.json({ status: "ok" });
|
|
1925
|
+
});
|
|
1926
|
+
app.post("/v1/signup", async (c) => {
|
|
1927
|
+
const body = await c.req.json();
|
|
1928
|
+
if (!body.name || typeof body.name !== "string" || body.name.trim().length === 0) {
|
|
1929
|
+
return c.json({ error: "name is required" }, 400);
|
|
1930
|
+
}
|
|
1931
|
+
const username = body.name.trim();
|
|
1932
|
+
const usernameError = validateUsername(username);
|
|
1933
|
+
if (usernameError) {
|
|
1934
|
+
return c.json({ error: usernameError }, 400);
|
|
1935
|
+
}
|
|
1936
|
+
const isFirstUser = !hasAnyContributor();
|
|
1937
|
+
if (!isFirstUser) {
|
|
1938
|
+
if (!body.invite) {
|
|
1939
|
+
return c.json({ error: "Invite code is required" }, 400);
|
|
1940
|
+
}
|
|
1941
|
+
const invite = getInvite(body.invite);
|
|
1942
|
+
if (!invite) {
|
|
1943
|
+
return c.json({ error: "Invalid invite code" }, 400);
|
|
1944
|
+
}
|
|
1945
|
+
if (invite.used_at) {
|
|
1946
|
+
return c.json({ error: "Invite code has already been used" }, 400);
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
if (getContributor(username)) {
|
|
1950
|
+
return c.json({ error: "A contributor with that username already exists" }, 409);
|
|
1951
|
+
}
|
|
1952
|
+
const contributor = createContributor(username, isFirstUser);
|
|
1953
|
+
await ensureContributorDir(storageRoot, contributor.username);
|
|
1954
|
+
addCollection(storageRoot, contributor).catch((e) => console.error("Failed to register QMD collection:", e));
|
|
1955
|
+
const rawToken = generateToken();
|
|
1956
|
+
createApiKey(hashToken(rawToken), `${username}-default`, contributor.username);
|
|
1957
|
+
if (!isFirstUser && body.invite) {
|
|
1958
|
+
markInviteUsed(body.invite, contributor.username);
|
|
1959
|
+
}
|
|
1960
|
+
return c.json({
|
|
1961
|
+
contributor: {
|
|
1962
|
+
username: contributor.username,
|
|
1963
|
+
createdAt: contributor.created_at
|
|
1964
|
+
},
|
|
1965
|
+
token: rawToken
|
|
1966
|
+
}, 201);
|
|
1967
|
+
});
|
|
1968
|
+
const authed = new Hono2;
|
|
1969
|
+
authed.use("*", authMiddleware);
|
|
1970
|
+
authed.get("/v1/me", (c) => {
|
|
1971
|
+
const { contributor } = getAuthCtx(c);
|
|
1972
|
+
return c.json({
|
|
1973
|
+
username: contributor.username,
|
|
1974
|
+
createdAt: contributor.created_at
|
|
1975
|
+
});
|
|
1976
|
+
});
|
|
1977
|
+
authed.post("/v1/invites", (c) => {
|
|
1978
|
+
const { contributor } = getAuthCtx(c);
|
|
1979
|
+
if (!contributor.is_operator) {
|
|
1980
|
+
return c.json({ error: "Only the operator can generate invite codes" }, 403);
|
|
1981
|
+
}
|
|
1982
|
+
const invite = createInvite(contributor.username);
|
|
1983
|
+
return c.json({
|
|
1984
|
+
invite: invite.id,
|
|
1985
|
+
createdAt: invite.created_at
|
|
1986
|
+
}, 201);
|
|
1987
|
+
});
|
|
1988
|
+
authed.get("/v1/contributors", (c) => {
|
|
1989
|
+
const contributors = listContributors();
|
|
1990
|
+
return c.json({
|
|
1991
|
+
contributors: contributors.map((b) => ({
|
|
1992
|
+
username: b.username,
|
|
1993
|
+
createdAt: b.created_at
|
|
1994
|
+
}))
|
|
1995
|
+
});
|
|
1996
|
+
});
|
|
1997
|
+
authed.put("/v1/contributors/:username/files/*", async (c) => {
|
|
1998
|
+
const { contributor } = getAuthCtx(c);
|
|
1999
|
+
const username = c.req.param("username");
|
|
2000
|
+
if (contributor.username !== username) {
|
|
2001
|
+
return c.json({ error: "You can only write to your own contributor" }, 403);
|
|
2002
|
+
}
|
|
2003
|
+
if (!getContributor(username)) {
|
|
2004
|
+
return c.json({ error: "Contributor not found" }, 404);
|
|
2005
|
+
}
|
|
2006
|
+
const filePath = extractFilePath(c.req.path, username);
|
|
2007
|
+
if (filePath === null) {
|
|
2008
|
+
return c.json({ error: "Invalid URL encoding in path" }, 400);
|
|
2009
|
+
}
|
|
2010
|
+
const pathError = validatePath(filePath);
|
|
2011
|
+
if (pathError) {
|
|
2012
|
+
return c.json({ error: pathError }, 400);
|
|
2013
|
+
}
|
|
2014
|
+
const content = await c.req.text();
|
|
2015
|
+
try {
|
|
2016
|
+
const result = await writeFileAtomic(storageRoot, username, filePath, content);
|
|
2017
|
+
broadcast("file_updated", {
|
|
2018
|
+
contributor: username,
|
|
2019
|
+
path: result.path,
|
|
2020
|
+
size: result.size,
|
|
2021
|
+
modifiedAt: result.modifiedAt
|
|
2022
|
+
});
|
|
2023
|
+
triggerUpdate();
|
|
2024
|
+
return c.json(result);
|
|
2025
|
+
} catch (e) {
|
|
2026
|
+
if (e instanceof FileTooLargeError) {
|
|
2027
|
+
return c.json({ error: e.message }, 413);
|
|
2028
|
+
}
|
|
2029
|
+
throw e;
|
|
2030
|
+
}
|
|
2031
|
+
});
|
|
2032
|
+
authed.delete("/v1/contributors/:username/files/*", async (c) => {
|
|
2033
|
+
const { contributor } = getAuthCtx(c);
|
|
2034
|
+
const username = c.req.param("username");
|
|
2035
|
+
if (contributor.username !== username) {
|
|
2036
|
+
return c.json({ error: "You can only delete from your own contributor" }, 403);
|
|
2037
|
+
}
|
|
2038
|
+
const filePath = extractFilePath(c.req.path, username);
|
|
2039
|
+
if (filePath === null) {
|
|
2040
|
+
return c.json({ error: "Invalid URL encoding in path" }, 400);
|
|
2041
|
+
}
|
|
2042
|
+
const pathError = validatePath(filePath);
|
|
2043
|
+
if (pathError) {
|
|
2044
|
+
return c.json({ error: pathError }, 400);
|
|
2045
|
+
}
|
|
2046
|
+
try {
|
|
2047
|
+
await deleteFile(storageRoot, username, filePath);
|
|
2048
|
+
broadcast("file_deleted", {
|
|
2049
|
+
contributor: username,
|
|
2050
|
+
path: filePath
|
|
2051
|
+
});
|
|
2052
|
+
triggerUpdate();
|
|
2053
|
+
return c.body(null, 204);
|
|
2054
|
+
} catch (e) {
|
|
2055
|
+
if (e instanceof FileNotFoundError) {
|
|
2056
|
+
return c.json({ error: "File not found" }, 404);
|
|
2057
|
+
}
|
|
2058
|
+
throw e;
|
|
2059
|
+
}
|
|
2060
|
+
});
|
|
2061
|
+
authed.get("/v1/contributors/:username/files", async (c) => {
|
|
2062
|
+
const username = c.req.param("username");
|
|
2063
|
+
if (!getContributor(username)) {
|
|
2064
|
+
return c.json({ error: "Contributor not found" }, 404);
|
|
2065
|
+
}
|
|
2066
|
+
const prefix = c.req.query("prefix") || undefined;
|
|
2067
|
+
const files = await listFiles(storageRoot, username, prefix);
|
|
2068
|
+
return c.json({ files });
|
|
2069
|
+
});
|
|
2070
|
+
authed.get("/v1/contributors/:username/files/*", async (c) => {
|
|
2071
|
+
const username = c.req.param("username");
|
|
2072
|
+
if (!getContributor(username)) {
|
|
2073
|
+
return c.json({ error: "Contributor not found" }, 404);
|
|
2074
|
+
}
|
|
2075
|
+
const filePath = extractFilePath(c.req.path, username);
|
|
2076
|
+
if (filePath === null) {
|
|
2077
|
+
return c.json({ error: "Invalid URL encoding in path" }, 400);
|
|
2078
|
+
}
|
|
2079
|
+
const pathError = validatePath(filePath);
|
|
2080
|
+
if (pathError) {
|
|
2081
|
+
return c.json({ error: pathError }, 400);
|
|
2082
|
+
}
|
|
2083
|
+
try {
|
|
2084
|
+
const content = await readFileContent(storageRoot, username, filePath);
|
|
2085
|
+
return c.text(content, 200, {
|
|
2086
|
+
"Content-Type": "text/markdown"
|
|
2087
|
+
});
|
|
2088
|
+
} catch (e) {
|
|
2089
|
+
if (e instanceof FileNotFoundError) {
|
|
2090
|
+
return c.json({ error: "File not found" }, 404);
|
|
2091
|
+
}
|
|
2092
|
+
throw e;
|
|
2093
|
+
}
|
|
2094
|
+
});
|
|
2095
|
+
authed.get("/v1/events", (c) => {
|
|
2096
|
+
let ctrl;
|
|
2097
|
+
const stream = new ReadableStream({
|
|
2098
|
+
start(controller) {
|
|
2099
|
+
ctrl = controller;
|
|
2100
|
+
addClient(controller);
|
|
2101
|
+
const msg = `event: connected
|
|
2102
|
+
data: {}
|
|
2103
|
+
|
|
2104
|
+
`;
|
|
2105
|
+
controller.enqueue(new TextEncoder().encode(msg));
|
|
2106
|
+
},
|
|
2107
|
+
cancel() {
|
|
2108
|
+
removeClient(ctrl);
|
|
2109
|
+
}
|
|
2110
|
+
});
|
|
2111
|
+
return new Response(stream, {
|
|
2112
|
+
headers: {
|
|
2113
|
+
"Content-Type": "text/event-stream",
|
|
2114
|
+
"Cache-Control": "no-cache",
|
|
2115
|
+
Connection: "keep-alive"
|
|
2116
|
+
}
|
|
2117
|
+
});
|
|
2118
|
+
});
|
|
2119
|
+
authed.get("/v1/search", async (c) => {
|
|
2120
|
+
const q = c.req.query("q");
|
|
2121
|
+
if (!q) {
|
|
2122
|
+
return c.json({ error: "q parameter is required" }, 400);
|
|
2123
|
+
}
|
|
2124
|
+
const contributorParam = c.req.query("contributor") || undefined;
|
|
2125
|
+
const limit = parseInt(c.req.query("limit") || "10", 10);
|
|
2126
|
+
let collectionName;
|
|
2127
|
+
if (contributorParam) {
|
|
2128
|
+
const contributor = getContributor(contributorParam);
|
|
2129
|
+
if (!contributor) {
|
|
2130
|
+
return c.json({ error: "Contributor not found" }, 404);
|
|
2131
|
+
}
|
|
2132
|
+
collectionName = contributor.username;
|
|
2133
|
+
}
|
|
2134
|
+
const results = await search(q, { collection: collectionName, limit });
|
|
2135
|
+
return c.json({ results });
|
|
2136
|
+
});
|
|
2137
|
+
app.route("/", authed);
|
|
2138
|
+
return app;
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
// src/index.ts
|
|
2142
|
+
var PORT = parseInt(process.env.PORT || "3000", 10);
|
|
2143
|
+
var DATA_DIR = process.env.DATA_DIR || join2(homedir(), ".seedvault", "data");
|
|
2144
|
+
var dbPath = join2(DATA_DIR, "seedvault.db");
|
|
2145
|
+
var storageRoot = join2(DATA_DIR, "files");
|
|
2146
|
+
await mkdir2(DATA_DIR, { recursive: true });
|
|
2147
|
+
await mkdir2(storageRoot, { recursive: true });
|
|
2148
|
+
initDb(dbPath);
|
|
2149
|
+
var app = createApp(storageRoot);
|
|
2150
|
+
console.log(`Seedvault server starting on port ${PORT}`);
|
|
2151
|
+
console.log(` Data dir: ${DATA_DIR}`);
|
|
2152
|
+
console.log(` Database: ${dbPath}`);
|
|
2153
|
+
console.log(` Storage: ${storageRoot}`);
|
|
2154
|
+
var qmdAvailable = await isQmdAvailable();
|
|
2155
|
+
if (qmdAvailable) {
|
|
2156
|
+
console.log(" QMD: available");
|
|
2157
|
+
const contributors = listContributors();
|
|
2158
|
+
if (contributors.length > 0) {
|
|
2159
|
+
await syncContributors(storageRoot, contributors);
|
|
2160
|
+
console.log(` QMD: synced ${contributors.length} collection(s)`);
|
|
2161
|
+
}
|
|
2162
|
+
} else {
|
|
2163
|
+
console.log(" QMD: not found (search disabled)");
|
|
2164
|
+
}
|
|
2165
|
+
var src_default = {
|
|
2166
|
+
port: PORT,
|
|
2167
|
+
fetch: app.fetch
|
|
2168
|
+
};
|
|
2169
|
+
export {
|
|
2170
|
+
src_default as default
|
|
2171
|
+
};
|