@codemem/core 0.44.0-alpha.1 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/automatic-recall.d.ts +45 -0
- package/dist/automatic-recall.d.ts.map +1 -0
- package/dist/coordinator-actions.d.ts +5 -0
- package/dist/coordinator-actions.d.ts.map +1 -1
- package/dist/{coordinator-api-Dlr65yhR.js → coordinator-api-C2ckGC2b.js} +680 -651
- package/dist/coordinator-api-C2ckGC2b.js.map +1 -0
- package/dist/coordinator-api.d.ts.map +1 -1
- package/dist/db.d.ts.map +1 -1
- package/dist/export-import.d.ts.map +1 -1
- package/dist/extraction-benchmark-scoring.d.ts +1 -0
- package/dist/extraction-benchmark-scoring.d.ts.map +1 -1
- package/dist/extraction-replay.d.ts +29 -0
- package/dist/extraction-replay.d.ts.map +1 -1
- package/dist/index.d.ts +16 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9995 -8606
- package/dist/index.js.map +1 -1
- package/dist/ingest-pipeline.d.ts.map +1 -1
- package/dist/ingest-prompts.d.ts +3 -1
- package/dist/ingest-prompts.d.ts.map +1 -1
- package/dist/ingest-xml-parser.d.ts.map +1 -1
- package/dist/internal/cloudflare-coordinator.js +220 -220
- package/dist/internal/cloudflare-coordinator.js.map +1 -1
- package/dist/legacy-team-setup-completion-manifest.d.ts +4 -0
- package/dist/legacy-team-setup-completion-manifest.d.ts.map +1 -1
- package/dist/legacy-team-setup-errors.d.ts +2 -0
- package/dist/legacy-team-setup-errors.d.ts.map +1 -1
- package/dist/legacy-team-setup-limits.d.ts +3 -1
- package/dist/legacy-team-setup-limits.d.ts.map +1 -1
- package/dist/maintenance/ai-structured.d.ts.map +1 -1
- package/dist/native-runtime.d.ts +12 -0
- package/dist/native-runtime.d.ts.map +1 -0
- package/dist/observer-client.d.ts +10 -0
- package/dist/observer-client.d.ts.map +1 -1
- package/dist/observer-concepts.d.ts +5 -0
- package/dist/observer-concepts.d.ts.map +1 -0
- package/dist/observer-config.d.ts.map +1 -1
- package/dist/observer-forced-tool.d.ts +34 -0
- package/dist/observer-forced-tool.d.ts.map +1 -0
- package/dist/observer-output-schema.d.ts +57 -0
- package/dist/observer-output-schema.d.ts.map +1 -0
- package/dist/observer-output.d.ts +59 -0
- package/dist/observer-output.d.ts.map +1 -0
- package/dist/pack.d.ts +7 -7
- package/dist/pack.d.ts.map +1 -1
- package/dist/project-identity.d.ts +4 -0
- package/dist/project-identity.d.ts.map +1 -0
- package/dist/project-invite-identity.d.ts +1 -0
- package/dist/project-invite-identity.d.ts.map +1 -1
- package/dist/project-scope-settings.d.ts.map +1 -1
- package/dist/raw-event-flush.d.ts.map +1 -1
- package/dist/raw-event-ingest.d.ts.map +1 -1
- package/dist/raw-event-sweeper.d.ts +2 -3
- package/dist/raw-event-sweeper.d.ts.map +1 -1
- package/dist/recipient-policy-review.d.ts +6 -0
- package/dist/recipient-policy-review.d.ts.map +1 -1
- package/dist/ref-queries.d.ts +2 -0
- package/dist/ref-queries.d.ts.map +1 -1
- package/dist/release-discovery.d.ts +4 -0
- package/dist/release-discovery.d.ts.map +1 -1
- package/dist/schema-bootstrap.d.ts.map +1 -1
- package/dist/schema.d.ts +76 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/scope-resolution.d.ts.map +1 -1
- package/dist/search.d.ts +4 -4
- package/dist/search.d.ts.map +1 -1
- package/dist/store.d.ts +16 -11
- package/dist/store.d.ts.map +1 -1
- package/dist/summary-memory.d.ts +6 -0
- package/dist/summary-memory.d.ts.map +1 -1
- package/dist/sync-daemon.d.ts.map +1 -1
- package/dist/test-schema.generated.d.ts +1 -1
- package/dist/test-schema.generated.d.ts.map +1 -1
- package/dist/types.d.ts +16 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/vector-migration.d.ts.map +1 -1
- package/dist/vectors.d.ts +7 -1
- package/dist/vectors.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/coordinator-api-Dlr65yhR.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coordinator-api-C2ckGC2b.js","names":["Hono","Node","Node","HonoBase"],"sources":["../src/project-identity.ts","../src/scope-resolution.ts","../src/legacy-team-setup-limits.ts","../src/recipient-policy-identifiers.ts","../src/coordinator-legacy-team-completion.ts","../src/coordinator-membership-effects.ts","../src/coordinator-store-contract.ts","../src/project-invite-identity.ts","../src/recipient-reviewed-intent.ts","../src/sync-fingerprint.ts","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/compose.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/request/constants.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/buffer.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/body.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/url.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/request.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/html.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/context.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/constants.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/hono-base.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/utils.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/matcher.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/node.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/trie.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/smart-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/trie-router/node.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/trie-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/hono.js","../src/coordinator-invites.ts","../src/project-invite-acceptance.ts","../src/project-share-intent.ts","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/clock.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/TokenBucket.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/RateLimiter.js","../src/request-rate-limit.ts","../src/scope-membership-semantics.ts","../src/sync-auth-constants.ts","../src/coordinator-api.ts"],"sourcesContent":["const COMMAND_FAILURE_PREFIX = /^(?:command failed(?:\\s|:)|error:\\s|fatal:\\s|git:\\s)/iu;\nconst WRAPPED_GIT_FAILURE =\n\t/^(?:giterror|git error|git command failed):[^\\r\\n]*(?:not a git repository|unknown revision or path|no such remote)\\b/iu;\n\n/** Return true when a discovery failure was supplied where Project identity was expected. */\nexport function isMalformedProjectIdentity(value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tconst cleaned = value.trim();\n\tif (!cleaned) return false;\n\tif (cleaned.includes(\"\\n\") || cleaned.includes(\"\\r\")) return true;\n\treturn COMMAND_FAILURE_PREFIX.test(cleaned) || WRAPPED_GIT_FAILURE.test(cleaned);\n}\n\nexport function cleanProjectIdentity(value: string | null | undefined): string | null {\n\tconst cleaned = value?.trim();\n\tif (!cleaned || isMalformedProjectIdentity(cleaned)) return null;\n\treturn cleaned;\n}\n","import { createHash } from \"node:crypto\";\nimport { resolve } from \"node:path\";\nimport type { Database } from \"better-sqlite3\";\nimport { cleanProjectIdentity, isMalformedProjectIdentity } from \"./project-identity.js\";\n\nexport const LOCAL_DEFAULT_SCOPE_ID = \"local-default\";\n\n/**\n * Scope id used by the conservative migration backfill for legacy shared\n * memories that cannot yet be assigned to a concrete team/org scope. Single\n * source of truth: filters.ts and scope-backfill.ts re-import this so the\n * read-visibility predicate and the backfill agree on one literal.\n */\nexport const LEGACY_SHARED_REVIEW_SCOPE_ID = \"legacy-shared-review\";\n\n/**\n * Upper bound on how many scope ids we will inline into the index-eligible\n * `scope_id IN (...)` fast path (one bound parameter each). Kept well under\n * SQLite's compiled `SQLITE_MAX_VARIABLE_NUMBER` so a device with an\n * unrealistically large visible set falls back to the fixed-param EXISTS\n * predicate instead of throwing \"too many SQL variables\" at prepare time.\n */\nexport const MAX_SCOPE_IN_PARAMS = 500;\n\nexport type WorkspaceIdentitySource =\n\t| \"git_remote\"\n\t| \"git_remote_branch\"\n\t| \"cwd\"\n\t| \"workspace_id\"\n\t| \"unmapped\";\n\nexport interface WorkspaceIdentityInput {\n\tgitRemote?: string | null;\n\tgitBranch?: string | null;\n\tcwd?: string | null;\n\tworkspaceId?: string | null;\n\tproject?: string | null;\n\tbranchScoped?: boolean;\n}\n\nexport interface CanonicalWorkspaceIdentity {\n\tvalue: string;\n\tsource: WorkspaceIdentitySource;\n\tdisplayProject: string | null;\n}\n\nexport interface ScopeMapping {\n\tid?: number | null;\n\tworkspace_identity?: string | null;\n\tproject_pattern: string;\n\tscope_id: string;\n\tpriority?: number | null;\n\tupdated_at?: string | null;\n\tsource?: string | null;\n}\n\nexport type ScopeResolutionReason =\n\t| \"explicit_override\"\n\t| \"exact_mapping\"\n\t| \"pattern_mapping\"\n\t| \"local_default\";\n\nexport interface ScopeResolution {\n\tscopeId: string;\n\treason: ScopeResolutionReason;\n\tworkspaceIdentity: CanonicalWorkspaceIdentity;\n\tmapping: ScopeMapping | null;\n\tmatchedPattern: string | null;\n}\n\nexport interface ResolveProjectScopeInput extends WorkspaceIdentityInput {\n\texplicitScopeId?: string | null;\n\tmappings?: ScopeMapping[];\n\tlocalDefaultScopeId?: string;\n}\n\ninterface MappingCandidate {\n\tmapping: ScopeMapping;\n\tspecificity: number;\n\tmatchedPattern: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction normalizeSlash(value: string): string {\n\tconst normalized = value.trim().replaceAll(\"\\\\\", \"/\").replace(/\\/+$/, \"\");\n\treturn normalized || value.trim();\n}\n\nfunction normalizeCwd(cwd: string): string {\n\t// Callers should pass an already-realpathed session cwd when symlink\n\t// resolution matters; this pure helper only normalizes path syntax.\n\treturn normalizeSlash(resolve(cwd));\n}\n\nfunction normalizeMappingIdentity(value: string | null | undefined): string | null {\n\tconst cleaned = clean(value);\n\treturn cleaned ? normalizeSlash(cleaned) : null;\n}\n\nfunction unmappedIdentity(input: WorkspaceIdentityInput): string {\n\tconst validSeed = [input.cwd, input.project, input.workspaceId]\n\t\t.map((value) => cleanProjectIdentity(value))\n\t\t.find((value) => value !== null);\n\tconst identityTuple = [\n\t\tinput.gitRemote,\n\t\tinput.gitBranch,\n\t\tinput.cwd,\n\t\tinput.project,\n\t\tinput.workspaceId,\n\t].map((value) => (typeof value === \"string\" ? value.trim() : null));\n\tlet seed = validSeed ?? \"unknown\";\n\tif (!validSeed && identityTuple.some(isMalformedProjectIdentity)) {\n\t\tseed = JSON.stringify(identityTuple);\n\t}\n\tconst digest = createHash(\"sha256\").update(seed, \"utf8\").digest(\"hex\");\n\treturn `unmapped:${digest}`;\n}\n\nexport function canonicalWorkspaceIdentity(\n\tinput: WorkspaceIdentityInput,\n): CanonicalWorkspaceIdentity {\n\tconst gitRemote = cleanProjectIdentity(input.gitRemote);\n\tconst gitBranch = cleanProjectIdentity(input.gitBranch);\n\tconst cwd = cleanProjectIdentity(input.cwd);\n\tconst workspaceId = cleanProjectIdentity(input.workspaceId);\n\tconst project = cleanProjectIdentity(input.project);\n\n\tif (gitRemote) {\n\t\tconst normalizedRemote = normalizeSlash(gitRemote);\n\t\tif (input.branchScoped && gitBranch) {\n\t\t\treturn {\n\t\t\t\tvalue: `${normalizedRemote}:${gitBranch}`,\n\t\t\t\tsource: \"git_remote_branch\",\n\t\t\t\tdisplayProject: project,\n\t\t\t};\n\t\t}\n\t\treturn { value: normalizedRemote, source: \"git_remote\", displayProject: project };\n\t}\n\n\tif (cwd) {\n\t\treturn { value: normalizeCwd(cwd), source: \"cwd\", displayProject: project };\n\t}\n\n\tif (workspaceId) {\n\t\treturn { value: normalizeSlash(workspaceId), source: \"workspace_id\", displayProject: project };\n\t}\n\n\treturn { value: unmappedIdentity(input), source: \"unmapped\", displayProject: project };\n}\n\nfunction isBasenameOnlyPattern(pattern: string): boolean {\n\treturn !/[\\\\/:]/.test(pattern);\n}\n\nfunction escapeRegex(value: string): string {\n\treturn value.replace(/[|\\\\{}()[\\]^$+?.*]/g, \"\\\\$&\");\n}\n\nfunction patternSpecificity(pattern: string): number {\n\treturn pattern.replace(/[*?]/g, \"\").length;\n}\n\nfunction matchesPattern(identity: string, pattern: string): boolean {\n\tconst normalizedPattern = normalizeSlash(pattern);\n\tif (!normalizedPattern || isBasenameOnlyPattern(normalizedPattern)) return false;\n\tif (!/[*?]/.test(normalizedPattern)) return identity === normalizedPattern;\n\tconst regex = new RegExp(\n\t\t`^${escapeRegex(normalizedPattern).replaceAll(\"\\\\*\", \".*\").replaceAll(\"\\\\?\", \".\")}$`,\n\t);\n\treturn regex.test(identity);\n}\n\nfunction candidatePriority(candidate: MappingCandidate): number {\n\treturn candidate.mapping.priority ?? 0;\n}\n\nfunction candidateUpdatedAt(candidate: MappingCandidate): number {\n\tconst updatedAt = clean(candidate.mapping.updated_at);\n\tif (!updatedAt) return 0;\n\tconst time = Date.parse(updatedAt);\n\treturn Number.isFinite(time) ? time : 0;\n}\n\nfunction compareCandidates(a: MappingCandidate, b: MappingCandidate): number {\n\treturn (\n\t\tcandidatePriority(b) - candidatePriority(a) ||\n\t\tb.specificity - a.specificity ||\n\t\tcandidateUpdatedAt(b) - candidateUpdatedAt(a) ||\n\t\t(b.mapping.id ?? 0) - (a.mapping.id ?? 0) ||\n\t\ta.mapping.scope_id.localeCompare(b.mapping.scope_id)\n\t);\n}\n\nfunction bestCandidate(candidates: MappingCandidate[]): MappingCandidate | null {\n\treturn candidates.toSorted(compareCandidates)[0] ?? null;\n}\n\nexport function resolveProjectScope(input: ResolveProjectScopeInput): ScopeResolution {\n\tconst workspaceIdentity = canonicalWorkspaceIdentity(input);\n\tconst explicitScopeId = clean(input.explicitScopeId);\n\tif (explicitScopeId) {\n\t\treturn {\n\t\t\tscopeId: explicitScopeId,\n\t\t\treason: \"explicit_override\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\tif (workspaceIdentity.source === \"unmapped\") {\n\t\treturn {\n\t\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\t\treason: \"local_default\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst mappings = input.mappings ?? [];\n\tconst exact = bestCandidate(\n\t\tmappings\n\t\t\t.filter(\n\t\t\t\t(mapping) =>\n\t\t\t\t\tnormalizeMappingIdentity(mapping.workspace_identity) === workspaceIdentity.value,\n\t\t\t)\n\t\t\t.map((mapping) => ({\n\t\t\t\tmapping,\n\t\t\t\tmatchedPattern: null,\n\t\t\t\tspecificity: workspaceIdentity.value.length,\n\t\t\t})),\n\t);\n\tif (exact) {\n\t\treturn {\n\t\t\tscopeId: exact.mapping.scope_id,\n\t\t\treason: \"exact_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: exact.mapping,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst pattern = bestCandidate(\n\t\tmappings.flatMap((mapping): MappingCandidate[] => {\n\t\t\tif (clean(mapping.workspace_identity)) return [];\n\t\t\tconst projectPattern = clean(mapping.project_pattern);\n\t\t\tif (!projectPattern || !matchesPattern(workspaceIdentity.value, projectPattern)) return [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tmapping,\n\t\t\t\t\tmatchedPattern: normalizeSlash(projectPattern),\n\t\t\t\t\tspecificity: patternSpecificity(projectPattern),\n\t\t\t\t},\n\t\t\t];\n\t\t}),\n\t);\n\tif (pattern) {\n\t\treturn {\n\t\t\tscopeId: pattern.mapping.scope_id,\n\t\t\treason: \"pattern_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: pattern.mapping,\n\t\t\tmatchedPattern: pattern.matchedPattern,\n\t\t};\n\t}\n\n\treturn {\n\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\treason: \"local_default\",\n\t\tworkspaceIdentity,\n\t\tmapping: null,\n\t\tmatchedPattern: null,\n\t};\n}\n\n/**\n * Resolve, once per request, the full set of scope_ids that `deviceId` may read.\n *\n * This is the index-eligible equivalent of the per-row EXISTS predicate in\n * `addScopeVisibilityFilter`'s fallback branch (filters.ts): instead of\n * evaluating the replication_scopes / scope_memberships subqueries for every\n * candidate row, we compute the visible set up front and let the SQL filter use\n * a plain `scope_id IN (...)`. The membership predicate (active membership with\n * `membership_epoch >= scope.membership_epoch`) is preserved exactly.\n *\n * Lives in this leaf module (it imports nothing from filters/search/store/\n * vectors) so all three OwnershipFilterContext builders can share it without an\n * import cycle.\n *\n * NULL scope_ids are skipped here — a NULL scope_id is handled by the filter's\n * dedicated `IS NULL` branch, not by membership in this set.\n */\nexport function resolveVisibleScopeIds(db: Database, deviceId: string): string[] {\n\tconst visible = new Set<string>([\"\", LOCAL_DEFAULT_SCOPE_ID, LEGACY_SHARED_REVIEW_SCOPE_ID]);\n\tconst localScopes = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id\n\t\t\t FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'local'`,\n\t\t)\n\t\t.all() as Array<{ scope_id: string | null }>;\n\tfor (const row of localScopes) {\n\t\tif (row.scope_id != null) visible.add(row.scope_id);\n\t}\n\tconst memberScopes = db\n\t\t.prepare(\n\t\t\t`SELECT sm.scope_id AS scope_id\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch`,\n\t\t)\n\t\t.all(deviceId) as Array<{ scope_id: string | null }>;\n\tfor (const row of memberScopes) {\n\t\tif (row.scope_id != null) visible.add(row.scope_id);\n\t}\n\treturn [...visible];\n}\n","import type { Database } from \"./db.js\";\n\nexport const LEGACY_TEAM_SETUP_MAX_DEVICES = 500;\nexport const LEGACY_TEAM_SETUP_MAX_PROJECTS = 500;\nexport const LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS = 10_000;\n\nexport function requireLegacyTeamSetupSnapshotWithinLimits(input: {\n\tdevices: readonly unknown[];\n\tprojects: readonly unknown[];\n}): void {\n\tif (\n\t\tinput.devices.length > LEGACY_TEAM_SETUP_MAX_DEVICES ||\n\t\tinput.projects.length > LEGACY_TEAM_SETUP_MAX_PROJECTS ||\n\t\tinput.devices.length * input.projects.length > LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\n/**\n * Bounds the access-delta derivation itself. Activation recomputes effective\n * devices for every Project the Team touches plus every Project with an\n * active recipient edge, across every assigned device, so a tiny draft can\n * still fan out past the pair budget when the installation already holds many\n * recipients or assignments.\n */\nexport function requireLegacyTeamSetupAccessDeltaTraversalWithinLimit(input: {\n\tprojectIdentities: ReadonlySet<string>;\n\tdeviceCount: number;\n}): void {\n\tif (\n\t\tinput.projectIdentities.size * input.deviceCount >\n\t\tLEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\n/**\n * Readiness checks re-derive effective devices for every completed Project,\n * and that derivation walks every persisted assignment row. Bound that fan-out\n * so a small roster cannot hide an unbounded Project-by-assignment traversal.\n */\nexport function requireLegacyTeamSetupReachableDevicesWithinLimit(\n\tdb: Database,\n\tdevices: readonly { deviceId: string }[],\n\tprojects: readonly unknown[],\n): void {\n\tif (projects.length === 0) return;\n\tconst deviceIds = [...new Set(devices.map((device) => device.deviceId))];\n\tconst excludeRoster =\n\t\tdeviceIds.length > 0 ? `WHERE device_id NOT IN (${deviceIds.map(() => \"?\").join(\", \")})` : \"\";\n\tconst assignmentRows = Number(\n\t\tdb\n\t\t\t.prepare(`SELECT COUNT(*) FROM identity_devices ${excludeRoster}`)\n\t\t\t.pluck()\n\t\t\t.get(...deviceIds) ?? 0,\n\t);\n\tif (\n\t\t(deviceIds.length + assignmentRows) * projects.length >\n\t\tLEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\nexport function requireLegacyTeamSetupEffectiveDevicesWithinLimit(\n\tdb: Database,\n\tdevices: readonly { deviceId: string }[],\n\tprojects: readonly unknown[],\n\tpreviousAttemptId: string | null,\n): void {\n\tif (!previousAttemptId) return;\n\tconst currentDeviceIds = [...new Set(devices.map((device) => device.deviceId))];\n\tconst placeholders = currentDeviceIds.map(() => \"?\").join(\", \");\n\tconst excludeCurrent = placeholders ? `AND device_id NOT IN (${placeholders})` : \"\";\n\tconst carriedDeviceCount = Number(\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT COUNT(*) FROM legacy_team_setup_draft_devices\n\t\t\t\t WHERE attempt_id = ? ${excludeCurrent}`,\n\t\t\t)\n\t\t\t.pluck()\n\t\t\t.get(previousAttemptId, ...currentDeviceIds) ?? 0,\n\t);\n\tconst effectiveDeviceCount = devices.length + carriedDeviceCount;\n\tif (\n\t\teffectiveDeviceCount > LEGACY_TEAM_SETUP_MAX_DEVICES ||\n\t\teffectiveDeviceCount * projects.length > LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Locale-independent UTF-16 code-unit comparison. Every fingerprint and digest\n * in the recipient-policy feature relies on byte-identical ordering across\n * machines, so `localeCompare` (ICU-collation dependent) must never feed a\n * digest.\n */\nexport function compareCodepoints(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nconst RECIPIENT_POLICY_ID_CONTROL_OR_FORMAT_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\n\nfunction isStrictRecipientPolicyText(value: unknown, maxUtf16Units: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue === value.trim() &&\n\t\tvalue.length <= maxUtf16Units &&\n\t\t!RECIPIENT_POLICY_ID_CONTROL_OR_FORMAT_CHARACTER.test(value)\n\t);\n}\n\nexport function isStrictRecipientPolicyId(value: unknown): value is string {\n\treturn isStrictRecipientPolicyText(value, 256);\n}\n\nexport function isStrictRecipientPolicyProjectIdentity(value: unknown): value is string {\n\treturn isStrictRecipientPolicyText(value, 2_048);\n}\n\nconst INVALID_CANONICAL_JSON_MESSAGE = \"Recipient policy value must be strict JSON data\";\n\nfunction invalidCanonicalJson(): never {\n\tthrow new TypeError(INVALID_CANONICAL_JSON_MESSAGE);\n}\n\nfunction serializeJsonString(value: string): string {\n\tconst serialized = JSON.stringify(value);\n\tif (serialized === undefined) return invalidCanonicalJson();\n\treturn serialized;\n}\n\nfunction canonicalJson(value: unknown, ancestors: WeakSet<object>): string {\n\tif (value === null) return \"null\";\n\tif (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n\tif (typeof value === \"string\") return serializeJsonString(value);\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value) || Object.is(value, -0)) return invalidCanonicalJson();\n\t\treturn String(value);\n\t}\n\tif (typeof value !== \"object\") return invalidCanonicalJson();\n\tif (ancestors.has(value)) return invalidCanonicalJson();\n\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getPrototypeOf(value) !== Array.prototype) return invalidCanonicalJson();\n\t\t\tconst keys = Reflect.ownKeys(value);\n\t\t\tif (keys.length !== value.length + 1 || keys.some((key) => typeof key !== \"string\")) {\n\t\t\t\treturn invalidCanonicalJson();\n\t\t\t}\n\t\t\tconst children: string[] = [];\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) return invalidCanonicalJson();\n\t\t\t\tchildren.push(canonicalJson(descriptor.value, ancestors));\n\t\t\t}\n\t\t\treturn `[${children.join(\",\")}]`;\n\t\t}\n\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) return invalidCanonicalJson();\n\t\tconst entries = Reflect.ownKeys(value).map((key): [string, unknown] => {\n\t\t\tif (typeof key !== \"string\") return invalidCanonicalJson();\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) return invalidCanonicalJson();\n\t\t\treturn [key, descriptor.value];\n\t\t});\n\t\treturn `{${entries\n\t\t\t.toSorted(([left], [right]) => compareCodepoints(left, right))\n\t\t\t.map(([key, child]) => `${serializeJsonString(key)}:${canonicalJson(child, ancestors)}`)\n\t\t\t.join(\",\")}}`;\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\nexport function canonicalRecipientPolicyJson(value: unknown): string {\n\treturn canonicalJson(value, new WeakSet());\n}\n\nexport function recipientPolicyDigest(prefix: string, value: unknown): string {\n\t// Node replaces unpaired UTF-16 surrogates with U+FFFD during UTF-8\n\t// encoding, so accepting them would make distinct domains hash identically.\n\tif (prefix.includes(\"\\0\") || !prefix.isWellFormed()) {\n\t\tthrow new TypeError(\"Recipient policy digest prefix must be well-formed without NUL\");\n\t}\n\treturn `${prefix}:${createHash(\"sha256\")\n\t\t.update(prefix, \"utf8\")\n\t\t.update(\"\\0\", \"utf8\")\n\t\t.update(canonicalRecipientPolicyJson(value), \"utf8\")\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Compatibility digest for identifiers persisted by released recipient-policy\n * flows before domain separation was introduced. New digest domains must use\n * `recipientPolicyDigest`; changing these bytes requires an explicit DB rekey.\n */\nexport function legacyRecipientPolicyDigest(prefix: string, value: unknown): string {\n\treturn `${prefix}:${createHash(\"sha256\")\n\t\t.update(canonicalRecipientPolicyJson(value), \"utf8\")\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Decision and membership provenances owned by the invite flows. Activation\n * deliberately preserves these rows and readiness must tolerate them; every\n * layer that classifies invite ownership must use this single set —\n * hand-repeated literals with opposite polarity (allowlist vs denylist) are\n * how the two sides drift apart.\n */\nexport const INVITE_DECISION_PROVENANCES = [\"team_invite\", \"coordinator_invite\"] as const;\n\n/**\n * Frozen compatibility identifier persisted by released legacy Team drafts.\n * Changing the JSON tuple bytes or truncation requires an explicit DB rekey.\n */\nexport function legacyTeamCandidateId(coordinatorId: string, groupId: string): string {\n\tconst digest = createHash(\"sha256\")\n\t\t.update(JSON.stringify([coordinatorId, groupId]))\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `legacy-team-candidate:${digest}`;\n}\n\nexport function legacyTeamProjectRef(candidateId: string, sourceProjectIdentity: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-project-ref-v1\", [candidateId, sourceProjectIdentity]);\n}\n\nexport function legacyTeamCanonicalProjectRef(\n\tcandidateId: string,\n\tcanonicalProjectIdentity: string,\n): string {\n\treturn recipientPolicyDigest(\"legacy-team-canonical-project-ref-v1\", [\n\t\tcandidateId,\n\t\tcanonicalProjectIdentity,\n\t]);\n}\n\nexport function legacyTeamDeviceRef(candidateId: string, deviceId: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-device-ref-v1\", [candidateId, deviceId]);\n}\n\nexport function deterministicPolicyTeamId(teamCandidateId: string): string {\n\treturn legacyRecipientPolicyDigest(\"policy-team-v1\", teamCandidateId);\n}\n\nexport function legacyTeamRosterFingerprint(\n\tdevices: ReadonlyArray<{\n\t\tdeviceId: string;\n\t\tfingerprint: string;\n\t\tenabled: boolean;\n\t\tidentityId: string | null;\n\t}>,\n): string {\n\treturn recipientPolicyDigest(\n\t\t\"legacy-team-roster-v1\",\n\t\tdevices\n\t\t\t.map((device) => ({\n\t\t\t\tdeviceId: device.deviceId,\n\t\t\t\tfingerprint: device.fingerprint,\n\t\t\t\tenabled: device.enabled,\n\t\t\t\tidentityId: device.identityId,\n\t\t\t}))\n\t\t\t.toSorted((left, right) => compareCodepoints(left.deviceId, right.deviceId)),\n\t);\n}\n","import {\n\tLEGACY_TEAM_SETUP_MAX_DEVICES,\n\tLEGACY_TEAM_SETUP_MAX_PROJECTS,\n} from \"./legacy-team-setup-limits.js\";\nimport {\n\tcompareCodepoints,\n\tdeterministicPolicyTeamId,\n\tlegacyTeamCandidateId,\n} from \"./recipient-policy-identifiers.js\";\n\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION = 1 as const;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS = 50;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS = 500;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES = 1_500_000;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES =\n\t25 * COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES;\nconst COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS = 256;\nconst COORDINATOR_LEGACY_TEAM_COMPLETION_RECORD_ENVELOPE_BYTES = 64;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_RESPONSE_BYTES =\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES +\n\t(COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS +\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_RECORD_ENVELOPE_BYTES) *\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS +\n\t1024;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT = \"completion_conflict\" as const;\n\nexport interface CoordinatorLegacyTeamCompletionMembershipV1 {\n\tidentity_id: string;\n\trole: \"member\";\n}\n\nexport interface CoordinatorLegacyTeamCompletionDeviceDecisionV1 {\n\tdevice_id: string;\n\tkey_fingerprint: string;\n\tenabled: boolean;\n\tidentity_id: string | null;\n\tdecision: \"included\" | \"excluded\";\n}\n\nexport interface CoordinatorLegacyTeamCompletionProjectMappingV1 {\n\tproject_ref: string;\n\tresolved_project_ref: string;\n\tscope_id: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionRecipientV1 {\n\tresolved_project_ref: string;\n\tteam_id: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionManifestV1 {\n\tversion: typeof COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION;\n\tcoordinator_id: string;\n\tcandidate_ref: string;\n\tcandidate_digest: string;\n\tteam_id: string;\n\tteam_digest: string;\n\tsource_digest: string;\n\tfinish_digest: string;\n\taccess_delta_digest: string;\n\tteam: {\n\t\tdisplay_name: string;\n\t\tpolicy_revision: string;\n\t\tdevice_eligibility_mode: \"reviewed_allowlist\";\n\t};\n\tmemberships: CoordinatorLegacyTeamCompletionMembershipV1[];\n\tdevice_decisions: CoordinatorLegacyTeamCompletionDeviceDecisionV1[];\n\tproject_mappings: CoordinatorLegacyTeamCompletionProjectMappingV1[];\n\tproject_recipients: CoordinatorLegacyTeamCompletionRecipientV1[];\n\tcompleted_at: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionWriteResult {\n\tstatus: \"created\" | \"existing\";\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\n\nexport interface CoordinatorLegacyTeamCompletionRecord {\n\tgroup_id: string;\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\n\nexport interface CoordinatorLegacyTeamCompletionScopeBinding {\n\tscope_id: string | null;\n\tauthority_type: string | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tstatus: string | null;\n}\n\nexport class CoordinatorLegacyTeamCompletionConflictError extends Error {\n\treadonly code = COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT;\n\n\tconstructor() {\n\t\tsuper(COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT);\n\t\tthis.name = \"CoordinatorLegacyTeamCompletionConflictError\";\n\t}\n}\n\nfunction invalid(): never {\n\tthrow new Error(\"completion_manifest_invalid\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) invalid();\n\treturn value as Record<string, unknown>;\n}\n\nfunction exactFields(value: Record<string, unknown>, fields: readonly string[]): void {\n\tconst allowed = new Set(fields);\n\tif (Object.keys(value).some((field) => !allowed.has(field))) invalid();\n}\n\nfunction isLocalArtifactPath(value: string): boolean {\n\treturn /^(?:[\\\\/]{2}|\\.{1,2}[\\\\/]|\\/|~[\\\\/]|[a-z]:[\\\\/]|file:)/iu.test(value);\n}\n\nfunction identifier(value: unknown): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue !== value.trim() ||\n\t\tvalue.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(value) ||\n\t\tisLocalArtifactPath(value)\n\t) {\n\t\tinvalid();\n\t}\n\treturn value;\n}\n\nfunction digest(value: unknown): string {\n\tconst normalized = identifier(value);\n\tif (!/^[a-f0-9]{64}$/u.test(normalized)) invalid();\n\treturn normalized;\n}\n\nfunction displayName(value: unknown): string {\n\tif (typeof value !== \"string\") invalid();\n\tconst normalized = value.normalize(\"NFC\").trim();\n\tif (\n\t\t!normalized ||\n\t\t[...normalized].length > 120 ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(normalized) ||\n\t\tisLocalArtifactPath(normalized)\n\t) {\n\t\tinvalid();\n\t}\n\treturn normalized;\n}\n\nfunction timestamp(value: unknown): string {\n\tif (typeof value !== \"string\" || !value) invalid();\n\tconst parsed = new Date(value);\n\tif (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) invalid();\n\treturn value;\n}\n\nfunction array(value: unknown, max: number): unknown[] {\n\tif (!Array.isArray(value) || value.length > max) invalid();\n\treturn value;\n}\n\nfunction uniqueSorted<T>(items: T[], key: (item: T) => string): T[] {\n\tconst sorted = items.toSorted((left, right) => compareCodepoints(key(left), key(right)));\n\tif (sorted.some((item, index) => index > 0 && key(sorted[index - 1] as T) === key(item)))\n\t\tinvalid();\n\treturn sorted;\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionGroupIds(value: unknown): string[] {\n\treturn uniqueSorted(\n\t\tarray(value, COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS).map(identifier),\n\t\t(item) => item,\n\t);\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionCandidateRef(value: unknown): string {\n\tconst normalized = identifier(value);\n\tif (!/^legacy-team-candidate:[a-f0-9]{32}$/u.test(normalized)) invalid();\n\treturn normalized;\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionManifest(\n\tvalue: unknown,\n): CoordinatorLegacyTeamCompletionManifestV1 {\n\tconst input = record(value);\n\texactFields(input, [\n\t\t\"version\",\n\t\t\"coordinator_id\",\n\t\t\"candidate_ref\",\n\t\t\"candidate_digest\",\n\t\t\"team_id\",\n\t\t\"team_digest\",\n\t\t\"source_digest\",\n\t\t\"finish_digest\",\n\t\t\"access_delta_digest\",\n\t\t\"team\",\n\t\t\"memberships\",\n\t\t\"device_decisions\",\n\t\t\"project_mappings\",\n\t\t\"project_recipients\",\n\t\t\"completed_at\",\n\t]);\n\tif (input.version !== COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION) invalid();\n\tconst team = record(input.team);\n\texactFields(team, [\"display_name\", \"policy_revision\", \"device_eligibility_mode\"]);\n\tif (team.device_eligibility_mode !== \"reviewed_allowlist\") invalid();\n\tconst teamId = identifier(input.team_id);\n\tconst memberships = uniqueSorted(\n\t\tarray(input.memberships, LEGACY_TEAM_SETUP_MAX_DEVICES).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"identity_id\", \"role\"]);\n\t\t\tif (item.role !== \"member\") invalid();\n\t\t\treturn { identity_id: identifier(item.identity_id), role: \"member\" as const };\n\t\t}),\n\t\t(item) => item.identity_id,\n\t);\n\tconst deviceDecisions = uniqueSorted(\n\t\tarray(input.device_decisions, LEGACY_TEAM_SETUP_MAX_DEVICES).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"device_id\", \"key_fingerprint\", \"enabled\", \"identity_id\", \"decision\"]);\n\t\t\tif (item.decision !== \"included\" && item.decision !== \"excluded\") invalid();\n\t\t\tif (typeof item.enabled !== \"boolean\") invalid();\n\t\t\tconst identityId = item.identity_id == null ? null : identifier(item.identity_id);\n\t\t\tif ((item.decision === \"included\") !== Boolean(identityId)) invalid();\n\t\t\tif (item.decision === \"included\" && !item.enabled) invalid();\n\t\t\tconst decision: CoordinatorLegacyTeamCompletionDeviceDecisionV1[\"decision\"] = item.decision;\n\t\t\treturn {\n\t\t\t\tdevice_id: identifier(item.device_id),\n\t\t\t\tkey_fingerprint: digest(item.key_fingerprint),\n\t\t\t\tenabled: item.enabled,\n\t\t\t\tidentity_id: identityId,\n\t\t\t\tdecision,\n\t\t\t};\n\t\t}),\n\t\t(item) => item.device_id,\n\t);\n\tif (deviceDecisions.length === 0) invalid();\n\tconst membershipIds = new Set(memberships.map((membership) => membership.identity_id));\n\tconst includedIdentityIds = new Set(\n\t\tdeviceDecisions.flatMap((decision) => (decision.identity_id ? [decision.identity_id] : [])),\n\t);\n\tif (\n\t\tmembershipIds.size !== includedIdentityIds.size ||\n\t\t[...includedIdentityIds].some((identityId) => !membershipIds.has(identityId))\n\t) {\n\t\tinvalid();\n\t}\n\tconst projectMappings = uniqueSorted(\n\t\tarray(input.project_mappings, LEGACY_TEAM_SETUP_MAX_PROJECTS).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"project_ref\", \"resolved_project_ref\", \"scope_id\"]);\n\t\t\tconst projectRef = identifier(item.project_ref);\n\t\t\tconst resolvedProjectRef = identifier(item.resolved_project_ref);\n\t\t\tif (!/^legacy-team-project-ref-v1:[0-9a-f]{64}$/u.test(projectRef)) invalid();\n\t\t\tif (!/^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u.test(resolvedProjectRef)) {\n\t\t\t\tinvalid();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tproject_ref: projectRef,\n\t\t\t\tresolved_project_ref: resolvedProjectRef,\n\t\t\t\tscope_id: identifier(item.scope_id),\n\t\t\t};\n\t\t}),\n\t\t(item) => item.project_ref,\n\t);\n\tconst resolvedScopes = new Map<string, string>();\n\tfor (const mapping of projectMappings) {\n\t\tconst priorScopeId = resolvedScopes.get(mapping.resolved_project_ref);\n\t\tif (priorScopeId && priorScopeId !== mapping.scope_id) invalid();\n\t\tresolvedScopes.set(mapping.resolved_project_ref, mapping.scope_id);\n\t}\n\tconst projectRecipients = uniqueSorted(\n\t\tarray(input.project_recipients, LEGACY_TEAM_SETUP_MAX_PROJECTS).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"resolved_project_ref\", \"team_id\"]);\n\t\t\tconst recipientTeamId = identifier(item.team_id);\n\t\t\tif (recipientTeamId !== teamId) invalid();\n\t\t\tconst resolvedProjectRef = identifier(item.resolved_project_ref);\n\t\t\tif (!/^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u.test(resolvedProjectRef)) {\n\t\t\t\tinvalid();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresolved_project_ref: resolvedProjectRef,\n\t\t\t\tteam_id: recipientTeamId,\n\t\t\t};\n\t\t}),\n\t\t(item) => item.resolved_project_ref,\n\t);\n\tconst mappedRecipientRefs = [\n\t\t...new Set(projectMappings.map((mapping) => mapping.resolved_project_ref)),\n\t].toSorted(compareCodepoints);\n\tconst recipientRefs = projectRecipients.map((recipient) => recipient.resolved_project_ref);\n\tif (JSON.stringify(recipientRefs) !== JSON.stringify(mappedRecipientRefs)) {\n\t\tinvalid();\n\t}\n\tconst manifest: CoordinatorLegacyTeamCompletionManifestV1 = {\n\t\tversion: COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION,\n\t\tcoordinator_id: identifier(input.coordinator_id),\n\t\tcandidate_ref: normalizeCoordinatorLegacyTeamCompletionCandidateRef(input.candidate_ref),\n\t\tcandidate_digest: digest(input.candidate_digest),\n\t\tteam_id: teamId,\n\t\tteam_digest: digest(input.team_digest),\n\t\tsource_digest: digest(input.source_digest),\n\t\tfinish_digest: digest(input.finish_digest),\n\t\taccess_delta_digest: digest(input.access_delta_digest),\n\t\tteam: {\n\t\t\tdisplay_name: displayName(team.display_name),\n\t\t\tpolicy_revision: digest(team.policy_revision),\n\t\t\tdevice_eligibility_mode: \"reviewed_allowlist\",\n\t\t},\n\t\tmemberships,\n\t\tdevice_decisions: deviceDecisions,\n\t\tproject_mappings: projectMappings,\n\t\tproject_recipients: projectRecipients,\n\t\tcompleted_at: timestamp(input.completed_at),\n\t};\n\tif (\n\t\tnew TextEncoder().encode(JSON.stringify(manifest)).byteLength >\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t) {\n\t\tinvalid();\n\t}\n\treturn manifest;\n}\n\nexport function canonicalCoordinatorLegacyTeamCompletionManifestJson(value: unknown): string {\n\treturn JSON.stringify(normalizeCoordinatorLegacyTeamCompletionManifest(value));\n}\n\nexport function requireCoordinatorLegacyTeamCompletionTeamBinding(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n): void {\n\tif (manifest.team_id !== deterministicPolicyTeamId(manifest.candidate_ref)) invalid();\n}\n\nexport function requireCoordinatorLegacyTeamCompletionCandidateBinding(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\tgroupId: string,\n): void {\n\tif (legacyTeamCandidateId(manifest.coordinator_id, groupId) !== manifest.candidate_ref) invalid();\n}\n\nexport function requireCoordinatorLegacyTeamCompletionScopeBindings(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\tgroupId: string,\n\tbindings: CoordinatorLegacyTeamCompletionScopeBinding[],\n): string | null {\n\trequireCoordinatorLegacyTeamCompletionCandidateBinding(manifest, groupId);\n\tconst requestedScopeIds = new Set(manifest.project_mappings.map((mapping) => mapping.scope_id));\n\tif (bindings.length !== requestedScopeIds.size) invalid();\n\tconst coordinatorId = manifest.coordinator_id;\n\tfor (const binding of bindings) {\n\t\tif (\n\t\t\t!binding.scope_id ||\n\t\t\t!requestedScopeIds.has(binding.scope_id) ||\n\t\t\tbinding.authority_type !== \"coordinator\" ||\n\t\t\t!binding.coordinator_id ||\n\t\t\tbinding.group_id !== groupId ||\n\t\t\tbinding.status !== \"active\" ||\n\t\t\tbinding.coordinator_id !== coordinatorId\n\t\t) {\n\t\t\tinvalid();\n\t\t}\n\t}\n\treturn coordinatorId;\n}\n","import type {\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScopeMembership,\n} from \"./coordinator-store-contract.js\";\n\nexport const SCOPE_MEMBERSHIP_EFFECT_CONFLICT = \"scope_membership_effect_conflict\";\n\nexport type CoordinatorMembershipErrorCode =\n\t| \"device_not_enrolled\"\n\t| \"scope_group_mismatch\"\n\t| \"scope_inactive\"\n\t| \"scope_not_found\";\n\nconst MEMBERSHIP_ERROR_MESSAGES: Record<CoordinatorMembershipErrorCode, string> = {\n\tdevice_not_enrolled: \"device must be enrolled and enabled in the scope group.\",\n\tscope_group_mismatch: \"membership groupId must match the scope groupId.\",\n\tscope_inactive: \"scope is not active.\",\n\tscope_not_found: \"scopeId must reference an existing scope.\",\n};\n\nexport class CoordinatorMembershipError extends Error {\n\treadonly code: CoordinatorMembershipErrorCode;\n\n\tconstructor(code: CoordinatorMembershipErrorCode) {\n\t\tsuper(MEMBERSHIP_ERROR_MESSAGES[code]);\n\t\tthis.name = \"CoordinatorMembershipError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface CoordinatorMembershipEffectReceipt {\n\teffect_id: string;\n\taction: \"grant\" | \"revoke\";\n\trequest_json: string;\n\toutcome_applied: number;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string | null;\n\tmembership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string | null;\n\tcreated_at: string;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst normalized = value?.trim();\n\treturn normalized ? normalized : null;\n}\n\nexport function normalizeMembershipEffectId(value: string): string {\n\tconst effectId = clean(value);\n\tif (!effectId) throw new Error(\"effectId is required.\");\n\tif (effectId.length > 512 || /[\\p{Cc}\\p{Cf}]/u.test(effectId)) {\n\t\tthrow new Error(\"effectId is invalid.\");\n\t}\n\treturn effectId;\n}\n\nexport function grantMembershipEffectRequestJson(\n\topts: CoordinatorGrantScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\trole: clean(opts.role),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function revokeMembershipEffectRequestJson(\n\topts: CoordinatorRevokeScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function assertMatchingMembershipEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n\taction: CoordinatorMembershipEffectReceipt[\"action\"],\n\trequestJson: string,\n): void {\n\tif (receipt.action !== action || receipt.request_json !== requestJson) {\n\t\tthrow new Error(SCOPE_MEMBERSHIP_EFFECT_CONFLICT);\n\t}\n}\n\nexport function membershipFromEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n): CoordinatorScopeMembership {\n\tif (\n\t\treceipt.action !== \"grant\" ||\n\t\treceipt.outcome_applied !== 1 ||\n\t\treceipt.role == null ||\n\t\treceipt.status == null ||\n\t\treceipt.membership_epoch == null ||\n\t\treceipt.updated_at == null\n\t) {\n\t\tthrow new Error(\"scope_membership_effect_receipt_invalid\");\n\t}\n\treturn {\n\t\tscope_id: receipt.scope_id,\n\t\tdevice_id: receipt.device_id,\n\t\trole: receipt.role,\n\t\tstatus: receipt.status,\n\t\tmembership_epoch: receipt.membership_epoch,\n\t\tcoordinator_id: receipt.coordinator_id,\n\t\tgroup_id: receipt.group_id,\n\t\tmanifest_issuer_device_id: receipt.manifest_issuer_device_id,\n\t\tmanifest_hash: receipt.manifest_hash,\n\t\tsigned_manifest_json: receipt.signed_manifest_json,\n\t\tupdated_at: receipt.updated_at,\n\t};\n}\n","import type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport type { RecipientReviewedIntentV1 } from \"./recipient-reviewed-intent.js\";\n\n/**\n * Normalize a caller-supplied invite expiry to a canonical UTC ISO-8601\n * (`...Z`) string. Invite lookups filter with a SQL `expires_at > ?` string\n * comparison against `new Date().toISOString()`, which is only correct when\n * stored values share that exact format — a `+00:00` offset or date-only value\n * would compare wrong. Shared by both coordinator store implementations.\n */\nexport function normalizeInviteExpiresAt(value: string): string {\n\tconst trimmed = value.trim();\n\tconst parsed = new Date(trimmed);\n\tif (!trimmed || Number.isNaN(parsed.getTime())) {\n\t\tthrow new Error(\"expiresAt must be a valid date.\");\n\t}\n\treturn parsed.toISOString();\n}\n\nexport interface CoordinatorGroup {\n\tgroup_id: string;\n\tdisplay_name: string | null;\n\tarchived_at: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollment {\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n\tdisplay_name: string | null;\n\tenabled: number;\n\tcreated_at: string;\n\t/** Authenticated presence expiry for this exact group/device enrollment. */\n\tpresence_expires_at?: string;\n\t/** Token-free capabilities from the same authenticated presence record. */\n\tpresence_capabilities?: Record<string, unknown>;\n}\n\nexport interface CoordinatorInvite {\n\tinvite_id: string;\n\tgroup_id: string;\n\ttoken: string;\n\tpolicy: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\tteam_name_snapshot: string | null;\n\trevoked_at: string | null;\n\t/** Null/absent identifies a legacy enrollment invite, which grants no project intent by itself. */\n\toperation_id?: string | null;\n\t/** Digest reference only; the reviewed project set remains server-owned operation state. */\n\treviewed_project_set_digest?: string | null;\n\ttoken_digest?: string | null;\n\tinviter_actor_id?: string | null;\n\tinviter_display_name?: string | null;\n\tinviter_device_id?: string | null;\n\tpending_person_id?: string | null;\n\tproject_summaries_json?: string | null;\n\tproject_intent_json?: string | null;\n\tconsumed_at?: string | null;\n\tbound_device_id?: string | null;\n\tbound_public_key?: string | null;\n\tbound_fingerprint?: string | null;\n\trecipient_actor_id?: string | null;\n\trecipient_display_name?: string | null;\n\trecipient_device_display_name?: string | null;\n\ttrust_state?: string | null;\n\tbootstrap_grant_id?: string | null;\n\t/** Explicit lifecycle kind. Null is retained only for pre-migration rows. */\n\tinvite_kind?: CoordinatorInviteKind | null;\n\t/** Policy Team identifier for team-member invitations; never a coordinator group grant. */\n\tpolicy_team_id?: string | null;\n\t/** Identity fixed by an add-device invitation. */\n\ttarget_identity_id?: string | null;\n\t/** Opaque Identity minted by the coordinator for a Team-member invitation. */\n\tassigned_identity_id?: string | null;\n\t/** Digest of the server-owned preview reviewed before invitation creation. */\n\treviewed_preview_digest?: string | null;\n\t/** Canonical JSON for the inviter-reviewed access intent. */\n\treviewed_intent_json?: string | null;\n}\n\nexport type CoordinatorInviteKind =\n\t| \"legacy_enrollment\"\n\t| \"project_share\"\n\t| \"team_member\"\n\t| \"add_device\";\n\nexport type CoordinatorRecipientInviteKind = Extract<\n\tCoordinatorInviteKind,\n\t\"team_member\" | \"add_device\"\n>;\n\nconst COORDINATOR_ASSIGNED_IDENTITY_PATTERN = /^identity:[A-Za-z0-9_-]{18,24}$/u;\n\nexport function isCoordinatorAssignedIdentityId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue === value.trim() &&\n\t\tCOORDINATOR_ASSIGNED_IDENTITY_PATTERN.test(value)\n\t);\n}\n\nexport function recipientInviteAuthoritativeIdentityId(value: {\n\tkind: CoordinatorRecipientInviteKind;\n\tassigned_identity_id?: unknown;\n\ttarget_identity_id?: unknown;\n}): string {\n\treturn String(\n\t\tvalue.kind === \"team_member\"\n\t\t\t? (value.assigned_identity_id ?? \"\")\n\t\t\t: (value.target_identity_id ?? \"\"),\n\t).trim();\n}\n\nexport interface CoordinatorProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport interface CoordinatorProjectInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\tenrollment: CoordinatorEnrollment;\n\tseed_enrollment: CoordinatorEnrollment | null;\n\tbootstrap_grant: CoordinatorBootstrapGrant | null;\n}\n\nexport type CoordinatorRecipientInviteInspection =\n\t| {\n\t\t\tkind: \"team_member\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\tpolicy_team_id: string;\n\t\t\tassigned_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t }\n\t| {\n\t\t\tkind: \"add_device\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\ttarget_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t };\n\nexport interface CoordinatorRecipientInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\treviewed_intent?: RecipientReviewedIntentV1;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorJoinRequest {\n\trequest_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\ttoken: string;\n\tstatus: string;\n\tcreated_at: string;\n\treviewed_at: string | null;\n\treviewed_by: string | null;\n}\n\nexport interface CoordinatorJoinRequestReviewResult extends CoordinatorJoinRequest {\n\t_no_transition?: boolean;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorReviewJoinRequestBootstrapGrantInput {\n\tseedDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorPresenceRecord {\n\tgroup_id: string;\n\tdevice_id: string;\n\taddresses: string[];\n\texpires_at: string;\n}\n\nexport interface CoordinatorPeerRecord {\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\taddresses: string[];\n\tlast_seen_at: string | null;\n\texpires_at: string | null;\n\tstale: boolean;\n\tcapabilities: Record<string, unknown>;\n}\n\nexport interface CoordinatorReciprocalApproval {\n\trequest_id: string;\n\tgroup_id: string;\n\trequesting_device_id: string;\n\trequested_device_id: string;\n\tstatus: string;\n\tcreated_at: string;\n\tresolved_at: string | null;\n}\n\nexport interface CoordinatorBootstrapGrant {\n\tgrant_id: string;\n\tgroup_id: string;\n\tseed_device_id: string;\n\tworker_device_id: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\trevoked_at: string | null;\n}\n\nexport interface CoordinatorScope {\n\tscope_id: string;\n\tlabel: string;\n\tkind: string;\n\tauthority_type: string;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmembership_epoch: number;\n\tmanifest_hash: string | null;\n\tstatus: string;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\nexport interface CoordinatorScopeMembership {\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string;\n\tstatus: string;\n\tmembership_epoch: number;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string;\n}\n\nexport type CoordinatorScopeMembershipAuditAction = \"grant\" | \"revoke\";\n\nexport interface CoordinatorScopeMembershipAuditEvent {\n\tevent_id: number;\n\teffect_id: string | null;\n\taction: CoordinatorScopeMembershipAuditAction;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string;\n\tmembership_epoch: number;\n\tprevious_role: string | null;\n\tprevious_status: string | null;\n\tprevious_membership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tactor_type: string | null;\n\tactor_id: string | null;\n\tmanifest_hash: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollDeviceInput {\n\tdeviceId: string;\n\tfingerprint: string;\n\tpublicKey: string;\n\tdisplayName?: string | null;\n\t/** Null or omitted means the enrollment has no authoritative issuance binding. */\n\tidentityId?: string | null;\n}\n\nexport interface CoordinatorCreateInviteInput {\n\tgroupId: string;\n\tpolicy: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n\toperationId?: string | null;\n\treviewedProjectSetDigest?: string | null;\n\tinviterActorId?: string | null;\n\tinviterDisplayName?: string | null;\n\tinviterDeviceId?: string | null;\n\tpendingPersonId?: string | null;\n\tprojectSummaries?: CoordinatorProjectInviteSummary[] | null;\n\tprojectIntent?: Array<CoordinatorProjectInviteSummary & { canonical_identity: string }> | null;\n\tinviteKind?: CoordinatorInviteKind | null;\n\tpolicyTeamId?: string | null;\n\ttargetIdentityId?: string | null;\n\treviewedPreviewDigest?: string | null;\n\treviewedIntent?: unknown;\n}\n\nexport interface CoordinatorConsumeProjectInviteInput {\n\ttoken: string;\n\toperationId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientActorId: string;\n\trecipientDisplayName: string;\n\tdeviceDisplayName: string;\n\t/** Runtime-authoritative timestamp used for expiry, binding, and grant creation. */\n\tnow: string;\n}\n\nexport interface CoordinatorInspectRecipientInviteInput {\n\ttoken: string;\n\tnow: string;\n}\n\nexport interface CoordinatorConsumeRecipientInviteInput {\n\ttoken: string;\n\tinviteKind: CoordinatorRecipientInviteKind;\n\tidentityId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientDisplayName?: string | null;\n\tdeviceDisplayName?: string | null;\n\t/** Runtime-authoritative timestamp used for expiry and binding. */\n\tnow: string;\n}\n\nexport interface CoordinatorCreateJoinRequestInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tdisplayName?: string | null;\n\ttoken: string;\n}\n\nexport interface CoordinatorReviewJoinRequestInput {\n\trequestId: string;\n\tapproved: boolean;\n\treviewedBy?: string | null;\n\tbootstrapGrant?: CoordinatorReviewJoinRequestBootstrapGrantInput | null;\n}\n\nexport interface CoordinatorUpsertPresenceInput {\n\tgroupId: string;\n\tdeviceId: string;\n\taddresses: string[];\n\tttlS: number;\n\tcapabilities?: Record<string, unknown> | null;\n}\n\nexport interface CoordinatorCreateReciprocalApprovalInput {\n\tgroupId: string;\n\trequestingDeviceId: string;\n\trequestedDeviceId: string;\n\t/** Complete only this exact pending request in the reverse direction. */\n\texpectedIncomingRequestId?: string;\n}\n\nexport const RECIPROCAL_APPROVAL_REQUEST_CHANGED = \"reciprocal_approval_request_changed\" as const;\n\nexport class CoordinatorReciprocalApprovalRequestChangedError extends Error {\n\treadonly code = RECIPROCAL_APPROVAL_REQUEST_CHANGED;\n\n\tconstructor() {\n\t\tsuper(RECIPROCAL_APPROVAL_REQUEST_CHANGED);\n\t\tthis.name = \"CoordinatorReciprocalApprovalRequestChangedError\";\n\t}\n}\n\nexport interface CoordinatorCreateBootstrapGrantInput {\n\tgroupId: string;\n\tseedDeviceId: string;\n\tworkerDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorCreateScopeInput {\n\tscopeId: string;\n\tlabel: string;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorUpdateScopeInput {\n\t/** Internal sharing-domain identifier (`scope_id`). */\n\tscopeId: string;\n\t/** User-facing Sharing domain label. Omitted fields keep existing metadata. */\n\tlabel?: string | null;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorListScopesInput {\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tstatus?: string | null;\n\tincludeInactive?: boolean;\n}\n\nexport interface CoordinatorGrantScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\trole?: string | null;\n\tmembershipEpoch?: number | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tcoordinatorId?: string | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorRevokeScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorListScopeMembershipAuditInput {\n\tscopeId: string;\n\tdeviceId?: string | null;\n\tlimit?: number | null;\n}\n\nexport interface CoordinatorListReciprocalApprovalsInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tdirection: \"incoming\" | \"outgoing\";\n\tstatus?: string;\n}\n\nexport interface CoordinatorStore {\n\tclose(): Promise<void>;\n\tcreateGroup(groupId: string, displayName?: string | null): Promise<void>;\n\tgetGroup(groupId: string): Promise<CoordinatorGroup | null>;\n\tlistGroups(includeArchived?: boolean): Promise<CoordinatorGroup[]>;\n\trenameGroup(groupId: string, displayName: string): Promise<boolean>;\n\tarchiveGroup(groupId: string, archivedAt?: string): Promise<boolean>;\n\tunarchiveGroup(groupId: string): Promise<boolean>;\n\tenrollDevice(groupId: string, opts: CoordinatorEnrollDeviceInput): Promise<void>;\n\tlistEnrolledDevices(groupId: string, includeDisabled?: boolean): Promise<CoordinatorEnrollment[]>;\n\tgetEnrollment(\n\t\tgroupId: string,\n\t\tdeviceId: string,\n\t\tincludeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment | null>;\n\trenameDevice(groupId: string, deviceId: string, displayName: string): Promise<boolean>;\n\tsetDeviceEnabled(groupId: string, deviceId: string, enabled: boolean): Promise<boolean>;\n\tremoveDevice(groupId: string, deviceId: string): Promise<boolean>;\n\trecordNonce(deviceId: string, nonce: string, createdAt: string): Promise<boolean>;\n\tcleanupNonces(cutoff: string): Promise<void>;\n\tcreateInvite(opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite>;\n\tgetInviteByToken(token: string): Promise<CoordinatorInvite | null>;\n\tgetInviteByTokenForInspection(token: string): Promise<CoordinatorInvite | null>;\n\tinspectRecipientInvite(\n\t\topts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null>;\n\tconsumeProjectInvite(\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance>;\n\tconsumeRecipientInvite(\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance>;\n\tlistInvites(groupId: string): Promise<CoordinatorInvite[]>;\n\tcreateJoinRequest(opts: CoordinatorCreateJoinRequestInput): Promise<CoordinatorJoinRequest>;\n\tlistJoinRequests(groupId: string, status?: string): Promise<CoordinatorJoinRequest[]>;\n\treviewJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null>;\n\tcreateReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval>;\n\tcreateBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant>;\n\tcreateScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope>;\n\tupdateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null>;\n\tlistScopes(opts?: CoordinatorListScopesInput): Promise<CoordinatorScope[]>;\n\tgrantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership>;\n\trevokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean>;\n\tlistScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked?: boolean,\n\t): Promise<CoordinatorScopeMembership[]>;\n\t/**\n\t * List one device's memberships across every scope, ordered by scope_id.\n\t *\n\t * Answers \"which scopes is this device in\" with a single indexed lookup,\n\t * rather than reading every member of every scope one scope at a time.\n\t */\n\tlistDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked?: boolean,\n\t): Promise<CoordinatorScopeMembership[]>;\n\tlistScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]>;\n\tgetBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null>;\n\tlistBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]>;\n\trevokeBootstrapGrant(grantId: string, revokedAt?: string): Promise<boolean>;\n\tlistReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]>;\n\tcreateLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult>;\n\tgetLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null>;\n\tlistLegacyTeamCompletions(groupIds: string[]): Promise<CoordinatorLegacyTeamCompletionRecord[]>;\n\tupsertPresence(opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord>;\n\tlistGroupPeers(groupId: string, requestingDeviceId: string): Promise<CoordinatorPeerRecord[]>;\n}\n\nexport interface CoordinatorBootstrapGrantVerification {\n\tgrant: CoordinatorBootstrapGrant;\n\tworker_enrollment: CoordinatorEnrollment;\n}\n","const MAX_IDENTITY_DISPLAY_LENGTH = 120;\n// Keep machine-shaped cases synchronized with ui/src/lib/identity-presentation.ts.\nconst UUID_NAME = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu;\nconst MACHINE_PREFIX_NAME = /^(?:actor|device|identity|local):\\S+$/iu;\nconst MACHINE_SLUG_NAME = /^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu;\nconst PENDING_PERSON_NAME = /^pending[_-]\\S+$/iu;\nconst HEX_HOSTNAME = /^[a-f0-9]{12,64}$/iu;\nconst HOSTNAME_NAME =\n\t/^(?=.{1,253}$)(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.){2,}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.local)$/iu;\n\nexport interface ProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport function normalizeIdentityDisplayName(value: string, field: string): string {\n\tif ([...value].some((character) => /[\\p{Cc}\\p{Cf}]/u.test(character))) {\n\t\tthrow new Error(`${field}_invalid`);\n\t}\n\tconst normalized = value.replace(/\\s+/gu, \" \").trim();\n\tif (!normalized) throw new Error(`${field}_required`);\n\tif ([...normalized].length > MAX_IDENTITY_DISPLAY_LENGTH) {\n\t\tthrow new Error(`${field}_too_long`);\n\t}\n\treturn normalized;\n}\n\nexport function isHumanPresentationName(value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tlet normalized: string;\n\ttry {\n\t\tnormalized = normalizeIdentityDisplayName(value, \"display_name\");\n\t} catch {\n\t\treturn false;\n\t}\n\treturn ![\n\t\tUUID_NAME,\n\t\tMACHINE_PREFIX_NAME,\n\t\tMACHINE_SLUG_NAME,\n\t\tPENDING_PERSON_NAME,\n\t\tHEX_HOSTNAME,\n\t].some((pattern) => pattern.test(normalized));\n}\n\nexport function normalizeHumanPresentationName(value: string, field: string): string {\n\tconst normalized = normalizeIdentityDisplayName(value, field);\n\tif (!isHumanPresentationName(normalized)) throw new Error(`${field}_invalid`);\n\treturn normalized;\n}\n\nexport function normalizeDeviceDisplayName(value: string, field: string): string {\n\tconst normalized = normalizeIdentityDisplayName(value, field);\n\tif (!HOSTNAME_NAME.test(normalized) && !isHumanPresentationName(normalized)) {\n\t\tthrow new Error(`${field}_invalid`);\n\t}\n\treturn normalized;\n}\n\nexport function normalizeDeviceNameHint(value: string | null | undefined): string | null {\n\tconst candidate = String(value ?? \"\").trim();\n\tconst raw = candidate.replace(/\\.local$/iu, \"\");\n\tif (!raw) return null;\n\tconst normalized = HOSTNAME_NAME.test(candidate) ? raw : raw.replace(/[-_]+/gu, \" \");\n\treturn normalizeDeviceDisplayName(normalized, \"device_display_name\");\n}\n\nexport function friendlyDeviceName(input: {\n\texplicitName?: string | null;\n\tosName?: string | null;\n\tcoordinatorName?: string | null;\n\tfallbackSeed?: string | null;\n}): string {\n\tfor (const candidate of [input.explicitName, input.osName, input.coordinatorName]) {\n\t\tconst candidateText = String(candidate ?? \"\").trim();\n\t\tconst raw = candidateText.replace(/\\.local$/iu, \"\");\n\t\t// Classify before separator normalization so UUIDs and machine slugs cannot\n\t\t// be disguised as human labels by replacing hyphens or underscores.\n\t\tif (HOSTNAME_NAME.test(candidateText)) {\n\t\t\ttry {\n\t\t\t\tconst normalized = normalizeDeviceNameHint(candidateText);\n\t\t\t\tif (normalized) return normalized;\n\t\t\t} catch {\n\t\t\t\t// Unusable automatic hints must degrade to the generated fallback.\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!raw || !isHumanPresentationName(raw)) continue;\n\t\ttry {\n\t\t\tconst normalized = normalizeDeviceNameHint(candidate);\n\t\t\tif (normalized && isHumanPresentationName(normalized)) return normalized;\n\t\t} catch {\n\t\t\t// Unusable automatic hints must degrade to the generated fallback.\n\t\t}\n\t}\n\tconst seed = String(input.fallbackSeed ?? \"\")\n\t\t.replace(/[^a-z0-9]/giu, \"\")\n\t\t.slice(0, 6);\n\treturn seed ? `Codemem device ${seed}` : \"Codemem device\";\n}\n\nexport function normalizeProjectInviteSummaries(value: unknown): ProjectInviteSummary[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"project_summaries_invalid\");\n\t}\n\treturn value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (\n\t\t\t!Number.isSafeInteger(record.existing_memory_count) ||\n\t\t\tNumber(record.existing_memory_count) < 0\n\t\t) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tdisplay_name: normalizeIdentityDisplayName(String(record.display_name ?? \"\"), \"project_name\"),\n\t\t\texisting_memory_count: Number(record.existing_memory_count),\n\t\t};\n\t});\n}\n","import { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\n\nexport const RECIPIENT_REVIEWED_INTENT_VERSION = 1 as const;\n\nexport type RecipientReviewedIntentProjectSourceV1 =\n\t| { kind: \"direct\" }\n\t| { kind: \"team\"; teamId: string; displayName: string };\n\nexport interface RecipientReviewedIntentProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n\tfutureMemoriesShared: true;\n\tsources: RecipientReviewedIntentProjectSourceV1[];\n}\n\nexport interface RecipientReviewedIntentExcludedProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n}\n\ninterface RecipientReviewedIntentBaseV1 {\n\tversion: 1;\n\tprojects: RecipientReviewedIntentProjectV1[];\n\texcludedProjects: RecipientReviewedIntentExcludedProjectV1[];\n}\n\nexport type RecipientReviewedIntentV1 =\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"team\";\n\t\t\tteam: { teamId: string; displayName: string; futureProjectsInherit: true };\n\t })\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"add_device\";\n\t\t\ttargetIdentity: { identityId: string; displayName: string };\n\t });\n\nexport type RecipientReviewedIntentTargetV1 =\n\t| { kind: \"team_member\"; policyTeamId: string }\n\t| { kind: \"add_device\"; targetIdentityId: string };\n\nexport class RecipientReviewedIntentError extends Error {\n\treadonly code: \"recipient_reviewed_intent_invalid\" | \"recipient_invite_intent_mismatch\";\n\n\tconstructor(code: RecipientReviewedIntentError[\"code\"]) {\n\t\tsuper(code);\n\t\tthis.name = \"RecipientReviewedIntentError\";\n\t\tthis.code = code;\n\t}\n}\n\nconst CONTROL_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\nconst MAX_PROJECTS = 100;\nconst MAX_CANONICAL_BYTES = 64 * 1024;\n\nfunction invalid(): never {\n\tthrow new RecipientReviewedIntentError(\"recipient_reviewed_intent_invalid\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) invalid();\n\treturn value as Record<string, unknown>;\n}\n\nfunction assertKeys(value: Record<string, unknown>, keys: readonly string[]): void {\n\tif (Object.keys(value).some((key) => !keys.includes(key))) invalid();\n}\n\nfunction strictText(value: unknown, maxLength: number): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue !== value.trim() ||\n\t\tvalue.length > maxLength ||\n\t\tCONTROL_CHARACTER.test(value)\n\t) {\n\t\tinvalid();\n\t}\n\treturn value;\n}\n\nfunction displayName(value: unknown): string {\n\tif (typeof value !== \"string\" || CONTROL_CHARACTER.test(value)) invalid();\n\tconst normalized = value.trim().replace(/\\s+/gu, \" \");\n\tif (!normalized || normalized.length > 256) invalid();\n\treturn normalized;\n}\n\nfunction identityDisplayName(value: unknown): string {\n\tif (typeof value !== \"string\") invalid();\n\ttry {\n\t\treturn normalizeIdentityDisplayName(value, \"identity_display_name\");\n\t} catch {\n\t\treturn invalid();\n\t}\n}\n\nfunction memoryCount(value: unknown): number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) invalid();\n\treturn value;\n}\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction sourceKey(source: RecipientReviewedIntentProjectSourceV1): string {\n\treturn source.kind === \"direct\" ? \"direct\" : `team\\u0000${source.teamId}`;\n}\n\nfunction normalizeSource(value: unknown): RecipientReviewedIntentProjectSourceV1 {\n\tconst input = record(value);\n\tif (input.kind === \"direct\") {\n\t\tassertKeys(input, [\"kind\"]);\n\t\treturn { kind: \"direct\" };\n\t}\n\tif (input.kind !== \"team\") invalid();\n\tassertKeys(input, [\"kind\", \"teamId\", \"displayName\"]);\n\treturn {\n\t\tkind: \"team\",\n\t\tteamId: strictText(input.teamId, 256),\n\t\tdisplayName: displayName(input.displayName),\n\t};\n}\n\nfunction normalizeProject(value: unknown): RecipientReviewedIntentProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\n\t\t\"canonicalProjectIdentity\",\n\t\t\"displayName\",\n\t\t\"existingMemoryCount\",\n\t\t\"futureMemoriesShared\",\n\t\t\"sources\",\n\t]);\n\tif (\n\t\tinput.futureMemoriesShared !== true ||\n\t\t!Array.isArray(input.sources) ||\n\t\t!input.sources.length\n\t) {\n\t\tinvalid();\n\t}\n\tconst sources = input.sources\n\t\t.map(normalizeSource)\n\t\t.toSorted((left, right) => compareText(sourceKey(left), sourceKey(right)));\n\tif (new Set(sources.map(sourceKey)).size !== sources.length) invalid();\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t\tfutureMemoriesShared: true,\n\t\tsources,\n\t};\n}\n\nfunction normalizeExcludedProject(value: unknown): RecipientReviewedIntentExcludedProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\"canonicalProjectIdentity\", \"displayName\", \"existingMemoryCount\"]);\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t};\n}\n\nfunction normalizeProjectLists(\n\tinput: Record<string, unknown>,\n): Pick<RecipientReviewedIntentBaseV1, \"projects\" | \"excludedProjects\"> {\n\tif (\n\t\t!Array.isArray(input.projects) ||\n\t\t!Array.isArray(input.excludedProjects) ||\n\t\tinput.projects.length > MAX_PROJECTS\n\t) {\n\t\tinvalid();\n\t}\n\tconst projects = input.projects\n\t\t.map(normalizeProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst excludedProjects = input.excludedProjects\n\t\t.map(normalizeExcludedProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst includedIds = projects.map((project) => project.canonicalProjectIdentity);\n\tconst excludedIds = excludedProjects.map((project) => project.canonicalProjectIdentity);\n\tif (\n\t\tnew Set(includedIds).size !== includedIds.length ||\n\t\tnew Set(excludedIds).size !== excludedIds.length ||\n\t\texcludedIds.some((projectId) => includedIds.includes(projectId))\n\t) {\n\t\tinvalid();\n\t}\n\treturn { projects, excludedProjects };\n}\n\nfunction assertTarget(\n\tintent: RecipientReviewedIntentV1,\n\ttarget: RecipientReviewedIntentTargetV1,\n): void {\n\tconst matches =\n\t\t(intent.journey === \"team\" &&\n\t\t\ttarget.kind === \"team_member\" &&\n\t\t\tintent.team.teamId === target.policyTeamId) ||\n\t\t(intent.journey === \"add_device\" &&\n\t\t\ttarget.kind === \"add_device\" &&\n\t\t\tintent.targetIdentity.identityId === target.targetIdentityId);\n\tif (!matches) throw new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n}\n\nexport function normalizeRecipientReviewedIntent(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): RecipientReviewedIntentV1 {\n\tconst input = record(value);\n\tif (input.version !== RECIPIENT_REVIEWED_INTENT_VERSION) invalid();\n\tconst projectLists = normalizeProjectLists(input);\n\tlet intent: RecipientReviewedIntentV1;\n\tif (input.journey === \"team\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"team\", \"projects\", \"excludedProjects\"]);\n\t\tconst team = record(input.team);\n\t\tassertKeys(team, [\"teamId\", \"displayName\", \"futureProjectsInherit\"]);\n\t\tif (team.futureProjectsInherit !== true) invalid();\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tteam: {\n\t\t\t\tteamId: strictText(team.teamId, 256),\n\t\t\t\tdisplayName: displayName(team.displayName),\n\t\t\t\tfutureProjectsInherit: true,\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else if (input.journey === \"add_device\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"targetIdentity\", \"projects\", \"excludedProjects\"]);\n\t\tconst identity = record(input.targetIdentity);\n\t\tassertKeys(identity, [\"identityId\", \"displayName\"]);\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"add_device\",\n\t\t\ttargetIdentity: {\n\t\t\t\tidentityId: strictText(identity.identityId, 256),\n\t\t\t\tdisplayName: identityDisplayName(identity.displayName),\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else {\n\t\tinvalid();\n\t}\n\tif (target) assertTarget(intent, target);\n\tif (new TextEncoder().encode(canonicalJson(intent)).byteLength > MAX_CANONICAL_BYTES) invalid();\n\treturn intent;\n}\n\nfunction canonicalJson(value: unknown): string {\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n\tif (value && typeof value === \"object\") {\n\t\treturn `{${Object.entries(value as Record<string, unknown>)\n\t\t\t.toSorted(([left], [right]) => compareText(left, right))\n\t\t\t.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`)\n\t\t\t.join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value) ?? \"null\";\n}\n\nexport function canonicalRecipientReviewedIntentJson(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): string {\n\treturn canonicalJson(normalizeRecipientReviewedIntent(value, target));\n}\n\nexport async function recipientReviewedIntentDigest(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): Promise<string> {\n\tconst canonical = canonicalRecipientReviewedIntentJson(value, target);\n\tconst bytes = new TextEncoder().encode(`recipient-reviewed-intent-v1\\n${canonical}`);\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function verifyRecipientReviewedIntent(\n\tvalue: unknown,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tconst normalized = normalizeRecipientReviewedIntent(value, options.target);\n\tif ((await recipientReviewedIntentDigest(normalized)) !== options.digest) {\n\t\tthrow new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n\t}\n\treturn normalized;\n}\n\nexport async function parseStoredRecipientReviewedIntent(\n\tjson: string | null | undefined,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tif (!json) throw new Error(\"recipient_invite_review_unavailable\");\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(json);\n\t} catch {\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n\ttry {\n\t\tconst normalized = normalizeRecipientReviewedIntent(parsed, options.target);\n\t\tif (canonicalJson(normalized) !== json) {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn await verifyRecipientReviewedIntent(normalized, options);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (error instanceof Error && error.message === \"recipient_invite_review_unavailable\") {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n}\n","import { createHash } from \"node:crypto\";\n\n/** SHA-256 hex digest of a public key string. */\nexport function fingerprintPublicKey(publicKey: string): string {\n\treturn createHash(\"sha256\").update(publicKey, \"utf-8\").digest(\"hex\");\n}\n","// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n","// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n","// src/utils/buffer.ts\nimport { sha256 } from \"./crypto.js\";\nvar equal = (a, b) => {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n const va = new DataView(a);\n const vb = new DataView(b);\n let i = va.byteLength;\n while (i--) {\n if (va.getUint8(i) !== vb.getUint8(i)) {\n return false;\n }\n }\n return true;\n};\nvar constantTimeEqualString = (a, b) => {\n const aLen = a.length;\n const bLen = b.length;\n const maxLen = Math.max(aLen, bLen);\n let out = aLen ^ bLen;\n for (let i = 0; i < maxLen; i++) {\n const aChar = i < aLen ? a.charCodeAt(i) : 0;\n const bChar = i < bLen ? b.charCodeAt(i) : 0;\n out |= aChar ^ bChar;\n }\n return out === 0;\n};\nvar timingSafeEqualString = async (a, b, hashFunction) => {\n if (!hashFunction) {\n hashFunction = sha256;\n }\n const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n if (sa == null || sb == null || typeof sa !== \"string\" || typeof sb !== \"string\") {\n return false;\n }\n const hashEqual = constantTimeEqualString(sa, sb);\n const originalEqual = constantTimeEqualString(a, b);\n return hashEqual && originalEqual;\n};\nvar timingSafeEqual = async (a, b, hashFunction) => {\n if (typeof a === \"string\" && typeof b === \"string\") {\n return timingSafeEqualString(a, b, hashFunction);\n }\n if (!hashFunction) {\n hashFunction = sha256;\n }\n const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n if (!sa || !sb || typeof sa !== \"string\" || typeof sb !== \"string\") {\n return false;\n }\n return timingSafeEqualString(sa, sb);\n};\nvar bufferToString = (buffer) => {\n if (buffer instanceof ArrayBuffer) {\n const enc = new TextDecoder(\"utf-8\");\n return enc.decode(buffer);\n }\n return buffer;\n};\nvar bufferToFormData = (arrayBuffer, contentType) => {\n const response = new Response(arrayBuffer, {\n headers: {\n // Normalize the media type (case-insensitive) while keeping parameters like the boundary\n \"Content-Type\": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase())\n }\n });\n return response.formData();\n};\nexport {\n bufferToFormData,\n bufferToString,\n equal,\n timingSafeEqual\n};\n","// src/utils/body.ts\nimport { bufferToFormData } from \"./buffer.js\";\nvar MAX_NESTING_DEPTH = 32;\nvar MAX_NESTED_OBJECTS = 1e4;\nvar isRawRequest = (request) => \"headers\" in request;\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = isRawRequest(request) ? request.headers : request.raw.headers;\n const contentType = headers.get(\"Content-Type\");\n const mediaType = contentType?.split(\";\")[0].trim().toLowerCase();\n if (mediaType === \"multipart/form-data\" || mediaType === \"application/x-www-form-urlencoded\") {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n if (!isRawRequest(request) && request.bodyCache.formData) {\n return convertFormDataToBodyData(\n await request.bodyCache.formData,\n options\n );\n }\n const headers = isRawRequest(request) ? request.headers : request.raw.headers;\n const arrayBuffer = await request.arrayBuffer();\n const formDataPromise = bufferToFormData(arrayBuffer, headers.get(\"Content-Type\") || \"\");\n if (!isRawRequest(request)) {\n request.bodyCache.formData = formDataPromise;\n }\n const formData = await formDataPromise;\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n const nestingState = { count: 0 };\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value, nestingState);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value, state) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\", MAX_NESTING_DEPTH + 2);\n if (keys.length > MAX_NESTING_DEPTH + 1) {\n throwNestingLimitExceeded();\n }\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n if (state.count++ >= MAX_NESTED_OBJECTS) {\n throwNestingLimitExceeded();\n }\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nvar throwNestingLimitExceeded = () => {\n throw new Error(\"Nesting limit exceeded\");\n};\nexport {\n parseBody\n};\n","// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n if (queryIndex === -1) {\n return \"\";\n }\n const hashIndex = url.indexOf(\"#\", 8);\n return hashIndex === -1 ? url.slice(queryIndex) : queryIndex < hashIndex ? url.slice(queryIndex, hashIndex) : \"\";\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (segment.charCodeAt(segment.length - 1) === 63) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.slice(0, -1);\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar tryDecodeURIComponent = (str) => str.indexOf(\"%\") !== -1 ? tryDecode(str, decodeURIComponent_) : str;\nvar _decodeURI = (value) => {\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return tryDecodeURIComponent(value);\n};\nvar _getQueryParam = (url, key, multiple) => {\n const hashIndex = url.indexOf(\"#\", 8);\n if (hashIndex !== -1) {\n url = url.slice(0, hashIndex);\n }\n let encoded;\n if (!multiple && key && key.indexOf(\"%\") === -1 && key.indexOf(\"+\") === -1) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = /* @__PURE__ */ Object.create(null);\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI,\n tryDecodeURIComponent\n};\n","// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { getQueryParam, getQueryParams, tryDecodeURIComponent } from \"./utils/url.js\";\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];\n const param = this.#getParamValue(paramKey);\n return param && tryDecodeURIComponent(param);\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = tryDecodeURIComponent(value);\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = /* @__PURE__ */ Object.create(null);\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n for (const anyCachedKey in bodyCache) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * `.bytes()` parses the request body as a `Uint8Array`.\n *\n * @see {@link https://hono.dev/docs/api/request#bytes}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.bytes()\n * })\n * ```\n */\n bytes() {\n return this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n ;\n (this.#validatedData ??= {})[target] = data;\n }\n valid(target) {\n return this.#validatedData?.[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n let body = await req[cacheKey]();\n const headers = req.header();\n if (cacheKey === \"json\") {\n body = JSON.stringify(body);\n delete headers[\"content-length\"];\n } else if (body instanceof FormData) {\n delete headers[\"content-type\"];\n delete headers[\"content-length\"];\n }\n const requestInit = {\n body,\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers,\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * <html>\n * <body>\n * <p>{content}</p>\n * </body>\n * </html>\n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * // Append multiple headers using the append option (e.g. Vary)\n * c.header('Vary', 'Accept-Encoding', { append: true })\n * c.header('Vary', 'User-Agent', { append: true })\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;\n if (typeof arg === \"object\" && arg.headers) {\n responseHeaders ??= new Headers();\n for (const [key, value] of new Headers(arg.headers)) {\n if (key === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n if (!responseHeaders) {\n let count = 0;\n for (const k in headers) {\n if (++count > 1 || typeof headers[k] !== \"string\") {\n responseHeaders = new Headers();\n break;\n }\n }\n }\n if (responseHeaders) {\n for (const k in headers) {\n const v = headers[k];\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, {\n status,\n headers: responseHeaders ?? headers\n });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n","// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\", \"query\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n","// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n","// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n query;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler, r.basePath);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = this.getPath(request).slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler, baseRoutePath) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = {\n basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n path,\n method,\n handler\n };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} env - env Object\n * @param {ExecutionContext} executionCtx - context of execution\n * @returns {Response | Promise<Response>} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n","// src/router/utils.ts\nvar createNullObject = () => /* @__PURE__ */ Object.create(null);\nexport {\n createNullObject\n};\n","// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n","// src/router/reg-exp-router/node.ts\nimport { createNullObject } from \"../utils.js\";\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n // handler index of a dynamic path, or -1 for a static path terminal\n #index;\n #varIndex;\n #children = createNullObject();\n insert(tokens, index, paramMap, context, isStatic) {\n let node = this;\n for (let i = 0, len = tokens.length; i < len; i++) {\n const token = tokens[i];\n const pattern = token.length === 1 ? token === \"*\" ? i === len - 1 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : null : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let nextNode;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n nextNode = node.#children[regexpStr];\n if (!nextNode) {\n if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {\n for (const k in node.#children) {\n if (\n // a single-char pattern coexists with single-char literals as a literal does\n (regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n ) {\n throw PATH_ERROR;\n }\n }\n }\n nextNode = node.#children[regexpStr] = new _Node();\n }\n if (name !== \"\") {\n nextNode.#varIndex ??= context.varIndex++;\n paramMap.push([name, nextNode.#varIndex]);\n }\n } else {\n nextNode = node.#children[token];\n if (!nextNode) {\n for (const k in node.#children) {\n if (k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) {\n throw PATH_ERROR;\n }\n }\n nextNode = node.#children[token] = new _Node();\n }\n }\n node = nextNode;\n }\n if (node.#index !== void 0) {\n throw PATH_ERROR;\n }\n node.#index = isStatic ? -1 : index;\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n const childStr = c.buildRegExpStr();\n return childStr === \"\" ? \"\" : (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + childStr;\n }).filter(Boolean);\n if (typeof this.#index === \"number\" && this.#index !== -1) {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n LABEL_REG_EXP_STR,\n Node,\n ONLY_WILDCARD_REG_EXP_STR,\n PATH_ERROR,\n TAIL_WILDCARD_REG_EXP_STR\n};\n","// src/router/reg-exp-router/trie.ts\nimport { createNullObject } from \"../utils.js\";\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n #index = 0;\n // dynamic path -> [handler index, param assoc]; static paths are not registered\n paths = createNullObject();\n insert(path, isStatic) {\n if (isStatic) {\n this.#root.insert(path.split(\"\"), 0, [], this.#context, true);\n return;\n }\n const paramAssoc = [];\n const groups = [];\n let markedPath = path;\n for (let i = 0; ; ) {\n let replaced = false;\n markedPath = markedPath.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = markedPath.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);\n this.paths[path] = [this.#index++, paramAssoc];\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n","// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { createNullObject } from \"../utils.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport {\n LABEL_REG_EXP_STR,\n ONLY_WILDCARD_REG_EXP_STR,\n PATH_ERROR,\n TAIL_WILDCARD_REG_EXP_STR\n} from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar wildcardRegExpCache = createNullObject();\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n `^${path.replace(\n /\\/:[^/{}]+(?:\\{\\[\\^\\/]\\+})?(?=[/{]|$)|\\/?\\*$|([.\\\\+*[^\\]$()?{}|])/g,\n (match2, metaChar) => metaChar ? `\\\\${metaChar}` : match2 === \"/*\" ? TAIL_WILDCARD_REG_EXP_STR : match2 === \"*\" ? ONLY_WILDCARD_REG_EXP_STR : `/:${LABEL_REG_EXP_STR}`\n )}$`\n );\n}\nfunction findMiddleware(middleware, path) {\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n #tries;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: createNullObject() };\n this.#routes = { [METHOD_NAME_ALL]: createNullObject() };\n this.#tries = { [METHOD_NAME_ALL]: new Trie() };\n }\n #insertPath(method, path) {\n try {\n this.#tries[method].insert(path, !/\\*|\\/:/.test(path));\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n this.#tries[method] = new Trie();\n for (const handlerMap of [middleware, routes]) {\n handlerMap[method] = createNullObject();\n for (const p in handlerMap[METHOD_NAME_ALL]) {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n this.#insertPath(method, p);\n }\n }\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method];\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n for (const m of methods) {\n if (!middleware[m][path]) {\n this.#insertPath(m, path);\n middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n }\n for (const handlerMap of [middleware, routes]) {\n for (const m of methods) {\n for (const p in handlerMap[m]) {\n re.test(p) && handlerMap[m][p].push([handler, path]);\n }\n }\n }\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (const path2 of paths) {\n for (const m of methods) {\n if (!routes[m][path2]) {\n this.#insertPath(m, path2);\n routes[m][path2] = findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [];\n }\n routes[m][path2].push([handler, path2]);\n }\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = createNullObject();\n for (const method of Object.keys(this.#routes)) {\n matchers[method] = this.#buildMatcher(method);\n }\n this.#middleware = this.#routes = this.#tries = void 0;\n wildcardRegExpCache = createNullObject();\n return matchers;\n }\n #buildMatcher(method) {\n const middleware = this.#middleware[method];\n const routes = this.#routes[method];\n const trie = this.#tries[method];\n const staticMap = createNullObject();\n const handlerData = [];\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (const r of [middleware, routes]) {\n for (const path in r) {\n const handlers = r[path];\n const pathData = trie.paths[path];\n if (!pathData) {\n staticMap[path] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];\n continue;\n }\n handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [\n h,\n trie.paths[handlerPath][1].reduceRight((map, [key], i) => {\n map[key] = paramReplacementMap[pathData[1][i][1]];\n return map;\n }, createNullObject())\n ]);\n }\n }\n return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap];\n }\n};\nexport {\n RegExpRouter\n};\n","// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n","// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nimport { createNullObject } from \"../utils.js\";\nvar emptyParams = createNullObject();\nvar order = 0;\nvar Node = class _Node {\n #methods = [];\n #children = createNullObject();\n #patterns = [];\n #pattern;\n #params = emptyParams;\n insert(method, path, handler) {\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = /* @__PURE__ */ new Set();\n let i = 0;\n for (const p of parts) {\n const nextP = parts[++i];\n const pattern = getPattern(p, nextP) || (nextP === void 0 && p && p.indexOf(\"*\") === p.length - 1 ? p : null);\n const isParam = Array.isArray(pattern);\n const key = isParam ? pattern[0] : pattern || p;\n const child = curNode.#children[key] ||= new _Node();\n if (pattern && !child.#pattern) {\n child.#pattern = pattern;\n curNode.#patterns.push(child);\n }\n curNode = child;\n if (isParam) {\n possibleKeys.add(pattern[1]);\n }\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: [...possibleKeys],\n score: ++order\n }\n });\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n if (handlerSet) {\n handlerSet.params = createNullObject();\n handlerSets.push(handlerSet);\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (const child of node.#patterns) {\n const pattern = child.#pattern;\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (typeof pattern === \"string\") {\n if (pattern === \"*\" || part.startsWith(pattern.slice(0, -1))) {\n this.#pushHandlerSets(handlerSets, child, method, node.#params);\n if (pattern === \"*\") {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n continue;\n }\n const [, name, matcher] = pattern;\n if (!part && matcher === true) {\n continue;\n }\n if (matcher !== true) {\n if (!partOffsets) {\n partOffsets = [];\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.slice(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (m[0].length === restPathString.length && child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n node.#params,\n params\n );\n }\n for (const _ in child.#children) {\n child.#params = params;\n const componentCount = m[0].match(/\\//g)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n break;\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets[1]) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n","// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node = new Node();\n add(method, path, handler) {\n for (const result of checkOptionalParameter(path) || [path]) {\n this.#node.insert(method, result, handler);\n }\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n","// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n","/**\n * Invite link encoding/decoding for the coordinator join flow.\n *\n * Ported from codemem/coordinator_invites.py.\n */\n\nexport interface InvitePayload {\n\tv: number;\n\tkind: \"coordinator_team_invite\" | \"team_member\" | \"add_device\" | string;\n\tcoordinator_url: string;\n\tgroup_id: string;\n\tpolicy: string;\n\ttoken: string;\n\texpires_at: string;\n\tteam_name: string | null;\n\t/** Present only for project-first invites. All values are display-only; access intent stays coordinator-owned. */\n\toperation_id?: string;\n\tinviter_name?: string | null;\n\tinviter_device_id?: string;\n\tproject_summaries?: Array<{ display_name: string; existing_memory_count: number }>;\n\t/** Policy metadata for recipient-aware invites. It is preview-only and never grants scope access. */\n\tpolicy_team_id?: string;\n\ttarget_identity_id?: string;\n\tassigned_identity_id?: string;\n\treviewed_preview_digest?: string;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) binary += String.fromCharCode(byte);\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n\tconst binary = atob(base64);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let index = 0; index < binary.length; index += 1) {\n\t\tbytes[index] = binary.charCodeAt(index);\n\t}\n\treturn bytes;\n}\n\nfunction toBase64Url(base64: string): string {\n\treturn base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(value: string): string {\n\tconst padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\treturn padded + \"=\".repeat((4 - (padded.length % 4)) % 4);\n}\n\n/** Encode an invite payload as a compact base64url string (no padding). */\nexport function encodeInvitePayload(payload: InvitePayload): string {\n\tconst json = JSON.stringify(payload);\n\tconst bytes = new TextEncoder().encode(json);\n\treturn toBase64Url(bytesToBase64(bytes));\n}\n\n/** Decode a base64url invite payload string back to an InvitePayload. */\nexport function decodeInvitePayload(value: string): InvitePayload {\n\tconst json = new TextDecoder().decode(base64ToBytes(fromBase64Url(value)));\n\tconst data: unknown = JSON.parse(json);\n\tif (typeof data !== \"object\" || data === null) {\n\t\tthrow new Error(\"invalid invite payload\");\n\t}\n\treturn data as InvitePayload;\n}\n\n/** Build a `codemem://join?invite=...` link from an encoded payload. */\nexport function inviteLink(encodedPayload: string): string {\n\treturn `codemem://join?invite=${encodeURIComponent(encodedPayload)}`;\n}\n\n/**\n * Extract the raw encoded payload from either a `codemem://` link or a raw value.\n *\n * Throws if a `codemem://` link is provided but has no `invite` query parameter.\n */\nexport function extractInvitePayload(value: string): string {\n\tconst raw = value.trim();\n\tif (raw.startsWith(\"codemem://\")) {\n\t\tconst url = new URL(raw);\n\t\tconst invite = url.searchParams.get(\"invite\") ?? \"\";\n\t\tif (!invite) {\n\t\t\tthrow new Error(\"invite payload missing from link\");\n\t\t}\n\t\treturn invite;\n\t}\n\treturn raw;\n}\n","export const PROJECT_INVITE_PENDING_STATUS = \"pending_setup\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILED = \"project_sync_enablement_failed\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL =\n\t\"Invitation was accepted, but sync could not be enabled. Make the codemem config writable, then retry.\";\n\nexport class ProjectSyncEnablementError extends Error {\n\treadonly code = PROJECT_SYNC_ENABLEMENT_FAILED;\n\treadonly detail = PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL;\n\n\tconstructor(options?: ErrorOptions) {\n\t\tsuper(PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL, options);\n\t\tthis.name = \"ProjectSyncEnablementError\";\n\t}\n}\n\nexport function isProjectSyncEnablementError(error: unknown): error is ProjectSyncEnablementError {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\terror.code === PROJECT_SYNC_ENABLEMENT_FAILED &&\n\t\t\"detail\" in error &&\n\t\terror.detail === PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL\n\t);\n}\n","import { createHash } from \"node:crypto\";\nimport { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\nimport { canonicalWorkspaceIdentity } from \"./scope-resolution.js\";\n\nexport const SHARE_HISTORY_POLICY = \"existing_and_future\" as const;\n\nexport interface ShareProjectIntent {\n\tcanonicalIdentity: string;\n\tdisplayName: string;\n\tidentitySource: string;\n\texistingMemoryCount: number;\n}\n\nexport interface AcceptedProjectIntent {\n\tcanonical_identity: string;\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nfunction digest(value: unknown): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\n\nexport function shareProjectSetDigest(projects: ShareProjectIntent[]): string {\n\tconst reviewedProjects = projects\n\t\t.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonicalIdentity,\n\t\t\texistingMemoryCount: project.existingMemoryCount,\n\t\t}))\n\t\t.toSorted((left, right) => left.canonicalIdentity.localeCompare(right.canonicalIdentity));\n\treturn digest({ v: 1, historyPolicy: SHARE_HISTORY_POLICY, projects: reviewedProjects });\n}\n\nexport function acceptedProjectIntentDigest(projects: AcceptedProjectIntent[]): string {\n\treturn shareProjectSetDigest(\n\t\tprojects.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonical_identity,\n\t\t\tdisplayName: project.display_name,\n\t\t\tidentitySource: \"coordinator_acceptance\",\n\t\t\texistingMemoryCount: project.existing_memory_count,\n\t\t})),\n\t);\n}\n\nexport function parseAcceptedProjectIntent(value: unknown): AcceptedProjectIntent[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\tconst projects = value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (typeof record.canonical_identity !== \"string\" || typeof record.display_name !== \"string\") {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst canonicalIdentityRaw = record.canonical_identity;\n\t\tconst canonicalIdentity = canonicalIdentityRaw.trim();\n\t\tconst displayNameRaw = record.display_name;\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeIdentityDisplayName(displayNameRaw, \"project_name\");\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst count = record.existing_memory_count;\n\t\tconst canonicalIdentityRoundTrip = canonicalWorkspaceIdentity({\n\t\t\tgitRemote: canonicalIdentity,\n\t\t}).value;\n\t\tif (\n\t\t\t!canonicalIdentity ||\n\t\t\tcanonicalIdentity !== canonicalIdentityRaw ||\n\t\t\tcanonicalIdentity.length > 2048 ||\n\t\t\tcanonicalIdentity.startsWith(\"unmapped:\") ||\n\t\t\tcanonicalIdentityRoundTrip !== canonicalIdentity ||\n\t\t\tdisplayName !== displayNameRaw ||\n\t\t\t!Number.isSafeInteger(count) ||\n\t\t\tNumber(count) < 0 ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(canonicalIdentity) ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(displayName)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tcanonical_identity: canonicalIdentity,\n\t\t\tdisplay_name: displayName,\n\t\t\texisting_memory_count: Number(count),\n\t\t};\n\t});\n\tif (new Set(projects.map((project) => project.canonical_identity)).size !== projects.length) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\treturn projects.toSorted((left, right) =>\n\t\tleft.canonical_identity.localeCompare(right.canonical_identity),\n\t);\n}\n","// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nfunction hrtime(previousTimestamp) {\n const clocktime = performance.now() * 1e-3;\n let seconds = Math.floor(clocktime);\n let nanoseconds = Math.floor((clocktime % 1) * 1e9);\n if (previousTimestamp != undefined) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds, nanoseconds];\n}\n// The current timestamp in whole milliseconds\nexport function getMilliseconds() {\n const [seconds, nanoseconds] = hrtime();\n return seconds * 1e3 + Math.floor(nanoseconds / 1e6);\n}\n// Wait for a specified number of milliseconds before fulfilling the returned promise.\nexport function wait(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n//# sourceMappingURL=clock.js.map","import { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A hierarchical token bucket for rate limiting. See\n * http://en.wikipedia.org/wiki/Token_bucket for more information.\n *\n * @param options\n * @param options.bucketSize Maximum number of tokens to hold in the bucket.\n * Also known as the burst rate.\n * @param options.tokensPerInterval Number of tokens to drip into the bucket\n * over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.parentBucket Optional. A token bucket that will act as\n * the parent of this bucket.\n */\nexport class TokenBucket {\n bucketSize;\n tokensPerInterval;\n interval;\n parentBucket;\n content;\n lastDrip;\n constructor({ bucketSize, tokensPerInterval, interval, parentBucket }) {\n this.bucketSize = bucketSize;\n this.tokensPerInterval = tokensPerInterval;\n if (typeof interval === \"string\") {\n switch (interval) {\n case \"sec\":\n case \"second\":\n this.interval = 1000;\n break;\n case \"min\":\n case \"minute\":\n this.interval = 1000 * 60;\n break;\n case \"hr\":\n case \"hour\":\n this.interval = 1000 * 60 * 60;\n break;\n case \"day\":\n this.interval = 1000 * 60 * 60 * 24;\n break;\n default:\n throw new Error(\"Invalid interval \" + interval);\n }\n }\n else {\n this.interval = interval;\n }\n this.parentBucket = parentBucket;\n this.content = 0;\n this.lastDrip = getMilliseconds();\n }\n /**\n * Remove the requested number of tokens. If the bucket (and any parent\n * buckets) contains enough tokens this will happen immediately. Otherwise,\n * the removal will happen when enough tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Is this an infinite size bucket?\n if (this.bucketSize === 0) {\n return Number.POSITIVE_INFINITY;\n }\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds bucket size ${this.bucketSize}`);\n }\n // Drip new tokens into this bucket\n this.drip();\n const comeBackLater = async () => {\n // How long do we need to wait to make up the difference in tokens?\n const waitMs = Math.ceil((count - this.content) * (this.interval / this.tokensPerInterval));\n await wait(waitMs);\n return this.removeTokens(count);\n };\n // If we don't have enough tokens in this bucket, come back later\n if (count > this.content)\n return comeBackLater();\n if (this.parentBucket != undefined) {\n // Remove the requested from the parent bucket first\n const remainingTokens = await this.parentBucket.removeTokens(count);\n // Check that we still have enough tokens in this bucket\n if (count > this.content)\n return comeBackLater();\n // Tokens were removed from the parent bucket, now remove them from\n // this bucket. Note that we look at the current bucket and parent\n // bucket's remaining tokens and return the smaller of the two values\n this.content -= count;\n return Math.min(remainingTokens, this.content);\n }\n else {\n // Remove the requested tokens from this bucket\n this.content -= count;\n return this.content;\n }\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens this will\n * return true, otherwise false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Is this an infinite size bucket?\n if (!this.bucketSize)\n return true;\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize)\n return false;\n // Drip new tokens into this bucket\n this.drip();\n // If we don't have enough tokens in this bucket, return false\n if (count > this.content)\n return false;\n // Try to remove the requested tokens from the parent bucket\n if (this.parentBucket && !this.parentBucket.tryRemoveTokens(count))\n return false;\n // Remove the requested tokens from this bucket and return\n this.content -= count;\n return true;\n }\n /**\n * Add any new tokens to the bucket since the last drip.\n * @returns {Boolean} True if new tokens were added, otherwise false.\n */\n drip() {\n if (this.tokensPerInterval === 0) {\n const prevContent = this.content;\n this.content = this.bucketSize;\n return this.content > prevContent;\n }\n const now = getMilliseconds();\n const deltaMS = Math.max(now - this.lastDrip, 0);\n this.lastDrip = now;\n const dripAmount = deltaMS * (this.tokensPerInterval / this.interval);\n const prevContent = this.content;\n this.content = Math.min(this.content + dripAmount, this.bucketSize);\n return Math.floor(this.content) > Math.floor(prevContent);\n }\n}\n//# sourceMappingURL=TokenBucket.js.map","import { TokenBucket } from \"./TokenBucket.js\";\nimport { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A generic rate limiter. Underneath the hood, this uses a token bucket plus\n * an additional check to limit how many tokens we can remove each interval.\n *\n * @param options\n * @param options.tokensPerInterval Maximum number of tokens that can be\n * removed at any given moment and over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.fireImmediately Whether or not the promise will resolve\n * immediately when rate limiting is in effect (default is false).\n */\nexport class RateLimiter {\n tokenBucket;\n curIntervalStart;\n tokensThisInterval;\n fireImmediately;\n constructor({ tokensPerInterval, interval, fireImmediately }) {\n this.tokenBucket = new TokenBucket({\n bucketSize: tokensPerInterval,\n tokensPerInterval,\n interval,\n });\n // Fill the token bucket to start\n this.tokenBucket.content = tokensPerInterval;\n this.curIntervalStart = getMilliseconds();\n this.tokensThisInterval = 0;\n this.fireImmediately = fireImmediately ?? false;\n }\n /**\n * Remove the requested number of tokens. If the rate limiter contains enough\n * tokens and we haven't spent too many tokens in this interval already, this\n * will happen immediately. Otherwise, the removal will happen when enough\n * tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);\n }\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, wait until the\n // next interval\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {\n if (this.fireImmediately) {\n return -1;\n }\n else {\n const waitMs = Math.ceil(this.curIntervalStart + this.tokenBucket.interval - now);\n await wait(waitMs);\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n }\n // Remove the requested number of tokens from the token bucket\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens and we\n * haven't spent too many tokens in this interval already, this will return\n * true. Otherwise, false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize)\n return false;\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, return false\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval)\n return false;\n // Try to remove the requested number of tokens from the token bucket\n const removed = this.tokenBucket.tryRemoveTokens(count);\n if (removed) {\n this.tokensThisInterval += count;\n }\n return removed;\n }\n /**\n * Returns the number of tokens remaining in the TokenBucket.\n * @returns {Number} The number of tokens remaining.\n */\n getTokensRemaining() {\n this.tokenBucket.drip();\n return this.tokenBucket.content;\n }\n}\n//# sourceMappingURL=RateLimiter.js.map","import { RateLimiter } from \"limiter\";\n\nexport interface InMemoryRequestRateLimiter {\n\tcheck(key: string, limit: number): { allowed: boolean; retryAfterS: number };\n}\n\nexport interface CreateInMemoryRequestRateLimiterOptions {\n\twindowMs?: number;\n\tnow?: () => number;\n}\n\n/**\n * Best-effort, per-isolate request rate limiter.\n *\n * Buckets live in a module-local Map, so on Cloudflare Workers the limits are\n * enforced per isolate, not fleet-wide: the effective ceiling is multiplied by\n * the number of live isolates and resets whenever an isolate is evicted. This\n * is acceptable as a coarse abuse brake but is NOT a hard global limit. The\n * unauthenticated /v1/join surface is the most exposed to this gap. Real\n * fleet-wide enforcement needs a shared counter backed by a Durable Object or\n * D1/KV.\n */\nexport function createInMemoryRequestRateLimiter(\n\toptions: CreateInMemoryRequestRateLimiterOptions = {},\n): InMemoryRequestRateLimiter {\n\tconst windowMs = Math.max(1000, Math.trunc(options.windowMs ?? 60_000));\n\tconst now = options.now ?? (() => Date.now());\n\tconst buckets = new Map<string, { limiter: RateLimiter; lastUsedAt: number }>();\n\tlet checks = 0;\n\n\tfunction estimatedRetryAfterS(limit: number): number {\n\t\treturn Math.max(1, Math.ceil(windowMs / Math.max(1, limit) / 1000));\n\t}\n\n\tfunction cleanupExpiredBuckets(currentNow: number): void {\n\t\tif (buckets.size < 64 || checks % 64 !== 0) return;\n\t\tconst staleBefore = currentNow - windowMs * 10;\n\t\tfor (const [key, bucket] of buckets) {\n\t\t\tif (bucket.lastUsedAt < staleBefore) buckets.delete(key);\n\t\t}\n\t}\n\n\treturn {\n\t\tcheck(key: string, limit: number) {\n\t\t\tconst safeLimit = Math.max(1, Math.trunc(limit));\n\t\t\tchecks += 1;\n\t\t\tconst currentNow = now();\n\t\t\tcleanupExpiredBuckets(currentNow);\n\t\t\tconst bucketKey = `${safeLimit}:${key}`;\n\t\t\tlet bucket = buckets.get(bucketKey);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = {\n\t\t\t\t\tlimiter: new RateLimiter({\n\t\t\t\t\t\ttokensPerInterval: safeLimit,\n\t\t\t\t\t\tinterval: windowMs,\n\t\t\t\t\t\tfireImmediately: true,\n\t\t\t\t\t}),\n\t\t\t\t\tlastUsedAt: currentNow,\n\t\t\t\t};\n\t\t\t\tbuckets.set(bucketKey, bucket);\n\t\t\t}\n\t\t\tbucket.lastUsedAt = currentNow;\n\t\t\tif (bucket.limiter.tryRemoveTokens(1)) {\n\t\t\t\treturn { allowed: true, retryAfterS: 0 };\n\t\t\t}\n\t\t\treturn { allowed: false, retryAfterS: estimatedRetryAfterS(safeLimit) };\n\t\t},\n\t};\n}\n","export const SCOPE_MEMBERSHIP_REVOCATION_LIMITATION =\n\t\"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.\";\n\nexport interface ScopeMembershipRevocationNotice {\n\tscope_id: string;\n\tdevice_id: string;\n\tmembership_epoch: number | null;\n\tprevents_future_sync: true;\n\tdeletes_already_copied_data: false;\n\tmessage: string;\n}\n\nexport interface ScopeMembershipEpochStatus {\n\tmembership_epoch: number | null;\n\trequired_epoch: number | null;\n\tstale: boolean;\n\treason: \"current\" | \"stale_epoch\" | \"unknown_epoch\";\n}\n\nexport function scopeMembershipEpochStatus(input: {\n\tmembershipEpoch?: number | null;\n\trequiredEpoch?: number | null;\n}): ScopeMembershipEpochStatus {\n\tconst membershipEpoch = Number.isFinite(input.membershipEpoch)\n\t\t? Number(input.membershipEpoch)\n\t\t: null;\n\tconst requiredEpoch = Number.isFinite(input.requiredEpoch) ? Number(input.requiredEpoch) : null;\n\tif (membershipEpoch == null || requiredEpoch == null) {\n\t\treturn {\n\t\t\tmembership_epoch: membershipEpoch,\n\t\t\trequired_epoch: requiredEpoch,\n\t\t\tstale: false,\n\t\t\treason: \"unknown_epoch\",\n\t\t};\n\t}\n\treturn {\n\t\tmembership_epoch: membershipEpoch,\n\t\trequired_epoch: requiredEpoch,\n\t\tstale: membershipEpoch < requiredEpoch,\n\t\treason: membershipEpoch < requiredEpoch ? \"stale_epoch\" : \"current\",\n\t};\n}\n\nexport function explainScopeMembershipRevocation(input: {\n\tscopeId: string;\n\tdeviceId: string;\n\tmembershipEpoch?: number | null;\n}): ScopeMembershipRevocationNotice {\n\treturn {\n\t\tscope_id: input.scopeId,\n\t\tdevice_id: input.deviceId,\n\t\tmembership_epoch: Number.isFinite(input.membershipEpoch) ? Number(input.membershipEpoch) : null,\n\t\tprevents_future_sync: true,\n\t\tdeletes_already_copied_data: false,\n\t\tmessage: SCOPE_MEMBERSHIP_REVOCATION_LIMITATION,\n\t};\n}\n","export const DEFAULT_TIME_WINDOW_S = 300;\n","/**\n * Coordinator API — Hono-based HTTP server for the coordinator relay.\n *\n * Manages device enrollment, presence, invites, and join requests.\n * Ported from codemem/coordinator_api.py.\n */\n\nimport type { Context } from \"hono\";\nimport { Hono } from \"hono\";\nimport type { InvitePayload } from \"./coordinator-invites.js\";\nimport { encodeInvitePayload, inviteLink } from \"./coordinator-invites.js\";\nimport type { CoordinatorLegacyTeamCompletionManifestV1 } from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCoordinatorMembershipError,\n\tSCOPE_MEMBERSHIP_EFFECT_CONFLICT,\n} from \"./coordinator-membership-effects.js\";\nimport type {\n\tCoordinatorBootstrapGrantVerification,\n\tCoordinatorEnrollment,\n\tCoordinatorInviteKind,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorStore,\n} from \"./coordinator-store-contract.js\";\nimport { CoordinatorReciprocalApprovalRequestChangedError } from \"./coordinator-store-contract.js\";\nimport { PROJECT_INVITE_PENDING_STATUS } from \"./project-invite-acceptance.js\";\nimport {\n\tnormalizeDeviceDisplayName,\n\tnormalizeHumanPresentationName,\n\tnormalizeProjectInviteSummaries,\n} from \"./project-invite-identity.js\";\nimport { acceptedProjectIntentDigest, parseAcceptedProjectIntent } from \"./project-share-intent.js\";\nimport {\n\tRecipientReviewedIntentError,\n\ttype RecipientReviewedIntentV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\nimport { explainScopeMembershipRevocation } from \"./scope-membership-semantics.js\";\nimport { DEFAULT_TIME_WINDOW_S } from \"./sync-auth-constants.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst MAX_BODY_BYTES = 64 * 1024;\nconst MAX_LEGACY_TEAM_COMPLETION_BODY_BYTES = COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES + 1024;\nconst ADMIN_HEADER = \"X-Codemem-Coordinator-Admin\";\nconst ADMIN_ACTOR_HEADER = \"X-Codemem-Coordinator-Admin-Actor\";\nconst DEFAULT_COORDINATOR_READ_LIMIT = 120;\nconst DEFAULT_COORDINATOR_MUTATION_LIMIT = 30;\n\nexport interface CoordinatorRequestRateLimitOptions {\n\tlimiter?: InMemoryRequestRateLimiter;\n\treadLimit?: number;\n\tmutationLimit?: number;\n\tunauthenticatedReadLimit?: number;\n\tunauthenticatedMutationLimit?: number;\n}\n\nexport interface CoordinatorRuntimeDeps {\n\tadminSecret(): string | null;\n\tnow(): string;\n}\n\nexport interface CreateCoordinatorAppOptions {\n\tstoreFactory: () => CoordinatorStore;\n\truntime: CoordinatorRuntimeDeps;\n\trequestVerifier: CoordinatorRequestVerifier;\n\trequestRateLimit?: CoordinatorRequestRateLimitOptions;\n}\n\nexport interface CoordinatorVerifyRequestInput {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Uint8Array;\n\ttimestamp: string;\n\tnonce: string;\n\tsignature: string;\n\tpublicKey: string;\n\tdeviceId: string;\n}\n\nexport type CoordinatorRequestVerifier = (\n\tinput: CoordinatorVerifyRequestInput,\n) => Promise<boolean> | boolean;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction authorizeAdmin(\n\theaderValue: string | null | undefined,\n\truntime: CoordinatorRuntimeDeps,\n): { ok: boolean; error: string } {\n\tconst expected = runtime.adminSecret();\n\tif (!expected) return { ok: false, error: \"admin_not_configured\" };\n\tconst provided = (headerValue ?? \"\").trim();\n\tif (!provided) return { ok: false, error: \"missing_admin_header\" };\n\tif (provided !== expected) return { ok: false, error: \"invalid_admin_secret\" };\n\treturn { ok: true, error: \"ok\" };\n}\n\n/** Extract path + query string from a full URL for signature verification. */\nfunction pathWithQuery(url: string): string {\n\tconst parsed = new URL(url);\n\treturn parsed.search ? `${parsed.pathname}${parsed.search}` : parsed.pathname;\n}\n\nasync function recordNonce(\n\tstore: CoordinatorStore,\n\tdeviceId: string,\n\tnonce: string,\n\tcreatedAt: string,\n): Promise<boolean> {\n\treturn await store.recordNonce(deviceId, nonce, createdAt);\n}\n\nasync function cleanupNonces(store: CoordinatorStore, cutoff: string): Promise<void> {\n\tawait store.cleanupNonces(cutoff);\n}\n\ninterface AuthResult {\n\tok: boolean;\n\terror: string;\n\tenrollment: CoordinatorEnrollment | null;\n}\n\nasync function authorizeRequest(\n\tstore: CoordinatorStore,\n\truntime: CoordinatorRuntimeDeps,\n\trequestVerifier: CoordinatorRequestVerifier,\n\topts: {\n\t\tmethod: string;\n\t\turl: string;\n\t\tgroupId: string;\n\t\tbody: Uint8Array;\n\t\tdeviceId: string | null;\n\t\tsignature: string | null;\n\t\ttimestamp: string | null;\n\t\tnonce: string | null;\n\t},\n): Promise<AuthResult> {\n\tconst { deviceId, signature, timestamp, nonce } = opts;\n\tif (!deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, error: \"missing_headers\", enrollment: null };\n\t}\n\n\tconst enrollment = await store.getEnrollment(opts.groupId, deviceId, true);\n\tif (!enrollment) {\n\t\treturn { ok: false, error: \"unknown_device\", enrollment: null };\n\t}\n\tif (enrollment.enabled !== 1) {\n\t\treturn { ok: false, error: \"device_disabled\", enrollment: null };\n\t}\n\tconst group = await store.getGroup(opts.groupId);\n\tif (!group) {\n\t\treturn { ok: false, error: \"group_not_found\", enrollment: null };\n\t}\n\tif (group.archived_at) {\n\t\treturn { ok: false, error: \"group_archived\", enrollment: null };\n\t}\n\n\tlet valid: boolean;\n\ttry {\n\t\tvalid = await requestVerifier({\n\t\t\tmethod: opts.method,\n\t\t\tpathWithQuery: pathWithQuery(opts.url),\n\t\t\tbodyBytes: opts.body,\n\t\t\ttimestamp,\n\t\t\tnonce,\n\t\t\tsignature,\n\t\t\tpublicKey: String(enrollment.public_key),\n\t\t\tdeviceId,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, error: \"signature_verification_error\", enrollment: null };\n\t}\n\n\tif (!valid) {\n\t\treturn { ok: false, error: \"invalid_signature\", enrollment: null };\n\t}\n\n\tconst createdAt = runtime.now();\n\tif (!(await recordNonce(store, deviceId, nonce, createdAt))) {\n\t\treturn { ok: false, error: \"nonce_replay\", enrollment: null };\n\t}\n\n\t// Clock-source note: the nonce timestamp/cutoff below is driven by the\n\t// injected runtime.now(), while the request freshness window is enforced\n\t// inside requestVerifier using real Date.now() (see the worker's\n\t// request-verifier). In production both are wall-clock so they agree. Under\n\t// an injected/frozen clock they can diverge; the freshness check is not\n\t// reachable from runtime.now(), so tests that freeze runtime.now() must keep\n\t// timestamps within DEFAULT_TIME_WINDOW_S of real time for the verifier to\n\t// accept them. Unifying the two would require threading the clock into the\n\t// verifier signature across the core/worker boundary.\n\tconst cutoff = new Date(\n\t\tnew Date(createdAt).getTime() - DEFAULT_TIME_WINDOW_S * 2 * 1000,\n\t).toISOString();\n\tawait cleanupNonces(store, cutoff);\n\n\treturn { ok: true, error: \"ok\", enrollment };\n}\n\nfunction authErrorStatus(error: string): 401 | 403 | 409 {\n\tif (error === \"device_disabled\") return 403;\n\tif (error === \"group_archived\") return 409;\n\treturn 401;\n}\n\n// ---------------------------------------------------------------------------\n// App factory\n// ---------------------------------------------------------------------------\n\nexport function createCoordinatorApp(\n\topts?: CreateCoordinatorAppOptions,\n): InstanceType<typeof Hono> {\n\tif (!opts?.storeFactory || !opts.runtime || !opts.requestVerifier) {\n\t\tthrow new Error(\"createCoordinatorApp requires storeFactory, runtime, and requestVerifier.\");\n\t}\n\tconst runtime = opts.runtime;\n\tconst createStore = opts.storeFactory;\n\tconst requestVerifier = opts.requestVerifier;\n\tconst requestRateLimit = opts.requestRateLimit ?? {};\n\tconst rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();\n\tconst readLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.readLimit ?? DEFAULT_COORDINATOR_READ_LIMIT),\n\t);\n\tconst mutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.mutationLimit ?? DEFAULT_COORDINATOR_MUTATION_LIMIT),\n\t);\n\tconst unauthenticatedReadLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit)),\n\t);\n\tconst unauthenticatedMutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)),\n\t);\n\tconst app = new Hono();\n\tconst textDecoder = new TextDecoder();\n\n\tfunction rateLimitedResponse(c: Context, key: string, authenticated: boolean) {\n\t\tconst isRead = c.req.method === \"GET\" || c.req.method === \"HEAD\" || c.req.method === \"OPTIONS\";\n\t\tconst result = rateLimiter.check(\n\t\t\t`${c.req.method}:${authenticated ? \"auth\" : \"anon\"}:${key}`,\n\t\t\tauthenticated\n\t\t\t\t? isRead\n\t\t\t\t\t? readLimit\n\t\t\t\t\t: mutationLimit\n\t\t\t\t: isRead\n\t\t\t\t\t? unauthenticatedReadLimit\n\t\t\t\t\t: unauthenticatedMutationLimit,\n\t\t);\n\t\tif (result.allowed) return null;\n\t\tc.header(\"Retry-After\", String(result.retryAfterS));\n\t\treturn c.json({ error: \"rate_limited\", retry_after_s: result.retryAfterS }, 429);\n\t}\n\n\tasync function readRequestBytes(\n\t\tc: Context,\n\t\tmaxBytes = MAX_BODY_BYTES,\n\t): Promise<Uint8Array | null> {\n\t\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\t\tif (Number.isFinite(contentLength) && contentLength > maxBytes) {\n\t\t\treturn null;\n\t\t}\n\t\tconst stream = c.req.raw.body;\n\t\tif (!stream) return new Uint8Array();\n\t\tconst reader = stream.getReader();\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!value) continue;\n\t\t\t\ttotal += value.byteLength;\n\t\t\t\tif (total > maxBytes) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t\tconst combined = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tcombined.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn combined;\n\t}\n\n\tfunction parseJsonObject(raw: Uint8Array): Record<string, unknown> | null {\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(textDecoder.decode(raw));\n\t\t\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn data as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tfunction optionalString(data: Record<string, unknown>, key: string): string | null {\n\t\tconst value = data[key];\n\t\tif (value == null) return null;\n\t\treturn String(value).trim() || null;\n\t}\n\n\tfunction optionalHeaderString(value: string | null | undefined): string | null {\n\t\treturn value?.trim() || null;\n\t}\n\n\tfunction optionalNumber(data: Record<string, unknown>, key: string): number | null {\n\t\tconst value = data[key];\n\t\tif (value == null || value === \"\") return null;\n\t\tif (typeof value !== \"number\" && typeof value !== \"string\") return Number.NaN;\n\t\tif (typeof value === \"string\") {\n\t\t\tconst trimmed = value.trim();\n\t\t\tif (!trimmed) return Number.NaN;\n\t\t\tconst number = Number(trimmed);\n\t\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t\t}\n\t\tconst number = value;\n\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t}\n\n\tfunction queryFlag(value: string | undefined | null): boolean {\n\t\treturn [\"1\", \"true\", \"yes\"].includes(\n\t\t\tString(value ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase(),\n\t\t);\n\t}\n\n\tfunction storedProjectIntent(value: string | null | undefined) {\n\t\ttry {\n\t\t\treturn parseAcceptedProjectIntent(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tfunction buildAcceptedProjectIntent(invite: {\n\t\toperation_id?: string | null;\n\t\treviewed_project_set_digest?: string | null;\n\t\tproject_intent_json?: string | null;\n\t}) {\n\t\tconst operationId = String(invite.operation_id ?? \"\").trim();\n\t\tconst reviewedProjectSetDigest = String(invite.reviewed_project_set_digest ?? \"\").trim();\n\t\tif (\n\t\t\t!/^share_[a-f0-9]{40}$/u.test(operationId) ||\n\t\t\t!/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst projects = storedProjectIntent(invite.project_intent_json);\n\t\tconst computedDigest = acceptedProjectIntentDigest(projects);\n\t\tif (computedDigest !== reviewedProjectSetDigest) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\toperation_id: operationId,\n\t\t\treviewed_project_set_digest: reviewedProjectSetDigest,\n\t\t\tprojects,\n\t\t};\n\t}\n\n\tfunction storedProjectSummaries(\n\t\tvalue: string | null | undefined,\n\t): ReturnType<typeof normalizeProjectInviteSummaries> {\n\t\ttry {\n\t\t\treturn normalizeProjectInviteSummaries(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tasync function requireActiveAdminGroup(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst group = await store.getGroup(groupId);\n\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\t\treturn null;\n\t}\n\n\tasync function findAdminScope(\n\t\tstore: CoordinatorStore,\n\t\tgroupId: string,\n\t\tscopeId: string,\n\t\tc: Context,\n\t): Promise<{ scope: CoordinatorScope | null; response: Response | null }> {\n\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\tif (groupError) return { scope: null, response: groupError };\n\t\tif (!scopeId) return { scope: null, response: c.json({ error: \"scope_id_required\" }, 400) };\n\t\tconst matching = await store.listScopes({ groupId, includeInactive: true });\n\t\tconst scope = matching.find((item) => item.scope_id === scopeId) ?? null;\n\t\tif (!scope) return { scope: null, response: c.json({ error: \"scope_not_found\" }, 404) };\n\t\treturn { scope, response: null };\n\t}\n\n\tasync function authorizeGroupMember(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\tmethod: c.req.method,\n\t\t\turl: c.req.url,\n\t\t\tgroupId,\n\t\t\tbody: new Uint8Array(0),\n\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t});\n\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\treturn {\n\t\t\t\tauth,\n\t\t\t\tresponse:\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error)),\n\t\t\t};\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\treturn { auth, response: limited };\n\t}\n\n\tfunction activeCurrentMembership(\n\t\tmembership: CoordinatorScopeMembership,\n\t\tscope: CoordinatorScope,\n\t): boolean {\n\t\treturn membership.status === \"active\" && membership.membership_epoch >= scope.membership_epoch;\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/presence — upsert device presence (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/presence\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tif (data.fingerprint && String(data.fingerprint) !== String(auth.enrollment.fingerprint)) {\n\t\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 401);\n\t\t\t}\n\n\t\t\tconst rawAddresses = data.addresses ?? [];\n\t\t\tif (!Array.isArray(rawAddresses) || !rawAddresses.every((item) => typeof item === \"string\")) {\n\t\t\t\treturn c.json({ error: \"addresses_must_be_list_of_strings\" }, 400);\n\t\t\t}\n\n\t\t\tlet ttlS: number;\n\t\t\ttry {\n\t\t\t\tttlS = Math.max(1, Number.parseInt(String(data.ttl_s ?? 180), 10));\n\t\t\t\tif (Number.isNaN(ttlS)) {\n\t\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t}\n\n\t\t\tconst response = await store.upsertPresence({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\taddresses: rawAddresses as string[],\n\t\t\t\tttlS,\n\t\t\t\tcapabilities:\n\t\t\t\t\ttypeof data.capabilities === \"object\" &&\n\t\t\t\t\tdata.capabilities !== null &&\n\t\t\t\t\t!Array.isArray(data.capabilities)\n\t\t\t\t\t\t? (data.capabilities as Record<string, unknown>)\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\n\t\t\treturn c.json({ ok: true, ...response });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/peers — list group peers (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/peers\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tconst items = await store.listGroupPeers(groupId, String(auth.enrollment.device_id));\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes — list syncable scopes for the authenticated group member\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\tconst scopes = await store.listScopes({ groupId, includeInactive: false });\n\t\t\t// One indexed lookup of the requester's own memberships, rather than\n\t\t\t// reading every member of every scope to answer a question about one\n\t\t\t// device. (scope_id, device_id) is unique, so the map is 1:1.\n\t\t\tconst memberships = await store.listDeviceScopeMemberships(\n\t\t\t\tString(auth.enrollment.device_id),\n\t\t\t\tfalse,\n\t\t\t);\n\t\t\tconst membershipByScope = new Map(\n\t\t\t\tmemberships.map((membership) => [membership.scope_id, membership]),\n\t\t\t);\n\t\t\tconst items: CoordinatorScope[] = scopes.filter((scope) => {\n\t\t\t\tif (scope.status !== \"active\") return false;\n\t\t\t\tconst membership = membershipByScope.get(scope.scope_id);\n\t\t\t\treturn Boolean(membership && activeCurrentMembership(membership, scope));\n\t\t\t});\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes/:scope_id/members — list members of an authorized scope\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes/:scope_id/members\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\tconst scopes = await store.listScopes({ groupId, includeInactive: false });\n\t\t\tconst scope = scopes.find((item) => item.scope_id === scopeId) ?? null;\n\t\t\tif (scope?.status !== \"active\") return c.json({ error: \"scope_not_found\" }, 404);\n\t\t\tconst memberships = await store.listScopeMemberships(scopeId, false);\n\t\t\tconst requesterAuthorized = memberships.some(\n\t\t\t\t(membership) =>\n\t\t\t\t\tmembership.device_id === String(auth.enrollment?.device_id) &&\n\t\t\t\t\tactiveCurrentMembership(membership, scope),\n\t\t\t);\n\t\t\tif (!requesterAuthorized) return c.json({ error: \"scope_not_authorized\" }, 403);\n\t\t\treturn c.json({\n\t\t\t\titems: memberships.filter((membership) => activeCurrentMembership(membership, scope)),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/reciprocal-approvals — list pending local approval state\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst direction = (c.req.query(\"direction\") ?? \"incoming\").trim();\n\t\tconst status = (c.req.query(\"status\") ?? \"pending\").trim() || \"pending\";\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\t\tif (![\"incoming\", \"outgoing\"].includes(direction)) {\n\t\t\treturn c.json({ error: \"direction_must_be_incoming_or_outgoing\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tconst items = await store.listReciprocalApprovals({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\tdirection: direction as \"incoming\" | \"outgoing\",\n\t\t\t\tstatus,\n\t\t\t});\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/reciprocal-approvals — register a local trust action\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst requestedDeviceId = String(data.requested_device_id ?? \"\").trim();\n\t\tconst expectedIncomingRequestId = Object.hasOwn(data, \"expected_incoming_request_id\")\n\t\t\t? String(data.expected_incoming_request_id ?? \"\").trim()\n\t\t\t: undefined;\n\t\tif (!groupId || !requestedDeviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_requested_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tif (requestedDeviceId === String(auth.enrollment.device_id)) {\n\t\t\t\treturn c.json({ error: \"requested_device_must_differ\" }, 400);\n\t\t\t}\n\t\t\tconst targetEnrollment = await store.getEnrollment(groupId, requestedDeviceId);\n\t\t\tif (!targetEnrollment) {\n\t\t\t\treturn c.json({ error: \"requested_device_not_found\" }, 404);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst request = await store.createReciprocalApproval({\n\t\t\t\t\tgroupId,\n\t\t\t\t\trequestingDeviceId: String(auth.enrollment.device_id),\n\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\t...(expectedIncomingRequestId !== undefined ? { expectedIncomingRequestId } : {}),\n\t\t\t\t});\n\t\t\t\treturn c.json({ ok: true, request });\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof CoordinatorReciprocalApprovalRequestChangedError) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/invites/add-device — create an Identity-owned device invite\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/invites/add-device\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst allowedFields = new Set([\n\t\t\t\"group_id\",\n\t\t\t\"expires_at\",\n\t\t\t\"reviewed_preview_digest\",\n\t\t\t\"reviewed_intent\",\n\t\t]);\n\t\tif (Object.keys(data).some((key) => !allowedFields.has(key))) {\n\t\t\treturn c.json({ error: \"unexpected_add_device_invite_fields\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim();\n\t\tif (!groupId || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (!/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (data.reviewed_intent == null) {\n\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tconst targetIdentityId = auth.enrollment.identity_id;\n\t\t\tif (\n\t\t\t\t!targetIdentityId ||\n\t\t\t\ttargetIdentityId !== targetIdentityId.trim() ||\n\t\t\t\ttargetIdentityId.length > 256 ||\n\t\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(targetIdentityId)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"identity_binding_required\" }, 403);\n\t\t\t}\n\n\t\t\tlet reviewedIntent: RecipientReviewedIntentV1;\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget: { kind: \"add_device\", targetIdentityId },\n\t\t\t\t\tdigest: reviewedPreviewDigest,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy: targetIdentityId,\n\t\t\t\tinviterDeviceId: String(auth.enrollment.device_id),\n\t\t\t\tinviteKind: \"add_device\",\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind: \"add_device\",\n\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// Admin routes\n\t// -----------------------------------------------------------------------\n\n\t// POST /v1/admin/devices — enroll a device\n\tapp.post(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\n\t\tif (!groupId || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"group_id_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tawait store.createGroup(groupId);\n\t\t\tawait store.enrollDevice(groupId, {\n\t\t\t\tdeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublicKey,\n\t\t\t\tdisplayName,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\n\t\treturn c.json({ ok: true });\n\t});\n\n\t// GET /v1/admin/groups — list coordinator groups\n\tapp.get(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst includeArchived = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_archived\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listGroups(includeArchived) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tawait store.createGroup(groupId, displayName);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\t\tif (!groupId || !displayName) {\n\t\t\treturn c.json({ error: \"group_id_and_display_name_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameGroup(groupId, displayName);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/archive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.archiveGroup(groupId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_already_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/unarchive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.unarchiveGroup(groupId);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_not_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes — list Sharing domains for a group\n\tapp.get(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst includeInactive = queryFlag(c.req.query(\"include_inactive\"));\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopes({ groupId, includeInactive }),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes — create a Sharing domain\n\tapp.post(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = optionalString(data, \"scope_id\");\n\t\tconst label = optionalString(data, \"label\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId || !label) return c.json({ error: \"scope_id_and_label_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst scope = await store.createScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel,\n\t\t\t\tkind: optionalString(data, \"kind\"),\n\t\t\t\tauthorityType: optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: optionalString(data, \"status\"),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, scope }, 201);\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// PATCH /v1/admin/groups/:group_id/scopes/:scope_id — update Sharing domain metadata\n\tapp.patch(\"/v1/admin/groups/:group_id/scopes/:scope_id\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst scope = await store.updateScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel: data.label === undefined ? undefined : optionalString(data, \"label\"),\n\t\t\t\tkind: data.kind === undefined ? undefined : optionalString(data, \"kind\"),\n\t\t\t\tauthorityType:\n\t\t\t\t\tdata.authority_type === undefined ? undefined : optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId:\n\t\t\t\t\tdata.coordinator_id === undefined ? undefined : optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId:\n\t\t\t\t\tdata.manifest_issuer_device_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash:\n\t\t\t\t\tdata.manifest_hash === undefined ? undefined : optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: data.status === undefined ? undefined : optionalString(data, \"status\"),\n\t\t\t});\n\t\t\tif (!scope) return c.json({ error: \"scope_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, scope });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes/:scope_id/members — list explicit grants\n\tapp.get(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopeMemberships(scopeId, queryFlag(c.req.query(\"include_revoked\"))),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members — grant device access\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst deviceId = optionalString(data, \"device_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst membership = await store.grantScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole: optionalString(data, \"role\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, membership }, 201);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (\n\t\t\t\terror instanceof CoordinatorMembershipError &&\n\t\t\t\t(error.code === \"scope_not_found\" || error.code === \"scope_group_mismatch\")\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"device_not_enrolled\") {\n\t\t\t\treturn c.json({ error: \"device_not_enrolled_for_scope_group\" }, 404);\n\t\t\t}\n\t\t\tconst scopeInactive =\n\t\t\t\terror instanceof CoordinatorMembershipError && error.code === \"scope_inactive\";\n\t\t\treturn c.json(\n\t\t\t\t{ error: scopeInactive ? \"scope_not_active\" : message },\n\t\t\t\tmessage === SCOPE_MEMBERSHIP_EFFECT_CONFLICT || scopeInactive ? 409 : 400,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = raw.byteLength > 0 ? parseJsonObject(raw) : {};\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst ok = await store.revokeScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\tgroupId,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"membership_not_found\" }, 404);\n\t\t\tlet revokedMembership: CoordinatorScopeMembership | undefined;\n\t\t\ttry {\n\t\t\t\trevokedMembership = (await store.listScopeMemberships(scopeId, true)).find(\n\t\t\t\t\t(membership) => membership.device_id === deviceId,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\trevokedMembership = undefined;\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tdevice_id: deviceId,\n\t\t\t\trevocation: explainScopeMembershipRevocation({\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch: revokedMembership?.membership_epoch ?? membershipEpoch,\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"scope_group_mismatch\") {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\treturn c.json({ error: message }, message === SCOPE_MEMBERSHIP_EFFECT_CONFLICT ? 409 : 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/devices — list enrolled devices\n\tapp.get(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst includeDisabled = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_disabled\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listEnrolledDevices(groupId, includeDisabled) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/rename\n\tapp.post(\"/v1/admin/devices/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\t\tif (!displayName) {\n\t\t\treturn c.json({ error: \"display_name_required\" }, 400);\n\t\t}\n\t\tlet normalizedDisplayName: string;\n\t\ttry {\n\t\t\tnormalizedDisplayName = normalizeHumanPresentationName(displayName, \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameDevice(groupId, deviceId, normalizedDisplayName);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\tconst device = await store.getEnrollment(groupId, deviceId);\n\t\t\treturn c.json({ ok: true, device });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/disable\n\tapp.post(\"/v1/admin/devices/disable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, false);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/enable\n\tapp.post(\"/v1/admin/devices/enable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, true);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/remove\n\tapp.post(\"/v1/admin/devices/remove\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.removeDevice(groupId, deviceId);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/legacy-team-completions\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst raw = await readRequestBytes(c, MAX_LEGACY_TEAM_COMPLETION_BODY_BYTES);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\t\tif (Object.keys(data).some((key) => key !== \"group_id\" && key !== \"manifest\")) {\n\t\t\treturn c.json({ error: \"completion_manifest_invalid\" }, 400);\n\t\t}\n\t\tlet groupId: string;\n\t\tlet manifest: CoordinatorLegacyTeamCompletionManifestV1;\n\t\ttry {\n\t\t\tconst groupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds([data.group_id]);\n\t\t\tconst normalizedGroupId = groupIds[0];\n\t\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\t\tgroupId = normalizedGroupId;\n\t\t\tmanifest = normalizeCoordinatorLegacyTeamCompletionManifest(data.manifest);\n\t\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(manifest);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"completion_manifest_invalid\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst result = await store.createLegacyTeamCompletion(groupId, manifest);\n\t\t\treturn c.json({ ok: true, ...result }, result.status === \"created\" ? 201 : 200);\n\t\t} catch (error) {\n\t\t\tif (error instanceof CoordinatorLegacyTeamCompletionConflictError) {\n\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t}\n\t\t\tconst code = error instanceof Error ? error.message : \"completion_manifest_invalid\";\n\t\t\tif (code === \"group_not_found\") return c.json({ error: code }, 404);\n\t\t\tif (code === \"group_archived\") return c.json({ error: code }, 409);\n\t\t\tif (code === \"completion_manifest_unavailable\") {\n\t\t\t\treturn c.json({ error: code }, 409);\n\t\t\t}\n\t\t\tif (code === \"completion_manifest_invalid\") return c.json({ error: code }, 400);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/legacy-team-completions\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tlet candidateRef: string;\n\t\ttry {\n\t\t\tif (normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]).length !== 1) {\n\t\t\t\tthrow new Error(\"completion_manifest_invalid\");\n\t\t\t}\n\t\t\tcandidateRef = normalizeCoordinatorLegacyTeamCompletionCandidateRef(\n\t\t\t\tc.req.query(\"candidate_ref\"),\n\t\t\t);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"group_id_and_candidate_ref_required\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst manifest = await store.getLegacyTeamCompletion(groupId, candidateRef);\n\t\t\treturn manifest ? c.json({ manifest }) : c.json({ error: \"completion_not_found\" }, 404);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/legacy-team-completions/query\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data || Object.keys(data).some((key) => key !== \"group_ids\")) {\n\t\t\treturn c.json({ error: \"completion_query_invalid\" }, 400);\n\t\t}\n\t\tlet groupIds: string[];\n\t\ttry {\n\t\t\tgroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(data.group_ids);\n\t\t\tif (groupIds.length === 0) throw new Error(\"completion_query_invalid\");\n\t\t} catch {\n\t\t\treturn c.json({ error: \"completion_query_invalid\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listLegacyTeamCompletions(groupIds) });\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"completion_results_too_large\") {\n\t\t\t\treturn c.json({ error: error.message }, 413);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/invites — create an invite\n\tapp.post(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst policy = String(data.policy ?? \"auto_admit\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst createdBy = String(data.created_by ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(data.reviewed_project_set_digest ?? \"\").trim() || null;\n\t\tconst inviterActorId = String(data.inviter_actor_id ?? \"\").trim() || null;\n\t\tconst inviterDisplayName = String(data.inviter_display_name ?? \"\").trim() || null;\n\t\tconst inviterDeviceId = String(data.inviter_device_id ?? \"\").trim() || null;\n\t\tconst pendingPersonId = String(data.pending_person_id ?? \"\").trim() || null;\n\t\tconst requestedInviteKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\tconst policyTeamId = String(data.policy_team_id ?? \"\").trim() || null;\n\t\tconst targetIdentityId = String(data.target_identity_id ?? \"\").trim() || null;\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim() || null;\n\t\tlet reviewedIntent: RecipientReviewedIntentV1 | undefined;\n\t\tlet projectSummaries: ReturnType<typeof normalizeProjectInviteSummaries> | null = null;\n\t\tlet projectIntent: Array<{\n\t\t\tcanonical_identity: string;\n\t\t\tdisplay_name: string;\n\t\t\texisting_memory_count: number;\n\t\t}> | null = null;\n\n\t\tif (!groupId || ![\"auto_admit\", \"approval_required\"].includes(policy) || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_policy_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Object.hasOwn(data, \"assigned_identity_id\")) {\n\t\t\treturn c.json({ error: \"assigned_identity_id_forbidden\" }, 400);\n\t\t}\n\t\t// Validate the date at the boundary so store.createInvite's\n\t\t// normalizeInviteExpiresAt throw can't escape as an unhandled 500.\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_incomplete\" }, 400);\n\t\t}\n\t\tconst inviteKind = (requestedInviteKind ||\n\t\t\t(operationId ? \"project_share\" : \"legacy_enrollment\")) as CoordinatorInviteKind;\n\t\tif (\n\t\t\t!([\"legacy_enrollment\", \"project_share\", \"team_member\", \"add_device\"] as const).includes(\n\t\t\t\tinviteKind,\n\t\t\t)\n\t\t) {\n\t\t\treturn c.json({ error: \"invite_kind_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"project_share\" ? !operationId : Boolean(operationId)) {\n\t\t\treturn c.json({ error: \"invite_kind_intent_mismatch\" }, 400);\n\t\t}\n\t\tif (reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(inviteKind === \"team_member\" &&\n\t\t\t\t(!policyTeamId || !reviewedPreviewDigest || Boolean(targetIdentityId))) ||\n\t\t\t(inviteKind === \"add_device\" &&\n\t\t\t\t(!targetIdentityId || !reviewedPreviewDigest || Boolean(policyTeamId))) ||\n\t\t\t(![\"team_member\", \"add_device\"].includes(inviteKind) &&\n\t\t\t\tBoolean(policyTeamId || targetIdentityId || reviewedPreviewDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t[policyTeamId, targetIdentityId]\n\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_identifier_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"team_member\" || inviteKind === \"add_device\") {\n\t\t\tif (data.reviewed_intent == null) {\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget:\n\t\t\t\t\t\tinviteKind === \"team_member\"\n\t\t\t\t\t\t\t? { kind: \"team_member\", policyTeamId: String(policyTeamId) }\n\t\t\t\t\t\t\t: { kind: \"add_device\", targetIdentityId: String(targetIdentityId) },\n\t\t\t\t\tdigest: String(reviewedPreviewDigest),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t} else if (data.reviewed_intent != null) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(operationId && !/^share_[a-f0-9]{40}$/u.test(operationId)) ||\n\t\t\t(reviewedProjectSetDigest && !/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_invalid\" }, 400);\n\t\t}\n\t\tif (operationId) {\n\t\t\tif (!inviterActorId || !inviterDisplayName || !inviterDeviceId || !pendingPersonId) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_required\" }, 400);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t[inviterActorId, inviterDeviceId, pendingPersonId].some(\n\t\t\t\t\t(value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_invalid\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tnormalizeHumanPresentationName(inviterDisplayName, \"inviter_display_name\");\n\t\t\t\tprojectSummaries = normalizeProjectInviteSummaries(data.project_summaries);\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(data.project_intent) ||\n\t\t\t\t\tdata.project_intent.length !== projectSummaries.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t\tprojectIntent = data.project_intent.map((item, index) => {\n\t\t\t\t\tlet parsed: ReturnType<typeof parseAcceptedProjectIntent>[number] | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparsed = parseAcceptedProjectIntent([item])[0];\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\tconst summary = projectSummaries?.[index];\n\t\t\t\t\tif (\n\t\t\t\t\t\t!parsed ||\n\t\t\t\t\t\t!summary ||\n\t\t\t\t\t\tparsed.display_name !== summary.display_name ||\n\t\t\t\t\t\tparsed.existing_memory_count !== summary.existing_memory_count\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t});\n\t\t\t\tif (\n\t\t\t\t\tnew Set(projectIntent.map((item) => item.canonical_identity)).size !==\n\t\t\t\t\tprojectIntent.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_invalid\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst group = await store.getGroup(groupId);\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy,\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy,\n\t\t\t\toperationId,\n\t\t\t\treviewedProjectSetDigest,\n\t\t\t\tinviterActorId,\n\t\t\t\tinviterDisplayName,\n\t\t\t\tinviterDeviceId,\n\t\t\t\tpendingPersonId,\n\t\t\t\tprojectSummaries,\n\t\t\t\tprojectIntent,\n\t\t\t\tinviteKind,\n\t\t\t\tpolicyTeamId,\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind:\n\t\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\"\n\t\t\t\t\t\t? invite.invite_kind\n\t\t\t\t\t\t: \"coordinator_team_invite\",\n\t\t\t\tcoordinator_url: String(data.coordinator_url ?? \"\").trim(),\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\t...(invite.operation_id\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\t\t\tproject_summaries: projectSummaries ?? [],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"team_member\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpolicy_team_id: invite.policy_team_id ?? undefined,\n\t\t\t\t\t\t\tassigned_identity_id: invite.assigned_identity_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"add_device\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\n\t\t\t// Omit token from the returned invite object (matches Python)\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"invite_operation_intent_conflict\") {\n\t\t\t\treturn c.json({ error: \"invite_operation_intent_conflict\" }, 409);\n\t\t\t}\n\t\t\tif (error instanceof Error && error.message === \"invite_already_bound\") {\n\t\t\t\treturn c.json({ error: \"invite_already_bound\" }, 409);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/invites/inspect\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tif (!token) return c.json({ error: \"invite_invalid\" }, 404);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite || invite.revoked_at) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tif (invite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst inspection = await store.inspectRecipientInvite({ token, now: runtime.now() });\n\t\t\t\t\tif (!inspection) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\tinspection.kind === \"team_member\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\tpolicy_team_id: inspection.policy_team_id,\n\t\t\t\t\t\t\t\t\tassigned_identity_id: inspection.assigned_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\ttarget_identity_id: inspection.target_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tif (\n\t\t\t\tnew Date(invite.expires_at) <= new Date(runtime.now()) &&\n\t\t\t\t(!projectInvite || !invite.consumed_at)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"invite_expired\" }, 410);\n\t\t\t}\n\t\t\tif (!invite.operation_id) {\n\t\t\t\treturn c.json({ kind: \"legacy_team_invite\", team_name: invite.team_name_snapshot });\n\t\t\t}\n\t\t\tif (!invite.project_intent_json || !invite.project_summaries_json) {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t}\n\t\t\tlet projects: ReturnType<typeof normalizeProjectInviteSummaries>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectSummaries(invite.project_summaries_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tkind: \"project_share_invite\",\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tinviter_name: invite.inviter_display_name,\n\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\tprojects,\n\t\t\t\tbound: Boolean(invite.consumed_at),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/invites — list invites\n\tapp.get(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst rows = (await store.listInvites(groupId)).map(\n\t\t\t\t({ token: _token, ...inviteWithoutToken }) => inviteWithoutToken,\n\t\t\t);\n\t\t\treturn c.json({ items: rows });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/project-invites/:operationId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok) return c.json({ error: adminAuth.error }, 401);\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!operationId || !groupId)\n\t\t\treturn c.json({ error: \"operation_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = (await store.listInvites(groupId)).find(\n\t\t\t\t(item) => item.operation_id === operationId,\n\t\t\t);\n\t\t\tif (!invite) return c.json({ error: \"operation_not_found\" }, 404);\n\t\t\tlet projects: ReturnType<typeof storedProjectIntent>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectIntent(invite.project_intent_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t}\n\t\t\tlet inviteLinkValue: string | null = null;\n\t\t\tif (\n\t\t\t\t!invite.consumed_at &&\n\t\t\t\t!invite.revoked_at &&\n\t\t\t\tnew Date(invite.expires_at) > new Date(runtime.now()) &&\n\t\t\t\tinvite.token &&\n\t\t\t\t!invite.token.startsWith(\"consumed:\")\n\t\t\t) {\n\t\t\t\tconst summaries = projects.map((project) => ({\n\t\t\t\t\tdisplay_name: String(project.display_name ?? \"\"),\n\t\t\t\t\texisting_memory_count: Number(project.existing_memory_count ?? 0),\n\t\t\t\t}));\n\t\t\t\tconst payload: InvitePayload = {\n\t\t\t\t\tv: 1,\n\t\t\t\t\tkind: \"coordinator_team_invite\",\n\t\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\ttoken: invite.token,\n\t\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\t\toperation_id: operationId,\n\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\tproject_summaries: summaries,\n\t\t\t\t};\n\t\t\t\tinviteLinkValue = inviteLink(encodeInvitePayload(payload));\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\treviewed_project_set_digest: invite.reviewed_project_set_digest,\n\t\t\t\tstate: invite.consumed_at ? \"accepted\" : \"waiting_for_acceptance\",\n\t\t\t\tpending_person_id: invite.pending_person_id,\n\t\t\t\trecipient_actor_id: invite.recipient_actor_id,\n\t\t\t\trecipient_display_name: invite.recipient_display_name,\n\t\t\t\trecipient_device_id: invite.bound_device_id,\n\t\t\t\trecipient_device_display_name: invite.recipient_device_display_name,\n\t\t\t\trecipient_public_key: invite.bound_public_key,\n\t\t\t\trecipient_fingerprint: invite.bound_fingerprint,\n\t\t\t\tconsumed_at: invite.consumed_at,\n\t\t\t\tbootstrap_grant_id: invite.bootstrap_grant_id,\n\t\t\t\ttrust_state: invite.trust_state,\n\t\t\t\tprojects,\n\t\t\t\tinvite_link: inviteLinkValue,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst grant = await store.getBootstrapGrant(grantId);\n\t\t\tif (!grant) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\tconst workerEnrollment = await store.getEnrollment(grant.group_id, grant.worker_device_id);\n\t\t\tif (!workerEnrollment) return c.json({ error: \"worker_enrollment_not_found\" }, 404);\n\t\t\tconst payload: CoordinatorBootstrapGrantVerification = {\n\t\t\t\tgrant,\n\t\t\t\tworker_enrollment: workerEnrollment,\n\t\t\t};\n\t\t\treturn c.json(payload);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!grantId || !groupId) return c.json({ error: \"grant_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tconst grant = await store.getBootstrapGrant(grantId);\n\t\t\tif (\n\t\t\t\t!grant ||\n\t\t\t\tgrant.group_id !== groupId ||\n\t\t\t\tgrant.seed_device_id !== String(auth.enrollment.device_id)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"grant_not_found\" }, 404);\n\t\t\t}\n\t\t\tconst workerEnrollment = await store.getEnrollment(groupId, grant.worker_device_id);\n\t\t\tif (!workerEnrollment) return c.json({ error: \"worker_enrollment_not_found\" }, 404);\n\t\t\treturn c.json({ grant, worker_enrollment: workerEnrollment });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listBootstrapGrants(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/bootstrap-grants/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst grantId = String(data.grant_id ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.revokeBootstrapGrant(grantId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, grant_id: grantId });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/join-requests/approve\n\tapp.post(\"/v1/admin/join-requests/approve\", async (c) => {\n\t\treturn handleJoinRequestReview(c, true, { createStore, runtime, rateLimitedResponse });\n\t});\n\n\t// POST /v1/admin/join-requests/deny\n\tapp.post(\"/v1/admin/join-requests/deny\", async (c) => {\n\t\treturn handleJoinRequestReview(c, false, { createStore, runtime, rateLimitedResponse });\n\t});\n\n\t// GET /v1/admin/join-requests — list join requests\n\tapp.get(\"/v1/admin/join-requests\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listJoinRequests(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/join — join via invite token (unauthenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/join\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim();\n\t\tconst recipientActorId = String(data.recipient_actor_id ?? \"\").trim();\n\t\tconst recipientDisplayName = String(data.recipient_display_name ?? \"\").trim();\n\t\tconst deviceDisplayName = String(data.device_display_name ?? \"\").trim();\n\n\t\tif (!token || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"token_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tconst recipientInvite =\n\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\";\n\t\t\tif (invite.revoked_at) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_invalid\" : \"revoked_token\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(runtime.now())) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_expired\" : \"expired_token\" },\n\t\t\t\t\t410,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (recipientInvite) {\n\t\t\t\tconst allowedRecipientAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"invite_kind\",\n\t\t\t\t\t\"kind\",\n\t\t\t\t\t\"identity_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedRecipientAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_recipient_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tconst requestedKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\t\t\tconst identityId = String(data.identity_id ?? \"\").trim();\n\t\t\t\tif (!identityId || requestedKind !== invite.invite_kind) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_binding_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (identityId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(identityId)) {\n\t\t\t\t\treturn c.json({ error: \"identity_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientDisplayName: string | null = null;\n\t\t\t\tlet normalizedDeviceDisplayName: string | null = null;\n\t\t\t\ttry {\n\t\t\t\t\tif (data.recipient_display_name != null) {\n\t\t\t\t\t\tif (typeof data.recipient_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"recipient_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedRecipientDisplayName = normalizeHumanPresentationName(\n\t\t\t\t\t\t\tdata.recipient_display_name,\n\t\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (data.device_display_name != null) {\n\t\t\t\t\t\tif (typeof data.device_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"device_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedDeviceDisplayName = normalizeDeviceDisplayName(\n\t\t\t\t\t\t\tdata.device_display_name,\n\t\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: error instanceof Error ? error.message : \"recipient_invite_identity_invalid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tinvite.invite_kind === \"add_device\" &&\n\t\t\t\t\tString(invite.inviter_device_id ?? \"\").trim() === deviceId\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: \"add_device_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeRecipientInvite({\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tinviteKind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t\t\t\t\tidentityId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceDisplayName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: acceptance.status,\n\t\t\t\t\t\tkind: acceptance.invite.invite_kind,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\tidentity_id: acceptance.invite.recipient_actor_id,\n\t\t\t\t\t\tpolicy_team_id: acceptance.invite.policy_team_id ?? null,\n\t\t\t\t\t\ttarget_identity_id: acceptance.invite.target_identity_id ?? null,\n\t\t\t\t\t\tassigned_identity_id: acceptance.invite.assigned_identity_id ?? null,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.bootstrap_grant\n\t\t\t\t\t\t\t? await store.getEnrollment(\n\t\t\t\t\t\t\t\t\tacceptance.invite.group_id,\n\t\t\t\t\t\t\t\t\tacceptance.bootstrap_grant.seed_device_id,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\treviewed_preview_digest: acceptance.invite.reviewed_preview_digest,\n\t\t\t\t\t\treviewed_intent: acceptance.reviewed_intent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (invite.operation_id || invite.reviewed_project_set_digest) {\n\t\t\t\tconst allowedProjectAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"operation_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"display_name\",\n\t\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedProjectAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (!operationId || !recipientActorId || !recipientDisplayName || !deviceDisplayName) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_identity_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (String(invite.inviter_device_id ?? \"\").trim() === deviceId) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\tif (recipientActorId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(recipientActorId)) {\n\t\t\t\t\treturn c.json({ error: \"recipient_actor_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientName: string;\n\t\t\t\tlet normalizedDeviceName: string;\n\t\t\t\ttry {\n\t\t\t\t\tnormalizedRecipientName = normalizeHumanPresentationName(\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t);\n\t\t\t\t\tnormalizedDeviceName = normalizeDeviceDisplayName(\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_identity_invalid\" },\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet acceptedIntent: ReturnType<typeof buildAcceptedProjectIntent>;\n\t\t\t\ttry {\n\t\t\t\t\tacceptedIntent = buildAcceptedProjectIntent(invite);\n\t\t\t\t} catch {\n\t\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeProjectInvite({\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientActorId,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: PROJECT_INVITE_PENDING_STATUS,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\toperation_id: acceptance.invite.operation_id,\n\t\t\t\t\t\ttrust_state: acceptance.invite.trust_state,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.seed_enrollment\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tdevice_id: acceptance.seed_enrollment.device_id,\n\t\t\t\t\t\t\t\t\tpublic_key: acceptance.seed_enrollment.public_key,\n\t\t\t\t\t\t\t\t\tfingerprint: acceptance.seed_enrollment.fingerprint,\n\t\t\t\t\t\t\t\t\tdisplay_name: acceptance.seed_enrollment.display_name,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\taccepted_project_intent: acceptedIntent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectAcceptanceFields = [\n\t\t\t\t\"operation_id\",\n\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\"device_display_name\",\n\t\t\t];\n\t\t\tif (projectAcceptanceFields.some((field) => Object.hasOwn(data, field))) {\n\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t}\n\t\t\tconst group = await store.getGroup(String(invite.group_id));\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst inviteGroupId = String(invite.group_id);\n\t\t\tconst existing = await store.getEnrollment(inviteGroupId, deviceId);\n\t\t\tif (existing) {\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"already_enrolled\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst invitePolicy = String(invite.policy);\n\t\t\tif (![\"auto_admit\", \"approval_required\"].includes(invitePolicy)) {\n\t\t\t\treturn c.json({ error: `unknown invite policy: ${invitePolicy}` }, 400);\n\t\t\t}\n\n\t\t\tif (invitePolicy === \"approval_required\") {\n\t\t\t\tconst request = await store.createJoinRequest({\n\t\t\t\t\tgroupId: inviteGroupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tdisplayName,\n\t\t\t\t\ttoken,\n\t\t\t\t});\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\trequest_id: request.request_id,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait store.enrollDevice(inviteGroupId, {\n\t\t\t\tdeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublicKey,\n\t\t\t\tdisplayName,\n\t\t\t});\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tstatus: \"enrolled\",\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------------\n// Shared handler for approve/deny\n// ---------------------------------------------------------------------------\n\nasync function handleJoinRequestReview(\n\tc: Context,\n\tapproved: boolean,\n\tdeps: {\n\t\tcreateStore: () => CoordinatorStore;\n\t\truntime: CoordinatorRuntimeDeps;\n\t\trateLimitedResponse: (c: Context, key: string, authenticated: boolean) => Response | null;\n\t},\n) {\n\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), deps.runtime);\n\tif (!adminAuth.ok)\n\t\treturn (\n\t\t\tdeps.rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401)\n\t\t);\n\tconst limited = deps.rateLimitedResponse(c, \"admin\", true);\n\tif (limited) return limited;\n\n\tconst raw = await (async () => {\n\t\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\t\tif (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {\n\t\t\treturn null;\n\t\t}\n\t\tconst stream = c.req.raw.body;\n\t\tif (!stream) return new Uint8Array();\n\t\tconst reader = stream.getReader();\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!value) continue;\n\t\t\t\ttotal += value.byteLength;\n\t\t\t\tif (total > MAX_BODY_BYTES) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t\tconst combined = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tcombined.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn combined;\n\t})();\n\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\tlet data: Record<string, unknown> | null;\n\ttry {\n\t\tconst textDecoder = new TextDecoder();\n\t\tconst parsed: unknown = JSON.parse(textDecoder.decode(raw));\n\t\tdata =\n\t\t\ttypeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n\t\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t\t: null;\n\t} catch {\n\t\tdata = null;\n\t}\n\tif (!data) {\n\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t}\n\n\tconst requestId = String(data.request_id ?? \"\").trim();\n\tconst reviewedBy = String(data.reviewed_by ?? \"\").trim() || null;\n\tconst bootstrapGrantSeedDeviceId = String(data.bootstrap_grant_seed_device_id ?? \"\").trim();\n\tconst bootstrapGrantExpiresAt = String(data.bootstrap_grant_expires_at ?? \"\").trim();\n\n\tif (!requestId) return c.json({ error: \"request_id_required\" }, 400);\n\tconst bootstrapGrantFields = [bootstrapGrantSeedDeviceId, bootstrapGrantExpiresAt].filter(\n\t\tBoolean,\n\t).length;\n\tif (bootstrapGrantFields > 0 && bootstrapGrantFields < 2) {\n\t\treturn c.json(\n\t\t\t{ error: \"bootstrap_grant_seed_device_id_and_expires_at_required_together\" },\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst store = deps.createStore();\n\ttry {\n\t\tconst request = await store.reviewJoinRequest({\n\t\t\trequestId,\n\t\t\tapproved,\n\t\t\treviewedBy,\n\t\t\tbootstrapGrant:\n\t\t\t\tapproved && bootstrapGrantSeedDeviceId && bootstrapGrantExpiresAt\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tseedDeviceId: bootstrapGrantSeedDeviceId,\n\t\t\t\t\t\t\texpiresAt: bootstrapGrantExpiresAt,\n\t\t\t\t\t\t\tcreatedBy: reviewedBy,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t});\n\n\t\tif (!request) return c.json({ error: \"request_not_found\" }, 404);\n\n\t\tif (request._no_transition) {\n\t\t\treturn c.json({ error: \"request_not_pending\", status: request.status }, 409);\n\t\t}\n\n\t\treturn c.json({ ok: true, request });\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n"],"x_google_ignoreList":[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,33,34,35],"mappings":";;;AAAA,IAAM,IAAyB,0DACzB,IACL;AAGD,SAAgB,EAA2B,GAAyB;CACnE,IAAI,OAAO,KAAU,UAAU,OAAO;CACtC,IAAM,IAAU,EAAM,KAAK;CAG3B,OAFK,IACD,EAAQ,SAAS,IAAI,KAAK,EAAQ,SAAS,IAAI,IAAU,KACtD,EAAuB,KAAK,CAAO,KAAK,EAAoB,KAAK,CAAO,IAF1D;AAGtB;AAEA,SAAgB,EAAqB,GAAiD;CACrF,IAAM,IAAU,GAAO,KAAK;CAE5B,OADI,CAAC,KAAW,EAA2B,CAAO,IAAU,OACrD;AACR;;;ACZA,IAAa,IAAyB,iBAQzB,IAAgC;AAqE7C,SAAS,EAAM,GAAiD;CAE/D,OADgB,GAAO,KAAK,KACD;AAC5B;AAEA,SAAS,EAAe,GAAuB;CAE9C,OADmB,EAAM,KAAK,CAAC,CAAC,WAAW,MAAM,GAAG,CAAC,CAAC,QAAQ,QAAQ,EAC/D,KAAc,EAAM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