@codemem/core 0.40.1 → 0.41.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.
Files changed (62) hide show
  1. package/dist/api-types.d.ts +3 -0
  2. package/dist/api-types.d.ts.map +1 -1
  3. package/dist/coordinator-api-Bxw5Q3py.js +3072 -0
  4. package/dist/coordinator-api-Bxw5Q3py.js.map +1 -0
  5. package/dist/coordinator-api.d.ts.map +1 -1
  6. package/dist/coordinator-runtime.d.ts.map +1 -1
  7. package/dist/db.d.ts +7 -3
  8. package/dist/db.d.ts.map +1 -1
  9. package/dist/index.d.ts +12 -6
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +23263 -4185
  12. package/dist/index.js.map +1 -1
  13. package/dist/internal/cloudflare-coordinator.js +156 -156
  14. package/dist/legacy-recipient-policy-projection.d.ts +2 -0
  15. package/dist/legacy-recipient-policy-projection.d.ts.map +1 -1
  16. package/dist/operational-status.d.ts +36 -0
  17. package/dist/operational-status.d.ts.map +1 -0
  18. package/dist/policy-team-device-eligibility.d.ts +51 -0
  19. package/dist/policy-team-device-eligibility.d.ts.map +1 -0
  20. package/dist/project-share-intent.d.ts +16 -0
  21. package/dist/project-share-intent.d.ts.map +1 -0
  22. package/dist/recipient-policy-edges.d.ts.map +1 -1
  23. package/dist/recipient-policy-intent.d.ts.map +1 -1
  24. package/dist/recipient-policy-onboarding.d.ts +3 -1
  25. package/dist/recipient-policy-onboarding.d.ts.map +1 -1
  26. package/dist/recipient-policy-reconciliation.d.ts +10 -1
  27. package/dist/recipient-policy-reconciliation.d.ts.map +1 -1
  28. package/dist/recipient-policy-review.d.ts +4 -0
  29. package/dist/recipient-policy-review.d.ts.map +1 -1
  30. package/dist/release-discovery.d.ts +47 -0
  31. package/dist/release-discovery.d.ts.map +1 -0
  32. package/dist/schema-bootstrap.d.ts.map +1 -1
  33. package/dist/schema.d.ts +464 -0
  34. package/dist/schema.d.ts.map +1 -1
  35. package/dist/scope-membership-cache.d.ts +2 -0
  36. package/dist/scope-membership-cache.d.ts.map +1 -1
  37. package/dist/share-operation.d.ts +4 -15
  38. package/dist/share-operation.d.ts.map +1 -1
  39. package/dist/store.d.ts +1 -0
  40. package/dist/store.d.ts.map +1 -1
  41. package/dist/sync-auth.d.ts +3 -0
  42. package/dist/sync-auth.d.ts.map +1 -1
  43. package/dist/sync-bootstrap-constants.d.ts +7 -0
  44. package/dist/sync-bootstrap-constants.d.ts.map +1 -0
  45. package/dist/sync-bootstrap.d.ts +2 -11
  46. package/dist/sync-bootstrap.d.ts.map +1 -1
  47. package/dist/sync-daemon.d.ts +2 -2
  48. package/dist/sync-daemon.d.ts.map +1 -1
  49. package/dist/sync-identity.d.ts +10 -2
  50. package/dist/sync-identity.d.ts.map +1 -1
  51. package/dist/sync-pass.d.ts +1 -0
  52. package/dist/sync-pass.d.ts.map +1 -1
  53. package/dist/sync-replication.d.ts.map +1 -1
  54. package/dist/sync-scope-protocol.d.ts +1 -3
  55. package/dist/sync-scope-protocol.d.ts.map +1 -1
  56. package/dist/test-schema.generated.d.ts +1 -1
  57. package/dist/test-schema.generated.d.ts.map +1 -1
  58. package/dist/viewer-probe.d.ts +50 -0
  59. package/dist/viewer-probe.d.ts.map +1 -0
  60. package/package.json +1 -1
  61. package/dist/coordinator-api-CvU8oTg1.js +0 -21107
  62. package/dist/coordinator-api-CvU8oTg1.js.map +0 -1
