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