@codemem/core 0.40.0-alpha.1 → 0.40.1

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