@@ -0,0 +1,3072 @@
1
+ import { resolve as e } from "node:path";
2
+ import { createHash as t } from "node:crypto";
3
+ //#region src/coordinator-membership-effects.ts
4
+ var n = "scope_membership_effect_conflict", r = {
5
+ device_not_enrolled: "device must be enrolled and enabled in the scope group.",
6
+ scope_group_mismatch: "membership groupId must match the scope groupId.",
7
+ scope_inactive: "scope is not active.",
8
+ scope_not_found: "scopeId must reference an existing scope."
9
+ }, i = class extends Error {
10
+ code;
11
+ constructor(e) {
12
+ super(r[e]), this.name = "CoordinatorMembershipError", this.code = e;
13
+ }
14
+ };
15
+ function a(e) {
16
+ return e?.trim() || null;
17
+ }
18
+ function o(e) {
19
+ let t = a(e);
20
+ if (!t) throw Error("effectId is required.");
21
+ if (t.length > 512 || /[\p{Cc}\p{Cf}]/u.test(t)) throw Error("effectId is invalid.");
22
+ return t;
23
+ }
24
+ function s(e) {
25
+ return JSON.stringify({
26
+ scopeId: a(e.scopeId),
27
+ deviceId: a(e.deviceId),
28
+ role: a(e.role),
29
+ membershipEpoch: e.membershipEpoch ?? null,
30
+ coordinatorId: a(e.coordinatorId),
31
+ groupId: a(e.groupId),
32
+ manifestIssuerDeviceId: a(e.manifestIssuerDeviceId),
33
+ manifestHash: a(e.manifestHash),
34
+ signedManifestJson: a(e.signedManifestJson),
35
+ actorType: a(e.actorType),
36
+ actorId: a(e.actorId)
37
+ });
38
+ }
39
+ function c(e) {
40
+ return JSON.stringify({
41
+ scopeId: a(e.scopeId),
42
+ deviceId: a(e.deviceId),
43
+ groupId: a(e.groupId),
44
+ membershipEpoch: e.membershipEpoch ?? null,
45
+ manifestHash: a(e.manifestHash),
46
+ signedManifestJson: a(e.signedManifestJson),
47
+ actorType: a(e.actorType),
48
+ actorId: a(e.actorId)
49
+ });
50
+ }
51
+ function l(e, t, r) {
52
+ if (e.action !== t || e.request_json !== r) throw Error(n);
53
+ }
54
+ function u(e) {
55
+ if (e.action !== "grant" || e.outcome_applied !== 1 || e.role == null || e.status == null || e.membership_epoch == null || e.updated_at == null) throw Error("scope_membership_effect_receipt_invalid");
56
+ return {
57
+ scope_id: e.scope_id,
58
+ device_id: e.device_id,
59
+ role: e.role,
60
+ status: e.status,
61
+ membership_epoch: e.membership_epoch,
62
+ coordinator_id: e.coordinator_id,
63
+ group_id: e.group_id,
64
+ manifest_issuer_device_id: e.manifest_issuer_device_id,
65
+ manifest_hash: e.manifest_hash,
66
+ signed_manifest_json: e.signed_manifest_json,
67
+ updated_at: e.updated_at
68
+ };
69
+ }
70
+ //#endregion
71
+ //#region src/coordinator-store-contract.ts
72
+ function d(e) {
73
+ let t = e.trim(), n = new Date(t);
74
+ if (!t || Number.isNaN(n.getTime())) throw Error("expiresAt must be a valid date.");
75
+ return n.toISOString();
76
+ }
77
+ var f = /^identity:[A-Za-z0-9_-]{18,24}$/u;
78
+ function p(e) {
79
+ return typeof e == "string" && e === e.trim() && f.test(e);
80
+ }
81
+ function m(e) {
82
+ return String(e.kind === "team_member" ? e.assigned_identity_id ?? "" : e.target_identity_id ?? "").trim();
83
+ }
84
+ //#endregion
85
+ //#region src/project-invite-identity.ts
86
+ var h = 120;
87
+ function g(e, t) {
88
+ if ([...e].some((e) => /[\p{Cc}\p{Cf}]/u.test(e))) throw Error(`${t}_invalid`);
89
+ let n = e.replace(/\s+/gu, " ").trim();
90
+ if (!n) throw Error(`${t}_required`);
91
+ if ([...n].length > h) throw Error(`${t}_too_long`);
92
+ return n;
93
+ }
94
+ function _(e) {
95
+ let t = String(e ?? "").replace(/\.local$/iu, "");
96
+ return t.trim() ? g(t.replace(/[-_]+/gu, " "), "device_display_name") : null;
97
+ }
98
+ function v(e) {
99
+ for (let t of [
100
+ e.explicitName,
101
+ e.osName,
102
+ e.coordinatorName
103
+ ]) {
104
+ let e = _(t);
105
+ if (e) return e;
106
+ }
107
+ let t = String(e.fallbackSeed ?? "").replace(/[^a-z0-9]/giu, "").slice(0, 6);
108
+ return t ? `Codemem device ${t}` : "Codemem device";
109
+ }
110
+ function y(e) {
111
+ if (!Array.isArray(e) || e.length === 0 || e.length > 100) throw Error("project_summaries_invalid");
112
+ return e.map((e) => {
113
+ if (!e || typeof e != "object" || Array.isArray(e)) throw Error("project_summaries_invalid");
114
+ let t = e;
115
+ if (!Number.isSafeInteger(t.existing_memory_count) || Number(t.existing_memory_count) < 0) throw Error("project_summaries_invalid");
116
+ return {
117
+ display_name: g(String(t.display_name ?? ""), "project_name"),
118
+ existing_memory_count: Number(t.existing_memory_count)
119
+ };
120
+ });
121
+ }
122
+ //#endregion
123
+ //#region src/recipient-reviewed-intent.ts
124
+ var b = 1, x = class extends Error {
125
+ code;
126
+ constructor(e) {
127
+ super(e), this.name = "RecipientReviewedIntentError", this.code = e;
128
+ }
129
+ }, S = /[\p{Cc}\p{Cf}]/u, C = 100, w = 64 * 1024;
130
+ function T() {
131
+ throw new x("recipient_reviewed_intent_invalid");
132
+ }
133
+ function E(e) {
134
+ return (!e || typeof e != "object" || Array.isArray(e)) && T(), e;
135
+ }
136
+ function D(e, t) {
137
+ Object.keys(e).some((e) => !t.includes(e)) && T();
138
+ }
139
+ function O(e, t) {
140
+ return (typeof e != "string" || !e || e !== e.trim() || e.length > t || S.test(e)) && T(), e;
141
+ }
142
+ function k(e) {
143
+ (typeof e != "string" || S.test(e)) && T();
144
+ let t = e.trim().replace(/\s+/gu, " ");
145
+ return (!t || t.length > 256) && T(), t;
146
+ }
147
+ function A(e) {
148
+ typeof e != "string" && T();
149
+ try {
150
+ return g(e, "identity_display_name");
151
+ } catch {
152
+ return T();
153
+ }
154
+ }
155
+ function j(e) {
156
+ return (typeof e != "number" || !Number.isSafeInteger(e) || e < 0) && T(), e;
157
+ }
158
+ function M(e, t) {
159
+ return e < t ? -1 : +(e > t);
160
+ }
161
+ function ee(e) {
162
+ return e.kind === "direct" ? "direct" : `team\u0000${e.teamId}`;
163
+ }
164
+ function te(e) {
165
+ let t = E(e);
166
+ return t.kind === "direct" ? (D(t, ["kind"]), { kind: "direct" }) : (t.kind !== "team" && T(), D(t, [
167
+ "kind",
168
+ "teamId",
169
+ "displayName"
170
+ ]), {
171
+ kind: "team",
172
+ teamId: O(t.teamId, 256),
173
+ displayName: k(t.displayName)
174
+ });
175
+ }
176
+ function ne(e) {
177
+ let t = E(e);
178
+ D(t, [
179
+ "canonicalProjectIdentity",
180
+ "displayName",
181
+ "existingMemoryCount",
182
+ "futureMemoriesShared",
183
+ "sources"
184
+ ]), (t.futureMemoriesShared !== !0 || !Array.isArray(t.sources) || !t.sources.length) && T();
185
+ let n = t.sources.map(te).toSorted((e, t) => M(ee(e), ee(t)));
186
+ return new Set(n.map(ee)).size !== n.length && T(), {
187
+ canonicalProjectIdentity: O(t.canonicalProjectIdentity, 512),
188
+ displayName: k(t.displayName),
189
+ existingMemoryCount: j(t.existingMemoryCount),
190
+ futureMemoriesShared: !0,
191
+ sources: n
192
+ };
193
+ }
194
+ function re(e) {
195
+ let t = E(e);
196
+ return D(t, [
197
+ "canonicalProjectIdentity",
198
+ "displayName",
199
+ "existingMemoryCount"
200
+ ]), {
201
+ canonicalProjectIdentity: O(t.canonicalProjectIdentity, 512),
202
+ displayName: k(t.displayName),
203
+ existingMemoryCount: j(t.existingMemoryCount)
204
+ };
205
+ }
206
+ function ie(e) {
207
+ (!Array.isArray(e.projects) || !Array.isArray(e.excludedProjects) || e.projects.length > C) && T();
208
+ let t = e.projects.map(ne).toSorted((e, t) => M(e.canonicalProjectIdentity, t.canonicalProjectIdentity)), n = e.excludedProjects.map(re).toSorted((e, t) => M(e.canonicalProjectIdentity, t.canonicalProjectIdentity)), r = t.map((e) => e.canonicalProjectIdentity), i = n.map((e) => e.canonicalProjectIdentity);
209
+ return (new Set(r).size !== r.length || new Set(i).size !== i.length || i.some((e) => r.includes(e))) && T(), {
210
+ projects: t,
211
+ excludedProjects: n
212
+ };
213
+ }
214
+ function ae(e, t) {
215
+ if (!(e.journey === "team" && t.kind === "team_member" && e.team.teamId === t.policyTeamId || e.journey === "add_device" && t.kind === "add_device" && e.targetIdentity.identityId === t.targetIdentityId)) throw new x("recipient_invite_intent_mismatch");
216
+ }
217
+ function N(e, t) {
218
+ let n = E(e);
219
+ n.version !== 1 && T();
220
+ let r = ie(n), i;
221
+ if (n.journey === "team") {
222
+ D(n, [
223
+ "version",
224
+ "journey",
225
+ "team",
226
+ "projects",
227
+ "excludedProjects"
228
+ ]);
229
+ let e = E(n.team);
230
+ D(e, [
231
+ "teamId",
232
+ "displayName",
233
+ "futureProjectsInherit"
234
+ ]), e.futureProjectsInherit !== !0 && T(), i = {
235
+ version: 1,
236
+ journey: "team",
237
+ team: {
238
+ teamId: O(e.teamId, 256),
239
+ displayName: k(e.displayName),
240
+ futureProjectsInherit: !0
241
+ },
242
+ ...r
243
+ };
244
+ } else if (n.journey === "add_device") {
245
+ D(n, [
246
+ "version",
247
+ "journey",
248
+ "targetIdentity",
249
+ "projects",
250
+ "excludedProjects"
251
+ ]);
252
+ let e = E(n.targetIdentity);
253
+ D(e, ["identityId", "displayName"]), i = {
254
+ version: 1,
255
+ journey: "add_device",
256
+ targetIdentity: {
257
+ identityId: O(e.identityId, 256),
258
+ displayName: A(e.displayName)
259
+ },
260
+ ...r
261
+ };
262
+ } else T();
263
+ return t && ae(i, t), new TextEncoder().encode(P(i)).byteLength > w && T(), i;
264
+ }
265
+ function P(e) {
266
+ return Array.isArray(e) ? `[${e.map(P).join(",")}]` : e && typeof e == "object" ? `{${Object.entries(e).toSorted(([e], [t]) => M(e, t)).map(([e, t]) => `${JSON.stringify(e)}:${P(t)}`).join(",")}}` : JSON.stringify(e) ?? "null";
267
+ }
268
+ function oe(e, t) {
269
+ return P(N(e, t));
270
+ }
271
+ async function se(e, t) {
272
+ let n = oe(e, t), r = new TextEncoder().encode(`recipient-reviewed-intent-v1\n${n}`), i = await globalThis.crypto.subtle.digest("SHA-256", r);
273
+ return Array.from(new Uint8Array(i), (e) => e.toString(16).padStart(2, "0")).join("");
274
+ }
275
+ async function F(e, t) {
276
+ let n = N(e, t.target);
277
+ if (await se(n) !== t.digest) throw new x("recipient_invite_intent_mismatch");
278
+ return n;
279
+ }
280
+ async function ce(e, t) {
281
+ if (!e) throw Error("recipient_invite_review_unavailable");
282
+ let n;
283
+ try {
284
+ n = JSON.parse(e);
285
+ } catch {
286
+ throw Error("recipient_invite_review_unavailable");
287
+ }
288
+ try {
289
+ let r = N(n, t.target);
290
+ if (P(r) !== e) throw Error("recipient_invite_review_unavailable");
291
+ return await F(r, t);
292
+ } catch (e) {
293
+ throw e instanceof x && e.code === "recipient_invite_intent_mismatch" || e instanceof Error && e.message === "recipient_invite_review_unavailable" ? e : Error("recipient_invite_review_unavailable");
294
+ }
295
+ }
296
+ //#endregion
297
+ //#region src/sync-fingerprint.ts
298
+ function le(e) {
299
+ return t("sha256").update(e, "utf-8").digest("hex");
300
+ }
301
+ //#endregion
302
+ //#region ../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/compose.js
303
+ var ue = (e, t, n) => (r, i) => {
304
+ let a = -1;
305
+ return o(0);
306
+ async function o(s) {
307
+ if (s <= a) throw Error("next() called multiple times");
308
+ a = s;
309
+ let c, l = !1, u;
310
+ if (e[s] ? (u = e[s][0][0], r.req.routeIndex = s) : u = s === e.length && i || void 0, u) try {
311
+ c = await u(r, () => o(s + 1));
312
+ } catch (e) {
313
+ if (e instanceof Error && t) r.error = e, c = await t(e, r), l = !0;
314
+ else throw e;
315
+ }
316
+ else r.finalized === !1 && n && (c = await n(r));
317
+ return c && (r.finalized === !1 || l) && (r.res = c), r;
318
+ }
319
+ }, de = /* @__PURE__ */ Symbol(), fe = async (e, t = /* @__PURE__ */ Object.create(null)) => {
320
+ let { all: n = !1, dot: r = !1 } = t, i = (e instanceof Pe ? e.raw.headers : e.headers).get("Content-Type");
321
+ return i?.startsWith("multipart/form-data") || i?.startsWith("application/x-www-form-urlencoded") ? pe(e, {
322
+ all: n,
323
+ dot: r
324
+ }) : {};
325
+ };
326
+ async function pe(e, t) {
327
+ let n = await e.formData();
328
+ return n ? me(n, t) : {};
329
+ }
330
+ function me(e, t) {
331
+ let n = /* @__PURE__ */ Object.create(null);
332
+ return e.forEach((e, r) => {
333
+ t.all || r.endsWith("[]") ? he(n, r, e) : n[r] = e;
334
+ }), t.dot && Object.entries(n).forEach(([e, t]) => {
335
+ e.includes(".") && (ge(n, e, t), delete n[e]);
336
+ }), n;
337
+ }
338
+ var he = (e, t, n) => {
339
+ 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];
340
+ }, ge = (e, t, n) => {
341
+ if (/(?:^|\.)__proto__\./.test(t)) return;
342
+ let r = e, i = t.split(".");
343
+ i.forEach((e, t) => {
344
+ 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]);
345
+ });
346
+ }, _e = (e) => {
347
+ let t = e.split("/");
348
+ return t[0] === "" && t.shift(), t;
349
+ }, ve = (e) => {
350
+ let { groups: t, path: n } = ye(e);
351
+ return be(_e(n), t);
352
+ }, ye = (e) => {
353
+ let t = [];
354
+ return e = e.replace(/\{[^}]+\}/g, (e, n) => {
355
+ let r = `@${n}`;
356
+ return t.push([r, e]), r;
357
+ }), {
358
+ groups: t,
359
+ path: e
360
+ };
361
+ }, be = (e, t) => {
362
+ for (let n = t.length - 1; n >= 0; n--) {
363
+ let [r] = t[n];
364
+ for (let i = e.length - 1; i >= 0; i--) if (e[i].includes(r)) {
365
+ e[i] = e[i].replace(r, t[n][1]);
366
+ break;
367
+ }
368
+ }
369
+ return e;
370
+ }, xe = {}, Se = (e, t) => {
371
+ if (e === "*") return "*";
372
+ let n = e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
373
+ if (n) {
374
+ let r = `${e}#${t}`;
375
+ return xe[r] || (n[2] ? xe[r] = t && t[0] !== ":" && t[0] !== "*" ? [
376
+ r,
377
+ n[1],
378
+ RegExp(`^${n[2]}(?=/${t})`)
379
+ ] : [
380
+ e,
381
+ n[1],
382
+ RegExp(`^${n[2]}$`)
383
+ ] : xe[r] = [
384
+ e,
385
+ n[1],
386
+ !0
387
+ ]), xe[r];
388
+ }
389
+ return null;
390
+ }, Ce = (e, t) => {
391
+ try {
392
+ return t(e);
393
+ } catch {
394
+ return e.replace(/(?:%[0-9A-Fa-f]{2})+/g, (e) => {
395
+ try {
396
+ return t(e);
397
+ } catch {
398
+ return e;
399
+ }
400
+ });
401
+ }
402
+ }, we = (e) => Ce(e, decodeURI), Te = (e) => {
403
+ let t = e.url, n = t.indexOf("/", t.indexOf(":") + 4), r = n;
404
+ for (; r < t.length; r++) {
405
+ let e = t.charCodeAt(r);
406
+ if (e === 37) {
407
+ 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);
408
+ return we(o.includes("%25") ? o.replace(/%25/g, "%2525") : o);
409
+ } else if (e === 63 || e === 35) break;
410
+ }
411
+ return t.slice(n, r);
412
+ }, Ee = (e) => {
413
+ let t = Te(e);
414
+ return t.length > 1 && t.at(-1) === "/" ? t.slice(0, -1) : t;
415
+ }, I = (e, t, ...n) => (n.length && (t = I(t, ...n)), `${e?.[0] === "/" ? "" : "/"}${e}${t === "/" ? "" : `${e?.at(-1) === "/" ? "" : "/"}${t?.[0] === "/" ? t.slice(1) : t}`}`), De = (e) => {
416
+ if (e.charCodeAt(e.length - 1) !== 63 || !e.includes(":")) return null;
417
+ let t = e.split("/"), n = [], r = "";
418
+ return t.forEach((e) => {
419
+ if (e !== "" && !/\:/.test(e)) r += "/" + e;
420
+ else if (/\:/.test(e)) if (/\?/.test(e)) {
421
+ n.length === 0 && r === "" ? n.push("/") : n.push(r);
422
+ let t = e.replace("?", "");
423
+ r += "/" + t, n.push(r);
424
+ } else r += "/" + e;
425
+ }), n.filter((e, t, n) => n.indexOf(e) === t);
426
+ }, Oe = (e) => /[%+]/.test(e) ? (e.indexOf("+") !== -1 && (e = e.replace(/\+/g, " ")), e.indexOf("%") === -1 ? e : Ce(e, Me)) : e, ke = (e, t, n) => {
427
+ let r;
428
+ if (!n && t && !/[%+]/.test(t)) {
429
+ let n = e.indexOf("?", 8);
430
+ if (n === -1) return;
431
+ for (e.startsWith(t, n + 1) || (n = e.indexOf(`&${t}`, n + 1)); n !== -1;) {
432
+ let r = e.charCodeAt(n + t.length + 1);
433
+ if (r === 61) {
434
+ let r = n + t.length + 2, i = e.indexOf("&", r);
435
+ return Oe(e.slice(r, i === -1 ? void 0 : i));
436
+ } else if (r == 38 || isNaN(r)) return "";
437
+ n = e.indexOf(`&${t}`, n + 1);
438
+ }
439
+ if (r = /[%+]/.test(e), !r) return;
440
+ }
441
+ let i = {};
442
+ r ??= /[%+]/.test(e);
443
+ let a = e.indexOf("?", 8);
444
+ for (; a !== -1;) {
445
+ let t = e.indexOf("&", a + 1), o = e.indexOf("=", a);
446
+ o > t && t !== -1 && (o = -1);
447
+ let s = e.slice(a + 1, o === -1 ? t === -1 ? void 0 : t : o);
448
+ if (r && (s = Oe(s)), a = t, s === "") continue;
449
+ let c;
450
+ o === -1 ? c = "" : (c = e.slice(o + 1, t === -1 ? void 0 : t), r && (c = Oe(c))), n ? (i[s] && Array.isArray(i[s]) || (i[s] = []), i[s].push(c)) : i[s] ??= c;
451
+ }
452
+ return t ? i[t] : i;
453
+ }, Ae = ke, je = (e, t) => ke(e, t, !0), Me = decodeURIComponent, Ne = (e) => Ce(e, Me), Pe = class {
454
+ raw;
455
+ #e;
456
+ #t;
457
+ routeIndex = 0;
458
+ path;
459
+ bodyCache = {};
460
+ constructor(e, t = "/", n = [[]]) {
461
+ this.raw = e, this.path = t, this.#t = n, this.#e = {};
462
+ }
463
+ param(e) {
464
+ return e ? this.#n(e) : this.#r();
465
+ }
466
+ #n(e) {
467
+ let t = this.#t[0][this.routeIndex][1][e], n = this.#i(t);
468
+ return n && /\%/.test(n) ? Ne(n) : n;
469
+ }
470
+ #r() {
471
+ let e = {}, t = Object.keys(this.#t[0][this.routeIndex][1]);
472
+ for (let n of t) {
473
+ let t = this.#i(this.#t[0][this.routeIndex][1][n]);
474
+ t !== void 0 && (e[n] = /\%/.test(t) ? Ne(t) : t);
475
+ }
476
+ return e;
477
+ }
478
+ #i(e) {
479
+ return this.#t[1] ? this.#t[1][e] : e;
480
+ }
481
+ query(e) {
482
+ return Ae(this.url, e);
483
+ }
484
+ queries(e) {
485
+ return je(this.url, e);
486
+ }
487
+ header(e) {
488
+ if (e) return this.raw.headers.get(e) ?? void 0;
489
+ let t = {};
490
+ return this.raw.headers.forEach((e, n) => {
491
+ t[n] = e;
492
+ }), t;
493
+ }
494
+ async parseBody(e) {
495
+ return fe(this, e);
496
+ }
497
+ #a = (e) => {
498
+ let { bodyCache: t, raw: n } = this, r = t[e];
499
+ if (r) return r;
500
+ let i = Object.keys(t)[0];
501
+ return i ? t[i].then((t) => (i === "json" && (t = JSON.stringify(t)), new Response(t)[e]())) : t[e] = n[e]();
502
+ };
503
+ json() {
504
+ return this.#a("text").then((e) => JSON.parse(e));
505
+ }
506
+ text() {
507
+ return this.#a("text");
508
+ }
509
+ arrayBuffer() {
510
+ return this.#a("arrayBuffer");
511
+ }
512
+ bytes() {
513
+ return this.#a("arrayBuffer").then((e) => new Uint8Array(e));
514
+ }
515
+ blob() {
516
+ return this.#a("blob");
517
+ }
518
+ formData() {
519
+ return this.#a("formData");
520
+ }
521
+ addValidatedData(e, t) {
522
+ this.#e[e] = t;
523
+ }
524
+ valid(e) {
525
+ return this.#e[e];
526
+ }
527
+ get url() {
528
+ return this.raw.url;
529
+ }
530
+ get method() {
531
+ return this.raw.method;
532
+ }
533
+ get [de]() {
534
+ return this.#t;
535
+ }
536
+ get matchedRoutes() {
537
+ return this.#t[0].map(([[, e]]) => e);
538
+ }
539
+ get routePath() {
540
+ return this.#t[0].map(([[, e]]) => e)[this.routeIndex].path;
541
+ }
542
+ }, Fe = {
543
+ Stringify: 1,
544
+ BeforeStream: 2,
545
+ Stream: 3
546
+ }, Ie = (e, t) => {
547
+ let n = new String(e);
548
+ return n.isEscaped = !0, n.callbacks = t, n;
549
+ }, Le = async (e, t, n, r, i) => {
550
+ typeof e == "object" && !(e instanceof String) && (e instanceof Promise || (e = e.toString()), e instanceof Promise && (e = await e));
551
+ let a = e.callbacks;
552
+ if (!a?.length) return Promise.resolve(e);
553
+ i ? i[0] += e : i = [e];
554
+ let o = Promise.all(a.map((e) => e({
555
+ phase: t,
556
+ buffer: i,
557
+ context: r
558
+ }))).then((e) => Promise.all(e.filter(Boolean).map((e) => Le(e, t, !1, r, i))).then(() => i[0]));
559
+ return n ? Ie(await o, a) : o;
560
+ }, Re = "text/plain; charset=UTF-8", ze = (e, t) => ({
561
+ "Content-Type": e,
562
+ ...t
563
+ }), L = (e, t) => new Response(e, t), Be = class {
564
+ #e;
565
+ #t;
566
+ env = {};
567
+ #n;
568
+ finalized = !1;
569
+ error;
570
+ #r;
571
+ #i;
572
+ #a;
573
+ #o;
574
+ #s;
575
+ #c;
576
+ #l;
577
+ #u;
578
+ #d;
579
+ constructor(e, t) {
580
+ this.#e = e, t && (this.#i = t.executionCtx, this.env = t.env, this.#c = t.notFoundHandler, this.#d = t.path, this.#u = t.matchResult);
581
+ }
582
+ get req() {
583
+ return this.#t ??= new Pe(this.#e, this.#d, this.#u), this.#t;
584
+ }
585
+ get event() {
586
+ if (this.#i && "respondWith" in this.#i) return this.#i;
587
+ throw Error("This context has no FetchEvent");
588
+ }
589
+ get executionCtx() {
590
+ if (this.#i) return this.#i;
591
+ throw Error("This context has no ExecutionContext");
592
+ }
593
+ get res() {
594
+ return this.#a ||= L(null, { headers: this.#l ??= new Headers() });
595
+ }
596
+ set res(e) {
597
+ if (this.#a && e) {
598
+ e = L(e.body, e);
599
+ for (let [t, n] of this.#a.headers.entries()) if (t !== "content-type") if (t === "set-cookie") {
600
+ let t = this.#a.headers.getSetCookie();
601
+ e.headers.delete("set-cookie");
602
+ for (let n of t) e.headers.append("set-cookie", n);
603
+ } else e.headers.set(t, n);
604
+ }
605
+ this.#a = e, this.finalized = !0;
606
+ }
607
+ render = (...e) => (this.#s ??= (e) => this.html(e), this.#s(...e));
608
+ setLayout = (e) => this.#o = e;
609
+ getLayout = () => this.#o;
610
+ setRenderer = (e) => {
611
+ this.#s = e;
612
+ };
613
+ header = (e, t, n) => {
614
+ this.finalized && (this.#a = L(this.#a.body, this.#a));
615
+ let r = this.#a ? this.#a.headers : this.#l ??= new Headers();
616
+ t === void 0 ? r.delete(e) : n?.append ? r.append(e, t) : r.set(e, t);
617
+ };
618
+ status = (e) => {
619
+ this.#r = e;
620
+ };
621
+ set = (e, t) => {
622
+ this.#n ??= /* @__PURE__ */ new Map(), this.#n.set(e, t);
623
+ };
624
+ get = (e) => this.#n ? this.#n.get(e) : void 0;
625
+ get var() {
626
+ return this.#n ? Object.fromEntries(this.#n) : {};
627
+ }
628
+ #f(e, t, n) {
629
+ let r = this.#a ? new Headers(this.#a.headers) : this.#l ?? new Headers();
630
+ if (typeof t == "object" && "headers" in t) {
631
+ let e = t.headers instanceof Headers ? t.headers : new Headers(t.headers);
632
+ for (let [t, n] of e) t.toLowerCase() === "set-cookie" ? r.append(t, n) : r.set(t, n);
633
+ }
634
+ if (n) for (let [e, t] of Object.entries(n)) if (typeof t == "string") r.set(e, t);
635
+ else {
636
+ r.delete(e);
637
+ for (let n of t) r.append(e, n);
638
+ }
639
+ return L(e, {
640
+ status: typeof t == "number" ? t : t?.status ?? this.#r,
641
+ headers: r
642
+ });
643
+ }
644
+ newResponse = (...e) => this.#f(...e);
645
+ body = (e, t, n) => this.#f(e, t, n);
646
+ text = (e, t, n) => !this.#l && !this.#r && !t && !n && !this.finalized ? new Response(e) : this.#f(e, t, ze(Re, n));
647
+ json = (e, t, n) => this.#f(JSON.stringify(e), t, ze("application/json", n));
648
+ html = (e, t, n) => {
649
+ let r = (e) => this.#f(e, t, ze("text/html; charset=UTF-8", n));
650
+ return typeof e == "object" ? Le(e, Fe.Stringify, !1, {}).then(r) : r(e);
651
+ };
652
+ redirect = (e, t) => {
653
+ let n = String(e);
654
+ return this.header("Location", /[^\x00-\xFF]/.test(n) ? encodeURI(n) : n), this.newResponse(null, t ?? 302);
655
+ };
656
+ notFound = () => (this.#c ??= () => L(), this.#c(this));
657
+ }, Ve = [
658
+ "get",
659
+ "post",
660
+ "put",
661
+ "delete",
662
+ "options",
663
+ "patch"
664
+ ], He = "Can not add a route since the matcher is already built.", Ue = class extends Error {}, We = "__COMPOSED_HANDLER", Ge = (e) => e.text("404 Not Found", 404), Ke = (e, t) => {
665
+ if ("getResponse" in e) {
666
+ let n = e.getResponse();
667
+ return t.newResponse(n.body, n);
668
+ }
669
+ return console.error(e), t.text("Internal Server Error", 500);
670
+ }, qe = class e {
671
+ get;
672
+ post;
673
+ put;
674
+ delete;
675
+ options;
676
+ patch;
677
+ all;
678
+ on;
679
+ use;
680
+ router;
681
+ getPath;
682
+ _basePath = "/";
683
+ #e = "/";
684
+ routes = [];
685
+ constructor(e = {}) {
686
+ [...Ve, "all"].forEach((e) => {
687
+ this[e] = (t, ...n) => (typeof t == "string" ? this.#e = t : this.#r(e, this.#e, t), n.forEach((t) => {
688
+ this.#r(e, this.#e, t);
689
+ }), this);
690
+ }), this.on = (e, t, ...n) => {
691
+ for (let r of [t].flat()) {
692
+ this.#e = r;
693
+ for (let t of [e].flat()) n.map((e) => {
694
+ this.#r(t.toUpperCase(), this.#e, e);
695
+ });
696
+ }
697
+ return this;
698
+ }, this.use = (e, ...t) => (typeof e == "string" ? this.#e = e : (this.#e = "*", t.unshift(e)), t.forEach((e) => {
699
+ this.#r("ALL", this.#e, e);
700
+ }), this);
701
+ let { strict: t, ...n } = e;
702
+ Object.assign(this, n), this.getPath = t ?? !0 ? e.getPath ?? Te : Ee;
703
+ }
704
+ #t() {
705
+ let t = new e({
706
+ router: this.router,
707
+ getPath: this.getPath
708
+ });
709
+ return t.errorHandler = this.errorHandler, t.#n = this.#n, t.routes = this.routes, t;
710
+ }
711
+ #n = Ge;
712
+ errorHandler = Ke;
713
+ route(e, t) {
714
+ let n = this.basePath(e);
715
+ return t.routes.map((e) => {
716
+ let r;
717
+ t.errorHandler === Ke ? r = e.handler : (r = async (n, r) => (await ue([], t.errorHandler)(n, () => e.handler(n, r))).res, r[We] = e.handler), n.#r(e.method, e.path, r, e.basePath);
718
+ }), this;
719
+ }
720
+ basePath(e) {
721
+ let t = this.#t();
722
+ return t._basePath = I(this._basePath, e), t;
723
+ }
724
+ onError = (e) => (this.errorHandler = e, this);
725
+ notFound = (e) => (this.#n = e, this);
726
+ mount(e, t, n) {
727
+ let r, i;
728
+ n && (typeof n == "function" ? i = n : (i = n.optionHandler, r = n.replaceRequest === !1 ? (e) => e : n.replaceRequest));
729
+ let a = i ? (e) => {
730
+ let t = i(e);
731
+ return Array.isArray(t) ? t : [t];
732
+ } : (e) => {
733
+ let t;
734
+ try {
735
+ t = e.executionCtx;
736
+ } catch {}
737
+ return [e.env, t];
738
+ };
739
+ return r ||= (() => {
740
+ let t = I(this._basePath, e), n = t === "/" ? 0 : t.length;
741
+ return (e) => {
742
+ let t = new URL(e.url);
743
+ return t.pathname = this.getPath(e).slice(n) || "/", new Request(t, e);
744
+ };
745
+ })(), this.#r("ALL", I(e, "*"), async (e, n) => {
746
+ let i = await t(r(e.req.raw), ...a(e));
747
+ if (i) return i;
748
+ await n();
749
+ }), this;
750
+ }
751
+ #r(e, t, n, r) {
752
+ e = e.toUpperCase(), t = I(this._basePath, t);
753
+ let i = {
754
+ basePath: r === void 0 ? this._basePath : I(this._basePath, r),
755
+ path: t,
756
+ method: e,
757
+ handler: n
758
+ };
759
+ this.router.add(e, t, [n, i]), this.routes.push(i);
760
+ }
761
+ #i(e, t) {
762
+ if (e instanceof Error) return this.errorHandler(e, t);
763
+ throw e;
764
+ }
765
+ #a(e, t, n, r) {
766
+ if (r === "HEAD") return (async () => new Response(null, await this.#a(e, t, n, "GET")))();
767
+ let i = this.getPath(e, { env: n }), a = this.router.match(r, i), o = new Be(e, {
768
+ path: i,
769
+ matchResult: a,
770
+ env: n,
771
+ executionCtx: t,
772
+ notFoundHandler: this.#n
773
+ });
774
+ if (a[0].length === 1) {
775
+ let e;
776
+ try {
777
+ e = a[0][0][0][0](o, async () => {
778
+ o.res = await this.#n(o);
779
+ });
780
+ } catch (e) {
781
+ return this.#i(e, o);
782
+ }
783
+ return e instanceof Promise ? e.then((e) => e || (o.finalized ? o.res : this.#n(o))).catch((e) => this.#i(e, o)) : e ?? this.#n(o);
784
+ }
785
+ let s = ue(a[0], this.errorHandler, this.#n);
786
+ return (async () => {
787
+ try {
788
+ let e = await s(o);
789
+ if (!e.finalized) throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
790
+ return e.res;
791
+ } catch (e) {
792
+ return this.#i(e, o);
793
+ }
794
+ })();
795
+ }
796
+ fetch = (e, ...t) => this.#a(e, t[1], t[0], e.method);
797
+ 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${I("/", e)}`, t), n, r));
798
+ fire = () => {
799
+ addEventListener("fetch", (e) => {
800
+ e.respondWith(this.#a(e.request, e, void 0, e.request.method));
801
+ });
802
+ };
803
+ }, Je = [];
804
+ function Ye(e, t) {
805
+ let n = this.buildAllMatchers(), r = ((e, t) => {
806
+ let r = n[e] || n.ALL, i = r[2][t];
807
+ if (i) return i;
808
+ let a = t.match(r[0]);
809
+ if (!a) return [[], Je];
810
+ let o = a.indexOf("", 1);
811
+ return [r[1][o], a];
812
+ });
813
+ return this.match = r, r(e, t);
814
+ }
815
+ //#endregion
816
+ //#region ../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/reg-exp-router/node.js
817
+ var R = "[^/]+", z = ".*", B = "(?:|/.*)", V = /* @__PURE__ */ Symbol(), Xe = /* @__PURE__ */ new Set(".\\+*[^]$()");
818
+ function Ze(e, t) {
819
+ return e.length === 1 ? t.length === 1 ? e < t ? -1 : 1 : -1 : t.length === 1 || e === z || e === B ? 1 : t === z || t === B ? -1 : e === R ? 1 : t === R ? -1 : e.length === t.length ? e < t ? -1 : 1 : t.length - e.length;
820
+ }
821
+ var Qe = class e {
822
+ #e;
823
+ #t;
824
+ #n = /* @__PURE__ */ Object.create(null);
825
+ insert(t, n, r, i, a) {
826
+ if (t.length === 0) {
827
+ if (this.#e !== void 0) throw V;
828
+ if (a) return;
829
+ this.#e = n;
830
+ return;
831
+ }
832
+ let [o, ...s] = t, c = o === "*" ? s.length === 0 ? [
833
+ "",
834
+ "",
835
+ z
836
+ ] : [
837
+ "",
838
+ "",
839
+ R
840
+ ] : o === "/*" ? [
841
+ "",
842
+ "",
843
+ B
844
+ ] : o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/), l;
845
+ if (c) {
846
+ let t = c[1], n = c[2] || R;
847
+ if (t && c[2] && (n === ".*" || (n = n.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"), /\((?!\?:)/.test(n)))) throw V;
848
+ if (l = this.#n[n], !l) {
849
+ if (Object.keys(this.#n).some((e) => e !== z && e !== B)) throw V;
850
+ if (a) return;
851
+ l = this.#n[n] = new e(), t !== "" && (l.#t = i.varIndex++);
852
+ }
853
+ !a && t !== "" && r.push([t, l.#t]);
854
+ } else if (l = this.#n[o], !l) {
855
+ if (Object.keys(this.#n).some((e) => e.length > 1 && e !== z && e !== B)) throw V;
856
+ if (a) return;
857
+ l = this.#n[o] = new e();
858
+ }
859
+ l.insert(s, n, r, i, a);
860
+ }
861
+ buildRegExpStr() {
862
+ let e = Object.keys(this.#n).sort(Ze).map((e) => {
863
+ let t = this.#n[e];
864
+ return (typeof t.#t == "number" ? `(${e})@${t.#t}` : Xe.has(e) ? `\\${e}` : e) + t.buildRegExpStr();
865
+ });
866
+ return typeof this.#e == "number" && e.unshift(`#${this.#e}`), e.length === 0 ? "" : e.length === 1 ? e[0] : "(?:" + e.join("|") + ")";
867
+ }
868
+ }, $e = class {
869
+ #e = { varIndex: 0 };
870
+ #t = new Qe();
871
+ insert(e, t, n) {
872
+ let r = [], i = [];
873
+ for (let t = 0;;) {
874
+ let n = !1;
875
+ if (e = e.replace(/\{[^}]+\}/g, (e) => {
876
+ let r = `@\\${t}`;
877
+ return i[t] = [r, e], t++, n = !0, r;
878
+ }), !n) break;
879
+ }
880
+ let a = e.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
881
+ for (let e = i.length - 1; e >= 0; e--) {
882
+ let [t] = i[e];
883
+ for (let n = a.length - 1; n >= 0; n--) if (a[n].indexOf(t) !== -1) {
884
+ a[n] = a[n].replace(t, i[e][1]);
885
+ break;
886
+ }
887
+ }
888
+ return this.#t.insert(a, t, r, this.#e, n), r;
889
+ }
890
+ buildRegExp() {
891
+ let e = this.#t.buildRegExpStr();
892
+ if (e === "") return [
893
+ /^$/,
894
+ [],
895
+ []
896
+ ];
897
+ let t = 0, n = [], r = [];
898
+ return e = e.replace(/#(\d+)|@(\d+)|\.\*\$/g, (e, i, a) => i === void 0 ? (a === void 0 || (r[Number(a)] = ++t), "") : (n[++t] = Number(i), "$()")), [
899
+ RegExp(`^${e}`),
900
+ n,
901
+ r
902
+ ];
903
+ }
904
+ }, et = [
905
+ /^$/,
906
+ [],
907
+ /* @__PURE__ */ Object.create(null)
908
+ ], tt = /* @__PURE__ */ Object.create(null);
909
+ function nt(e) {
910
+ return tt[e] ??= RegExp(e === "*" ? "" : `^${e.replace(/\/\*$|([.\\+*[^\]$()])/g, (e, t) => t ? `\\${t}` : "(?:|/.*)")}$`);
911
+ }
912
+ function rt() {
913
+ tt = /* @__PURE__ */ Object.create(null);
914
+ }
915
+ function it(e) {
916
+ let t = new $e(), n = [];
917
+ if (e.length === 0) return et;
918
+ 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);
919
+ for (let e = 0, a = -1, o = r.length; e < o; e++) {
920
+ let [o, s, c] = r[e];
921
+ o ? i[s] = [c.map(([e]) => [e, /* @__PURE__ */ Object.create(null)]), Je] : a++;
922
+ let l;
923
+ try {
924
+ l = t.insert(s, a, o);
925
+ } catch (e) {
926
+ throw e === V ? new Ue(s) : e;
927
+ }
928
+ o || (n[a] = c.map(([e, t]) => {
929
+ let n = /* @__PURE__ */ Object.create(null);
930
+ for (--t; t >= 0; t--) {
931
+ let [e, r] = l[t];
932
+ n[e] = r;
933
+ }
934
+ return [e, n];
935
+ }));
936
+ }
937
+ let [a, o, s] = t.buildRegExp();
938
+ for (let e = 0, t = n.length; e < t; e++) for (let t = 0, r = n[e].length; t < r; t++) {
939
+ let r = n[e][t]?.[1];
940
+ if (!r) continue;
941
+ let i = Object.keys(r);
942
+ for (let e = 0, t = i.length; e < t; e++) r[i[e]] = s[r[i[e]]];
943
+ }
944
+ let c = [];
945
+ for (let e in o) c[e] = n[o[e]];
946
+ return [
947
+ a,
948
+ c,
949
+ i
950
+ ];
951
+ }
952
+ function H(e, t) {
953
+ if (e) {
954
+ for (let n of Object.keys(e).sort((e, t) => t.length - e.length)) if (nt(n).test(t)) return [...e[n]];
955
+ }
956
+ }
957
+ var at = class {
958
+ name = "RegExpRouter";
959
+ #e;
960
+ #t;
961
+ constructor() {
962
+ this.#e = { ALL: /* @__PURE__ */ Object.create(null) }, this.#t = { ALL: /* @__PURE__ */ Object.create(null) };
963
+ }
964
+ add(e, t, n) {
965
+ let r = this.#e, i = this.#t;
966
+ if (!r || !i) throw Error(He);
967
+ r[e] || [r, i].forEach((t) => {
968
+ t[e] = /* @__PURE__ */ Object.create(null), Object.keys(t.ALL).forEach((n) => {
969
+ t[e][n] = [...t.ALL[n]];
970
+ });
971
+ }), t === "/*" && (t = "*");
972
+ let a = (t.match(/\/:/g) || []).length;
973
+ if (/\*$/.test(t)) {
974
+ let o = nt(t);
975
+ e === "ALL" ? Object.keys(r).forEach((e) => {
976
+ r[e][t] ||= H(r[e], t) || H(r.ALL, t) || [];
977
+ }) : r[e][t] ||= H(r[e], t) || H(r.ALL, t) || [], Object.keys(r).forEach((t) => {
978
+ (e === "ALL" || e === t) && Object.keys(r[t]).forEach((e) => {
979
+ o.test(e) && r[t][e].push([n, a]);
980
+ });
981
+ }), Object.keys(i).forEach((t) => {
982
+ (e === "ALL" || e === t) && Object.keys(i[t]).forEach((e) => o.test(e) && i[t][e].push([n, a]));
983
+ });
984
+ return;
985
+ }
986
+ let o = De(t) || [t];
987
+ for (let t = 0, s = o.length; t < s; t++) {
988
+ let c = o[t];
989
+ Object.keys(i).forEach((o) => {
990
+ (e === "ALL" || e === o) && (i[o][c] ||= [...H(r[o], c) || H(r.ALL, c) || []], i[o][c].push([n, a - s + t + 1]));
991
+ });
992
+ }
993
+ }
994
+ match = Ye;
995
+ buildAllMatchers() {
996
+ let e = /* @__PURE__ */ Object.create(null);
997
+ return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach((t) => {
998
+ e[t] ||= this.#n(t);
999
+ }), this.#e = this.#t = void 0, rt(), e;
1000
+ }
1001
+ #n(e) {
1002
+ let t = [], n = e === "ALL";
1003
+ return [this.#e, this.#t].forEach((r) => {
1004
+ let i = r[e] ? Object.keys(r[e]).map((t) => [t, r[e][t]]) : [];
1005
+ i.length === 0 ? e !== "ALL" && t.push(...Object.keys(r.ALL).map((e) => [e, r.ALL[e]])) : (n ||= !0, t.push(...i));
1006
+ }), n ? it(t) : null;
1007
+ }
1008
+ }, ot = class {
1009
+ name = "SmartRouter";
1010
+ #e = [];
1011
+ #t = [];
1012
+ constructor(e) {
1013
+ this.#e = e.routers;
1014
+ }
1015
+ add(e, t, n) {
1016
+ if (!this.#t) throw Error(He);
1017
+ this.#t.push([
1018
+ e,
1019
+ t,
1020
+ n
1021
+ ]);
1022
+ }
1023
+ match(e, t) {
1024
+ if (!this.#t) throw Error("Fatal error");
1025
+ let n = this.#e, r = this.#t, i = n.length, a = 0, o;
1026
+ for (; a < i; a++) {
1027
+ let i = n[a];
1028
+ try {
1029
+ for (let e = 0, t = r.length; e < t; e++) i.add(...r[e]);
1030
+ o = i.match(e, t);
1031
+ } catch (e) {
1032
+ if (e instanceof Ue) continue;
1033
+ throw e;
1034
+ }
1035
+ this.match = i.match.bind(i), this.#e = [i], this.#t = void 0;
1036
+ break;
1037
+ }
1038
+ if (a === i) throw Error("Fatal error");
1039
+ return this.name = `SmartRouter + ${this.activeRouter.name}`, o;
1040
+ }
1041
+ get activeRouter() {
1042
+ if (this.#t || this.#e.length !== 1) throw Error("No active router has been determined yet.");
1043
+ return this.#e[0];
1044
+ }
1045
+ }, U = /* @__PURE__ */ Object.create(null), st = (e) => {
1046
+ for (let t in e) return !0;
1047
+ return !1;
1048
+ }, ct = class e {
1049
+ #e;
1050
+ #t;
1051
+ #n;
1052
+ #r = 0;
1053
+ #i = U;
1054
+ constructor(e, t, n) {
1055
+ if (this.#t = n || /* @__PURE__ */ Object.create(null), this.#e = [], e && t) {
1056
+ let n = /* @__PURE__ */ Object.create(null);
1057
+ n[e] = {
1058
+ handler: t,
1059
+ possibleKeys: [],
1060
+ score: 0
1061
+ }, this.#e = [n];
1062
+ }
1063
+ this.#n = [];
1064
+ }
1065
+ insert(t, n, r) {
1066
+ this.#r = ++this.#r;
1067
+ let i = this, a = ve(n), o = [];
1068
+ for (let t = 0, n = a.length; t < n; t++) {
1069
+ let n = a[t], r = a[t + 1], s = Se(n, r), c = Array.isArray(s) ? s[0] : n;
1070
+ if (c in i.#t) {
1071
+ i = i.#t[c], s && o.push(s[1]);
1072
+ continue;
1073
+ }
1074
+ i.#t[c] = new e(), s && (i.#n.push(s), o.push(s[1])), i = i.#t[c];
1075
+ }
1076
+ return i.#e.push({ [t]: {
1077
+ handler: r,
1078
+ possibleKeys: o.filter((e, t, n) => n.indexOf(e) === t),
1079
+ score: this.#r
1080
+ } }), i;
1081
+ }
1082
+ #a(e, t, n, r, i) {
1083
+ for (let a = 0, o = t.#e.length; a < o; a++) {
1084
+ let o = t.#e[a], s = o[n] || o.ALL, c = {};
1085
+ 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++) {
1086
+ let t = s.possibleKeys[e], n = c[s.score];
1087
+ s.params[t] = i?.[t] && !n ? i[t] : r[t] ?? i?.[t], c[s.score] = !0;
1088
+ }
1089
+ }
1090
+ }
1091
+ search(e, t) {
1092
+ let n = [];
1093
+ this.#i = U;
1094
+ let r = [this], i = _e(t), a = [], o = i.length, s = null;
1095
+ for (let c = 0; c < o; c++) {
1096
+ let l = i[c], u = c === o - 1, d = [];
1097
+ for (let f = 0, p = r.length; f < p; f++) {
1098
+ let p = r[f], m = p.#t[l];
1099
+ 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));
1100
+ for (let r = 0, f = p.#n.length; r < f; r++) {
1101
+ let f = p.#n[r], m = p.#i === U ? {} : { ...p.#i };
1102
+ if (f === "*") {
1103
+ let t = p.#t["*"];
1104
+ t && (this.#a(n, t, e, p.#i), t.#i = m, d.push(t));
1105
+ continue;
1106
+ }
1107
+ let [h, g, _] = f;
1108
+ if (!l && !(_ instanceof RegExp)) continue;
1109
+ let v = p.#t[h];
1110
+ if (_ instanceof RegExp) {
1111
+ if (s === null) {
1112
+ s = Array(o);
1113
+ let e = +(t[0] === "/");
1114
+ for (let t = 0; t < o; t++) s[t] = e, e += i[t].length + 1;
1115
+ }
1116
+ let r = t.substring(s[c]), l = _.exec(r);
1117
+ if (l) {
1118
+ if (m[g] = l[0], this.#a(n, v, e, p.#i, m), st(v.#t)) {
1119
+ v.#i = m;
1120
+ let e = l[0].match(/\//)?.length ?? 0;
1121
+ (a[e] ||= []).push(v);
1122
+ }
1123
+ continue;
1124
+ }
1125
+ }
1126
+ (_ === !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)));
1127
+ }
1128
+ }
1129
+ let f = a.shift();
1130
+ r = f ? d.concat(f) : d;
1131
+ }
1132
+ return n.length > 1 && n.sort((e, t) => e.score - t.score), [n.map(({ handler: e, params: t }) => [e, t])];
1133
+ }
1134
+ }, lt = class {
1135
+ name = "TrieRouter";
1136
+ #e;
1137
+ constructor() {
1138
+ this.#e = new ct();
1139
+ }
1140
+ add(e, t, n) {
1141
+ let r = De(t);
1142
+ if (r) {
1143
+ for (let t = 0, i = r.length; t < i; t++) this.#e.insert(e, r[t], n);
1144
+ return;
1145
+ }
1146
+ this.#e.insert(e, t, n);
1147
+ }
1148
+ match(e, t) {
1149
+ return this.#e.search(e, t);
1150
+ }
1151
+ }, ut = class extends qe {
1152
+ constructor(e = {}) {
1153
+ super(e), this.router = e.router ?? new ot({ routers: [new at(), new lt()] });
1154
+ }
1155
+ };
1156
+ //#endregion
1157
+ //#region src/coordinator-invites.ts
1158
+ function dt(e) {
1159
+ let t = "";
1160
+ for (let n of e) t += String.fromCharCode(n);
1161
+ return btoa(t);
1162
+ }
1163
+ function ft(e) {
1164
+ let t = atob(e), n = new Uint8Array(t.length);
1165
+ for (let e = 0; e < t.length; e += 1) n[e] = t.charCodeAt(e);
1166
+ return n;
1167
+ }
1168
+ function pt(e) {
1169
+ return e.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1170
+ }
1171
+ function mt(e) {
1172
+ let t = e.replace(/-/g, "+").replace(/_/g, "/");
1173
+ return t + "=".repeat((4 - t.length % 4) % 4);
1174
+ }
1175
+ function W(e) {
1176
+ let t = JSON.stringify(e);
1177
+ return pt(dt(new TextEncoder().encode(t)));
1178
+ }
1179
+ function ht(e) {
1180
+ let t = new TextDecoder().decode(ft(mt(e))), n = JSON.parse(t);
1181
+ if (typeof n != "object" || !n) throw Error("invalid invite payload");
1182
+ return n;
1183
+ }
1184
+ function G(e) {
1185
+ return `codemem://join?invite=${encodeURIComponent(e)}`;
1186
+ }
1187
+ function gt(e) {
1188
+ let t = e.trim();
1189
+ if (t.startsWith("codemem://")) {
1190
+ let e = new URL(t).searchParams.get("invite") ?? "";
1191
+ if (!e) throw Error("invite payload missing from link");
1192
+ return e;
1193
+ }
1194
+ return t;
1195
+ }
1196
+ //#endregion
1197
+ //#region src/project-invite-acceptance.ts
1198
+ var _t = "pending_setup", vt = "project_sync_enablement_failed", yt = "Invitation was accepted, but sync could not be enabled. Make the codemem config writable, then retry.", bt = class extends Error {
1199
+ code = vt;
1200
+ detail = yt;
1201
+ constructor(e) {
1202
+ super(yt, e), this.name = "ProjectSyncEnablementError";
1203
+ }
1204
+ };
1205
+ function xt(e) {
1206
+ return typeof e == "object" && !!e && "code" in e && e.code === "project_sync_enablement_failed" && "detail" in e && e.detail === "Invitation was accepted, but sync could not be enabled. Make the codemem config writable, then retry.";
1207
+ }
1208
+ //#endregion
1209
+ //#region src/scope-resolution.ts
1210
+ var St = "local-default", Ct = "legacy-shared-review";
1211
+ function K(e) {
1212
+ return e?.trim() || null;
1213
+ }
1214
+ function q(e) {
1215
+ return e.trim().replaceAll("\\", "/").replace(/\/+$/, "") || e.trim();
1216
+ }
1217
+ function wt(t) {
1218
+ return q(e(t));
1219
+ }
1220
+ function Tt(e) {
1221
+ let t = K(e);
1222
+ return t ? q(t) : null;
1223
+ }
1224
+ function Et(e) {
1225
+ let n = [
1226
+ e.cwd,
1227
+ e.project,
1228
+ e.workspaceId
1229
+ ].map((e) => K(e)).find((e) => e != null);
1230
+ return `unmapped:${t("sha256").update(n ?? "unknown", "utf8").digest("hex")}`;
1231
+ }
1232
+ function Dt(e) {
1233
+ let t = K(e.gitRemote), n = K(e.gitBranch), r = K(e.cwd), i = K(e.workspaceId), a = K(e.project);
1234
+ if (t) {
1235
+ let r = q(t);
1236
+ return e.branchScoped && n ? {
1237
+ value: `${r}:${n}`,
1238
+ source: "git_remote_branch",
1239
+ displayProject: a
1240
+ } : {
1241
+ value: r,
1242
+ source: "git_remote",
1243
+ displayProject: a
1244
+ };
1245
+ }
1246
+ return r ? {
1247
+ value: wt(r),
1248
+ source: "cwd",
1249
+ displayProject: a
1250
+ } : i ? {
1251
+ value: q(i),
1252
+ source: "workspace_id",
1253
+ displayProject: a
1254
+ } : {
1255
+ value: Et(e),
1256
+ source: "unmapped",
1257
+ displayProject: a
1258
+ };
1259
+ }
1260
+ function Ot(e) {
1261
+ return !/[\\/:]/.test(e);
1262
+ }
1263
+ function kt(e) {
1264
+ return e.replace(/[|\\{}()[\]^$+?.*]/g, "\\$&");
1265
+ }
1266
+ function At(e) {
1267
+ return e.replace(/[*?]/g, "").length;
1268
+ }
1269
+ function jt(e, t) {
1270
+ let n = q(t);
1271
+ return !n || Ot(n) ? !1 : /[*?]/.test(n) ? RegExp(`^${kt(n).replaceAll("\\*", ".*").replaceAll("\\?", ".")}$`).test(e) : e === n;
1272
+ }
1273
+ function Mt(e) {
1274
+ return e.mapping.priority ?? 0;
1275
+ }
1276
+ function Nt(e) {
1277
+ let t = K(e.mapping.updated_at);
1278
+ if (!t) return 0;
1279
+ let n = Date.parse(t);
1280
+ return Number.isFinite(n) ? n : 0;
1281
+ }
1282
+ function Pt(e, t) {
1283
+ return Mt(t) - Mt(e) || t.specificity - e.specificity || Nt(t) - Nt(e) || (t.mapping.id ?? 0) - (e.mapping.id ?? 0) || e.mapping.scope_id.localeCompare(t.mapping.scope_id);
1284
+ }
1285
+ function Ft(e) {
1286
+ return e.toSorted(Pt)[0] ?? null;
1287
+ }
1288
+ function It(e) {
1289
+ let t = Dt(e), n = K(e.explicitScopeId);
1290
+ if (n) return {
1291
+ scopeId: n,
1292
+ reason: "explicit_override",
1293
+ workspaceIdentity: t,
1294
+ mapping: null,
1295
+ matchedPattern: null
1296
+ };
1297
+ if (t.source === "unmapped") return {
1298
+ scopeId: e.localDefaultScopeId ?? "local-default",
1299
+ reason: "local_default",
1300
+ workspaceIdentity: t,
1301
+ mapping: null,
1302
+ matchedPattern: null
1303
+ };
1304
+ let r = e.mappings ?? [], i = Ft(r.filter((e) => Tt(e.workspace_identity) === t.value).map((e) => ({
1305
+ mapping: e,
1306
+ matchedPattern: null,
1307
+ specificity: t.value.length
1308
+ })));
1309
+ if (i) return {
1310
+ scopeId: i.mapping.scope_id,
1311
+ reason: "exact_mapping",
1312
+ workspaceIdentity: t,
1313
+ mapping: i.mapping,
1314
+ matchedPattern: null
1315
+ };
1316
+ let a = Ft(r.flatMap((e) => {
1317
+ if (K(e.workspace_identity)) return [];
1318
+ let n = K(e.project_pattern);
1319
+ return !n || !jt(t.value, n) ? [] : [{
1320
+ mapping: e,
1321
+ matchedPattern: q(n),
1322
+ specificity: At(n)
1323
+ }];
1324
+ }));
1325
+ return a ? {
1326
+ scopeId: a.mapping.scope_id,
1327
+ reason: "pattern_mapping",
1328
+ workspaceIdentity: t,
1329
+ mapping: a.mapping,
1330
+ matchedPattern: a.matchedPattern
1331
+ } : {
1332
+ scopeId: e.localDefaultScopeId ?? "local-default",
1333
+ reason: "local_default",
1334
+ workspaceIdentity: t,
1335
+ mapping: null,
1336
+ matchedPattern: null
1337
+ };
1338
+ }
1339
+ function Lt(e, t) {
1340
+ let n = new Set([
1341
+ "",
1342
+ St,
1343
+ Ct
1344
+ ]), r = e.prepare("SELECT scope_id\n FROM replication_scopes\n WHERE status = 'active' AND authority_type = 'local'").all();
1345
+ for (let e of r) e.scope_id != null && n.add(e.scope_id);
1346
+ let i = e.prepare("SELECT sm.scope_id AS scope_id\n FROM scope_memberships sm\n JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n WHERE sm.device_id = ?\n AND sm.status = 'active'\n AND rs.status = 'active'\n AND sm.membership_epoch >= rs.membership_epoch").all(t);
1347
+ for (let e of i) e.scope_id != null && n.add(e.scope_id);
1348
+ return [...n];
1349
+ }
1350
+ //#endregion
1351
+ //#region src/project-share-intent.ts
1352
+ var Rt = "existing_and_future";
1353
+ function zt(e) {
1354
+ return t("sha256").update(JSON.stringify(e)).digest("hex");
1355
+ }
1356
+ function Bt(e) {
1357
+ return zt({
1358
+ v: 1,
1359
+ historyPolicy: Rt,
1360
+ projects: e.map((e) => ({
1361
+ canonicalIdentity: e.canonicalIdentity,
1362
+ existingMemoryCount: e.existingMemoryCount
1363
+ })).toSorted((e, t) => e.canonicalIdentity.localeCompare(t.canonicalIdentity))
1364
+ });
1365
+ }
1366
+ function Vt(e) {
1367
+ return Bt(e.map((e) => ({
1368
+ canonicalIdentity: e.canonical_identity,
1369
+ displayName: e.display_name,
1370
+ identitySource: "coordinator_acceptance",
1371
+ existingMemoryCount: e.existing_memory_count
1372
+ })));
1373
+ }
1374
+ function Ht(e) {
1375
+ if (!Array.isArray(e) || e.length === 0 || e.length > 100) throw Error("operation_intent_invalid");
1376
+ let t = e.map((e) => {
1377
+ if (!e || typeof e != "object" || Array.isArray(e)) throw Error("operation_intent_invalid");
1378
+ let t = e;
1379
+ if (typeof t.canonical_identity != "string" || typeof t.display_name != "string") throw Error("operation_intent_invalid");
1380
+ let n = t.canonical_identity, r = n.trim(), i = t.display_name, a;
1381
+ try {
1382
+ a = g(i, "project_name");
1383
+ } catch {
1384
+ throw Error("operation_intent_invalid");
1385
+ }
1386
+ let o = t.existing_memory_count, s = Dt({ gitRemote: r }).value;
1387
+ if (!r || r !== n || r.length > 2048 || r.startsWith("unmapped:") || s !== r || a !== i || !Number.isSafeInteger(o) || Number(o) < 0 || /[\p{Cc}\p{Cf}]/u.test(r) || /[\p{Cc}\p{Cf}]/u.test(a)) throw Error("operation_intent_invalid");
1388
+ return {
1389
+ canonical_identity: r,
1390
+ display_name: a,
1391
+ existing_memory_count: Number(o)
1392
+ };
1393
+ });
1394
+ if (new Set(t.map((e) => e.canonical_identity)).size !== t.length) throw Error("operation_intent_invalid");
1395
+ return t.toSorted((e, t) => e.canonical_identity.localeCompare(t.canonical_identity));
1396
+ }
1397
+ //#endregion
1398
+ //#region ../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/clock.js
1399
+ function Ut(e) {
1400
+ let t = performance.now() * .001, n = Math.floor(t), r = Math.floor(t % 1 * 1e9);
1401
+ return e != null && (n -= e[0], r -= e[1], r < 0 && (n--, r += 1e9)), [n, r];
1402
+ }
1403
+ function J() {
1404
+ let [e, t] = Ut();
1405
+ return e * 1e3 + Math.floor(t / 1e6);
1406
+ }
1407
+ function Wt(e) {
1408
+ return new Promise((t) => setTimeout(t, e));
1409
+ }
1410
+ //#endregion
1411
+ //#region ../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/TokenBucket.js
1412
+ var Gt = class {
1413
+ bucketSize;
1414
+ tokensPerInterval;
1415
+ interval;
1416
+ parentBucket;
1417
+ content;
1418
+ lastDrip;
1419
+ constructor({ bucketSize: e, tokensPerInterval: t, interval: n, parentBucket: r }) {
1420
+ if (this.bucketSize = e, this.tokensPerInterval = t, typeof n == "string") switch (n) {
1421
+ case "sec":
1422
+ case "second":
1423
+ this.interval = 1e3;
1424
+ break;
1425
+ case "min":
1426
+ case "minute":
1427
+ this.interval = 1e3 * 60;
1428
+ break;
1429
+ case "hr":
1430
+ case "hour":
1431
+ this.interval = 1e3 * 60 * 60;
1432
+ break;
1433
+ case "day":
1434
+ this.interval = 1e3 * 60 * 60 * 24;
1435
+ break;
1436
+ default: throw Error("Invalid interval " + n);
1437
+ }
1438
+ else this.interval = n;
1439
+ this.parentBucket = r, this.content = 0, this.lastDrip = J();
1440
+ }
1441
+ async removeTokens(e) {
1442
+ if (this.bucketSize === 0) return Infinity;
1443
+ if (e > this.bucketSize) throw Error(`Requested tokens ${e} exceeds bucket size ${this.bucketSize}`);
1444
+ this.drip();
1445
+ let t = async () => (await Wt(Math.ceil((e - this.content) * (this.interval / this.tokensPerInterval))), this.removeTokens(e));
1446
+ if (e > this.content) return t();
1447
+ if (this.parentBucket != null) {
1448
+ let n = await this.parentBucket.removeTokens(e);
1449
+ return e > this.content ? t() : (this.content -= e, Math.min(n, this.content));
1450
+ } else return this.content -= e, this.content;
1451
+ }
1452
+ tryRemoveTokens(e) {
1453
+ return this.bucketSize ? e > this.bucketSize || (this.drip(), e > this.content) || this.parentBucket && !this.parentBucket.tryRemoveTokens(e) ? !1 : (this.content -= e, !0) : !0;
1454
+ }
1455
+ drip() {
1456
+ if (this.tokensPerInterval === 0) {
1457
+ let e = this.content;
1458
+ return this.content = this.bucketSize, this.content > e;
1459
+ }
1460
+ let e = J(), t = Math.max(e - this.lastDrip, 0);
1461
+ this.lastDrip = e;
1462
+ let n = t * (this.tokensPerInterval / this.interval), r = this.content;
1463
+ return this.content = Math.min(this.content + n, this.bucketSize), Math.floor(this.content) > Math.floor(r);
1464
+ }
1465
+ }, Kt = class {
1466
+ tokenBucket;
1467
+ curIntervalStart;
1468
+ tokensThisInterval;
1469
+ fireImmediately;
1470
+ constructor({ tokensPerInterval: e, interval: t, fireImmediately: n }) {
1471
+ this.tokenBucket = new Gt({
1472
+ bucketSize: e,
1473
+ tokensPerInterval: e,
1474
+ interval: t
1475
+ }), this.tokenBucket.content = e, this.curIntervalStart = J(), this.tokensThisInterval = 0, this.fireImmediately = n ?? !1;
1476
+ }
1477
+ async removeTokens(e) {
1478
+ if (e > this.tokenBucket.bucketSize) throw Error(`Requested tokens ${e} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);
1479
+ let t = J();
1480
+ if ((t < this.curIntervalStart || t - this.curIntervalStart >= this.tokenBucket.interval) && (this.curIntervalStart = t, this.tokensThisInterval = 0), e > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {
1481
+ if (this.fireImmediately) return -1;
1482
+ {
1483
+ await Wt(Math.ceil(this.curIntervalStart + this.tokenBucket.interval - t));
1484
+ let n = await this.tokenBucket.removeTokens(e);
1485
+ return this.tokensThisInterval += e, n;
1486
+ }
1487
+ }
1488
+ let n = await this.tokenBucket.removeTokens(e);
1489
+ return this.tokensThisInterval += e, n;
1490
+ }
1491
+ tryRemoveTokens(e) {
1492
+ if (e > this.tokenBucket.bucketSize) return !1;
1493
+ let t = J();
1494
+ if ((t < this.curIntervalStart || t - this.curIntervalStart >= this.tokenBucket.interval) && (this.curIntervalStart = t, this.tokensThisInterval = 0), e > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) return !1;
1495
+ let n = this.tokenBucket.tryRemoveTokens(e);
1496
+ return n && (this.tokensThisInterval += e), n;
1497
+ }
1498
+ getTokensRemaining() {
1499
+ return this.tokenBucket.drip(), this.tokenBucket.content;
1500
+ }
1501
+ };
1502
+ //#endregion
1503
+ //#region src/request-rate-limit.ts
1504
+ function qt(e = {}) {
1505
+ let t = Math.max(1e3, Math.trunc(e.windowMs ?? 6e4)), n = e.now ?? (() => Date.now()), r = /* @__PURE__ */ new Map(), i = 0;
1506
+ function a(e) {
1507
+ return Math.max(1, Math.ceil(t / Math.max(1, e) / 1e3));
1508
+ }
1509
+ function o(e) {
1510
+ if (r.size < 64 || i % 64 != 0) return;
1511
+ let n = e - t * 10;
1512
+ for (let [e, t] of r) t.lastUsedAt < n && r.delete(e);
1513
+ }
1514
+ return { check(e, s) {
1515
+ let c = Math.max(1, Math.trunc(s));
1516
+ i += 1;
1517
+ let l = n();
1518
+ o(l);
1519
+ let u = `${c}:${e}`, d = r.get(u);
1520
+ return d || (d = {
1521
+ limiter: new Kt({
1522
+ tokensPerInterval: c,
1523
+ interval: t,
1524
+ fireImmediately: !0
1525
+ }),
1526
+ lastUsedAt: l
1527
+ }, r.set(u, d)), d.lastUsedAt = l, d.limiter.tryRemoveTokens(1) ? {
1528
+ allowed: !0,
1529
+ retryAfterS: 0
1530
+ } : {
1531
+ allowed: !1,
1532
+ retryAfterS: a(c)
1533
+ };
1534
+ } };
1535
+ }
1536
+ //#endregion
1537
+ //#region src/scope-membership-semantics.ts
1538
+ var Jt = "Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.";
1539
+ function Yt(e) {
1540
+ let t = Number.isFinite(e.membershipEpoch) ? Number(e.membershipEpoch) : null, n = Number.isFinite(e.requiredEpoch) ? Number(e.requiredEpoch) : null;
1541
+ return t == null || n == null ? {
1542
+ membership_epoch: t,
1543
+ required_epoch: n,
1544
+ stale: !1,
1545
+ reason: "unknown_epoch"
1546
+ } : {
1547
+ membership_epoch: t,
1548
+ required_epoch: n,
1549
+ stale: t < n,
1550
+ reason: t < n ? "stale_epoch" : "current"
1551
+ };
1552
+ }
1553
+ function Xt(e) {
1554
+ return {
1555
+ scope_id: e.scopeId,
1556
+ device_id: e.deviceId,
1557
+ membership_epoch: Number.isFinite(e.membershipEpoch) ? Number(e.membershipEpoch) : null,
1558
+ prevents_future_sync: !0,
1559
+ deletes_already_copied_data: !1,
1560
+ message: Jt
1561
+ };
1562
+ }
1563
+ //#endregion
1564
+ //#region src/sync-auth-constants.ts
1565
+ var Zt = 300, Y = 64 * 1024, X = "X-Codemem-Coordinator-Admin", Qt = "X-Codemem-Coordinator-Admin-Actor", $t = 120, en = 30;
1566
+ function Z(e, t) {
1567
+ let n = t.adminSecret();
1568
+ if (!n) return {
1569
+ ok: !1,
1570
+ error: "admin_not_configured"
1571
+ };
1572
+ let r = (e ?? "").trim();
1573
+ return r ? r === n ? {
1574
+ ok: !0,
1575
+ error: "ok"
1576
+ } : {
1577
+ ok: !1,
1578
+ error: "invalid_admin_secret"
1579
+ } : {
1580
+ ok: !1,
1581
+ error: "missing_admin_header"
1582
+ };
1583
+ }
1584
+ function tn(e) {
1585
+ let t = new URL(e);
1586
+ return t.search ? `${t.pathname}${t.search}` : t.pathname;
1587
+ }
1588
+ async function nn(e, t, n, r) {
1589
+ return await e.recordNonce(t, n, r);
1590
+ }
1591
+ async function rn(e, t) {
1592
+ await e.cleanupNonces(t);
1593
+ }
1594
+ async function Q(e, t, n, r) {
1595
+ let { deviceId: i, signature: a, timestamp: o, nonce: s } = r;
1596
+ if (!i || !a || !o || !s) return {
1597
+ ok: !1,
1598
+ error: "missing_headers",
1599
+ enrollment: null
1600
+ };
1601
+ let c = await e.getEnrollment(r.groupId, i, !0);
1602
+ if (!c) return {
1603
+ ok: !1,
1604
+ error: "unknown_device",
1605
+ enrollment: null
1606
+ };
1607
+ if (c.enabled !== 1) return {
1608
+ ok: !1,
1609
+ error: "device_disabled",
1610
+ enrollment: null
1611
+ };
1612
+ let l = await e.getGroup(r.groupId);
1613
+ if (!l) return {
1614
+ ok: !1,
1615
+ error: "group_not_found",
1616
+ enrollment: null
1617
+ };
1618
+ if (l.archived_at) return {
1619
+ ok: !1,
1620
+ error: "group_archived",
1621
+ enrollment: null
1622
+ };
1623
+ let u;
1624
+ try {
1625
+ u = await n({
1626
+ method: r.method,
1627
+ pathWithQuery: tn(r.url),
1628
+ bodyBytes: r.body,
1629
+ timestamp: o,
1630
+ nonce: s,
1631
+ signature: a,
1632
+ publicKey: String(c.public_key),
1633
+ deviceId: i
1634
+ });
1635
+ } catch {
1636
+ return {
1637
+ ok: !1,
1638
+ error: "signature_verification_error",
1639
+ enrollment: null
1640
+ };
1641
+ }
1642
+ if (!u) return {
1643
+ ok: !1,
1644
+ error: "invalid_signature",
1645
+ enrollment: null
1646
+ };
1647
+ let d = t.now();
1648
+ return await nn(e, i, s, d) ? (await rn(e, (/* @__PURE__ */ new Date(new Date(d).getTime() - 300 * 2 * 1e3)).toISOString()), {
1649
+ ok: !0,
1650
+ error: "ok",
1651
+ enrollment: c
1652
+ }) : {
1653
+ ok: !1,
1654
+ error: "nonce_replay",
1655
+ enrollment: null
1656
+ };
1657
+ }
1658
+ function $(e) {
1659
+ return e === "device_disabled" ? 403 : e === "group_archived" ? 409 : 401;
1660
+ }
1661
+ function an(e) {
1662
+ if (!e?.storeFactory || !e.runtime || !e.requestVerifier) throw Error("createCoordinatorApp requires storeFactory, runtime, and requestVerifier.");
1663
+ let t = e.runtime, n = e.storeFactory, r = e.requestVerifier, a = e.requestRateLimit ?? {}, o = a.limiter ?? qt(), s = Math.max(1, Math.trunc(a.readLimit ?? $t)), c = Math.max(1, Math.trunc(a.mutationLimit ?? en)), l = Math.max(1, Math.trunc(a.unauthenticatedReadLimit ?? Math.min(20, s))), u = Math.max(1, Math.trunc(a.unauthenticatedMutationLimit ?? Math.min(10, c))), d = new ut(), f = new TextDecoder();
1664
+ function p(e, t, n) {
1665
+ let r = e.req.method === "GET" || e.req.method === "HEAD" || e.req.method === "OPTIONS", i = o.check(`${e.req.method}:${n ? "auth" : "anon"}:${t}`, n ? r ? s : c : r ? l : u);
1666
+ return i.allowed ? null : (e.header("Retry-After", String(i.retryAfterS)), e.json({
1667
+ error: "rate_limited",
1668
+ retry_after_s: i.retryAfterS
1669
+ }, 429));
1670
+ }
1671
+ async function m(e) {
1672
+ let t = Number.parseInt(e.req.header("content-length") ?? "", 10);
1673
+ if (Number.isFinite(t) && t > Y) return null;
1674
+ let n = e.req.raw.body;
1675
+ if (!n) return new Uint8Array();
1676
+ let r = n.getReader(), i = [], a = 0;
1677
+ try {
1678
+ for (;;) {
1679
+ let { done: e, value: t } = await r.read();
1680
+ if (e) break;
1681
+ if (t) {
1682
+ if (a += t.byteLength, a > Y) return await r.cancel(), null;
1683
+ i.push(t);
1684
+ }
1685
+ }
1686
+ } finally {
1687
+ r.releaseLock();
1688
+ }
1689
+ let o = new Uint8Array(a), s = 0;
1690
+ for (let e of i) o.set(e, s), s += e.byteLength;
1691
+ return o;
1692
+ }
1693
+ function h(e) {
1694
+ try {
1695
+ let t = JSON.parse(f.decode(e));
1696
+ return typeof t != "object" || !t || Array.isArray(t) ? null : t;
1697
+ } catch {
1698
+ return null;
1699
+ }
1700
+ }
1701
+ function _(e, t) {
1702
+ let n = e[t];
1703
+ return n == null ? null : String(n).trim() || null;
1704
+ }
1705
+ function v(e) {
1706
+ return e?.trim() || null;
1707
+ }
1708
+ function b(e, t) {
1709
+ let n = e[t];
1710
+ if (n == null || n === "") return null;
1711
+ if (typeof n != "number" && typeof n != "string") return NaN;
1712
+ if (typeof n == "string") {
1713
+ let e = n.trim();
1714
+ if (!e) return NaN;
1715
+ let t = Number(e);
1716
+ return Number.isFinite(t) ? Math.trunc(t) : NaN;
1717
+ }
1718
+ let r = n;
1719
+ return Number.isFinite(r) ? Math.trunc(r) : NaN;
1720
+ }
1721
+ function S(e) {
1722
+ return [
1723
+ "1",
1724
+ "true",
1725
+ "yes"
1726
+ ].includes(String(e ?? "").trim().toLowerCase());
1727
+ }
1728
+ function C(e) {
1729
+ try {
1730
+ return Ht(JSON.parse(e ?? ""));
1731
+ } catch {
1732
+ throw Error("operation_intent_invalid");
1733
+ }
1734
+ }
1735
+ function w(e) {
1736
+ let t = String(e.operation_id ?? "").trim(), n = String(e.reviewed_project_set_digest ?? "").trim();
1737
+ if (!/^share_[a-f0-9]{40}$/u.test(t) || !/^[a-f0-9]{64}$/u.test(n)) throw Error("operation_intent_invalid");
1738
+ let r = C(e.project_intent_json);
1739
+ if (Vt(r) !== n) throw Error("operation_intent_invalid");
1740
+ return {
1741
+ operation_id: t,
1742
+ reviewed_project_set_digest: n,
1743
+ projects: r
1744
+ };
1745
+ }
1746
+ function T(e) {
1747
+ try {
1748
+ return y(JSON.parse(e ?? ""));
1749
+ } catch {
1750
+ throw Error("operation_intent_invalid");
1751
+ }
1752
+ }
1753
+ async function E(e, t, n) {
1754
+ if (!t) return n.json({ error: "group_id_required" }, 400);
1755
+ let r = await e.getGroup(t);
1756
+ return r ? r.archived_at ? n.json({ error: "group_archived" }, 409) : null : n.json({ error: "group_not_found" }, 404);
1757
+ }
1758
+ async function D(e, t, n, r) {
1759
+ let i = await E(e, t, r);
1760
+ if (i) return {
1761
+ scope: null,
1762
+ response: i
1763
+ };
1764
+ if (!n) return {
1765
+ scope: null,
1766
+ response: r.json({ error: "scope_id_required" }, 400)
1767
+ };
1768
+ let a = (await e.listScopes({
1769
+ groupId: t,
1770
+ includeInactive: !0
1771
+ })).find((e) => e.scope_id === n) ?? null;
1772
+ return a ? {
1773
+ scope: a,
1774
+ response: null
1775
+ } : {
1776
+ scope: null,
1777
+ response: r.json({ error: "scope_not_found" }, 404)
1778
+ };
1779
+ }
1780
+ async function O(e, n, i) {
1781
+ let a = await Q(e, t, r, {
1782
+ method: i.req.method,
1783
+ url: i.req.url,
1784
+ groupId: n,
1785
+ body: new Uint8Array(),
1786
+ deviceId: i.req.header("X-Opencode-Device") ?? null,
1787
+ signature: i.req.header("X-Opencode-Signature") ?? null,
1788
+ timestamp: i.req.header("X-Opencode-Timestamp") ?? null,
1789
+ nonce: i.req.header("X-Opencode-Nonce") ?? null
1790
+ });
1791
+ return !a.ok || !a.enrollment ? {
1792
+ auth: a,
1793
+ response: p(i, i.req.path, !1) ?? i.json({ error: a.error }, $(a.error))
1794
+ } : {
1795
+ auth: a,
1796
+ response: p(i, String(a.enrollment.device_id), !0)
1797
+ };
1798
+ }
1799
+ function k(e, t) {
1800
+ return e.status === "active" && e.membership_epoch >= t.membership_epoch;
1801
+ }
1802
+ async function A(e, t, n) {
1803
+ return (await e.listScopeMemberships(t.scope_id, !1)).some((e) => e.device_id === n && k(e, t));
1804
+ }
1805
+ return d.post("/v1/presence", async (e) => {
1806
+ let i = await m(e);
1807
+ if (i == null) return e.json({ error: "body_too_large" }, 413);
1808
+ let a = h(i);
1809
+ if (!a) return e.json({ error: "invalid_json" }, 400);
1810
+ let o = String(a.group_id ?? "").trim();
1811
+ if (!o) return e.json({ error: "group_id_required" }, 400);
1812
+ let s = n();
1813
+ try {
1814
+ let n = await Q(s, t, r, {
1815
+ method: e.req.method,
1816
+ url: e.req.url,
1817
+ groupId: o,
1818
+ body: i,
1819
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1820
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1821
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1822
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1823
+ });
1824
+ if (!n.ok || !n.enrollment) return p(e, e.req.path, !1) || e.json({ error: n.error }, $(n.error));
1825
+ let c = p(e, String(n.enrollment.device_id), !0);
1826
+ if (c) return c;
1827
+ if (a.fingerprint && String(a.fingerprint) !== String(n.enrollment.fingerprint)) return e.json({ error: "fingerprint_mismatch" }, 401);
1828
+ let l = a.addresses ?? [];
1829
+ if (!Array.isArray(l) || !l.every((e) => typeof e == "string")) return e.json({ error: "addresses_must_be_list_of_strings" }, 400);
1830
+ let u;
1831
+ try {
1832
+ 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);
1833
+ } catch {
1834
+ return e.json({ error: "ttl_s_must_be_int" }, 400);
1835
+ }
1836
+ let d = await s.upsertPresence({
1837
+ groupId: o,
1838
+ deviceId: String(n.enrollment.device_id),
1839
+ addresses: l,
1840
+ ttlS: u,
1841
+ capabilities: typeof a.capabilities == "object" && a.capabilities !== null && !Array.isArray(a.capabilities) ? a.capabilities : void 0
1842
+ });
1843
+ return e.json({
1844
+ ok: !0,
1845
+ ...d
1846
+ });
1847
+ } finally {
1848
+ await s.close();
1849
+ }
1850
+ }), d.get("/v1/peers", async (e) => {
1851
+ let i = (e.req.query("group_id") ?? "").trim();
1852
+ if (!i) return e.json({ error: "group_id_required" }, 400);
1853
+ let a = n();
1854
+ try {
1855
+ let n = await Q(a, t, r, {
1856
+ method: e.req.method,
1857
+ url: e.req.url,
1858
+ groupId: i,
1859
+ body: new Uint8Array(),
1860
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1861
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1862
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1863
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1864
+ });
1865
+ if (!n.ok || !n.enrollment) return p(e, e.req.path, !1) || e.json({ error: n.error }, $(n.error));
1866
+ let o = p(e, String(n.enrollment.device_id), !0);
1867
+ if (o) return o;
1868
+ let s = await a.listGroupPeers(i, String(n.enrollment.device_id));
1869
+ return e.json({ items: s });
1870
+ } finally {
1871
+ await a.close();
1872
+ }
1873
+ }), d.get("/v1/scopes", async (e) => {
1874
+ let t = (e.req.query("group_id") ?? "").trim();
1875
+ if (!t) return e.json({ error: "group_id_required" }, 400);
1876
+ let r = n();
1877
+ try {
1878
+ let { auth: n, response: i } = await O(r, t, e);
1879
+ if (i) return i;
1880
+ if (!n.enrollment) return e.json({ error: "unknown_device" }, 401);
1881
+ let a = await r.listScopes({
1882
+ groupId: t,
1883
+ includeInactive: !1
1884
+ }), o = [];
1885
+ for (let e of a) e.status === "active" && await A(r, e, String(n.enrollment.device_id)) && o.push(e);
1886
+ return e.json({ items: o });
1887
+ } finally {
1888
+ await r.close();
1889
+ }
1890
+ }), d.get("/v1/scopes/:scope_id/members", async (e) => {
1891
+ let t = (e.req.query("group_id") ?? "").trim(), r = String(e.req.param("scope_id") ?? "").trim();
1892
+ if (!t) return e.json({ error: "group_id_required" }, 400);
1893
+ if (!r) return e.json({ error: "scope_id_required" }, 400);
1894
+ let i = n();
1895
+ try {
1896
+ let { auth: n, response: a } = await O(i, t, e);
1897
+ if (a) return a;
1898
+ if (!n.enrollment) return e.json({ error: "unknown_device" }, 401);
1899
+ let o = (await i.listScopes({
1900
+ groupId: t,
1901
+ includeInactive: !1
1902
+ })).find((e) => e.scope_id === r) ?? null;
1903
+ if (o?.status !== "active") return e.json({ error: "scope_not_found" }, 404);
1904
+ let s = await i.listScopeMemberships(r, !1);
1905
+ return s.some((e) => e.device_id === String(n.enrollment?.device_id) && k(e, o)) ? e.json({ items: s.filter((e) => k(e, o)) }) : e.json({ error: "scope_not_authorized" }, 403);
1906
+ } finally {
1907
+ await i.close();
1908
+ }
1909
+ }), d.get("/v1/reciprocal-approvals", async (e) => {
1910
+ let i = (e.req.query("group_id") ?? "").trim(), a = (e.req.query("direction") ?? "incoming").trim(), o = (e.req.query("status") ?? "pending").trim() || "pending";
1911
+ if (!i) return e.json({ error: "group_id_required" }, 400);
1912
+ if (!["incoming", "outgoing"].includes(a)) return e.json({ error: "direction_must_be_incoming_or_outgoing" }, 400);
1913
+ let s = n();
1914
+ try {
1915
+ let n = await Q(s, t, r, {
1916
+ method: e.req.method,
1917
+ url: e.req.url,
1918
+ groupId: i,
1919
+ body: new Uint8Array(),
1920
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1921
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1922
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1923
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1924
+ });
1925
+ if (!n.ok || !n.enrollment) return p(e, e.req.path, !1) ?? e.json({ error: n.error }, $(n.error));
1926
+ let c = p(e, String(n.enrollment.device_id), !0);
1927
+ if (c) return c;
1928
+ let l = await s.listReciprocalApprovals({
1929
+ groupId: i,
1930
+ deviceId: String(n.enrollment.device_id),
1931
+ direction: a,
1932
+ status: o
1933
+ });
1934
+ return e.json({ items: l });
1935
+ } finally {
1936
+ await s.close();
1937
+ }
1938
+ }), d.post("/v1/reciprocal-approvals", async (e) => {
1939
+ let i = await m(e);
1940
+ if (i == null) return e.json({ error: "body_too_large" }, 413);
1941
+ let a = h(i);
1942
+ if (!a) return e.json({ error: "invalid_json" }, 400);
1943
+ let o = String(a.group_id ?? "").trim(), s = String(a.requested_device_id ?? "").trim();
1944
+ if (!o || !s) return e.json({ error: "group_id_and_requested_device_id_required" }, 400);
1945
+ let c = n();
1946
+ try {
1947
+ let n = await Q(c, t, r, {
1948
+ method: e.req.method,
1949
+ url: e.req.url,
1950
+ groupId: o,
1951
+ body: i,
1952
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1953
+ signature: e.req.header("X-Opencode-Signature") ?? null,
1954
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
1955
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
1956
+ });
1957
+ if (!n.ok || !n.enrollment) return p(e, e.req.path, !1) ?? e.json({ error: n.error }, $(n.error));
1958
+ let a = p(e, String(n.enrollment.device_id), !0);
1959
+ if (a) return a;
1960
+ if (s === String(n.enrollment.device_id)) return e.json({ error: "requested_device_must_differ" }, 400);
1961
+ if (!await c.getEnrollment(o, s)) return e.json({ error: "requested_device_not_found" }, 404);
1962
+ let l = await c.createReciprocalApproval({
1963
+ groupId: o,
1964
+ requestingDeviceId: String(n.enrollment.device_id),
1965
+ requestedDeviceId: s
1966
+ });
1967
+ return e.json({
1968
+ ok: !0,
1969
+ request: l
1970
+ });
1971
+ } finally {
1972
+ await c.close();
1973
+ }
1974
+ }), d.post("/v1/invites/add-device", async (e) => {
1975
+ let i = await m(e);
1976
+ if (i == null) return e.json({ error: "body_too_large" }, 413);
1977
+ let a = h(i);
1978
+ if (!a) return e.json({ error: "invalid_json" }, 400);
1979
+ let o = new Set([
1980
+ "group_id",
1981
+ "expires_at",
1982
+ "reviewed_preview_digest",
1983
+ "reviewed_intent"
1984
+ ]);
1985
+ if (Object.keys(a).some((e) => !o.has(e))) return e.json({ error: "unexpected_add_device_invite_fields" }, 400);
1986
+ let s = String(a.group_id ?? "").trim(), c = String(a.expires_at ?? "").trim(), l = String(a.reviewed_preview_digest ?? "").trim();
1987
+ if (!s || !c) return e.json({ error: "group_id_and_expires_at_required" }, 400);
1988
+ if (Number.isNaN(new Date(c).getTime())) return e.json({ error: "invalid_expires_at" }, 400);
1989
+ if (!/^[a-f0-9]{64}$/u.test(l)) return e.json({ error: "reviewed_preview_digest_invalid" }, 400);
1990
+ if (a.reviewed_intent == null) return e.json({ error: "recipient_invite_review_unavailable" }, 400);
1991
+ let u = n();
1992
+ try {
1993
+ let n = await Q(u, t, r, {
1994
+ method: e.req.method,
1995
+ url: e.req.url,
1996
+ groupId: s,
1997
+ body: i,
1998
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
1999
+ signature: e.req.header("X-Opencode-Signature") ?? null,
2000
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
2001
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
2002
+ });
2003
+ if (!n.ok || !n.enrollment) return p(e, e.req.path, !1) ?? e.json({ error: n.error }, $(n.error));
2004
+ let o = p(e, String(n.enrollment.device_id), !0);
2005
+ if (o) return o;
2006
+ let d = n.enrollment.identity_id;
2007
+ if (!d || d !== d.trim() || d.length > 256 || /[\p{Cc}\p{Cf}]/u.test(d)) return e.json({ error: "identity_binding_required" }, 403);
2008
+ let f;
2009
+ try {
2010
+ f = await F(a.reviewed_intent, {
2011
+ target: {
2012
+ kind: "add_device",
2013
+ targetIdentityId: d
2014
+ },
2015
+ digest: l
2016
+ });
2017
+ } catch (t) {
2018
+ return t instanceof x && t.code === "recipient_invite_intent_mismatch" ? e.json({ error: t.code }, 409) : e.json({ error: "recipient_invite_review_unavailable" }, 400);
2019
+ }
2020
+ let m = await u.createInvite({
2021
+ groupId: s,
2022
+ policy: "auto_admit",
2023
+ expiresAt: c,
2024
+ createdBy: d,
2025
+ inviterDeviceId: String(n.enrollment.device_id),
2026
+ inviteKind: "add_device",
2027
+ targetIdentityId: d,
2028
+ reviewedPreviewDigest: l,
2029
+ reviewedIntent: f
2030
+ }), h = {
2031
+ v: 1,
2032
+ kind: "add_device",
2033
+ coordinator_url: new URL(e.req.url).origin,
2034
+ group_id: s,
2035
+ policy: m.policy,
2036
+ token: String(m.token ?? ""),
2037
+ expires_at: m.expires_at,
2038
+ team_name: m.team_name_snapshot ?? null,
2039
+ target_identity_id: m.target_identity_id ?? void 0,
2040
+ inviter_device_id: m.inviter_device_id ?? void 0,
2041
+ reviewed_preview_digest: m.reviewed_preview_digest ?? void 0
2042
+ }, g = W(h), { token: _, ...v } = m;
2043
+ return e.json({
2044
+ ok: !0,
2045
+ invite: v,
2046
+ payload: h,
2047
+ encoded: g,
2048
+ link: G(g)
2049
+ });
2050
+ } finally {
2051
+ await u.close();
2052
+ }
2053
+ }), d.post("/v1/admin/devices", async (e) => {
2054
+ let r = Z(e.req.header(X), t);
2055
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2056
+ let i = p(e, "admin", !0);
2057
+ if (i) return i;
2058
+ let a = await m(e);
2059
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2060
+ let o = h(a);
2061
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2062
+ 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;
2063
+ if (!s || !c || !l || !u) return e.json({ error: "group_id_device_id_fingerprint_public_key_required" }, 400);
2064
+ if (le(u) !== l) return e.json({ error: "fingerprint_mismatch" }, 400);
2065
+ let f = n();
2066
+ try {
2067
+ await f.createGroup(s), await f.enrollDevice(s, {
2068
+ deviceId: c,
2069
+ fingerprint: l,
2070
+ publicKey: u,
2071
+ displayName: d
2072
+ });
2073
+ } finally {
2074
+ await f.close();
2075
+ }
2076
+ return e.json({ ok: !0 });
2077
+ }), d.get("/v1/admin/groups", async (e) => {
2078
+ let r = Z(e.req.header(X), t);
2079
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2080
+ let i = p(e, "admin", !0);
2081
+ if (i) return i;
2082
+ let a = [
2083
+ "1",
2084
+ "true",
2085
+ "yes"
2086
+ ].includes((e.req.query("include_archived") ?? "0").trim().toLowerCase()), o = n();
2087
+ try {
2088
+ return e.json({ items: await o.listGroups(a) });
2089
+ } finally {
2090
+ await o.close();
2091
+ }
2092
+ }), d.post("/v1/admin/groups", async (e) => {
2093
+ let r = Z(e.req.header(X), t);
2094
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2095
+ let i = p(e, "admin", !0);
2096
+ if (i) return i;
2097
+ let a = await m(e);
2098
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2099
+ let o = h(a);
2100
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2101
+ let s = String(o.group_id ?? "").trim(), c = String(o.display_name ?? "").trim() || null;
2102
+ if (!s) return e.json({ error: "group_id_required" }, 400);
2103
+ let l = n();
2104
+ try {
2105
+ return await l.createGroup(s, c), e.json({
2106
+ ok: !0,
2107
+ group: await l.getGroup(s)
2108
+ });
2109
+ } finally {
2110
+ await l.close();
2111
+ }
2112
+ }), d.post("/v1/admin/groups/rename", async (e) => {
2113
+ let r = Z(e.req.header(X), t);
2114
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2115
+ let i = p(e, "admin", !0);
2116
+ if (i) return i;
2117
+ let a = await m(e);
2118
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2119
+ let o = h(a);
2120
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2121
+ let s = String(o.group_id ?? "").trim(), c = String(o.display_name ?? "").trim();
2122
+ if (!s || !c) return e.json({ error: "group_id_and_display_name_required" }, 400);
2123
+ let l = n();
2124
+ try {
2125
+ return await l.renameGroup(s, c) ? e.json({
2126
+ ok: !0,
2127
+ group: await l.getGroup(s)
2128
+ }) : e.json({ error: "group_not_found" }, 404);
2129
+ } finally {
2130
+ await l.close();
2131
+ }
2132
+ }), d.post("/v1/admin/groups/archive", async (e) => {
2133
+ let r = Z(e.req.header(X), t);
2134
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2135
+ let i = p(e, "admin", !0);
2136
+ if (i) return i;
2137
+ let a = await m(e);
2138
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2139
+ let o = h(a);
2140
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2141
+ let s = String(o.group_id ?? "").trim();
2142
+ if (!s) return e.json({ error: "group_id_required" }, 400);
2143
+ let c = n();
2144
+ try {
2145
+ return await c.archiveGroup(s, t.now()) ? e.json({
2146
+ ok: !0,
2147
+ group: await c.getGroup(s)
2148
+ }) : e.json({ error: "group_not_found_or_already_archived" }, 404);
2149
+ } finally {
2150
+ await c.close();
2151
+ }
2152
+ }), d.post("/v1/admin/groups/unarchive", async (e) => {
2153
+ let r = Z(e.req.header(X), t);
2154
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2155
+ let i = p(e, "admin", !0);
2156
+ if (i) return i;
2157
+ let a = await m(e);
2158
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2159
+ let o = h(a);
2160
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2161
+ let s = String(o.group_id ?? "").trim();
2162
+ if (!s) return e.json({ error: "group_id_required" }, 400);
2163
+ let c = n();
2164
+ try {
2165
+ return await c.unarchiveGroup(s) ? e.json({
2166
+ ok: !0,
2167
+ group: await c.getGroup(s)
2168
+ }) : e.json({ error: "group_not_found_or_not_archived" }, 404);
2169
+ } finally {
2170
+ await c.close();
2171
+ }
2172
+ }), d.get("/v1/admin/groups/:group_id/scopes", async (e) => {
2173
+ let r = Z(e.req.header(X), t);
2174
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2175
+ let i = p(e, "admin", !0);
2176
+ if (i) return i;
2177
+ let a = String(e.req.param("group_id") ?? "").trim(), o = n();
2178
+ try {
2179
+ let t = await E(o, a, e);
2180
+ if (t) return t;
2181
+ let n = S(e.req.query("include_inactive"));
2182
+ return e.json({ items: await o.listScopes({
2183
+ groupId: a,
2184
+ includeInactive: n
2185
+ }) });
2186
+ } finally {
2187
+ await o.close();
2188
+ }
2189
+ }), d.post("/v1/admin/groups/:group_id/scopes", async (e) => {
2190
+ let r = Z(e.req.header(X), t);
2191
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2192
+ let i = p(e, "admin", !0);
2193
+ if (i) return i;
2194
+ let a = await m(e);
2195
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2196
+ let o = h(a);
2197
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2198
+ let s = String(e.req.param("group_id") ?? "").trim(), c = _(o, "scope_id"), l = _(o, "label"), u = b(o, "membership_epoch");
2199
+ if (!c || !l) return e.json({ error: "scope_id_and_label_required" }, 400);
2200
+ if (Number.isNaN(u)) return e.json({ error: "membership_epoch_must_be_number" }, 400);
2201
+ let d = n();
2202
+ try {
2203
+ let t = await E(d, s, e);
2204
+ if (t) return t;
2205
+ let n = await d.createScope({
2206
+ scopeId: c,
2207
+ label: l,
2208
+ kind: _(o, "kind"),
2209
+ authorityType: _(o, "authority_type"),
2210
+ coordinatorId: _(o, "coordinator_id"),
2211
+ groupId: s,
2212
+ manifestIssuerDeviceId: _(o, "manifest_issuer_device_id"),
2213
+ membershipEpoch: u,
2214
+ manifestHash: _(o, "manifest_hash"),
2215
+ status: _(o, "status")
2216
+ });
2217
+ return e.json({
2218
+ ok: !0,
2219
+ scope: n
2220
+ }, 201);
2221
+ } catch (t) {
2222
+ return e.json({ error: t instanceof Error ? t.message : String(t) }, 400);
2223
+ } finally {
2224
+ await d.close();
2225
+ }
2226
+ }), d.patch("/v1/admin/groups/:group_id/scopes/:scope_id", async (e) => {
2227
+ let r = Z(e.req.header(X), t);
2228
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2229
+ let i = p(e, "admin", !0);
2230
+ if (i) return i;
2231
+ let a = await m(e);
2232
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2233
+ let o = h(a);
2234
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2235
+ let s = String(e.req.param("group_id") ?? "").trim(), c = String(e.req.param("scope_id") ?? "").trim(), l = b(o, "membership_epoch");
2236
+ if (!c) return e.json({ error: "scope_id_required" }, 400);
2237
+ if (Number.isNaN(l)) return e.json({ error: "membership_epoch_must_be_number" }, 400);
2238
+ let u = n();
2239
+ try {
2240
+ let t = await D(u, s, c, e);
2241
+ if (t.response) return t.response;
2242
+ let n = await u.updateScope({
2243
+ scopeId: c,
2244
+ label: o.label === void 0 ? void 0 : _(o, "label"),
2245
+ kind: o.kind === void 0 ? void 0 : _(o, "kind"),
2246
+ authorityType: o.authority_type === void 0 ? void 0 : _(o, "authority_type"),
2247
+ coordinatorId: o.coordinator_id === void 0 ? void 0 : _(o, "coordinator_id"),
2248
+ groupId: s,
2249
+ manifestIssuerDeviceId: o.manifest_issuer_device_id === void 0 ? void 0 : _(o, "manifest_issuer_device_id"),
2250
+ membershipEpoch: l,
2251
+ manifestHash: o.manifest_hash === void 0 ? void 0 : _(o, "manifest_hash"),
2252
+ status: o.status === void 0 ? void 0 : _(o, "status")
2253
+ });
2254
+ return n ? e.json({
2255
+ ok: !0,
2256
+ scope: n
2257
+ }) : e.json({ error: "scope_not_found" }, 404);
2258
+ } catch (t) {
2259
+ return e.json({ error: t instanceof Error ? t.message : String(t) }, 400);
2260
+ } finally {
2261
+ await u.close();
2262
+ }
2263
+ }), d.get("/v1/admin/groups/:group_id/scopes/:scope_id/members", async (e) => {
2264
+ let r = Z(e.req.header(X), t);
2265
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2266
+ let i = p(e, "admin", !0);
2267
+ if (i) return i;
2268
+ let a = String(e.req.param("group_id") ?? "").trim(), o = String(e.req.param("scope_id") ?? "").trim(), s = n();
2269
+ try {
2270
+ let t = await D(s, a, o, e);
2271
+ return t.response ? t.response : e.json({ items: await s.listScopeMemberships(o, S(e.req.query("include_revoked"))) });
2272
+ } finally {
2273
+ await s.close();
2274
+ }
2275
+ }), d.post("/v1/admin/groups/:group_id/scopes/:scope_id/members", async (e) => {
2276
+ let r = Z(e.req.header(X), t);
2277
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2278
+ let a = p(e, "admin", !0);
2279
+ if (a) return a;
2280
+ let o = await m(e);
2281
+ if (o == null) return e.json({ error: "body_too_large" }, 413);
2282
+ let s = h(o);
2283
+ if (!s) return e.json({ error: "invalid_json" }, 400);
2284
+ let c = String(e.req.param("group_id") ?? "").trim(), l = String(e.req.param("scope_id") ?? "").trim(), u = _(s, "effect_id"), d = _(s, "device_id"), f = b(s, "membership_epoch");
2285
+ if (!u) return e.json({ error: "effect_id_required" }, 400);
2286
+ if (!d) return e.json({ error: "device_id_required" }, 400);
2287
+ if (Number.isNaN(f)) return e.json({ error: "membership_epoch_must_be_number" }, 400);
2288
+ let g = n();
2289
+ try {
2290
+ let t = await D(g, c, l, e);
2291
+ if (t.response) return t.response;
2292
+ let n = await g.grantScopeMembership({
2293
+ effectId: u,
2294
+ scopeId: l,
2295
+ deviceId: d,
2296
+ role: _(s, "role"),
2297
+ membershipEpoch: f,
2298
+ coordinatorId: _(s, "coordinator_id"),
2299
+ groupId: c,
2300
+ manifestIssuerDeviceId: _(s, "manifest_issuer_device_id"),
2301
+ manifestHash: _(s, "manifest_hash"),
2302
+ signedManifestJson: _(s, "signed_manifest_json"),
2303
+ actorType: "admin",
2304
+ actorId: v(e.req.header(Qt))
2305
+ });
2306
+ return e.json({
2307
+ ok: !0,
2308
+ membership: n
2309
+ }, 201);
2310
+ } catch (t) {
2311
+ let n = t instanceof Error ? t.message : String(t);
2312
+ if (t instanceof i && (t.code === "scope_not_found" || t.code === "scope_group_mismatch")) return e.json({ error: "scope_not_found" }, 404);
2313
+ if (t instanceof i && t.code === "device_not_enrolled") return e.json({ error: "device_not_enrolled_for_scope_group" }, 404);
2314
+ let r = t instanceof i && t.code === "scope_inactive";
2315
+ return e.json({ error: r ? "scope_not_active" : n }, n === "scope_membership_effect_conflict" || r ? 409 : 400);
2316
+ } finally {
2317
+ await g.close();
2318
+ }
2319
+ }), d.post("/v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke", async (e) => {
2320
+ let r = Z(e.req.header(X), t);
2321
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2322
+ let a = p(e, "admin", !0);
2323
+ if (a) return a;
2324
+ let o = await m(e);
2325
+ if (o == null) return e.json({ error: "body_too_large" }, 413);
2326
+ let s = o.byteLength > 0 ? h(o) : {};
2327
+ if (!s) return e.json({ error: "invalid_json" }, 400);
2328
+ let c = String(e.req.param("group_id") ?? "").trim(), l = String(e.req.param("scope_id") ?? "").trim(), u = String(e.req.param("device_id") ?? "").trim(), d = _(s, "effect_id"), f = b(s, "membership_epoch");
2329
+ if (!d) return e.json({ error: "effect_id_required" }, 400);
2330
+ if (!u) return e.json({ error: "device_id_required" }, 400);
2331
+ if (Number.isNaN(f)) return e.json({ error: "membership_epoch_must_be_number" }, 400);
2332
+ let g = n();
2333
+ try {
2334
+ let t = await D(g, c, l, e);
2335
+ if (t.response) return t.response;
2336
+ if (!await g.revokeScopeMembership({
2337
+ effectId: d,
2338
+ scopeId: l,
2339
+ deviceId: u,
2340
+ groupId: c,
2341
+ membershipEpoch: f,
2342
+ manifestHash: _(s, "manifest_hash"),
2343
+ signedManifestJson: _(s, "signed_manifest_json"),
2344
+ actorType: "admin",
2345
+ actorId: v(e.req.header(Qt))
2346
+ })) return e.json({ error: "membership_not_found" }, 404);
2347
+ let n;
2348
+ try {
2349
+ n = (await g.listScopeMemberships(l, !0)).find((e) => e.device_id === u);
2350
+ } catch {
2351
+ n = void 0;
2352
+ }
2353
+ return e.json({
2354
+ ok: !0,
2355
+ scope_id: l,
2356
+ device_id: u,
2357
+ revocation: Xt({
2358
+ scopeId: l,
2359
+ deviceId: u,
2360
+ membershipEpoch: n?.membership_epoch ?? f
2361
+ })
2362
+ });
2363
+ } catch (t) {
2364
+ let n = t instanceof Error ? t.message : String(t);
2365
+ return t instanceof i && t.code === "scope_group_mismatch" ? e.json({ error: "scope_not_found" }, 404) : e.json({ error: n }, n === "scope_membership_effect_conflict" ? 409 : 400);
2366
+ } finally {
2367
+ await g.close();
2368
+ }
2369
+ }), d.get("/v1/admin/devices", async (e) => {
2370
+ let r = Z(e.req.header(X), t);
2371
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2372
+ let i = p(e, "admin", !0);
2373
+ if (i) return i;
2374
+ let a = (e.req.query("group_id") ?? "").trim();
2375
+ if (!a) return e.json({ error: "group_id_required" }, 400);
2376
+ let o = [
2377
+ "1",
2378
+ "true",
2379
+ "yes"
2380
+ ].includes((e.req.query("include_disabled") ?? "0").trim().toLowerCase()), s = n();
2381
+ try {
2382
+ return e.json({ items: await s.listEnrolledDevices(a, o) });
2383
+ } finally {
2384
+ await s.close();
2385
+ }
2386
+ }), d.post("/v1/admin/devices/rename", async (e) => {
2387
+ let r = Z(e.req.header(X), t);
2388
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2389
+ let i = p(e, "admin", !0);
2390
+ if (i) return i;
2391
+ let a = await m(e);
2392
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2393
+ let o = h(a);
2394
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2395
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim(), l = String(o.display_name ?? "").trim();
2396
+ if (!s || !c) return e.json({ error: "group_id_and_device_id_required" }, 400);
2397
+ if (!l) return e.json({ error: "display_name_required" }, 400);
2398
+ let u = n();
2399
+ try {
2400
+ if (!await u.renameDevice(s, c, l)) return e.json({ error: "device_not_found" }, 404);
2401
+ let t = await u.getEnrollment(s, c);
2402
+ return e.json({
2403
+ ok: !0,
2404
+ device: t
2405
+ });
2406
+ } finally {
2407
+ await u.close();
2408
+ }
2409
+ }), d.post("/v1/admin/devices/disable", async (e) => {
2410
+ let r = Z(e.req.header(X), t);
2411
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2412
+ let i = p(e, "admin", !0);
2413
+ if (i) return i;
2414
+ let a = await m(e);
2415
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2416
+ let o = h(a);
2417
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2418
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim();
2419
+ if (!s || !c) return e.json({ error: "group_id_and_device_id_required" }, 400);
2420
+ let l = n();
2421
+ try {
2422
+ return await l.setDeviceEnabled(s, c, !1) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
2423
+ } finally {
2424
+ await l.close();
2425
+ }
2426
+ }), d.post("/v1/admin/devices/enable", async (e) => {
2427
+ let r = Z(e.req.header(X), t);
2428
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2429
+ let i = p(e, "admin", !0);
2430
+ if (i) return i;
2431
+ let a = await m(e);
2432
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2433
+ let o = h(a);
2434
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2435
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim();
2436
+ if (!s || !c) return e.json({ error: "group_id_and_device_id_required" }, 400);
2437
+ let l = n();
2438
+ try {
2439
+ return await l.setDeviceEnabled(s, c, !0) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
2440
+ } finally {
2441
+ await l.close();
2442
+ }
2443
+ }), d.post("/v1/admin/devices/remove", async (e) => {
2444
+ let r = Z(e.req.header(X), t);
2445
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2446
+ let i = p(e, "admin", !0);
2447
+ if (i) return i;
2448
+ let a = await m(e);
2449
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2450
+ let o = h(a);
2451
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2452
+ let s = String(o.group_id ?? "").trim(), c = String(o.device_id ?? "").trim();
2453
+ if (!s || !c) return e.json({ error: "group_id_and_device_id_required" }, 400);
2454
+ let l = n();
2455
+ try {
2456
+ return await l.removeDevice(s, c) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
2457
+ } finally {
2458
+ await l.close();
2459
+ }
2460
+ }), d.post("/v1/admin/invites", async (e) => {
2461
+ let r = Z(e.req.header(X), t);
2462
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2463
+ let i = p(e, "admin", !0);
2464
+ if (i) return i;
2465
+ let a = await m(e);
2466
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2467
+ let o = h(a);
2468
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2469
+ 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, d = String(o.operation_id ?? "").trim() || null, f = String(o.reviewed_project_set_digest ?? "").trim() || null, _ = String(o.inviter_actor_id ?? "").trim() || null, v = String(o.inviter_display_name ?? "").trim() || null, b = String(o.inviter_device_id ?? "").trim() || null, S = String(o.pending_person_id ?? "").trim() || null, C = String(o.invite_kind ?? o.kind ?? "").trim(), w = String(o.policy_team_id ?? "").trim() || null, T = String(o.target_identity_id ?? "").trim() || null, E = String(o.reviewed_preview_digest ?? "").trim() || null, D, O = null, k = null;
2470
+ if (!s || !["auto_admit", "approval_required"].includes(c) || !l) return e.json({ error: "group_id_policy_and_expires_at_required" }, 400);
2471
+ if (Object.hasOwn(o, "assigned_identity_id")) return e.json({ error: "assigned_identity_id_forbidden" }, 400);
2472
+ if (Number.isNaN(new Date(l).getTime())) return e.json({ error: "invalid_expires_at" }, 400);
2473
+ if (!!d != !!f) return e.json({ error: "operation_intent_reference_incomplete" }, 400);
2474
+ let A = C || (d ? "project_share" : "legacy_enrollment");
2475
+ if (![
2476
+ "legacy_enrollment",
2477
+ "project_share",
2478
+ "team_member",
2479
+ "add_device"
2480
+ ].includes(A)) return e.json({ error: "invite_kind_invalid" }, 400);
2481
+ if (A === "project_share" ? !d : d) return e.json({ error: "invite_kind_intent_mismatch" }, 400);
2482
+ if (E && !/^[a-f0-9]{64}$/u.test(E)) return e.json({ error: "reviewed_preview_digest_invalid" }, 400);
2483
+ if (A === "team_member" && (!w || !E || T) || A === "add_device" && (!T || !E || w) || !["team_member", "add_device"].includes(A) && (w || T || E)) return e.json({ error: "recipient_invite_metadata_invalid" }, 400);
2484
+ if ([w, T].filter((e) => !!e).some((e) => e.length > 256 || /[\p{Cc}\p{Cf}]/u.test(e))) return e.json({ error: "recipient_invite_identifier_invalid" }, 400);
2485
+ if (A === "team_member" || A === "add_device") {
2486
+ if (o.reviewed_intent == null) return e.json({ error: "recipient_invite_review_unavailable" }, 400);
2487
+ try {
2488
+ D = await F(o.reviewed_intent, {
2489
+ target: A === "team_member" ? {
2490
+ kind: "team_member",
2491
+ policyTeamId: String(w)
2492
+ } : {
2493
+ kind: "add_device",
2494
+ targetIdentityId: String(T)
2495
+ },
2496
+ digest: String(E)
2497
+ });
2498
+ } catch (t) {
2499
+ return t instanceof x && t.code === "recipient_invite_intent_mismatch" ? e.json({ error: t.code }, 409) : e.json({ error: "recipient_invite_review_unavailable" }, 400);
2500
+ }
2501
+ } else if (o.reviewed_intent != null) return e.json({ error: "recipient_invite_metadata_invalid" }, 400);
2502
+ if (d && !/^share_[a-f0-9]{40}$/u.test(d) || f && !/^[a-f0-9]{64}$/u.test(f)) return e.json({ error: "operation_intent_reference_invalid" }, 400);
2503
+ if (d) {
2504
+ if (!_ || !v || !b || !S) return e.json({ error: "project_invite_identity_context_required" }, 400);
2505
+ if ([
2506
+ _,
2507
+ b,
2508
+ S
2509
+ ].some((e) => e.length > 256 || /[\p{Cc}\p{Cf}]/u.test(e))) return e.json({ error: "project_invite_identity_context_invalid" }, 400);
2510
+ try {
2511
+ if (g(v, "inviter_display_name"), O = y(o.project_summaries), !Array.isArray(o.project_intent) || o.project_intent.length !== O.length || (k = o.project_intent.map((e, t) => {
2512
+ let n;
2513
+ try {
2514
+ n = Ht([e])[0];
2515
+ } catch {
2516
+ throw Error("project_intent_invalid");
2517
+ }
2518
+ let r = O?.[t];
2519
+ if (!n || !r || n.display_name !== r.display_name || n.existing_memory_count !== r.existing_memory_count) throw Error("project_intent_invalid");
2520
+ return n;
2521
+ }), new Set(k.map((e) => e.canonical_identity)).size !== k.length)) throw Error("project_intent_invalid");
2522
+ } catch (t) {
2523
+ return e.json({ error: t instanceof Error ? t.message : "project_invite_invalid" }, 400);
2524
+ }
2525
+ }
2526
+ let j = n();
2527
+ try {
2528
+ let t = await j.getGroup(s);
2529
+ if (!t) return e.json({ error: "group_not_found" }, 404);
2530
+ if (t.archived_at) return e.json({ error: "group_archived" }, 409);
2531
+ let n = await j.createInvite({
2532
+ groupId: s,
2533
+ policy: c,
2534
+ expiresAt: l,
2535
+ createdBy: u,
2536
+ operationId: d,
2537
+ reviewedProjectSetDigest: f,
2538
+ inviterActorId: _,
2539
+ inviterDisplayName: v,
2540
+ inviterDeviceId: b,
2541
+ pendingPersonId: S,
2542
+ projectSummaries: O,
2543
+ projectIntent: k,
2544
+ inviteKind: A,
2545
+ policyTeamId: w,
2546
+ targetIdentityId: T,
2547
+ reviewedPreviewDigest: E,
2548
+ reviewedIntent: D
2549
+ }), r = {
2550
+ v: 1,
2551
+ kind: n.invite_kind === "team_member" || n.invite_kind === "add_device" ? n.invite_kind : "coordinator_team_invite",
2552
+ coordinator_url: String(o.coordinator_url ?? "").trim(),
2553
+ group_id: s,
2554
+ policy: n.policy,
2555
+ token: String(n.token ?? ""),
2556
+ expires_at: n.expires_at,
2557
+ team_name: n.team_name_snapshot ?? null,
2558
+ ...n.operation_id ? {
2559
+ operation_id: n.operation_id,
2560
+ inviter_name: n.inviter_display_name ?? null,
2561
+ project_summaries: O ?? []
2562
+ } : {},
2563
+ ...n.invite_kind === "team_member" ? {
2564
+ policy_team_id: n.policy_team_id ?? void 0,
2565
+ assigned_identity_id: n.assigned_identity_id ?? void 0,
2566
+ reviewed_preview_digest: n.reviewed_preview_digest ?? void 0
2567
+ } : {},
2568
+ ...n.invite_kind === "add_device" ? {
2569
+ target_identity_id: n.target_identity_id ?? void 0,
2570
+ inviter_device_id: n.inviter_device_id ?? void 0,
2571
+ reviewed_preview_digest: n.reviewed_preview_digest ?? void 0
2572
+ } : {}
2573
+ }, i = W(r), { token: a, ...p } = n;
2574
+ return e.json({
2575
+ ok: !0,
2576
+ invite: p,
2577
+ payload: r,
2578
+ encoded: i,
2579
+ link: G(i)
2580
+ });
2581
+ } catch (t) {
2582
+ if (t instanceof Error && t.message === "invite_operation_intent_conflict") return e.json({ error: "invite_operation_intent_conflict" }, 409);
2583
+ if (t instanceof Error && t.message === "invite_already_bound") return e.json({ error: "invite_already_bound" }, 409);
2584
+ throw t;
2585
+ } finally {
2586
+ await j.close();
2587
+ }
2588
+ }), d.post("/v1/invites/inspect", async (e) => {
2589
+ let r = await m(e);
2590
+ if (r == null) return e.json({ error: "body_too_large" }, 413);
2591
+ let i = h(r);
2592
+ if (!i) return e.json({ error: "invalid_json" }, 400);
2593
+ let a = String(i.token ?? "").trim();
2594
+ if (!a) return e.json({ error: "invite_invalid" }, 404);
2595
+ let o = n();
2596
+ try {
2597
+ let n = await o.getInviteByTokenForInspection(a);
2598
+ if (!n || n.revoked_at) return e.json({ error: "invite_invalid" }, 404);
2599
+ if (n.invite_kind === "team_member" || n.invite_kind === "add_device") try {
2600
+ let n = await o.inspectRecipientInvite({
2601
+ token: a,
2602
+ now: t.now()
2603
+ });
2604
+ return n ? e.json(n.kind === "team_member" ? {
2605
+ kind: n.kind,
2606
+ policy_team_id: n.policy_team_id,
2607
+ assigned_identity_id: n.assigned_identity_id,
2608
+ reviewed_preview_digest: n.reviewed_preview_digest,
2609
+ reviewed_intent: n.reviewed_intent,
2610
+ bound: n.bound
2611
+ } : {
2612
+ kind: n.kind,
2613
+ target_identity_id: n.target_identity_id,
2614
+ reviewed_preview_digest: n.reviewed_preview_digest,
2615
+ reviewed_intent: n.reviewed_intent,
2616
+ bound: n.bound
2617
+ }) : e.json({ error: "invite_invalid" }, 404);
2618
+ } catch (t) {
2619
+ let n = t instanceof Error ? t.message : "invite_invalid", r = n === "invite_expired" ? 410 : n === "invite_invalid" ? 404 : 409;
2620
+ return e.json({ error: n }, r);
2621
+ }
2622
+ let r = !!(n.operation_id || n.reviewed_project_set_digest);
2623
+ if (new Date(n.expires_at) <= new Date(t.now()) && (!r || !n.consumed_at)) return e.json({ error: "invite_expired" }, 410);
2624
+ if (!n.operation_id) return e.json({
2625
+ kind: "legacy_team_invite",
2626
+ team_name: n.team_name_snapshot
2627
+ });
2628
+ if (!n.project_intent_json || !n.project_summaries_json) return e.json({ error: "invite_invalid" }, 404);
2629
+ let i;
2630
+ try {
2631
+ i = T(n.project_summaries_json);
2632
+ } catch {
2633
+ return e.json({ error: "invite_invalid" }, 409);
2634
+ }
2635
+ return e.json({
2636
+ kind: "project_share_invite",
2637
+ operation_id: n.operation_id,
2638
+ inviter_name: n.inviter_display_name,
2639
+ team_name: n.team_name_snapshot,
2640
+ projects: i,
2641
+ bound: !!n.consumed_at
2642
+ });
2643
+ } finally {
2644
+ await o.close();
2645
+ }
2646
+ }), d.get("/v1/admin/invites", async (e) => {
2647
+ let r = Z(e.req.header(X), t);
2648
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2649
+ let i = p(e, "admin", !0);
2650
+ if (i) return i;
2651
+ let a = (e.req.query("group_id") ?? "").trim();
2652
+ if (!a) return e.json({ error: "group_id_required" }, 400);
2653
+ let o = n();
2654
+ try {
2655
+ let t = (await o.listInvites(a)).map(({ token: e, ...t }) => t);
2656
+ return e.json({ items: t });
2657
+ } finally {
2658
+ await o.close();
2659
+ }
2660
+ }), d.get("/v1/admin/project-invites/:operationId", async (e) => {
2661
+ let r = Z(e.req.header(X), t);
2662
+ if (!r.ok) return e.json({ error: r.error }, 401);
2663
+ let i = String(e.req.param("operationId") ?? "").trim(), a = String(e.req.query("group_id") ?? "").trim();
2664
+ if (!i || !a) return e.json({ error: "operation_id_and_group_id_required" }, 400);
2665
+ let o = n();
2666
+ try {
2667
+ let n = (await o.listInvites(a)).find((e) => e.operation_id === i);
2668
+ if (!n) return e.json({ error: "operation_not_found" }, 404);
2669
+ let r;
2670
+ try {
2671
+ r = C(n.project_intent_json);
2672
+ } catch {
2673
+ return e.json({ error: "operation_intent_invalid" }, 409);
2674
+ }
2675
+ let s = null;
2676
+ if (!n.consumed_at && !n.revoked_at && new Date(n.expires_at) > new Date(t.now()) && n.token && !n.token.startsWith("consumed:")) {
2677
+ let t = r.map((e) => ({
2678
+ display_name: String(e.display_name ?? ""),
2679
+ existing_memory_count: Number(e.existing_memory_count ?? 0)
2680
+ }));
2681
+ s = G(W({
2682
+ v: 1,
2683
+ kind: "coordinator_team_invite",
2684
+ coordinator_url: new URL(e.req.url).origin,
2685
+ group_id: n.group_id,
2686
+ policy: n.policy,
2687
+ token: n.token,
2688
+ expires_at: n.expires_at,
2689
+ team_name: n.team_name_snapshot,
2690
+ operation_id: i,
2691
+ inviter_name: n.inviter_display_name ?? null,
2692
+ project_summaries: t
2693
+ }));
2694
+ }
2695
+ return e.json({
2696
+ operation_id: n.operation_id,
2697
+ group_id: n.group_id,
2698
+ reviewed_project_set_digest: n.reviewed_project_set_digest,
2699
+ state: n.consumed_at ? "accepted" : "waiting_for_acceptance",
2700
+ pending_person_id: n.pending_person_id,
2701
+ recipient_actor_id: n.recipient_actor_id,
2702
+ recipient_display_name: n.recipient_display_name,
2703
+ recipient_device_id: n.bound_device_id,
2704
+ recipient_device_display_name: n.recipient_device_display_name,
2705
+ recipient_public_key: n.bound_public_key,
2706
+ recipient_fingerprint: n.bound_fingerprint,
2707
+ consumed_at: n.consumed_at,
2708
+ bootstrap_grant_id: n.bootstrap_grant_id,
2709
+ trust_state: n.trust_state,
2710
+ projects: r,
2711
+ invite_link: s
2712
+ });
2713
+ } finally {
2714
+ await o.close();
2715
+ }
2716
+ }), d.get("/v1/admin/bootstrap-grants/:grantId", async (e) => {
2717
+ let r = Z(e.req.header(X), t);
2718
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2719
+ let i = p(e, "admin", !0);
2720
+ if (i) return i;
2721
+ let a = String(e.req.param("grantId") ?? "").trim();
2722
+ if (!a) return e.json({ error: "grant_id_required" }, 400);
2723
+ let o = n();
2724
+ try {
2725
+ let t = await o.getBootstrapGrant(a);
2726
+ if (!t) return e.json({ error: "grant_not_found" }, 404);
2727
+ let n = await o.getEnrollment(t.group_id, t.worker_device_id);
2728
+ if (!n) return e.json({ error: "worker_enrollment_not_found" }, 404);
2729
+ let r = {
2730
+ grant: t,
2731
+ worker_enrollment: n
2732
+ };
2733
+ return e.json(r);
2734
+ } finally {
2735
+ await o.close();
2736
+ }
2737
+ }), d.get("/v1/bootstrap-grants/:grantId", async (e) => {
2738
+ let i = String(e.req.param("grantId") ?? "").trim(), a = String(e.req.query("group_id") ?? "").trim();
2739
+ if (!i || !a) return e.json({ error: "grant_id_and_group_id_required" }, 400);
2740
+ let o = n();
2741
+ try {
2742
+ let n = await Q(o, t, r, {
2743
+ method: e.req.method,
2744
+ url: e.req.url,
2745
+ groupId: a,
2746
+ body: new Uint8Array(),
2747
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
2748
+ signature: e.req.header("X-Opencode-Signature") ?? null,
2749
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
2750
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
2751
+ });
2752
+ if (!n.ok || !n.enrollment) return p(e, e.req.path, !1) ?? e.json({ error: n.error }, $(n.error));
2753
+ let s = p(e, String(n.enrollment.device_id), !0);
2754
+ if (s) return s;
2755
+ let c = await o.getBootstrapGrant(i);
2756
+ if (!c || c.group_id !== a || c.seed_device_id !== String(n.enrollment.device_id)) return e.json({ error: "grant_not_found" }, 404);
2757
+ let l = await o.getEnrollment(a, c.worker_device_id);
2758
+ return l ? e.json({
2759
+ grant: c,
2760
+ worker_enrollment: l
2761
+ }) : e.json({ error: "worker_enrollment_not_found" }, 404);
2762
+ } finally {
2763
+ await o.close();
2764
+ }
2765
+ }), d.get("/v1/admin/bootstrap-grants", async (e) => {
2766
+ let r = Z(e.req.header(X), t);
2767
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2768
+ let i = p(e, "admin", !0);
2769
+ if (i) return i;
2770
+ let a = (e.req.query("group_id") ?? "").trim();
2771
+ if (!a) return e.json({ error: "group_id_required" }, 400);
2772
+ let o = n();
2773
+ try {
2774
+ return e.json({ items: await o.listBootstrapGrants(a) });
2775
+ } finally {
2776
+ await o.close();
2777
+ }
2778
+ }), d.post("/v1/admin/bootstrap-grants/revoke", async (e) => {
2779
+ let r = Z(e.req.header(X), t);
2780
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2781
+ let i = p(e, "admin", !0);
2782
+ if (i) return i;
2783
+ let a = await m(e);
2784
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
2785
+ let o = h(a);
2786
+ if (!o) return e.json({ error: "invalid_json" }, 400);
2787
+ let s = String(o.grant_id ?? "").trim();
2788
+ if (!s) return e.json({ error: "grant_id_required" }, 400);
2789
+ let c = n();
2790
+ try {
2791
+ return await c.revokeBootstrapGrant(s, t.now()) ? e.json({
2792
+ ok: !0,
2793
+ grant_id: s
2794
+ }) : e.json({ error: "grant_not_found" }, 404);
2795
+ } finally {
2796
+ await c.close();
2797
+ }
2798
+ }), d.post("/v1/admin/join-requests/approve", async (e) => on(e, !0, {
2799
+ createStore: n,
2800
+ runtime: t,
2801
+ rateLimitedResponse: p
2802
+ })), d.post("/v1/admin/join-requests/deny", async (e) => on(e, !1, {
2803
+ createStore: n,
2804
+ runtime: t,
2805
+ rateLimitedResponse: p
2806
+ })), d.get("/v1/admin/join-requests", async (e) => {
2807
+ let r = Z(e.req.header(X), t);
2808
+ if (!r.ok) return p(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
2809
+ let i = p(e, "admin", !0);
2810
+ if (i) return i;
2811
+ let a = (e.req.query("group_id") ?? "").trim();
2812
+ if (!a) return e.json({ error: "group_id_required" }, 400);
2813
+ let o = n();
2814
+ try {
2815
+ return e.json({ items: await o.listJoinRequests(a) });
2816
+ } finally {
2817
+ await o.close();
2818
+ }
2819
+ }), d.post("/v1/join", async (e) => {
2820
+ let r = await m(e);
2821
+ if (r == null) return e.json({ error: "body_too_large" }, 413);
2822
+ let i = h(r);
2823
+ if (!i) return e.json({ error: "invalid_json" }, 400);
2824
+ 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, u = String(i.operation_id ?? "").trim(), d = String(i.recipient_actor_id ?? "").trim(), f = String(i.recipient_display_name ?? "").trim(), p = String(i.device_display_name ?? "").trim();
2825
+ if (!a || !o || !s || !c) return e.json({ error: "token_device_id_fingerprint_public_key_required" }, 400);
2826
+ if (le(c) !== s) return e.json({ error: "fingerprint_mismatch" }, 400);
2827
+ let _ = n();
2828
+ try {
2829
+ let n = await _.getInviteByTokenForInspection(a);
2830
+ if (!n) return e.json({ error: "invite_invalid" }, 404);
2831
+ let r = !!(n.operation_id || n.reviewed_project_set_digest), m = n.invite_kind === "team_member" || n.invite_kind === "add_device";
2832
+ if (n.revoked_at) return e.json({ error: r || m ? "invite_invalid" : "revoked_token" }, 400);
2833
+ if (!n.consumed_at && new Date(n.expires_at) <= new Date(t.now())) return e.json({ error: r || m ? "invite_expired" : "expired_token" }, 410);
2834
+ if (m) {
2835
+ let r = new Set([
2836
+ "token",
2837
+ "invite_kind",
2838
+ "kind",
2839
+ "identity_id",
2840
+ "device_id",
2841
+ "public_key",
2842
+ "fingerprint",
2843
+ "recipient_display_name",
2844
+ "device_display_name"
2845
+ ]);
2846
+ if (Object.keys(i).some((e) => !r.has(e))) return e.json({ error: "unexpected_recipient_invite_fields" }, 400);
2847
+ let l = String(i.invite_kind ?? i.kind ?? "").trim(), u = String(i.identity_id ?? "").trim();
2848
+ if (!u || l !== n.invite_kind) return e.json({ error: "recipient_invite_binding_required" }, 400);
2849
+ if (u.length > 256 || /[\p{Cc}\p{Cf}]/u.test(u)) return e.json({ error: "identity_id_invalid" }, 400);
2850
+ let d = null, f = null;
2851
+ try {
2852
+ if (i.recipient_display_name != null) {
2853
+ if (typeof i.recipient_display_name != "string") throw Error("recipient_display_name_invalid");
2854
+ d = g(i.recipient_display_name, "recipient_display_name");
2855
+ }
2856
+ if (i.device_display_name != null) {
2857
+ if (typeof i.device_display_name != "string") throw Error("device_display_name_invalid");
2858
+ f = g(i.device_display_name, "device_display_name");
2859
+ }
2860
+ } catch (t) {
2861
+ return e.json({ error: t instanceof Error ? t.message : "recipient_invite_identity_invalid" }, 400);
2862
+ }
2863
+ if (n.invite_kind === "add_device" && String(n.inviter_device_id ?? "").trim() === o) return e.json({ error: "add_device_invite_self_acceptance_forbidden" }, 409);
2864
+ try {
2865
+ let r = await _.consumeRecipientInvite({
2866
+ token: a,
2867
+ inviteKind: n.invite_kind,
2868
+ identityId: u,
2869
+ deviceId: o,
2870
+ publicKey: c,
2871
+ fingerprint: s,
2872
+ recipientDisplayName: d,
2873
+ deviceDisplayName: f,
2874
+ now: t.now()
2875
+ });
2876
+ return e.json({
2877
+ ok: !0,
2878
+ status: r.status,
2879
+ kind: r.invite.invite_kind,
2880
+ group_id: r.invite.group_id,
2881
+ identity_id: r.invite.recipient_actor_id,
2882
+ policy_team_id: r.invite.policy_team_id ?? null,
2883
+ target_identity_id: r.invite.target_identity_id ?? null,
2884
+ assigned_identity_id: r.invite.assigned_identity_id ?? null,
2885
+ bootstrap_grant_id: r.bootstrap_grant?.grant_id ?? null,
2886
+ inviter_device: r.bootstrap_grant ? await _.getEnrollment(r.invite.group_id, r.bootstrap_grant.seed_device_id) : null,
2887
+ reviewed_preview_digest: r.invite.reviewed_preview_digest,
2888
+ reviewed_intent: r.reviewed_intent
2889
+ });
2890
+ } catch (t) {
2891
+ let n = t instanceof Error ? t.message : "invite_invalid", r = n === "invite_expired" ? 410 : n === "invite_invalid" ? 404 : 409;
2892
+ return e.json({ error: n }, r);
2893
+ }
2894
+ }
2895
+ if (n.operation_id || n.reviewed_project_set_digest) {
2896
+ let r = new Set([
2897
+ "token",
2898
+ "operation_id",
2899
+ "device_id",
2900
+ "public_key",
2901
+ "fingerprint",
2902
+ "display_name",
2903
+ "recipient_actor_id",
2904
+ "recipient_display_name",
2905
+ "device_display_name"
2906
+ ]);
2907
+ if (Object.keys(i).some((e) => !r.has(e))) return e.json({ error: "unexpected_project_invite_fields" }, 400);
2908
+ if (!u || !d || !f || !p) return e.json({ error: "project_invite_identity_required" }, 400);
2909
+ if (String(n.inviter_device_id ?? "").trim() === o) return e.json({ error: "project_invite_self_acceptance_forbidden" }, 409);
2910
+ if (d.length > 256 || /[\p{Cc}\p{Cf}]/u.test(d)) return e.json({ error: "recipient_actor_id_invalid" }, 400);
2911
+ let l, m;
2912
+ try {
2913
+ l = g(f, "recipient_display_name"), m = g(p, "device_display_name");
2914
+ } catch (t) {
2915
+ return e.json({ error: t instanceof Error ? t.message : "project_invite_identity_invalid" }, 400);
2916
+ }
2917
+ let h;
2918
+ try {
2919
+ h = w(n);
2920
+ } catch {
2921
+ return e.json({ error: "operation_intent_invalid" }, 409);
2922
+ }
2923
+ try {
2924
+ let n = await _.consumeProjectInvite({
2925
+ token: a,
2926
+ operationId: u,
2927
+ deviceId: o,
2928
+ publicKey: c,
2929
+ fingerprint: s,
2930
+ recipientActorId: d,
2931
+ recipientDisplayName: l,
2932
+ deviceDisplayName: m,
2933
+ now: t.now()
2934
+ });
2935
+ return e.json({
2936
+ ok: !0,
2937
+ status: _t,
2938
+ group_id: n.invite.group_id,
2939
+ operation_id: n.invite.operation_id,
2940
+ trust_state: n.invite.trust_state,
2941
+ bootstrap_grant_id: n.bootstrap_grant?.grant_id ?? null,
2942
+ inviter_device: n.seed_enrollment ? {
2943
+ device_id: n.seed_enrollment.device_id,
2944
+ public_key: n.seed_enrollment.public_key,
2945
+ fingerprint: n.seed_enrollment.fingerprint,
2946
+ display_name: n.seed_enrollment.display_name
2947
+ } : null,
2948
+ accepted_project_intent: h
2949
+ });
2950
+ } catch (t) {
2951
+ let n = t instanceof Error ? t.message : "invite_invalid", r = n === "invite_expired" ? 410 : n === "invite_invalid" ? 404 : 409;
2952
+ return e.json({ error: n }, r);
2953
+ }
2954
+ }
2955
+ if ([
2956
+ "operation_id",
2957
+ "recipient_actor_id",
2958
+ "recipient_display_name",
2959
+ "device_display_name"
2960
+ ].some((e) => Object.hasOwn(i, e))) return e.json({ error: "unexpected_project_invite_fields" }, 400);
2961
+ let h = await _.getGroup(String(n.group_id));
2962
+ if (!h) return e.json({ error: "group_not_found" }, 404);
2963
+ if (h.archived_at) return e.json({ error: "group_archived" }, 409);
2964
+ let v = String(n.group_id);
2965
+ if (await _.getEnrollment(v, o)) return e.json({
2966
+ ok: !0,
2967
+ status: "already_enrolled",
2968
+ group_id: n.group_id,
2969
+ policy: n.policy
2970
+ });
2971
+ let y = String(n.policy);
2972
+ if (!["auto_admit", "approval_required"].includes(y)) return e.json({ error: `unknown invite policy: ${y}` }, 400);
2973
+ if (y === "approval_required") {
2974
+ let t = await _.createJoinRequest({
2975
+ groupId: v,
2976
+ deviceId: o,
2977
+ publicKey: c,
2978
+ fingerprint: s,
2979
+ displayName: l,
2980
+ token: a
2981
+ });
2982
+ return e.json({
2983
+ ok: !0,
2984
+ status: "pending",
2985
+ group_id: n.group_id,
2986
+ policy: n.policy,
2987
+ request_id: t.request_id
2988
+ });
2989
+ }
2990
+ return await _.enrollDevice(v, {
2991
+ deviceId: o,
2992
+ fingerprint: s,
2993
+ publicKey: c,
2994
+ displayName: l
2995
+ }), e.json({
2996
+ ok: !0,
2997
+ status: "enrolled",
2998
+ group_id: n.group_id,
2999
+ policy: n.policy
3000
+ });
3001
+ } finally {
3002
+ await _.close();
3003
+ }
3004
+ }), d;
3005
+ }
3006
+ async function on(e, t, n) {
3007
+ let r = Z(e.req.header(X), n.runtime);
3008
+ if (!r.ok) return n.rateLimitedResponse(e, e.req.path, !1) ?? e.json({ error: r.error }, 401);
3009
+ let i = n.rateLimitedResponse(e, "admin", !0);
3010
+ if (i) return i;
3011
+ let a = await (async () => {
3012
+ let t = Number.parseInt(e.req.header("content-length") ?? "", 10);
3013
+ if (Number.isFinite(t) && t > Y) return null;
3014
+ let n = e.req.raw.body;
3015
+ if (!n) return new Uint8Array();
3016
+ let r = n.getReader(), i = [], a = 0;
3017
+ try {
3018
+ for (;;) {
3019
+ let { done: e, value: t } = await r.read();
3020
+ if (e) break;
3021
+ if (t) {
3022
+ if (a += t.byteLength, a > Y) return await r.cancel(), null;
3023
+ i.push(t);
3024
+ }
3025
+ }
3026
+ } finally {
3027
+ r.releaseLock();
3028
+ }
3029
+ let o = new Uint8Array(a), s = 0;
3030
+ for (let e of i) o.set(e, s), s += e.byteLength;
3031
+ return o;
3032
+ })();
3033
+ if (a == null) return e.json({ error: "body_too_large" }, 413);
3034
+ let o;
3035
+ try {
3036
+ let e = new TextDecoder(), t = JSON.parse(e.decode(a));
3037
+ o = typeof t == "object" && t && !Array.isArray(t) ? t : null;
3038
+ } catch {
3039
+ o = null;
3040
+ }
3041
+ if (!o) return e.json({ error: "invalid_json" }, 400);
3042
+ let s = String(o.request_id ?? "").trim(), c = String(o.reviewed_by ?? "").trim() || null, l = String(o.bootstrap_grant_seed_device_id ?? "").trim(), u = String(o.bootstrap_grant_expires_at ?? "").trim();
3043
+ if (!s) return e.json({ error: "request_id_required" }, 400);
3044
+ let d = [l, u].filter(Boolean).length;
3045
+ if (d > 0 && d < 2) return e.json({ error: "bootstrap_grant_seed_device_id_and_expires_at_required_together" }, 400);
3046
+ let f = n.createStore();
3047
+ try {
3048
+ let n = await f.reviewJoinRequest({
3049
+ requestId: s,
3050
+ approved: t,
3051
+ reviewedBy: c,
3052
+ bootstrapGrant: t && l && u ? {
3053
+ seedDeviceId: l,
3054
+ expiresAt: u,
3055
+ createdBy: c
3056
+ } : null
3057
+ });
3058
+ return n ? n._no_transition ? e.json({
3059
+ error: "request_not_pending",
3060
+ status: n.status
3061
+ }, 409) : e.json({
3062
+ ok: !0,
3063
+ request: n
3064
+ }) : e.json({ error: "request_not_found" }, 404);
3065
+ } finally {
3066
+ await f.close();
3067
+ }
3068
+ }
3069
+ //#endregion
3070
+ export { se as A, l as B, G as C, oe as D, x as E, y as F, u as H, p as I, d as L, v as M, _ as N, N as O, g as P, m as R, gt as S, b as T, o as U, s as V, c as W, yt as _, Yt as a, ht as b, Ht as c, St as d, Dt as f, vt as g, _t as h, Xt as i, F as j, ce as k, Bt as l, Lt as m, Zt as n, Rt as o, It as p, Jt as r, Vt as s, an as t, Ct as u, bt as v, le as w, W as x, xt as y, i as z };
3071
+
3072
+ //# sourceMappingURL=coordinator-api-Bxw5Q3py.js.map