@codemem/core 0.22.0-alpha.5 → 0.22.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.
Files changed (56) hide show
  1. package/dist/api-types.d.ts +7 -0
  2. package/dist/api-types.d.ts.map +1 -1
  3. package/dist/better-sqlite-coordinator-runtime.d.ts.map +1 -1
  4. package/dist/better-sqlite-coordinator-store.d.ts +3 -1
  5. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  6. package/dist/coordinator-api-CEbQ6LHE.js +1575 -0
  7. package/dist/coordinator-api-CEbQ6LHE.js.map +1 -0
  8. package/dist/coordinator-api.d.ts +23 -2
  9. package/dist/coordinator-api.d.ts.map +1 -1
  10. package/dist/coordinator-invites.d.ts.map +1 -1
  11. package/dist/coordinator-runtime.d.ts +13 -1
  12. package/dist/coordinator-runtime.d.ts.map +1 -1
  13. package/dist/coordinator-store-contract.d.ts +23 -0
  14. package/dist/coordinator-store-contract.d.ts.map +1 -1
  15. package/dist/coordinator-store-test-harness.d.ts.map +1 -1
  16. package/dist/coordinator-store.d.ts +1 -1
  17. package/dist/coordinator-store.d.ts.map +1 -1
  18. package/dist/d1-coordinator-runtime.d.ts +2 -1
  19. package/dist/d1-coordinator-runtime.d.ts.map +1 -1
  20. package/dist/d1-coordinator-store.d.ts +3 -1
  21. package/dist/d1-coordinator-store.d.ts.map +1 -1
  22. package/dist/db.d.ts.map +1 -1
  23. package/dist/index.d.ts +6 -5
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +3182 -1919
  26. package/dist/index.js.map +1 -1
  27. package/dist/internal/cloudflare-coordinator.d.ts +2 -0
  28. package/dist/internal/cloudflare-coordinator.d.ts.map +1 -1
  29. package/dist/internal/cloudflare-coordinator.js +118 -70
  30. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  31. package/dist/maintenance.d.ts.map +1 -1
  32. package/dist/raw-event-flush.d.ts.map +1 -1
  33. package/dist/request-rate-limit.d.ts +12 -0
  34. package/dist/request-rate-limit.d.ts.map +1 -0
  35. package/dist/schema.d.ts +152 -0
  36. package/dist/schema.d.ts.map +1 -1
  37. package/dist/store.d.ts +5 -0
  38. package/dist/store.d.ts.map +1 -1
  39. package/dist/sync-auth-constants.d.ts +2 -0
  40. package/dist/sync-auth-constants.d.ts.map +1 -0
  41. package/dist/sync-auth.d.ts +0 -1
  42. package/dist/sync-auth.d.ts.map +1 -1
  43. package/dist/sync-daemon.d.ts +7 -0
  44. package/dist/sync-daemon.d.ts.map +1 -1
  45. package/dist/sync-fingerprint.d.ts +3 -0
  46. package/dist/sync-fingerprint.d.ts.map +1 -0
  47. package/dist/sync-identity.d.ts +1 -2
  48. package/dist/sync-identity.d.ts.map +1 -1
  49. package/dist/sync-replication.d.ts.map +1 -1
  50. package/dist/test-schema.generated.d.ts +1 -1
  51. package/dist/test-schema.generated.d.ts.map +1 -1
  52. package/dist/types.d.ts +4 -0
  53. package/dist/types.d.ts.map +1 -1
  54. package/package.json +2 -1
  55. package/dist/coordinator-api-By9BNOCL.js +0 -2397
  56. package/dist/coordinator-api-By9BNOCL.js.map +0 -1
@@ -0,0 +1,1575 @@
1
+ import { createHash as e } from "node:crypto";
2
+ //#region ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/compose.js
3
+ var t = (e, t, n) => (r, i) => {
4
+ let a = -1;
5
+ return o(0);
6
+ async function o(s) {
7
+ if (s <= a) throw Error("next() called multiple times");
8
+ a = s;
9
+ let c, l = !1, u;
10
+ if (e[s] ? (u = e[s][0][0], r.req.routeIndex = s) : u = s === e.length && i || void 0, u) try {
11
+ c = await u(r, () => o(s + 1));
12
+ } catch (e) {
13
+ if (e instanceof Error && t) r.error = e, c = await t(e, r), l = !0;
14
+ else throw e;
15
+ }
16
+ else r.finalized === !1 && n && (c = await n(r));
17
+ return c && (r.finalized === !1 || l) && (r.res = c), r;
18
+ }
19
+ }, n = /* @__PURE__ */ Symbol(), r = async (e, t = /* @__PURE__ */ Object.create(null)) => {
20
+ let { all: n = !1, dot: r = !1 } = t, a = (e instanceof T ? e.raw.headers : e.headers).get("Content-Type");
21
+ return a?.startsWith("multipart/form-data") || a?.startsWith("application/x-www-form-urlencoded") ? i(e, {
22
+ all: n,
23
+ dot: r
24
+ }) : {};
25
+ };
26
+ async function i(e, t) {
27
+ let n = await e.formData();
28
+ return n ? a(n, t) : {};
29
+ }
30
+ function a(e, t) {
31
+ let n = /* @__PURE__ */ Object.create(null);
32
+ return e.forEach((e, r) => {
33
+ t.all || r.endsWith("[]") ? o(n, r, e) : n[r] = e;
34
+ }), t.dot && Object.entries(n).forEach(([e, t]) => {
35
+ e.includes(".") && (s(n, e, t), delete n[e]);
36
+ }), n;
37
+ }
38
+ var o = (e, t, n) => {
39
+ e[t] === void 0 ? t.endsWith("[]") ? e[t] = [n] : e[t] = n : Array.isArray(e[t]) ? e[t].push(n) : e[t] = [e[t], n];
40
+ }, s = (e, t, n) => {
41
+ if (/(?:^|\.)__proto__\./.test(t)) return;
42
+ let r = e, i = t.split(".");
43
+ i.forEach((e, t) => {
44
+ t === i.length - 1 ? r[e] = n : ((!r[e] || typeof r[e] != "object" || Array.isArray(r[e]) || r[e] instanceof File) && (r[e] = /* @__PURE__ */ Object.create(null)), r = r[e]);
45
+ });
46
+ }, c = (e) => {
47
+ let t = e.split("/");
48
+ return t[0] === "" && t.shift(), t;
49
+ }, l = (e) => {
50
+ let { groups: t, path: n } = u(e);
51
+ return d(c(n), t);
52
+ }, u = (e) => {
53
+ let t = [];
54
+ return e = e.replace(/\{[^}]+\}/g, (e, n) => {
55
+ let r = `@${n}`;
56
+ return t.push([r, e]), r;
57
+ }), {
58
+ groups: t,
59
+ path: e
60
+ };
61
+ }, d = (e, t) => {
62
+ for (let n = t.length - 1; n >= 0; n--) {
63
+ let [r] = t[n];
64
+ for (let i = e.length - 1; i >= 0; i--) if (e[i].includes(r)) {
65
+ e[i] = e[i].replace(r, t[n][1]);
66
+ break;
67
+ }
68
+ }
69
+ return e;
70
+ }, f = {}, p = (e, t) => {
71
+ if (e === "*") return "*";
72
+ let n = e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
73
+ if (n) {
74
+ let r = `${e}#${t}`;
75
+ return f[r] || (n[2] ? f[r] = t && t[0] !== ":" && t[0] !== "*" ? [
76
+ r,
77
+ n[1],
78
+ RegExp(`^${n[2]}(?=/${t})`)
79
+ ] : [
80
+ e,
81
+ n[1],
82
+ RegExp(`^${n[2]}$`)
83
+ ] : f[r] = [
84
+ e,
85
+ n[1],
86
+ !0
87
+ ]), f[r];
88
+ }
89
+ return null;
90
+ }, m = (e, t) => {
91
+ try {
92
+ return t(e);
93
+ } catch {
94
+ return e.replace(/(?:%[0-9A-Fa-f]{2})+/g, (e) => {
95
+ try {
96
+ return t(e);
97
+ } catch {
98
+ return e;
99
+ }
100
+ });
101
+ }
102
+ }, h = (e) => m(e, decodeURI), g = (e) => {
103
+ let t = e.url, n = t.indexOf("/", t.indexOf(":") + 4), r = n;
104
+ for (; r < t.length; r++) {
105
+ let e = t.charCodeAt(r);
106
+ if (e === 37) {
107
+ let e = t.indexOf("?", r), i = t.indexOf("#", r), a = e === -1 ? i === -1 ? void 0 : i : i === -1 ? e : Math.min(e, i), o = t.slice(n, a);
108
+ return h(o.includes("%25") ? o.replace(/%25/g, "%2525") : o);
109
+ } else if (e === 63 || e === 35) break;
110
+ }
111
+ return t.slice(n, r);
112
+ }, _ = (e) => {
113
+ let t = g(e);
114
+ return t.length > 1 && t.at(-1) === "/" ? t.slice(0, -1) : t;
115
+ }, v = (e, t, ...n) => (n.length && (t = v(t, ...n)), `${e?.[0] === "/" ? "" : "/"}${e}${t === "/" ? "" : `${e?.at(-1) === "/" ? "" : "/"}${t?.[0] === "/" ? t.slice(1) : t}`}`), y = (e) => {
116
+ if (e.charCodeAt(e.length - 1) !== 63 || !e.includes(":")) return null;
117
+ let t = e.split("/"), n = [], r = "";
118
+ return t.forEach((e) => {
119
+ if (e !== "" && !/\:/.test(e)) r += "/" + e;
120
+ else if (/\:/.test(e)) if (/\?/.test(e)) {
121
+ n.length === 0 && r === "" ? n.push("/") : n.push(r);
122
+ let t = e.replace("?", "");
123
+ r += "/" + t, n.push(r);
124
+ } else r += "/" + e;
125
+ }), n.filter((e, t, n) => n.indexOf(e) === t);
126
+ }, b = (e) => /[%+]/.test(e) ? (e.indexOf("+") !== -1 && (e = e.replace(/\+/g, " ")), e.indexOf("%") === -1 ? e : m(e, C)) : e, x = (e, t, n) => {
127
+ let r;
128
+ if (!n && t && !/[%+]/.test(t)) {
129
+ let n = e.indexOf("?", 8);
130
+ if (n === -1) return;
131
+ for (e.startsWith(t, n + 1) || (n = e.indexOf(`&${t}`, n + 1)); n !== -1;) {
132
+ let r = e.charCodeAt(n + t.length + 1);
133
+ if (r === 61) {
134
+ let r = n + t.length + 2, i = e.indexOf("&", r);
135
+ return b(e.slice(r, i === -1 ? void 0 : i));
136
+ } else if (r == 38 || isNaN(r)) return "";
137
+ n = e.indexOf(`&${t}`, n + 1);
138
+ }
139
+ if (r = /[%+]/.test(e), !r) return;
140
+ }
141
+ let i = {};
142
+ r ??= /[%+]/.test(e);
143
+ let a = e.indexOf("?", 8);
144
+ for (; a !== -1;) {
145
+ let t = e.indexOf("&", a + 1), o = e.indexOf("=", a);
146
+ o > t && t !== -1 && (o = -1);
147
+ let s = e.slice(a + 1, o === -1 ? t === -1 ? void 0 : t : o);
148
+ if (r && (s = b(s)), a = t, s === "") continue;
149
+ let c;
150
+ o === -1 ? c = "" : (c = e.slice(o + 1, t === -1 ? void 0 : t), r && (c = b(c))), n ? (i[s] && Array.isArray(i[s]) || (i[s] = []), i[s].push(c)) : i[s] ??= c;
151
+ }
152
+ return t ? i[t] : i;
153
+ }, ee = x, S = (e, t) => x(e, t, !0), C = decodeURIComponent, w = (e) => m(e, C), T = class {
154
+ raw;
155
+ #e;
156
+ #t;
157
+ routeIndex = 0;
158
+ path;
159
+ bodyCache = {};
160
+ constructor(e, t = "/", n = [[]]) {
161
+ this.raw = e, this.path = t, this.#t = n, this.#e = {};
162
+ }
163
+ param(e) {
164
+ return e ? this.#n(e) : this.#r();
165
+ }
166
+ #n(e) {
167
+ let t = this.#t[0][this.routeIndex][1][e], n = this.#i(t);
168
+ return n && /\%/.test(n) ? w(n) : n;
169
+ }
170
+ #r() {
171
+ let e = {}, t = Object.keys(this.#t[0][this.routeIndex][1]);
172
+ for (let n of t) {
173
+ let t = this.#i(this.#t[0][this.routeIndex][1][n]);
174
+ t !== void 0 && (e[n] = /\%/.test(t) ? w(t) : t);
175
+ }
176
+ return e;
177
+ }
178
+ #i(e) {
179
+ return this.#t[1] ? this.#t[1][e] : e;
180
+ }
181
+ query(e) {
182
+ return ee(this.url, e);
183
+ }
184
+ queries(e) {
185
+ return S(this.url, e);
186
+ }
187
+ header(e) {
188
+ if (e) return this.raw.headers.get(e) ?? void 0;
189
+ let t = {};
190
+ return this.raw.headers.forEach((e, n) => {
191
+ t[n] = e;
192
+ }), t;
193
+ }
194
+ async parseBody(e) {
195
+ return this.bodyCache.parsedBody ??= await r(this, e);
196
+ }
197
+ #a = (e) => {
198
+ let { bodyCache: t, raw: n } = this, r = t[e];
199
+ if (r) return r;
200
+ let i = Object.keys(t)[0];
201
+ return i ? t[i].then((t) => (i === "json" && (t = JSON.stringify(t)), new Response(t)[e]())) : t[e] = n[e]();
202
+ };
203
+ json() {
204
+ return this.#a("text").then((e) => JSON.parse(e));
205
+ }
206
+ text() {
207
+ return this.#a("text");
208
+ }
209
+ arrayBuffer() {
210
+ return this.#a("arrayBuffer");
211
+ }
212
+ blob() {
213
+ return this.#a("blob");
214
+ }
215
+ formData() {
216
+ return this.#a("formData");
217
+ }
218
+ addValidatedData(e, t) {
219
+ this.#e[e] = t;
220
+ }
221
+ valid(e) {
222
+ return this.#e[e];
223
+ }
224
+ get url() {
225
+ return this.raw.url;
226
+ }
227
+ get method() {
228
+ return this.raw.method;
229
+ }
230
+ get [n]() {
231
+ return this.#t;
232
+ }
233
+ get matchedRoutes() {
234
+ return this.#t[0].map(([[, e]]) => e);
235
+ }
236
+ get routePath() {
237
+ return this.#t[0].map(([[, e]]) => e)[this.routeIndex].path;
238
+ }
239
+ }, te = {
240
+ Stringify: 1,
241
+ BeforeStream: 2,
242
+ Stream: 3
243
+ }, ne = (e, t) => {
244
+ let n = new String(e);
245
+ return n.isEscaped = !0, n.callbacks = t, n;
246
+ }, E = async (e, t, n, r, i) => {
247
+ typeof e == "object" && !(e instanceof String) && (e instanceof Promise || (e = e.toString()), e instanceof Promise && (e = await e));
248
+ let a = e.callbacks;
249
+ if (!a?.length) return Promise.resolve(e);
250
+ i ? i[0] += e : i = [e];
251
+ let o = Promise.all(a.map((e) => e({
252
+ phase: t,
253
+ buffer: i,
254
+ context: r
255
+ }))).then((e) => Promise.all(e.filter(Boolean).map((e) => E(e, t, !1, r, i))).then(() => i[0]));
256
+ return n ? ne(await o, a) : o;
257
+ }, re = "text/plain; charset=UTF-8", D = (e, t) => ({
258
+ "Content-Type": e,
259
+ ...t
260
+ }), O = (e, t) => new Response(e, t), k = class {
261
+ #e;
262
+ #t;
263
+ env = {};
264
+ #n;
265
+ finalized = !1;
266
+ error;
267
+ #r;
268
+ #i;
269
+ #a;
270
+ #o;
271
+ #s;
272
+ #c;
273
+ #l;
274
+ #u;
275
+ #d;
276
+ constructor(e, t) {
277
+ this.#e = e, t && (this.#i = t.executionCtx, this.env = t.env, this.#c = t.notFoundHandler, this.#d = t.path, this.#u = t.matchResult);
278
+ }
279
+ get req() {
280
+ return this.#t ??= new T(this.#e, this.#d, this.#u), this.#t;
281
+ }
282
+ get event() {
283
+ if (this.#i && "respondWith" in this.#i) return this.#i;
284
+ throw Error("This context has no FetchEvent");
285
+ }
286
+ get executionCtx() {
287
+ if (this.#i) return this.#i;
288
+ throw Error("This context has no ExecutionContext");
289
+ }
290
+ get res() {
291
+ return this.#a ||= O(null, { headers: this.#l ??= new Headers() });
292
+ }
293
+ set res(e) {
294
+ if (this.#a && e) {
295
+ e = O(e.body, e);
296
+ for (let [t, n] of this.#a.headers.entries()) if (t !== "content-type") if (t === "set-cookie") {
297
+ let t = this.#a.headers.getSetCookie();
298
+ e.headers.delete("set-cookie");
299
+ for (let n of t) e.headers.append("set-cookie", n);
300
+ } else e.headers.set(t, n);
301
+ }
302
+ this.#a = e, this.finalized = !0;
303
+ }
304
+ render = (...e) => (this.#s ??= (e) => this.html(e), this.#s(...e));
305
+ setLayout = (e) => this.#o = e;
306
+ getLayout = () => this.#o;
307
+ setRenderer = (e) => {
308
+ this.#s = e;
309
+ };
310
+ header = (e, t, n) => {
311
+ this.finalized && (this.#a = O(this.#a.body, this.#a));
312
+ let r = this.#a ? this.#a.headers : this.#l ??= new Headers();
313
+ t === void 0 ? r.delete(e) : n?.append ? r.append(e, t) : r.set(e, t);
314
+ };
315
+ status = (e) => {
316
+ this.#r = e;
317
+ };
318
+ set = (e, t) => {
319
+ this.#n ??= /* @__PURE__ */ new Map(), this.#n.set(e, t);
320
+ };
321
+ get = (e) => this.#n ? this.#n.get(e) : void 0;
322
+ get var() {
323
+ return this.#n ? Object.fromEntries(this.#n) : {};
324
+ }
325
+ #f(e, t, n) {
326
+ let r = this.#a ? new Headers(this.#a.headers) : this.#l ?? new Headers();
327
+ if (typeof t == "object" && "headers" in t) {
328
+ let e = t.headers instanceof Headers ? t.headers : new Headers(t.headers);
329
+ for (let [t, n] of e) t.toLowerCase() === "set-cookie" ? r.append(t, n) : r.set(t, n);
330
+ }
331
+ if (n) for (let [e, t] of Object.entries(n)) if (typeof t == "string") r.set(e, t);
332
+ else {
333
+ r.delete(e);
334
+ for (let n of t) r.append(e, n);
335
+ }
336
+ return O(e, {
337
+ status: typeof t == "number" ? t : t?.status ?? this.#r,
338
+ headers: r
339
+ });
340
+ }
341
+ newResponse = (...e) => this.#f(...e);
342
+ body = (e, t, n) => this.#f(e, t, n);
343
+ text = (e, t, n) => !this.#l && !this.#r && !t && !n && !this.finalized ? new Response(e) : this.#f(e, t, D(re, n));
344
+ json = (e, t, n) => this.#f(JSON.stringify(e), t, D("application/json", n));
345
+ html = (e, t, n) => {
346
+ let r = (e) => this.#f(e, t, D("text/html; charset=UTF-8", n));
347
+ return typeof e == "object" ? E(e, te.Stringify, !1, {}).then(r) : r(e);
348
+ };
349
+ redirect = (e, t) => {
350
+ let n = String(e);
351
+ return this.header("Location", /[^\x00-\xFF]/.test(n) ? encodeURI(n) : n), this.newResponse(null, t ?? 302);
352
+ };
353
+ notFound = () => (this.#c ??= () => O(), this.#c(this));
354
+ }, ie = [
355
+ "get",
356
+ "post",
357
+ "put",
358
+ "delete",
359
+ "options",
360
+ "patch"
361
+ ], A = "Can not add a route since the matcher is already built.", j = class extends Error {}, ae = "__COMPOSED_HANDLER", oe = (e) => e.text("404 Not Found", 404), M = (e, t) => {
362
+ if ("getResponse" in e) {
363
+ let n = e.getResponse();
364
+ return t.newResponse(n.body, n);
365
+ }
366
+ return console.error(e), t.text("Internal Server Error", 500);
367
+ }, se = class e {
368
+ get;
369
+ post;
370
+ put;
371
+ delete;
372
+ options;
373
+ patch;
374
+ all;
375
+ on;
376
+ use;
377
+ router;
378
+ getPath;
379
+ _basePath = "/";
380
+ #e = "/";
381
+ routes = [];
382
+ constructor(e = {}) {
383
+ [...ie, "all"].forEach((e) => {
384
+ this[e] = (t, ...n) => (typeof t == "string" ? this.#e = t : this.#r(e, this.#e, t), n.forEach((t) => {
385
+ this.#r(e, this.#e, t);
386
+ }), this);
387
+ }), this.on = (e, t, ...n) => {
388
+ for (let r of [t].flat()) {
389
+ this.#e = r;
390
+ for (let t of [e].flat()) n.map((e) => {
391
+ this.#r(t.toUpperCase(), this.#e, e);
392
+ });
393
+ }
394
+ return this;
395
+ }, this.use = (e, ...t) => (typeof e == "string" ? this.#e = e : (this.#e = "*", t.unshift(e)), t.forEach((e) => {
396
+ this.#r("ALL", this.#e, e);
397
+ }), this);
398
+ let { strict: t, ...n } = e;
399
+ Object.assign(this, n), this.getPath = t ?? !0 ? e.getPath ?? g : _;
400
+ }
401
+ #t() {
402
+ let t = new e({
403
+ router: this.router,
404
+ getPath: this.getPath
405
+ });
406
+ return t.errorHandler = this.errorHandler, t.#n = this.#n, t.routes = this.routes, t;
407
+ }
408
+ #n = oe;
409
+ errorHandler = M;
410
+ route(e, n) {
411
+ let r = this.basePath(e);
412
+ return n.routes.map((e) => {
413
+ let i;
414
+ n.errorHandler === M ? i = e.handler : (i = async (r, i) => (await t([], n.errorHandler)(r, () => e.handler(r, i))).res, i[ae] = e.handler), r.#r(e.method, e.path, i);
415
+ }), this;
416
+ }
417
+ basePath(e) {
418
+ let t = this.#t();
419
+ return t._basePath = v(this._basePath, e), t;
420
+ }
421
+ onError = (e) => (this.errorHandler = e, this);
422
+ notFound = (e) => (this.#n = e, this);
423
+ mount(e, t, n) {
424
+ let r, i;
425
+ n && (typeof n == "function" ? i = n : (i = n.optionHandler, r = n.replaceRequest === !1 ? (e) => e : n.replaceRequest));
426
+ let a = i ? (e) => {
427
+ let t = i(e);
428
+ return Array.isArray(t) ? t : [t];
429
+ } : (e) => {
430
+ let t;
431
+ try {
432
+ t = e.executionCtx;
433
+ } catch {}
434
+ return [e.env, t];
435
+ };
436
+ return r ||= (() => {
437
+ let t = v(this._basePath, e), n = t === "/" ? 0 : t.length;
438
+ return (e) => {
439
+ let t = new URL(e.url);
440
+ return t.pathname = t.pathname.slice(n) || "/", new Request(t, e);
441
+ };
442
+ })(), this.#r("ALL", v(e, "*"), async (e, n) => {
443
+ let i = await t(r(e.req.raw), ...a(e));
444
+ if (i) return i;
445
+ await n();
446
+ }), this;
447
+ }
448
+ #r(e, t, n) {
449
+ e = e.toUpperCase(), t = v(this._basePath, t);
450
+ let r = {
451
+ basePath: this._basePath,
452
+ path: t,
453
+ method: e,
454
+ handler: n
455
+ };
456
+ this.router.add(e, t, [n, r]), this.routes.push(r);
457
+ }
458
+ #i(e, t) {
459
+ if (e instanceof Error) return this.errorHandler(e, t);
460
+ throw e;
461
+ }
462
+ #a(e, n, r, i) {
463
+ if (i === "HEAD") return (async () => new Response(null, await this.#a(e, n, r, "GET")))();
464
+ let a = this.getPath(e, { env: r }), o = this.router.match(i, a), s = new k(e, {
465
+ path: a,
466
+ matchResult: o,
467
+ env: r,
468
+ executionCtx: n,
469
+ notFoundHandler: this.#n
470
+ });
471
+ if (o[0].length === 1) {
472
+ let e;
473
+ try {
474
+ e = o[0][0][0][0](s, async () => {
475
+ s.res = await this.#n(s);
476
+ });
477
+ } catch (e) {
478
+ return this.#i(e, s);
479
+ }
480
+ return e instanceof Promise ? e.then((e) => e || (s.finalized ? s.res : this.#n(s))).catch((e) => this.#i(e, s)) : e ?? this.#n(s);
481
+ }
482
+ let c = t(o[0], this.errorHandler, this.#n);
483
+ return (async () => {
484
+ try {
485
+ let e = await c(s);
486
+ if (!e.finalized) throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
487
+ return e.res;
488
+ } catch (e) {
489
+ return this.#i(e, s);
490
+ }
491
+ })();
492
+ }
493
+ fetch = (e, ...t) => this.#a(e, t[1], t[0], e.method);
494
+ request = (e, t, n, r) => e instanceof Request ? this.fetch(t ? new Request(e, t) : e, n, r) : (e = e.toString(), this.fetch(new Request(/^https?:\/\//.test(e) ? e : `http://localhost${v("/", e)}`, t), n, r));
495
+ fire = () => {
496
+ addEventListener("fetch", (e) => {
497
+ e.respondWith(this.#a(e.request, e, void 0, e.request.method));
498
+ });
499
+ };
500
+ }, N = [];
501
+ function P(e, t) {
502
+ let n = this.buildAllMatchers(), r = ((e, t) => {
503
+ let r = n[e] || n.ALL, i = r[2][t];
504
+ if (i) return i;
505
+ let a = t.match(r[0]);
506
+ if (!a) return [[], N];
507
+ let o = a.indexOf("", 1);
508
+ return [r[1][o], a];
509
+ });
510
+ return this.match = r, r(e, t);
511
+ }
512
+ //#endregion
513
+ //#region ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/reg-exp-router/node.js
514
+ var F = "[^/]+", I = ".*", L = "(?:|/.*)", R = /* @__PURE__ */ Symbol(), ce = /* @__PURE__ */ new Set(".\\+*[^]$()");
515
+ function le(e, t) {
516
+ return e.length === 1 ? t.length === 1 ? e < t ? -1 : 1 : -1 : t.length === 1 || e === I || e === L ? 1 : t === I || t === L ? -1 : e === F ? 1 : t === F ? -1 : e.length === t.length ? e < t ? -1 : 1 : t.length - e.length;
517
+ }
518
+ var ue = class e {
519
+ #e;
520
+ #t;
521
+ #n = /* @__PURE__ */ Object.create(null);
522
+ insert(t, n, r, i, a) {
523
+ if (t.length === 0) {
524
+ if (this.#e !== void 0) throw R;
525
+ if (a) return;
526
+ this.#e = n;
527
+ return;
528
+ }
529
+ let [o, ...s] = t, c = o === "*" ? s.length === 0 ? [
530
+ "",
531
+ "",
532
+ I
533
+ ] : [
534
+ "",
535
+ "",
536
+ F
537
+ ] : o === "/*" ? [
538
+ "",
539
+ "",
540
+ L
541
+ ] : o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/), l;
542
+ if (c) {
543
+ let t = c[1], n = c[2] || F;
544
+ if (t && c[2] && (n === ".*" || (n = n.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"), /\((?!\?:)/.test(n)))) throw R;
545
+ if (l = this.#n[n], !l) {
546
+ if (Object.keys(this.#n).some((e) => e !== I && e !== L)) throw R;
547
+ if (a) return;
548
+ l = this.#n[n] = new e(), t !== "" && (l.#t = i.varIndex++);
549
+ }
550
+ !a && t !== "" && r.push([t, l.#t]);
551
+ } else if (l = this.#n[o], !l) {
552
+ if (Object.keys(this.#n).some((e) => e.length > 1 && e !== I && e !== L)) throw R;
553
+ if (a) return;
554
+ l = this.#n[o] = new e();
555
+ }
556
+ l.insert(s, n, r, i, a);
557
+ }
558
+ buildRegExpStr() {
559
+ let e = Object.keys(this.#n).sort(le).map((e) => {
560
+ let t = this.#n[e];
561
+ return (typeof t.#t == "number" ? `(${e})@${t.#t}` : ce.has(e) ? `\\${e}` : e) + t.buildRegExpStr();
562
+ });
563
+ return typeof this.#e == "number" && e.unshift(`#${this.#e}`), e.length === 0 ? "" : e.length === 1 ? e[0] : "(?:" + e.join("|") + ")";
564
+ }
565
+ }, de = class {
566
+ #e = { varIndex: 0 };
567
+ #t = new ue();
568
+ insert(e, t, n) {
569
+ let r = [], i = [];
570
+ for (let t = 0;;) {
571
+ let n = !1;
572
+ if (e = e.replace(/\{[^}]+\}/g, (e) => {
573
+ let r = `@\\${t}`;
574
+ return i[t] = [r, e], t++, n = !0, r;
575
+ }), !n) break;
576
+ }
577
+ let a = e.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
578
+ for (let e = i.length - 1; e >= 0; e--) {
579
+ let [t] = i[e];
580
+ for (let n = a.length - 1; n >= 0; n--) if (a[n].indexOf(t) !== -1) {
581
+ a[n] = a[n].replace(t, i[e][1]);
582
+ break;
583
+ }
584
+ }
585
+ return this.#t.insert(a, t, r, this.#e, n), r;
586
+ }
587
+ buildRegExp() {
588
+ let e = this.#t.buildRegExpStr();
589
+ if (e === "") return [
590
+ /^$/,
591
+ [],
592
+ []
593
+ ];
594
+ let t = 0, n = [], r = [];
595
+ return e = e.replace(/#(\d+)|@(\d+)|\.\*\$/g, (e, i, a) => i === void 0 ? (a === void 0 || (r[Number(a)] = ++t), "") : (n[++t] = Number(i), "$()")), [
596
+ RegExp(`^${e}`),
597
+ n,
598
+ r
599
+ ];
600
+ }
601
+ }, fe = [
602
+ /^$/,
603
+ [],
604
+ /* @__PURE__ */ Object.create(null)
605
+ ], z = /* @__PURE__ */ Object.create(null);
606
+ function B(e) {
607
+ return z[e] ??= RegExp(e === "*" ? "" : `^${e.replace(/\/\*$|([.\\+*[^\]$()])/g, (e, t) => t ? `\\${t}` : "(?:|/.*)")}$`);
608
+ }
609
+ function V() {
610
+ z = /* @__PURE__ */ Object.create(null);
611
+ }
612
+ function pe(e) {
613
+ let t = new de(), n = [];
614
+ if (e.length === 0) return fe;
615
+ let r = e.map((e) => [!/\*|\/:/.test(e[0]), ...e]).sort(([e, t], [n, r]) => e ? 1 : n ? -1 : t.length - r.length), i = /* @__PURE__ */ Object.create(null);
616
+ for (let e = 0, a = -1, o = r.length; e < o; e++) {
617
+ let [o, s, c] = r[e];
618
+ o ? i[s] = [c.map(([e]) => [e, /* @__PURE__ */ Object.create(null)]), N] : a++;
619
+ let l;
620
+ try {
621
+ l = t.insert(s, a, o);
622
+ } catch (e) {
623
+ throw e === R ? new j(s) : e;
624
+ }
625
+ o || (n[a] = c.map(([e, t]) => {
626
+ let n = /* @__PURE__ */ Object.create(null);
627
+ for (--t; t >= 0; t--) {
628
+ let [e, r] = l[t];
629
+ n[e] = r;
630
+ }
631
+ return [e, n];
632
+ }));
633
+ }
634
+ let [a, o, s] = t.buildRegExp();
635
+ for (let e = 0, t = n.length; e < t; e++) for (let t = 0, r = n[e].length; t < r; t++) {
636
+ let r = n[e][t]?.[1];
637
+ if (!r) continue;
638
+ let i = Object.keys(r);
639
+ for (let e = 0, t = i.length; e < t; e++) r[i[e]] = s[r[i[e]]];
640
+ }
641
+ let c = [];
642
+ for (let e in o) c[e] = n[o[e]];
643
+ return [
644
+ a,
645
+ c,
646
+ i
647
+ ];
648
+ }
649
+ function H(e, t) {
650
+ if (e) {
651
+ for (let n of Object.keys(e).sort((e, t) => t.length - e.length)) if (B(n).test(t)) return [...e[n]];
652
+ }
653
+ }
654
+ var me = class {
655
+ name = "RegExpRouter";
656
+ #e;
657
+ #t;
658
+ constructor() {
659
+ this.#e = { ALL: /* @__PURE__ */ Object.create(null) }, this.#t = { ALL: /* @__PURE__ */ Object.create(null) };
660
+ }
661
+ add(e, t, n) {
662
+ let r = this.#e, i = this.#t;
663
+ if (!r || !i) throw Error(A);
664
+ r[e] || [r, i].forEach((t) => {
665
+ t[e] = /* @__PURE__ */ Object.create(null), Object.keys(t.ALL).forEach((n) => {
666
+ t[e][n] = [...t.ALL[n]];
667
+ });
668
+ }), t === "/*" && (t = "*");
669
+ let a = (t.match(/\/:/g) || []).length;
670
+ if (/\*$/.test(t)) {
671
+ let o = B(t);
672
+ e === "ALL" ? Object.keys(r).forEach((e) => {
673
+ r[e][t] ||= H(r[e], t) || H(r.ALL, t) || [];
674
+ }) : r[e][t] ||= H(r[e], t) || H(r.ALL, t) || [], Object.keys(r).forEach((t) => {
675
+ (e === "ALL" || e === t) && Object.keys(r[t]).forEach((e) => {
676
+ o.test(e) && r[t][e].push([n, a]);
677
+ });
678
+ }), Object.keys(i).forEach((t) => {
679
+ (e === "ALL" || e === t) && Object.keys(i[t]).forEach((e) => o.test(e) && i[t][e].push([n, a]));
680
+ });
681
+ return;
682
+ }
683
+ let o = y(t) || [t];
684
+ for (let t = 0, s = o.length; t < s; t++) {
685
+ let c = o[t];
686
+ Object.keys(i).forEach((o) => {
687
+ (e === "ALL" || e === o) && (i[o][c] ||= [...H(r[o], c) || H(r.ALL, c) || []], i[o][c].push([n, a - s + t + 1]));
688
+ });
689
+ }
690
+ }
691
+ match = P;
692
+ buildAllMatchers() {
693
+ let e = /* @__PURE__ */ Object.create(null);
694
+ return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach((t) => {
695
+ e[t] ||= this.#n(t);
696
+ }), this.#e = this.#t = void 0, V(), e;
697
+ }
698
+ #n(e) {
699
+ let t = [], n = e === "ALL";
700
+ return [this.#e, this.#t].forEach((r) => {
701
+ let i = r[e] ? Object.keys(r[e]).map((t) => [t, r[e][t]]) : [];
702
+ i.length === 0 ? e !== "ALL" && t.push(...Object.keys(r.ALL).map((e) => [e, r.ALL[e]])) : (n ||= !0, t.push(...i));
703
+ }), n ? pe(t) : null;
704
+ }
705
+ }, he = class {
706
+ name = "SmartRouter";
707
+ #e = [];
708
+ #t = [];
709
+ constructor(e) {
710
+ this.#e = e.routers;
711
+ }
712
+ add(e, t, n) {
713
+ if (!this.#t) throw Error(A);
714
+ this.#t.push([
715
+ e,
716
+ t,
717
+ n
718
+ ]);
719
+ }
720
+ match(e, t) {
721
+ if (!this.#t) throw Error("Fatal error");
722
+ let n = this.#e, r = this.#t, i = n.length, a = 0, o;
723
+ for (; a < i; a++) {
724
+ let i = n[a];
725
+ try {
726
+ for (let e = 0, t = r.length; e < t; e++) i.add(...r[e]);
727
+ o = i.match(e, t);
728
+ } catch (e) {
729
+ if (e instanceof j) continue;
730
+ throw e;
731
+ }
732
+ this.match = i.match.bind(i), this.#e = [i], this.#t = void 0;
733
+ break;
734
+ }
735
+ if (a === i) throw Error("Fatal error");
736
+ return this.name = `SmartRouter + ${this.activeRouter.name}`, o;
737
+ }
738
+ get activeRouter() {
739
+ if (this.#t || this.#e.length !== 1) throw Error("No active router has been determined yet.");
740
+ return this.#e[0];
741
+ }
742
+ }, U = /* @__PURE__ */ Object.create(null), ge = (e) => {
743
+ for (let t in e) return !0;
744
+ return !1;
745
+ }, _e = class e {
746
+ #e;
747
+ #t;
748
+ #n;
749
+ #r = 0;
750
+ #i = U;
751
+ constructor(e, t, n) {
752
+ if (this.#t = n || /* @__PURE__ */ Object.create(null), this.#e = [], e && t) {
753
+ let n = /* @__PURE__ */ Object.create(null);
754
+ n[e] = {
755
+ handler: t,
756
+ possibleKeys: [],
757
+ score: 0
758
+ }, this.#e = [n];
759
+ }
760
+ this.#n = [];
761
+ }
762
+ insert(t, n, r) {
763
+ this.#r = ++this.#r;
764
+ let i = this, a = l(n), o = [];
765
+ for (let t = 0, n = a.length; t < n; t++) {
766
+ let n = a[t], r = a[t + 1], s = p(n, r), c = Array.isArray(s) ? s[0] : n;
767
+ if (c in i.#t) {
768
+ i = i.#t[c], s && o.push(s[1]);
769
+ continue;
770
+ }
771
+ i.#t[c] = new e(), s && (i.#n.push(s), o.push(s[1])), i = i.#t[c];
772
+ }
773
+ return i.#e.push({ [t]: {
774
+ handler: r,
775
+ possibleKeys: o.filter((e, t, n) => n.indexOf(e) === t),
776
+ score: this.#r
777
+ } }), i;
778
+ }
779
+ #a(e, t, n, r, i) {
780
+ for (let a = 0, o = t.#e.length; a < o; a++) {
781
+ let o = t.#e[a], s = o[n] || o.ALL, c = {};
782
+ if (s !== void 0 && (s.params = /* @__PURE__ */ Object.create(null), e.push(s), r !== U || i && i !== U)) for (let e = 0, t = s.possibleKeys.length; e < t; e++) {
783
+ let t = s.possibleKeys[e], n = c[s.score];
784
+ s.params[t] = i?.[t] && !n ? i[t] : r[t] ?? i?.[t], c[s.score] = !0;
785
+ }
786
+ }
787
+ }
788
+ search(e, t) {
789
+ let n = [];
790
+ this.#i = U;
791
+ let r = [this], i = c(t), a = [], o = i.length, s = null;
792
+ for (let c = 0; c < o; c++) {
793
+ let l = i[c], u = c === o - 1, d = [];
794
+ for (let f = 0, p = r.length; f < p; f++) {
795
+ let p = r[f], m = p.#t[l];
796
+ m && (m.#i = p.#i, u ? (m.#t["*"] && this.#a(n, m.#t["*"], e, p.#i), this.#a(n, m, e, p.#i)) : d.push(m));
797
+ for (let r = 0, f = p.#n.length; r < f; r++) {
798
+ let f = p.#n[r], m = p.#i === U ? {} : { ...p.#i };
799
+ if (f === "*") {
800
+ let t = p.#t["*"];
801
+ t && (this.#a(n, t, e, p.#i), t.#i = m, d.push(t));
802
+ continue;
803
+ }
804
+ let [h, g, _] = f;
805
+ if (!l && !(_ instanceof RegExp)) continue;
806
+ let v = p.#t[h];
807
+ if (_ instanceof RegExp) {
808
+ if (s === null) {
809
+ s = Array(o);
810
+ let e = t[0] === "/" ? 1 : 0;
811
+ for (let t = 0; t < o; t++) s[t] = e, e += i[t].length + 1;
812
+ }
813
+ let r = t.substring(s[c]), l = _.exec(r);
814
+ if (l) {
815
+ if (m[g] = l[0], this.#a(n, v, e, p.#i, m), ge(v.#t)) {
816
+ v.#i = m;
817
+ let e = l[0].match(/\//)?.length ?? 0;
818
+ (a[e] ||= []).push(v);
819
+ }
820
+ continue;
821
+ }
822
+ }
823
+ (_ === !0 || _.test(l)) && (m[g] = l, u ? (this.#a(n, v, e, m, p.#i), v.#t["*"] && this.#a(n, v.#t["*"], e, m, p.#i)) : (v.#i = m, d.push(v)));
824
+ }
825
+ }
826
+ let f = a.shift();
827
+ r = f ? d.concat(f) : d;
828
+ }
829
+ return n.length > 1 && n.sort((e, t) => e.score - t.score), [n.map(({ handler: e, params: t }) => [e, t])];
830
+ }
831
+ }, ve = class {
832
+ name = "TrieRouter";
833
+ #e;
834
+ constructor() {
835
+ this.#e = new _e();
836
+ }
837
+ add(e, t, n) {
838
+ let r = y(t);
839
+ if (r) {
840
+ for (let t = 0, i = r.length; t < i; t++) this.#e.insert(e, r[t], n);
841
+ return;
842
+ }
843
+ this.#e.insert(e, t, n);
844
+ }
845
+ match(e, t) {
846
+ return this.#e.search(e, t);
847
+ }
848
+ }, ye = class extends se {
849
+ constructor(e = {}) {
850
+ super(e), this.router = e.router ?? new he({ routers: [new me(), new ve()] });
851
+ }
852
+ };
853
+ //#endregion
854
+ //#region src/coordinator-invites.ts
855
+ function be(e) {
856
+ let t = "";
857
+ for (let n of e) t += String.fromCharCode(n);
858
+ return btoa(t);
859
+ }
860
+ function xe(e) {
861
+ let t = atob(e), n = new Uint8Array(t.length);
862
+ for (let e = 0; e < t.length; e += 1) n[e] = t.charCodeAt(e);
863
+ return n;
864
+ }
865
+ function Se(e) {
866
+ return e.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
867
+ }
868
+ function Ce(e) {
869
+ let t = e.replace(/-/g, "+").replace(/_/g, "/");
870
+ return t + "=".repeat((4 - t.length % 4) % 4);
871
+ }
872
+ function W(e) {
873
+ let t = JSON.stringify(e);
874
+ return Se(be(new TextEncoder().encode(t)));
875
+ }
876
+ function we(e) {
877
+ let t = new TextDecoder().decode(xe(Ce(e))), n = JSON.parse(t);
878
+ if (typeof n != "object" || !n) throw Error("invalid invite payload");
879
+ return n;
880
+ }
881
+ function G(e) {
882
+ return `codemem://join?invite=${encodeURIComponent(e)}`;
883
+ }
884
+ function Te(e) {
885
+ let t = e.trim();
886
+ if (t.startsWith("codemem://")) {
887
+ let e = new URL(t).searchParams.get("invite") ?? "";
888
+ if (!e) throw Error("invite payload missing from link");
889
+ return e;
890
+ }
891
+ return t;
892
+ }
893
+ //#endregion
894
+ //#region ../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/clock.js
895
+ function Ee(e) {
896
+ let t = performance.now() * .001, n = Math.floor(t), r = Math.floor(t % 1 * 1e9);
897
+ return e != null && (n -= e[0], r -= e[1], r < 0 && (n--, r += 1e9)), [n, r];
898
+ }
899
+ function K() {
900
+ let [e, t] = Ee();
901
+ return e * 1e3 + Math.floor(t / 1e6);
902
+ }
903
+ function q(e) {
904
+ return new Promise((t) => setTimeout(t, e));
905
+ }
906
+ //#endregion
907
+ //#region ../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/TokenBucket.js
908
+ var De = class {
909
+ bucketSize;
910
+ tokensPerInterval;
911
+ interval;
912
+ parentBucket;
913
+ content;
914
+ lastDrip;
915
+ constructor({ bucketSize: e, tokensPerInterval: t, interval: n, parentBucket: r }) {
916
+ if (this.bucketSize = e, this.tokensPerInterval = t, typeof n == "string") switch (n) {
917
+ case "sec":
918
+ case "second":
919
+ this.interval = 1e3;
920
+ break;
921
+ case "min":
922
+ case "minute":
923
+ this.interval = 1e3 * 60;
924
+ break;
925
+ case "hr":
926
+ case "hour":
927
+ this.interval = 1e3 * 60 * 60;
928
+ break;
929
+ case "day":
930
+ this.interval = 1e3 * 60 * 60 * 24;
931
+ break;
932
+ default: throw Error("Invalid interval " + n);
933
+ }
934
+ else this.interval = n;
935
+ this.parentBucket = r, this.content = 0, this.lastDrip = K();
936
+ }
937
+ async removeTokens(e) {
938
+ if (this.bucketSize === 0) return Infinity;
939
+ if (e > this.bucketSize) throw Error(`Requested tokens ${e} exceeds bucket size ${this.bucketSize}`);
940
+ this.drip();
941
+ let t = async () => (await q(Math.ceil((e - this.content) * (this.interval / this.tokensPerInterval))), this.removeTokens(e));
942
+ if (e > this.content) return t();
943
+ if (this.parentBucket != null) {
944
+ let n = await this.parentBucket.removeTokens(e);
945
+ return e > this.content ? t() : (this.content -= e, Math.min(n, this.content));
946
+ } else return this.content -= e, this.content;
947
+ }
948
+ tryRemoveTokens(e) {
949
+ return this.bucketSize ? e > this.bucketSize || (this.drip(), e > this.content) || this.parentBucket && !this.parentBucket.tryRemoveTokens(e) ? !1 : (this.content -= e, !0) : !0;
950
+ }
951
+ drip() {
952
+ if (this.tokensPerInterval === 0) {
953
+ let e = this.content;
954
+ return this.content = this.bucketSize, this.content > e;
955
+ }
956
+ let e = K(), t = Math.max(e - this.lastDrip, 0);
957
+ this.lastDrip = e;
958
+ let n = t * (this.tokensPerInterval / this.interval), r = this.content;
959
+ return this.content = Math.min(this.content + n, this.bucketSize), Math.floor(this.content) > Math.floor(r);
960
+ }
961
+ }, Oe = class {
962
+ tokenBucket;
963
+ curIntervalStart;
964
+ tokensThisInterval;
965
+ fireImmediately;
966
+ constructor({ tokensPerInterval: e, interval: t, fireImmediately: n }) {
967
+ this.tokenBucket = new De({
968
+ bucketSize: e,
969
+ tokensPerInterval: e,
970
+ interval: t
971
+ }), this.tokenBucket.content = e, this.curIntervalStart = K(), this.tokensThisInterval = 0, this.fireImmediately = n ?? !1;
972
+ }
973
+ async removeTokens(e) {
974
+ if (e > this.tokenBucket.bucketSize) throw Error(`Requested tokens ${e} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);
975
+ let t = K();
976
+ if ((t < this.curIntervalStart || t - this.curIntervalStart >= this.tokenBucket.interval) && (this.curIntervalStart = t, this.tokensThisInterval = 0), e > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {
977
+ if (this.fireImmediately) return -1;
978
+ {
979
+ await q(Math.ceil(this.curIntervalStart + this.tokenBucket.interval - t));
980
+ let n = await this.tokenBucket.removeTokens(e);
981
+ return this.tokensThisInterval += e, n;
982
+ }
983
+ }
984
+ let n = await this.tokenBucket.removeTokens(e);
985
+ return this.tokensThisInterval += e, n;
986
+ }
987
+ tryRemoveTokens(e) {
988
+ if (e > this.tokenBucket.bucketSize) return !1;
989
+ let t = K();
990
+ if ((t < this.curIntervalStart || t - this.curIntervalStart >= this.tokenBucket.interval) && (this.curIntervalStart = t, this.tokensThisInterval = 0), e > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) return !1;
991
+ let n = this.tokenBucket.tryRemoveTokens(e);
992
+ return n && (this.tokensThisInterval += e), n;
993
+ }
994
+ getTokensRemaining() {
995
+ return this.tokenBucket.drip(), this.tokenBucket.content;
996
+ }
997
+ };
998
+ //#endregion
999
+ //#region src/request-rate-limit.ts
1000
+ function ke(e = {}) {
1001
+ let t = Math.max(1e3, Math.trunc(e.windowMs ?? 6e4)), n = e.now ?? (() => Date.now()), r = /* @__PURE__ */ new Map(), i = 0;
1002
+ function a(e) {
1003
+ return Math.max(1, Math.ceil(t / Math.max(1, e) / 1e3));
1004
+ }
1005
+ function o(e) {
1006
+ if (r.size < 64 || i % 64 != 0) return;
1007
+ let n = e - t * 10;
1008
+ for (let [e, t] of r) t.lastUsedAt < n && r.delete(e);
1009
+ }
1010
+ return { check(e, s) {
1011
+ let c = Math.max(1, Math.trunc(s));
1012
+ i += 1;
1013
+ let l = n();
1014
+ o(l);
1015
+ let u = `${c}:${e}`, d = r.get(u);
1016
+ return d || (d = {
1017
+ limiter: new Oe({
1018
+ tokensPerInterval: c,
1019
+ interval: t,
1020
+ fireImmediately: !0
1021
+ }),
1022
+ lastUsedAt: l
1023
+ }, r.set(u, d)), d.lastUsedAt = l, d.limiter.tryRemoveTokens(1) ? {
1024
+ allowed: !0,
1025
+ retryAfterS: 0
1026
+ } : {
1027
+ allowed: !1,
1028
+ retryAfterS: a(c)
1029
+ };
1030
+ } };
1031
+ }
1032
+ //#endregion
1033
+ //#region src/sync-auth-constants.ts
1034
+ var Ae = 300;
1035
+ //#endregion
1036
+ //#region src/sync-fingerprint.ts
1037
+ function J(t) {
1038
+ return e("sha256").update(t, "utf-8").digest("hex");
1039
+ }
1040
+ //#endregion
1041
+ //#region src/coordinator-api.ts
1042
+ var Y = 64 * 1024, X = "X-Codemem-Coordinator-Admin", je = 120, Me = 30;
1043
+ function Z(e, t) {
1044
+ let n = t.adminSecret();
1045
+ if (!n) return {
1046
+ ok: !1,
1047
+ error: "admin_not_configured"
1048
+ };
1049
+ let r = (e ?? "").trim();
1050
+ return r ? r === n ? {
1051
+ ok: !0,
1052
+ error: "ok"
1053
+ } : {
1054
+ ok: !1,
1055
+ error: "invalid_admin_secret"
1056
+ } : {
1057
+ ok: !1,
1058
+ error: "missing_admin_header"
1059
+ };
1060
+ }
1061
+ function Ne(e) {
1062
+ let t = new URL(e);
1063
+ return t.search ? `${t.pathname}${t.search}` : t.pathname;
1064
+ }
1065
+ async function Pe(e, t, n, r) {
1066
+ return await e.recordNonce(t, n, r);
1067
+ }
1068
+ async function Fe(e, t) {
1069
+ await e.cleanupNonces(t);
1070
+ }
1071
+ async function Q(e, t, n, r) {
1072
+ let { deviceId: i, signature: a, timestamp: o, nonce: s } = r;
1073
+ if (!i || !a || !o || !s) return {
1074
+ ok: !1,
1075
+ error: "missing_headers",
1076
+ enrollment: null
1077
+ };
1078
+ let c = await e.getEnrollment(r.groupId, i);
1079
+ if (!c) return {
1080
+ ok: !1,
1081
+ error: "unknown_device",
1082
+ enrollment: null
1083
+ };
1084
+ let l;
1085
+ try {
1086
+ l = await n({
1087
+ method: r.method,
1088
+ pathWithQuery: Ne(r.url),
1089
+ bodyBytes: r.body,
1090
+ timestamp: o,
1091
+ nonce: s,
1092
+ signature: a,
1093
+ publicKey: String(c.public_key),
1094
+ deviceId: i
1095
+ });
1096
+ } catch {
1097
+ return {
1098
+ ok: !1,
1099
+ error: "signature_verification_error",
1100
+ enrollment: null
1101
+ };
1102
+ }
1103
+ if (!l) return {
1104
+ ok: !1,
1105
+ error: "invalid_signature",
1106
+ enrollment: null
1107
+ };
1108
+ let u = t.now();
1109
+ return await Pe(e, i, s, u) ? (await Fe(e, (/* @__PURE__ */ new Date(new Date(u).getTime() - 300 * 2 * 1e3)).toISOString()), {
1110
+ ok: !0,
1111
+ error: "ok",
1112
+ enrollment: c
1113
+ }) : {
1114
+ ok: !1,
1115
+ error: "nonce_replay",
1116
+ enrollment: null
1117
+ };
1118
+ }
1119
+ function Ie(e) {
1120
+ if (!e?.storeFactory || !e.runtime || !e.requestVerifier) throw Error("createCoordinatorApp requires storeFactory, runtime, and requestVerifier.");
1121
+ let t = e.runtime, n = e.storeFactory, r = e.requestVerifier, i = e.requestRateLimit ?? {}, a = i.limiter ?? ke(), o = Math.max(1, Math.trunc(i.readLimit ?? je)), s = Math.max(1, Math.trunc(i.mutationLimit ?? Me)), c = Math.max(1, Math.trunc(i.unauthenticatedReadLimit ?? Math.min(20, o))), l = Math.max(1, Math.trunc(i.unauthenticatedMutationLimit ?? Math.min(10, s))), u = new ye(), d = new TextDecoder();
1122
+ function f(e, t, n) {
1123
+ let r = e.req.method === "GET" || e.req.method === "HEAD" || e.req.method === "OPTIONS", i = a.check(`${e.req.method}:${n ? "auth" : "anon"}:${t}`, n ? r ? o : s : r ? c : l);
1124
+ return i.allowed ? null : (e.header("Retry-After", String(i.retryAfterS)), e.json({
1125
+ error: "rate_limited",
1126
+ retry_after_s: i.retryAfterS
1127
+ }, 429));
1128
+ }
1129
+ async function p(e) {
1130
+ let t = Number.parseInt(e.req.header("content-length") ?? "", 10);
1131
+ if (Number.isFinite(t) && t > Y) return null;
1132
+ let n = e.req.raw.body;
1133
+ if (!n) return new Uint8Array();
1134
+ let r = n.getReader(), i = [], a = 0;
1135
+ try {
1136
+ for (;;) {
1137
+ let { done: e, value: t } = await r.read();
1138
+ if (e) break;
1139
+ if (t) {
1140
+ if (a += t.byteLength, a > Y) return await r.cancel(), null;
1141
+ i.push(t);
1142
+ }
1143
+ }
1144
+ } finally {
1145
+ r.releaseLock();
1146
+ }
1147
+ let o = new Uint8Array(a), s = 0;
1148
+ for (let e of i) o.set(e, s), s += e.byteLength;
1149
+ return o;
1150
+ }
1151
+ function m(e) {
1152
+ try {
1153
+ let t = JSON.parse(d.decode(e));
1154
+ return typeof t != "object" || !t || Array.isArray(t) ? null : t;
1155
+ } catch {
1156
+ return null;
1157
+ }
1158
+ }
1159
+ return u.post("/v1/presence", async (e) => {
1160
+ let i = await p(e);
1161
+ if (i == null) return e.json({ error: "body_too_large" }, 413);
1162
+ let a = m(i);
1163
+ if (!a) return e.json({ error: "invalid_json" }, 400);
1164
+ let o = String(a.group_id ?? "").trim();
1165
+ if (!o) return e.json({ error: "group_id_required" }, 400);
1166
+ let s = n();
1167
+ try {
1168
+ let n = await Q(s, t, r, {
1169
+ method: e.req.method,
1170
+ url: e.req.url,
1171
+ groupId: o,
1172
+ body: i,
1173
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1174
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1175
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1176
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1177
+ });
1178
+ if (!n.ok || !n.enrollment) return f(e, e.req.path, !1) ?? e.json({ error: n.error }, 401);
1179
+ let c = f(e, String(n.enrollment.device_id), !0);
1180
+ if (c) return c;
1181
+ if (a.fingerprint && String(a.fingerprint) !== String(n.enrollment.fingerprint)) return e.json({ error: "fingerprint_mismatch" }, 401);
1182
+ let l = a.addresses ?? [];
1183
+ if (!Array.isArray(l) || !l.every((e) => typeof e == "string")) return e.json({ error: "addresses_must_be_list_of_strings" }, 400);
1184
+ let u;
1185
+ try {
1186
+ if (u = Math.max(1, Number.parseInt(String(a.ttl_s ?? 180), 10)), Number.isNaN(u)) return e.json({ error: "ttl_s_must_be_int" }, 400);
1187
+ } catch {
1188
+ return e.json({ error: "ttl_s_must_be_int" }, 400);
1189
+ }
1190
+ let d = await s.upsertPresence({
1191
+ groupId: o,
1192
+ deviceId: String(n.enrollment.device_id),
1193
+ addresses: l,
1194
+ ttlS: u,
1195
+ capabilities: typeof a.capabilities == "object" && a.capabilities !== null && !Array.isArray(a.capabilities) ? a.capabilities : void 0
1196
+ });
1197
+ return e.json({
1198
+ ok: !0,
1199
+ ...d
1200
+ });
1201
+ } finally {
1202
+ await s.close();
1203
+ }
1204
+ }), u.get("/v1/peers", async (e) => {
1205
+ let i = (e.req.query("group_id") ?? "").trim();
1206
+ if (!i) return e.json({ error: "group_id_required" }, 400);
1207
+ let a = n();
1208
+ try {
1209
+ let n = await Q(a, t, r, {
1210
+ method: e.req.method,
1211
+ url: e.req.url,
1212
+ groupId: i,
1213
+ body: new Uint8Array(),
1214
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1215
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1216
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1217
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1218
+ });
1219
+ if (!n.ok || !n.enrollment) return f(e, e.req.path, !1) ?? e.json({ error: n.error }, 401);
1220
+ let o = f(e, String(n.enrollment.device_id), !0);
1221
+ if (o) return o;
1222
+ let s = await a.listGroupPeers(i, String(n.enrollment.device_id));
1223
+ return e.json({ items: s });
1224
+ } finally {
1225
+ await a.close();
1226
+ }
1227
+ }), u.get("/v1/reciprocal-approvals", async (e) => {
1228
+ let i = (e.req.query("group_id") ?? "").trim(), a = (e.req.query("direction") ?? "incoming").trim(), o = (e.req.query("status") ?? "pending").trim() || "pending";
1229
+ if (!i) return e.json({ error: "group_id_required" }, 400);
1230
+ if (!["incoming", "outgoing"].includes(a)) return e.json({ error: "direction_must_be_incoming_or_outgoing" }, 400);
1231
+ let s = n();
1232
+ try {
1233
+ let n = await Q(s, t, r, {
1234
+ method: e.req.method,
1235
+ url: e.req.url,
1236
+ groupId: i,
1237
+ body: new Uint8Array(),
1238
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1239
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1240
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1241
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1242
+ });
1243
+ if (!n.ok || !n.enrollment) return f(e, e.req.path, !1) ?? e.json({ error: n.error }, 401);
1244
+ let c = f(e, String(n.enrollment.device_id), !0);
1245
+ if (c) return c;
1246
+ let l = await s.listReciprocalApprovals({
1247
+ groupId: i,
1248
+ deviceId: String(n.enrollment.device_id),
1249
+ direction: a,
1250
+ status: o
1251
+ });
1252
+ return e.json({ items: l });
1253
+ } finally {
1254
+ await s.close();
1255
+ }
1256
+ }), u.post("/v1/reciprocal-approvals", async (e) => {
1257
+ let i = await p(e);
1258
+ if (i == null) return e.json({ error: "body_too_large" }, 413);
1259
+ let a = m(i);
1260
+ if (!a) return e.json({ error: "invalid_json" }, 400);
1261
+ let o = String(a.group_id ?? "").trim(), s = String(a.requested_device_id ?? "").trim();
1262
+ if (!o || !s) return e.json({ error: "group_id_and_requested_device_id_required" }, 400);
1263
+ let c = n();
1264
+ try {
1265
+ let n = await Q(c, t, r, {
1266
+ method: e.req.method,
1267
+ url: e.req.url,
1268
+ groupId: o,
1269
+ body: i,
1270
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1271
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1272
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1273
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1274
+ });
1275
+ if (!n.ok || !n.enrollment) return f(e, e.req.path, !1) ?? e.json({ error: n.error }, 401);
1276
+ let a = f(e, String(n.enrollment.device_id), !0);
1277
+ if (a) return a;
1278
+ if (s === String(n.enrollment.device_id)) return e.json({ error: "requested_device_must_differ" }, 400);
1279
+ if (!await c.getEnrollment(o, s)) return e.json({ error: "requested_device_not_found" }, 404);
1280
+ let l = await c.createReciprocalApproval({
1281
+ groupId: o,
1282
+ requestingDeviceId: String(n.enrollment.device_id),
1283
+ requestedDeviceId: s
1284
+ });
1285
+ return e.json({
1286
+ ok: !0,
1287
+ request: l
1288
+ });
1289
+ } finally {
1290
+ await c.close();
1291
+ }
1292
+ }), u.post("/v1/admin/devices", async (e) => {
1293
+ let r = Z(e.req.header(X), t);
1294
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1295
+ let i = f(e, "admin", !0);
1296
+ if (i) return i;
1297
+ let a = await p(e);
1298
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
1299
+ let o = m(a);
1300
+ if (!o) return e.json({ error: "invalid_json" }, 400);
1301
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim(), l = String(o.fingerprint ?? "").trim(), u = String(o.public_key ?? "").trim(), d = String(o.display_name ?? "").trim() || null;
1302
+ if (!s || !c || !l || !u) return e.json({ error: "group_id_device_id_fingerprint_public_key_required" }, 400);
1303
+ if (J(u) !== l) return e.json({ error: "fingerprint_mismatch" }, 400);
1304
+ let h = n();
1305
+ try {
1306
+ await h.createGroup(s), await h.enrollDevice(s, {
1307
+ deviceId: c,
1308
+ fingerprint: l,
1309
+ publicKey: u,
1310
+ displayName: d
1311
+ });
1312
+ } finally {
1313
+ await h.close();
1314
+ }
1315
+ return e.json({ ok: !0 });
1316
+ }), u.get("/v1/admin/devices", async (e) => {
1317
+ let r = Z(e.req.header(X), t);
1318
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1319
+ let i = f(e, "admin", !0);
1320
+ if (i) return i;
1321
+ let a = (e.req.query("group_id") ?? "").trim();
1322
+ if (!a) return e.json({ error: "group_id_required" }, 400);
1323
+ let o = [
1324
+ "1",
1325
+ "true",
1326
+ "yes"
1327
+ ].includes((e.req.query("include_disabled") ?? "0").trim().toLowerCase()), s = n();
1328
+ try {
1329
+ return e.json({ items: await s.listEnrolledDevices(a, o) });
1330
+ } finally {
1331
+ await s.close();
1332
+ }
1333
+ }), u.post("/v1/admin/devices/rename", async (e) => {
1334
+ let r = Z(e.req.header(X), t);
1335
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1336
+ let i = f(e, "admin", !0);
1337
+ if (i) return i;
1338
+ let a = await p(e);
1339
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
1340
+ let o = m(a);
1341
+ if (!o) return e.json({ error: "invalid_json" }, 400);
1342
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim(), l = String(o.display_name ?? "").trim();
1343
+ if (!s || !c) return e.json({ error: "group_id_and_device_id_required" }, 400);
1344
+ if (!l) return e.json({ error: "display_name_required" }, 400);
1345
+ let u = n();
1346
+ try {
1347
+ return await u.renameDevice(s, c, l) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
1348
+ } finally {
1349
+ await u.close();
1350
+ }
1351
+ }), u.post("/v1/admin/devices/disable", async (e) => {
1352
+ let r = Z(e.req.header(X), t);
1353
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1354
+ let i = f(e, "admin", !0);
1355
+ if (i) return i;
1356
+ let a = await p(e);
1357
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
1358
+ let o = m(a);
1359
+ if (!o) return e.json({ error: "invalid_json" }, 400);
1360
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim();
1361
+ if (!s || !c) return e.json({ error: "group_id_and_device_id_required" }, 400);
1362
+ let l = n();
1363
+ try {
1364
+ return await l.setDeviceEnabled(s, c, !1) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
1365
+ } finally {
1366
+ await l.close();
1367
+ }
1368
+ }), u.post("/v1/admin/devices/remove", async (e) => {
1369
+ let r = Z(e.req.header(X), t);
1370
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1371
+ let i = f(e, "admin", !0);
1372
+ if (i) return i;
1373
+ let a = await p(e);
1374
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
1375
+ let o = m(a);
1376
+ if (!o) return e.json({ error: "invalid_json" }, 400);
1377
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim();
1378
+ if (!s || !c) return e.json({ error: "group_id_and_device_id_required" }, 400);
1379
+ let l = n();
1380
+ try {
1381
+ return await l.removeDevice(s, c) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
1382
+ } finally {
1383
+ await l.close();
1384
+ }
1385
+ }), u.post("/v1/admin/invites", async (e) => {
1386
+ let r = Z(e.req.header(X), t);
1387
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1388
+ let i = f(e, "admin", !0);
1389
+ if (i) return i;
1390
+ let a = await p(e);
1391
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
1392
+ let o = m(a);
1393
+ if (!o) return e.json({ error: "invalid_json" }, 400);
1394
+ let s = String(o.group_id ?? "").trim(), c = String(o.policy ?? "auto_admit").trim(), l = String(o.expires_at ?? "").trim(), u = String(o.created_by ?? "").trim() || null;
1395
+ if (!s || !["auto_admit", "approval_required"].includes(c) || !l) return e.json({ error: "group_id_policy_and_expires_at_required" }, 400);
1396
+ let d = n();
1397
+ try {
1398
+ if (!await d.getGroup(s)) return e.json({ error: "group_not_found" }, 404);
1399
+ let t = await d.createInvite({
1400
+ groupId: s,
1401
+ policy: c,
1402
+ expiresAt: l,
1403
+ createdBy: u
1404
+ }), n = {
1405
+ v: 1,
1406
+ kind: "coordinator_team_invite",
1407
+ coordinator_url: String(o.coordinator_url ?? "").trim(),
1408
+ group_id: s,
1409
+ policy: c,
1410
+ token: String(t.token ?? ""),
1411
+ expires_at: l,
1412
+ team_name: t.team_name_snapshot ?? null
1413
+ }, r = W(n), { token: i, ...a } = t;
1414
+ return e.json({
1415
+ ok: !0,
1416
+ invite: a,
1417
+ payload: n,
1418
+ encoded: r,
1419
+ link: G(r)
1420
+ });
1421
+ } finally {
1422
+ await d.close();
1423
+ }
1424
+ }), u.get("/v1/admin/invites", async (e) => {
1425
+ let r = Z(e.req.header(X), t);
1426
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1427
+ let i = f(e, "admin", !0);
1428
+ if (i) return i;
1429
+ let a = (e.req.query("group_id") ?? "").trim();
1430
+ if (!a) return e.json({ error: "group_id_required" }, 400);
1431
+ let o = n();
1432
+ try {
1433
+ let t = (await o.listInvites(a)).map(({ token: e, ...t }) => t);
1434
+ return e.json({ items: t });
1435
+ } finally {
1436
+ await o.close();
1437
+ }
1438
+ }), u.post("/v1/admin/join-requests/approve", async (e) => $(e, !0, {
1439
+ createStore: n,
1440
+ runtime: t,
1441
+ rateLimitedResponse: f
1442
+ })), u.post("/v1/admin/join-requests/deny", async (e) => $(e, !1, {
1443
+ createStore: n,
1444
+ runtime: t,
1445
+ rateLimitedResponse: f
1446
+ })), u.get("/v1/admin/join-requests", async (e) => {
1447
+ let r = Z(e.req.header(X), t);
1448
+ if (!r.ok) return f(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1449
+ let i = f(e, "admin", !0);
1450
+ if (i) return i;
1451
+ let a = (e.req.query("group_id") ?? "").trim();
1452
+ if (!a) return e.json({ error: "group_id_required" }, 400);
1453
+ let o = n();
1454
+ try {
1455
+ return e.json({ items: await o.listJoinRequests(a) });
1456
+ } finally {
1457
+ await o.close();
1458
+ }
1459
+ }), u.post("/v1/join", async (e) => {
1460
+ let r = await p(e);
1461
+ if (r == null) return e.json({ error: "body_too_large" }, 413);
1462
+ let i = m(r);
1463
+ if (!i) return e.json({ error: "invalid_json" }, 400);
1464
+ let a = String(i.token ?? "").trim(), o = String(i.device_id ?? "").trim(), s = String(i.fingerprint ?? "").trim(), c = String(i.public_key ?? "").trim(), l = String(i.display_name ?? "").trim() || null;
1465
+ if (!a || !o || !s || !c) return e.json({ error: "token_device_id_fingerprint_public_key_required" }, 400);
1466
+ if (J(c) !== s) return e.json({ error: "fingerprint_mismatch" }, 400);
1467
+ let u = n();
1468
+ try {
1469
+ let n = await u.getInviteByToken(a);
1470
+ if (!n) return e.json({ error: "invalid_token" }, 404);
1471
+ if (n.revoked_at) return e.json({ error: "revoked_token" }, 400);
1472
+ let r = String(n.expires_at ?? "");
1473
+ if (r && new Date(r.replace("Z", "+00:00")) <= new Date(t.now())) return e.json({ error: "expired_token" }, 400);
1474
+ let i = String(n.group_id);
1475
+ if (await u.getEnrollment(i, o)) return e.json({
1476
+ ok: !0,
1477
+ status: "already_enrolled",
1478
+ group_id: n.group_id,
1479
+ policy: n.policy
1480
+ });
1481
+ let d = String(n.policy);
1482
+ if (!["auto_admit", "approval_required"].includes(d)) return e.json({ error: `unknown invite policy: ${d}` }, 400);
1483
+ if (d === "approval_required") {
1484
+ let t = await u.createJoinRequest({
1485
+ groupId: i,
1486
+ deviceId: o,
1487
+ publicKey: c,
1488
+ fingerprint: s,
1489
+ displayName: l,
1490
+ token: a
1491
+ });
1492
+ return e.json({
1493
+ ok: !0,
1494
+ status: "pending",
1495
+ group_id: n.group_id,
1496
+ policy: n.policy,
1497
+ request_id: t.request_id
1498
+ });
1499
+ }
1500
+ return await u.enrollDevice(i, {
1501
+ deviceId: o,
1502
+ fingerprint: s,
1503
+ publicKey: c,
1504
+ displayName: l
1505
+ }), e.json({
1506
+ ok: !0,
1507
+ status: "enrolled",
1508
+ group_id: n.group_id,
1509
+ policy: n.policy
1510
+ });
1511
+ } finally {
1512
+ await u.close();
1513
+ }
1514
+ }), u;
1515
+ }
1516
+ async function $(e, t, n) {
1517
+ let r = Z(e.req.header(X), n.runtime);
1518
+ if (!r.ok) return n.rateLimitedResponse(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
1519
+ let i = n.rateLimitedResponse(e, "admin", !0);
1520
+ if (i) return i;
1521
+ let a = await (async () => {
1522
+ let t = Number.parseInt(e.req.header("content-length") ?? "", 10);
1523
+ if (Number.isFinite(t) && t > Y) return null;
1524
+ let n = e.req.raw.body;
1525
+ if (!n) return new Uint8Array();
1526
+ let r = n.getReader(), i = [], a = 0;
1527
+ try {
1528
+ for (;;) {
1529
+ let { done: e, value: t } = await r.read();
1530
+ if (e) break;
1531
+ if (t) {
1532
+ if (a += t.byteLength, a > Y) return await r.cancel(), null;
1533
+ i.push(t);
1534
+ }
1535
+ }
1536
+ } finally {
1537
+ r.releaseLock();
1538
+ }
1539
+ let o = new Uint8Array(a), s = 0;
1540
+ for (let e of i) o.set(e, s), s += e.byteLength;
1541
+ return o;
1542
+ })();
1543
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
1544
+ let o;
1545
+ try {
1546
+ let e = new TextDecoder(), t = JSON.parse(e.decode(a));
1547
+ o = typeof t == "object" && t && !Array.isArray(t) ? t : null;
1548
+ } catch {
1549
+ o = null;
1550
+ }
1551
+ if (!o) return e.json({ error: "invalid_json" }, 400);
1552
+ let s = String(o.request_id ?? "").trim(), c = String(o.reviewed_by ?? "").trim() || null;
1553
+ if (!s) return e.json({ error: "request_id_required" }, 400);
1554
+ let l = n.createStore();
1555
+ try {
1556
+ let n = await l.reviewJoinRequest({
1557
+ requestId: s,
1558
+ approved: t,
1559
+ reviewedBy: c
1560
+ });
1561
+ return n ? n._no_transition ? e.json({
1562
+ error: "request_not_pending",
1563
+ status: n.status
1564
+ }, 409) : e.json({
1565
+ ok: !0,
1566
+ request: n
1567
+ }) : e.json({ error: "request_not_found" }, 404);
1568
+ } finally {
1569
+ await l.close();
1570
+ }
1571
+ }
1572
+ //#endregion
1573
+ export { W as a, we as i, J as n, Te as o, Ae as r, G as s, Ie as t };
1574
+
1575
+ //# sourceMappingURL=coordinator-api-CEbQ6LHE.js.map