gemi 0.237.2 → 0.237.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/ai/index.js +1 -1
  2. package/dist/{chunk-d6p5gm30.js → chunk-41bpne77.js} +1 -1
  3. package/dist/{chunk-mt68n713.js → chunk-5na9khtz.js} +1 -1
  4. package/dist/{chunk-8hfr1qwe.js → chunk-cvg01wc0.js} +1 -1
  5. package/dist/{chunk-kvfg84am.js → chunk-dnqmvmnp.js} +1 -1
  6. package/dist/{chunk-wgpg670d.js → chunk-f0bz1q3t.js} +1 -1
  7. package/dist/{chunk-c8s4rmej.js → chunk-fcbtgekt.js} +2 -2
  8. package/dist/{chunk-c8s4rmej.js.map → chunk-fcbtgekt.js.map} +1 -1
  9. package/dist/{chunk-8nwfpxh0.js → chunk-h1a4febx.js} +1 -1
  10. package/dist/chunk-mxqrmjha.js +13 -0
  11. package/dist/chunk-mxqrmjha.js.map +10 -0
  12. package/dist/{chunk-fhbre39m.js → chunk-psdcmh65.js} +1 -1
  13. package/dist/{chunk-j0bbh93g.js → chunk-szyr67g7.js} +1 -1
  14. package/dist/{chunk-8ccjtbm2.js → chunk-wt80ekv9.js} +1 -1
  15. package/dist/{chunk-g6re0kkk.js → chunk-y89vn9da.js} +1 -1
  16. package/dist/{chunk-2apm69wz.js → chunk-ycwv9n7m.js} +1 -1
  17. package/dist/console/run.js +1 -1
  18. package/dist/facades/index.js +1 -1
  19. package/dist/http/index.js +1 -1
  20. package/dist/i18n/index.js +1 -1
  21. package/dist/kernel/index.js +1 -1
  22. package/dist/orm/context.d.ts.map +1 -1
  23. package/dist/orm/index.js +1 -1
  24. package/dist/server/index.js +1 -1
  25. package/dist/services/index.js +1 -1
  26. package/dist/services/queue/work.js +1 -1
  27. package/package.json +1 -1
  28. package/dist/chunk-ab5xsxyx.js +0 -13
  29. package/dist/chunk-ab5xsxyx.js.map +0 -10
  30. /package/dist/{chunk-d6p5gm30.js.map → chunk-41bpne77.js.map} +0 -0
  31. /package/dist/{chunk-mt68n713.js.map → chunk-5na9khtz.js.map} +0 -0
  32. /package/dist/{chunk-8hfr1qwe.js.map → chunk-cvg01wc0.js.map} +0 -0
  33. /package/dist/{chunk-kvfg84am.js.map → chunk-dnqmvmnp.js.map} +0 -0
  34. /package/dist/{chunk-wgpg670d.js.map → chunk-f0bz1q3t.js.map} +0 -0
  35. /package/dist/{chunk-8nwfpxh0.js.map → chunk-h1a4febx.js.map} +0 -0
  36. /package/dist/{chunk-fhbre39m.js.map → chunk-psdcmh65.js.map} +0 -0
  37. /package/dist/{chunk-j0bbh93g.js.map → chunk-szyr67g7.js.map} +0 -0
  38. /package/dist/{chunk-8ccjtbm2.js.map → chunk-wt80ekv9.js.map} +0 -0
  39. /package/dist/{chunk-g6re0kkk.js.map → chunk-y89vn9da.js.map} +0 -0
  40. /package/dist/{chunk-2apm69wz.js.map → chunk-ycwv9n7m.js.map} +0 -0
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../orm/context.ts"],
4
+ "sourcesContent": [
5
+ "import type { SQL, TransactionSQL } from \"bun\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { SLOW_TRANSACTION_THRESHOLD } from \"../database/config\";\nimport {\n CrossConnectionTransactionError,\n DEFAULT_CONNECTION,\n} from \"../database/Connection\";\n\n/**\n * The ambient transaction: the ORM's own `AsyncLocalStorage`, holding nothing\n * but the open handle and how deep the nesting is.\n *\n * One store per scope with one owner, which is the pattern the framework\n * already follows — `kernel/context.ts` holds the Application,\n * `http/requestContext.ts` the request and its user. The reasoning for\n * not folding this into the kernel's is written up beside it, and the short\n * version is that a transaction scope has to *nest inside* an Application scope\n * without replacing it, and `foundation/app.ts` must keep reading exactly one\n * shape out of the kernel store or resolving a service becomes a transaction\n * concern.\n *\n * What makes an ALS the right home rather than a field somewhere: two concurrent\n * requests each in their own transaction must never see each other's handle.\n * Anything reachable from the Application — which is one object shared by every\n * in-flight request — fails that by construction, and fails it as silently\n * written data, not as an error. \"two concurrent transactions never see each\n * other's handle\" in `context.test.ts` is the test that would catch it.\n */\nexport interface OrmScope {\n /**\n * Bun's transaction handle. Every ORM statement in scope runs on it, which\n * means they all run on one reserved connection — so nothing here may issue\n * two statements concurrently. `Model.$exec` already runs its nested writes\n * and its relation reads sequentially, for exactly this reason.\n */\n tx?: TransactionSQL;\n /** 0 for the outermost transaction, 1+ for each savepoint inside it. */\n depth: number;\n /**\n * Which named connection this subtree's queries run on, and — when `tx` is\n * set — which connection the open transaction belongs to.\n *\n * Ambient rather than an argument threaded through `$exec`, for the same\n * reason the handle above is: a relation read resolves its target through the\n * registry and calls that class's `$exec`, so an argument would have to be\n * carried by every intermediate that has no interest in it, and the one that\n * forgot would silently read a nested `include` off the *other* pool. There\n * is no error that shape produces; there are just rows from the wrong place.\n *\n * `undefined` means the default connection. Kept as absent-rather-than-\n * `\"default\"` so that entering a scope on the default connection is\n * indistinguishable from not entering one, which is what makes the\n * cross-connection check below cost a comparison of two `undefined`s on every\n * application that never declares a second connection.\n */\n connection?: string;\n /**\n * Whether policies are suspended for this scope. Set only by\n * `Model.asSystem`, and never by anything ambient — the whole point is that\n * unscoped access is a decision visible at the call site, not the accidental\n * result of a missing user.\n */\n system?: boolean;\n /**\n * The user policies should scope to, when there is no request to read one\n * from. Set only by `Model.asUser`.\n *\n * A sentinel wrapper rather than the bare value, so that \"a scope was entered\n * with `null`\" stays distinguishable from \"no scope was entered\" — the two\n * mean different things under deny-by-default.\n */\n actor?: { user: unknown };\n /**\n * Work that must not happen unless this transaction commits — an event whose\n * `static afterCommit` is set, today, and nothing else.\n *\n * **Created by the outermost `withTransaction` and never by a savepoint.** A\n * savepoint's scope is a spread of its parent's (`{ ...current, tx: nested }`),\n * so the array arrives here already shared by reference with the transaction\n * that opened it — which is the behaviour wanted rather than a leak. A\n * dispatch made inside a savepoint that commits, in a transaction that then\n * rolls back, must not run: rolling back the outermost transaction discards\n * the list whole, savepoint entries included, because nothing ever drains it.\n *\n * The inverse — a savepoint that rolls back under a transaction that commits\n * — is the case sharing gets wrong on its own, and `withTransaction`'s\n * savepoint branch is where it is put right.\n *\n * Absent, rather than an empty array, on every scope that is not a\n * transaction: `runAsSystem`, `runAsUser` and `runOnConnection` spread\n * whatever they are given, so \"there is a list here\" and \"there is an open\n * transaction here\" have to stay the same question. `deferUntilCommit`\n * answers `false` when either half is missing and the caller runs the work\n * now, which is what keeps a hand-built scope carrying a `tx` — the shape\n * tests write — from swallowing a dispatch into a list nothing drains.\n */\n afterCommit?: AfterCommitCallback[];\n /**\n * Statements written on `tx` that the commit must wait for and must not\n * outlive — today, a job row the database queue driver wrote on the\n * transaction (#563), and nothing else. See `commitDependsOn`.\n *\n * Created and shared exactly as `afterCommit` is, and truncated with it\n * when a savepoint rolls back.\n */\n commitDependsOn?: Promise<unknown>[];\n /**\n * Set when a statement the ORM or `DB` ran on `tx` failed. Shared by the\n * outermost transaction and its savepoints, like `afterCommit`.\n *\n * On Postgres a failed statement aborts the transaction, and a caller that\n * catches the error and returns normally used to get a resolved\n * `Model.transaction` whose `COMMIT` had quietly been a rollback: nothing\n * written, and the after-commit work ran anyway. Bun 1.4.3 and later reject\n * that `COMMIT` with `ERR_POSTGRES_COMMIT_ROLLED_BACK`; earlier versions\n * resolve. So when this is set, `withTransaction` asks the transaction one\n * `select 1` before it commits, which fails on an aborted transaction on\n * every Bun version, and costs nothing on the path where nothing failed.\n */\n statementFailed?: { value: boolean };\n /**\n * Models whose soft-delete scope (`static $softDeletes`) is lifted or\n * inverted for this async subtree, by name — set only by\n * `Model.withTrashed(fn)` / `Model.onlyTrashed(fn)`.\n *\n * Keyed by model name rather than class because a nested relation read\n * resolves its target through the registry by name, and the block has to\n * reach those reads too. A fresh map per block, never mutated, so an inner\n * block cannot leak its entry back into the enclosing one.\n */\n trashed?: ReadonlyMap<string, TrashedMode>;\n /**\n * Postgres session settings for this subtree (#1158), set by\n * `DB.withSettings`: applied with `set_config(name, value, true)` at the\n * start of every transaction opened here, and of the implicit transaction a\n * single ORM call or `DB.query` gets when none is open. A fresh object per\n * scope, never mutated.\n */\n settings?: Readonly<Record<string, string>>;\n /**\n * What has been applied on `tx` so far, by name. Created by the outermost\n * `withTransaction` and shared by reference with its savepoints, so a\n * `withSettings` block entered inside the transaction applies only what is\n * new and resets it on the way out.\n */\n appliedSettings?: Map<string, string>;\n}\n\n/**\n * How a soft-deleted model's trashed rows are treated: `\"with\"` includes them,\n * `\"only\"` reads nothing else. Absent means the default — they are hidden.\n */\nexport type TrashedMode = \"with\" | \"only\";\n\n/**\n * Work deferred to a transaction's commit.\n *\n * Awaited when it is drained, and its rejection is caught there: a callback is\n * a side effect that the transaction is not waiting on and cannot be told\n * about, so the only thing left to do with a failure is report it.\n *\n * Not exported: a caller passes a lambda and never names this, and an export\n * nothing outside this file uses is what `orm/architecture.test.ts` is pointed\n * at. The declaration emit carries it along regardless, so `OrmScope` stays\n * readable from a `.d.ts`.\n */\ntype AfterCommitCallback = () => void | Promise<void>;\n\n/**\n * One ambient scope for the ORM, not one per feature.\n *\n * Transactions (iteration 5) and system access (iteration 6) are both\n * \"something is true for this async subtree and every query in it\", so they\n * share a store rather than minting a second `AsyncLocalStorage` each. The\n * inventory note in `kernel/context.ts` sets the bar for adding one; two\n * booleans-worth of ORM state does not clear it.\n */\nexport const ormContext = new AsyncLocalStorage<OrmScope>();\n\n/**\n * The ambient scope, without its transaction once that transaction has\n * finished (#1376).\n *\n * Work a transaction starts and doesn't wait for (a `setTimeout`, an\n * un-awaited call, an emitter callback) inherits its scope, handle included.\n * Run after the commit or rollback, that work would otherwise take a\n * savepoint on a finished transaction, or write on its handle. Without the\n * transaction it is outside one, as it is: its `transaction()` opens one of\n * its own, and its statements run on the pool. While the transaction is\n * still open it stays inside it (nested calls the transaction awaits look\n * the same). `deferUntilCommit` reads the raw scope: it goes by how the\n * transaction ended.\n *\n * \"Finished\" starts when the transaction's callback is done with it, before\n * `COMMIT` or `ROLLBACK` is sent: during that round-trip the handle takes\n * statements outside any transaction.\n */\nfunction liveScope(): OrmScope | undefined {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return store;\n if (!finishedLists.has(store.afterCommit)) return store;\n return {\n ...store,\n tx: undefined,\n depth: 0,\n afterCommit: undefined,\n commitDependsOn: undefined,\n statementFailed: undefined,\n appliedSettings: undefined,\n };\n}\n\n/**\n * The open transaction, or `undefined` outside one. This is what `Model.$exec`\n * consults to decide which connection a statement runs on.\n *\n * Exported as the escape hatch for code that genuinely needs the handle — a raw\n * query that must join the surrounding transaction, say. **Do not store what it\n * returns.** Bun's handle stays callable after its `begin` resolves: queries on\n * it then run on the pooled connection, outside any transaction, and succeed.\n * Verified against both dialects, and it is the reason `Model.transaction`'s\n * callback takes no argument.\n */\nexport function currentTransaction(): TransactionSQL | undefined {\n return liveScope()?.tx;\n}\n\n/**\n * The connection every query in this scope runs on unless it names another.\n *\n * `\"default\"` outside any scope, so callers get a name rather than a\n * `string | undefined` to normalise themselves — the store keeps it absent,\n * which is not the same distinction and is nobody else's business.\n */\nexport function currentConnectionName(): string {\n return liveScope()?.connection ?? DEFAULT_CONNECTION;\n}\n\n/**\n * Run `fn` with `name` as the ambient connection.\n *\n * Merged into the current scope rather than replacing it, exactly as\n * `runAsSystem` and `runAsUser` are: naming a connection must not drop an open\n * transaction handle or re-enable policies underneath it.\n *\n * Deliberately absent from `orm/index.ts`, so it is not part of what an\n * application can reach — `Model.on(name)` and `DB.connection(name)` are the\n * two doors, and both funnel through here so that a nested relation read,\n * which resolves its own class out of the registry and calls its `$exec`,\n * inherits the connection without anything having to pass it along.\n */\nexport function runOnConnection<T>(\n name: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = liveScope();\n if (currentConnectionName() === name) return fn();\n\n // ENTERING A CONNECTION IS WHERE THE CROSS-CONNECTION CHECK BELONGS, not at\n // each door — and it has to be *here*, before the scope is entered, because\n // entering it is what makes the check impossible afterwards.\n //\n // The scope carries `tx` and `connection` together, so overwriting the name\n // while an open handle stays in place produces a store that says \"a\n // transaction on analytics\" while holding the *default* connection's handle.\n // Every check downstream then agrees with itself and the statement runs on\n // the wrong connection's transaction. `Model.save` found this: it routes to\n // the row's own connection, so it is the one caller that switches connections\n // with a transaction already open.\n assertConnectionUsable(name);\n\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n },\n fn,\n );\n}\n\n/**\n * Refuse a statement that names one connection while a transaction is open on\n * another.\n *\n * The check `withTransaction`'s single-connection note asked for, and the\n * reasoning for refusing rather than routing is on\n * `CrossConnectionTransactionError`. Both doors call it — `Model.$exec` for\n * every model operation, `DB` for a raw fragment — because either one alone\n * leaves the other free to straddle the two connections, and a raw `DB.execute`\n * escaping a transaction is the more damaging of the two.\n *\n * Only ever fires on a query that *names* a connection: an unqualified one\n * resolves to the ambient name, which is the transaction's own.\n */\nexport function assertConnectionUsable(name: string): void {\n const store = liveScope();\n if (store?.tx === undefined) return;\n\n const open = store.connection ?? DEFAULT_CONNECTION;\n if (open === name) return;\n\n throw new CrossConnectionTransactionError(open, name);\n}\n\n/**\n * Hold `callback` until the open transaction commits, and say whether that\n * happened.\n *\n * `false` means there was nothing to wait for — no transaction is open, or the\n * scope was entered by hand rather than by `withTransaction` — and the caller\n * must run the work itself, now. That return value is the whole contract: a\n * caller that ignores it turns \"no transaction here\" into a side effect queued\n * on a list nothing will ever drain, which is a dispatch that silently never\n * happens.\n *\n * `true` means the callback is on the outermost scope's list and will run after\n * `begin` resolves, outside the transaction, whatever the caller does next. It\n * will not run at all if the transaction rolls back, or if a savepoint it was\n * registered inside rolls back — both of which are the point.\n *\n * Nothing here is ordered against anything but the other deferred callbacks:\n * they run in registration order, one at a time, after the commit round-trip.\n */\nexport function deferUntilCommit(callback: AfterCommitCallback): boolean {\n // The raw scope: a settled transaction's list says what to do with it.\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return false;\n\n // Async work started inside a transaction and not awaited by it — a sync\n // listener still awaiting, an un-awaited emit — can reach here after the\n // transaction settled, through a scope that still carries its handle and its\n // list. Pushing then would queue onto a list already drained (or discarded),\n // and the work would silently never run. A committed list answers \"run it\n // now\"; a rolled-back one keeps the promise that nothing runs: the callback\n // may announce the transaction's own writes (#875). During COMMIT the\n // outcome isn't known yet, so it is queued and runs if the commit does.\n // Detached work that opened a transaction of its own (#1376) is on that\n // one's list instead.\n const settled = settledLists.get(store.afterCommit);\n if (settled === \"committed\") return false;\n if (settled === \"rolled_back\") return true;\n\n store.afterCommit.push(callback);\n return true;\n}\n\n/**\n * The after-commit lists of outermost transactions whose callback is done\n * (committing, rolled back or settled): what `liveScope` drops.\n */\nconst finishedLists = new WeakSet<AfterCommitCallback[]>();\n\n/**\n * How each outermost transaction's after-commit list ended, once it has. Keyed\n * by the list itself, which every savepoint and every lingering async scope of\n * that transaction shares by reference.\n */\nconst settledLists = new WeakMap<AfterCommitCallback[], \"committed\" | \"rolled_back\">();\n\n/**\n * Run `callback` once the open transaction commits, or now when none is open.\n * Never when the transaction rolls back, nor when a savepoint it was\n * registered inside rolls back.\n *\n * The application-facing form of `deferUntilCommit`, exported from `gemi/orm`\n * (#786). The difference is the `false` branch: `deferUntilCommit` hands the\n * \"no transaction\" case back to the caller, who must remember to run the work\n * itself, and this runs it. A caller that wants a side effect only once its\n * writes are durable — waking a long-poll, notifying another process — has\n * nothing left to get wrong.\n *\n * Inside a transaction the callback joins the same list `static afterCommit`\n * events use, so it is drained after `begin` resolves, outside the\n * transaction, in registration order with them.\n *\n * The returned promise resolves once the callback has run (no transaction) or\n * been queued (inside one). It never rejects: a callback that throws is\n * reported on stderr, as a deferred one is at the drain, so a caller that does\n * not await — the usual case — cannot leave an unhandled rejection behind, and\n * the two branches fail the same way. A sync callback outside a transaction\n * runs before this returns.\n */\nexport function afterCommit(\n callback: () => void | Promise<void>,\n): Promise<void> {\n if (deferUntilCommit(callback)) return Promise.resolve();\n\n const report = (error: unknown) => {\n console.error(\n `An after-commit callback threw. No transaction was open, so it ran ` +\n `immediately.`,\n error,\n );\n };\n try {\n return Promise.resolve(callback()).catch(report);\n } catch (error) {\n report(error);\n return Promise.resolve();\n }\n}\n\n/**\n * Record that a statement run on `handle` failed, when `handle` is the open\n * transaction's. See `OrmScope.statementFailed`. @internal\n */\nexport function noteFailedStatement(handle: unknown): void {\n const store = liveScope();\n if (store?.tx !== undefined && store.tx === handle && store.statementFailed) {\n store.statementFailed.value = true;\n }\n}\n\n/**\n * Make the open transaction's commit depend on `write`, a statement issued on\n * its handle: the transaction does not commit until `write` settles, and\n * rolls back — rejecting with `TransactionDependencyError` — if it rejected.\n *\n * For a write the caller may not await. A queued listener's dispatch never is\n * (`EventManager` pushes it and moves on), and on Postgres a statement that\n * fails aborts the whole transaction: every statement after it is refused and\n * Bun's `COMMIT` quietly becomes a rollback. Without this, the callback's\n * promise resolved, `begin` resolved, and the rows the caller wrote were gone\n * with nothing to say so. MySQL does not abort on a failed statement, and is\n * failed here anyway, so that a joined write means the same thing on both:\n * it commits with the transaction or the transaction does not commit.\n *\n * `false` when there is no transaction to depend on, as for\n * `deferUntilCommit`.\n */\nexport function commitDependsOn(write: Promise<unknown>): boolean {\n const store = liveScope();\n if (store?.tx === undefined || store.commitDependsOn === undefined) {\n return false;\n }\n store.commitDependsOn.push(write);\n return true;\n}\n\n/**\n * A write the transaction's commit depended on failed, so the transaction —\n * or the savepoint the write was made in — rolled back. `cause` is the write's\n * own error.\n */\nexport class TransactionDependencyError extends Error {\n constructor(cause: unknown) {\n super(\n `A statement this transaction depended on failed after being issued on ` +\n `it, so the transaction rolled back instead of committing: ` +\n `${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.name = \"TransactionDependencyError\";\n }\n}\n\n/**\n * Wait for the writes registered from `mark` on, and throw if one failed.\n *\n * Called at the end of a transaction's or savepoint's callback, *inside*\n * `begin`/`savepoint`, so a throw is what makes Bun roll back rather than\n * commit — after `begin` has resolved it is too late to do anything but\n * report. Every write is settled before throwing, so none is still running on\n * the handle when the rollback is issued.\n */\nasync function awaitDependencies(\n writes: Promise<unknown>[],\n mark: number,\n): Promise<void> {\n if (writes.length === mark) return;\n const settled = await Promise.allSettled(writes.slice(mark));\n const failed = settled.find(\n (outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\",\n );\n if (failed) throw new TransactionDependencyError(failed.reason);\n}\n\n/** How deeply nested the current transaction is; `null` outside one. */\nexport function transactionDepth(): number | null {\n const store = liveScope();\n return store?.tx === undefined ? null : store.depth;\n}\n\n/** Whether policies are suspended for the current async scope. */\nexport function isSystemScope(): boolean {\n return liveScope()?.system === true;\n}\n\n/**\n * Run `fn` with policies suspended.\n *\n * The escape hatch the deny-by-default rule needs to be usable: a cron tick, a\n * queue worker or a seed script has no user, and under deny-by-default every\n * policied model would refuse it. This makes that intent explicit *at the call\n * site*, which is the property that matters — unscoped access must never be\n * what happens when a user simply fails to turn up.\n *\n * It nests inside a transaction and a transaction nests inside it: the scope is\n * merged rather than replaced, so `asSystem` does not silently drop an open\n * handle.\n */\nexport function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n const current = liveScope();\n return ormContext.run({ ...current, depth: current?.depth ?? 0, system: true }, fn);\n}\n\n/**\n * How `model`'s trashed rows are treated in this async scope, or `undefined`\n * for the default (hidden). See `OrmScope.trashed`.\n */\nexport function trashedMode(model: string): TrashedMode | undefined {\n return liveScope()?.trashed?.get(model);\n}\n\n/**\n * Run `fn` with `model`'s soft-delete scope lifted (`\"with\"`) or inverted\n * (`\"only\"`). Merged into the current scope like `runAsSystem`, so it keeps an\n * open transaction, the system flag and the actor — and every other policy.\n */\nexport function runWithTrashed<T>(\n model: string,\n mode: TrashedMode,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = liveScope();\n const trashed = new Map(current?.trashed);\n trashed.set(model, mode);\n return ormContext.run(\n { ...current, depth: current?.depth ?? 0, trashed },\n fn,\n );\n}\n\n/** The explicitly-set actor, or `undefined` when none was. */\nexport function currentActor(): { user: unknown } | undefined {\n return liveScope()?.actor;\n}\n\n/**\n * Run `fn` with policies scoped to `user`, for code with no request to read one\n * from.\n *\n * The counterpart to `runAsSystem`, and the reason that one is not the only\n * escape hatch. A queue worker processing \"send the invoice for organisation 7\"\n * genuinely acts *as somebody*; giving it `asSystem` would suspend policies\n * entirely and leave it hand-scoping every query — which is precisely the\n * unscoped-by-accident failure the deny-by-default rule exists to prevent. The\n * narrow tool should be the easy one.\n *\n * It is also what makes policies testable without reaching into\n * `RequestContext`'s internals.\n *\n * Takes precedence over the request store, so a job that says who it is acting\n * as is not quietly overridden by an ambient request that happens to enclose it.\n *\n * It also **clears `system`**, which is the more surprising half. Acting as a\n * user is strictly narrower than acting as the system, so naming one inside an\n * `asSystem` block has to narrow back — and the spread would otherwise carry\n * `system: true` forward, leaving `$exec` to skip policies entirely while\n * `currentUser()` cheerfully returned the actor. Silently unscoped, from the\n * realistic shape: a worker enters `asSystem` to read its job queue, then\n * narrows to the job's owner for the work itself. The reverse nesting —\n * `asSystem` inside `asUser` — suspends policies, which is what it should do.\n */\nexport function runAsUser<T>(user: unknown, fn: () => Promise<T>): Promise<T> {\n const current = liveScope();\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n system: false,\n actor: { user: user ?? null },\n },\n fn,\n );\n}\n\n/**\n * The warning threshold in milliseconds, or `null` when the warning is off.\n *\n * `configured` is `database.slowTransactionThreshold` — see `DatabaseConfig`.\n * It arrives as a value rather than being read from here so that this file\n * keeps knowing nothing about the container: `withTransaction` is reachable\n * with a bare pool, and its tests use one.\n *\n * Exported for its own tests. The behaviour worth pinning is the fallback —\n * that a malformed threshold lands on the default rather than disabling — and\n * that cannot be observed through `withTransaction`: \"no warning fired\" is what\n * a disabled warning looks like too, so a behavioural test of it passes just as\n * happily when the fallback is gone. Asserting the number directly is the only\n * form of that test that can fail.\n */\nexport function slowTransactionThreshold(\n configured?: number | false,\n): number | null {\n // Read per call, never cached at module scope. `scripts/build.ts` rewrites\n // `process.env.NODE_ENV` to `Bun.env.NODE_ENV` precisely so mode stays a\n // runtime question in the built framework; caching it here would undo that.\n if (process.env.NODE_ENV !== \"development\") return null;\n\n // The one way to switch it off, and it has to be spelled. Everything else\n // falls back, so the warning is never lost to a mistyped value — only to an\n // explicit `false`.\n if (configured === false) return null;\n\n if (configured === undefined) return SLOW_TRANSACTION_THRESHOLD;\n if (!Number.isFinite(configured) || configured <= 0) {\n return SLOW_TRANSACTION_THRESHOLD;\n }\n return configured;\n}\n\n/**\n * Warn, in development only, about a transaction that has been open too long.\n *\n * The risk is structural rather than occasional: an open transaction holds one\n * reserved connection for as long as its callback runs, and nothing about\n * `Model.transaction(async () => { ... })` stops that callback from awaiting a\n * `fetch`, an S3 upload or a slow queue push. Under concurrency that drains the\n * pool, and the symptom — every unrelated query in the process blocking on\n * connection acquisition — names neither the callback nor the I/O in it.\n *\n * A timer rather than measuring elapsed time on the way out, for one reason:\n * the worst case is the transaction that *never* settles (a hung request, a\n * lock wait, a deadlock). After-the-fact measurement is silent for exactly that\n * case; a timer fires while it is still open and still holding the connection.\n *\n * The `Error` is constructed up front and read only if the timer fires — V8\n * formats `.stack` lazily on first access, so an ordinary fast transaction pays\n * for an object allocation and nothing else.\n *\n * The clock starts at the `begin` call, not at the moment a connection is\n * acquired, and stops when `begin` settles rather than when the callback\n * returns — so it spans the pool wait and the commit round-trip as well as the\n * callback. That is deliberate: all three are time this transaction is in\n * flight, and a warning that only covered the callback would stay silent for a\n * transaction stuck waiting on an exhausted pool, which is the exact situation\n * a long transaction elsewhere creates. Hence \"not settled\" rather than \"open\n * for\" — the message must not claim a connection was held for the whole span.\n */\nfunction watchForSlowTransaction(configured?: number | false): () => void {\n const threshold = slowTransactionThreshold(configured);\n if (threshold === null) return () => {};\n\n const site = new Error(\"transaction opened here\");\n\n const timer = setTimeout(() => {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A database transaction has not settled after ${threshold}ms. It ` +\n `reserves a pooled connection until it does — check for network or ` +\n `filesystem I/O inside the callback, and move it outside the ` +\n `transaction if you find any.\\n${stack}\\n` +\n `(development only; set database.slowTransactionThreshold to change ` +\n `the threshold, or false to switch this off)`,\n );\n }, threshold);\n\n // Otherwise the warning timer is itself a reason the process stays alive,\n // which would turn a diagnostic into a hang in short-lived commands and\n // scripts.\n timer.unref?.();\n\n return () => clearTimeout(timer);\n}\n\n/**\n * Runs what a committed transaction deferred, outside the transaction it was\n * deferred by.\n *\n * `outside` is the scope that was ambient before `begin` — an `asSystem` block,\n * a named connection, or nothing at all — and re-entering it explicitly is the\n * guarantee rather than a tidy-up. The alternative is relying on where a `.then`\n * happens to have captured its context, and the failure that produces is the\n * one the whole feature is about: a listener that runs \"after commit\" while\n * still holding the closed transaction's handle joins nothing, because Bun's\n * handle stays callable and simply runs on the pool. So the scope is rebuilt\n * with `tx` and the drained list cleared, and a listener that opens its own\n * transaction gets a real one.\n *\n * Errors are caught per callback and the next one still runs, for the reason\n * the event subsystem catches per listener: these are independent side effects\n * whose order came from a filesystem walk. And the transaction is not failed by\n * one — it committed, the database kept the rows, and reporting a rejection to\n * the caller would have it roll back or retry work that is already durable.\n * stderr is all that is left, and it is enough: the caller has no decision to\n * make here.\n *\n * The transaction's own promise does not resolve until this has finished, which\n * is the one thing about `afterCommit` that a caller can feel. Deliberate: the\n * alternative is a floating promise whose rejection nobody sees and whose work\n * a short-lived process — a command, a seed — exits out from under.\n */\nasync function drainAfterCommit(\n callbacks: AfterCommitCallback[],\n outside: OrmScope | undefined,\n): Promise<void> {\n if (callbacks.length === 0) return;\n\n await ormContext.run(\n {\n ...outside,\n tx: undefined,\n afterCommit: undefined,\n commitDependsOn: undefined,\n depth: outside?.depth ?? 0,\n },\n async () => {\n for (const callback of callbacks) {\n try {\n await callback();\n } catch (error) {\n console.error(\n `An after-commit callback threw. The transaction it was waiting ` +\n `on had already committed and stays committed, and the ` +\n `callbacks after it still ran.`,\n error,\n );\n }\n }\n },\n );\n}\n\n/**\n * Run `fn` inside a transaction, entering the ambient scope for its whole async\n * subtree.\n *\n * The single implementation behind both `Model.transaction` and\n * `DB.transaction`, so the two cannot become transaction systems that ignore\n * each other: a `Model.create` inside a `DB.transaction` joins it, and a raw\n * `DB.sql` inside a `Model.transaction` can join it through\n * `currentTransaction()`.\n *\n * Nesting becomes a savepoint. Not a preference — Bun refuses the alternative\n * outright (`cannot call begin inside a transaction use savepoint() instead`),\n * and a savepoint is the semantics worth having anyway: an inner failure rolls\n * back to it and leaves the outer transaction usable, which a caller that\n * catches can rely on. Verified on SQLite and Postgres.\n *\n * Note Bun hands the savepoint callback the *same* handle object as the outer\n * transaction (`sp === tx`), so the depth counter is the only thing that\n * actually changes on the way in. The callback's argument is still what gets\n * stored, so this keeps working if that ever stops being true. The cast is\n * because Bun types a savepoint handle as plain `SQL` — without `savepoint` on\n * it — while the runtime object does carry the method, which is what makes\n * three levels of nesting work.\n *\n * Anything `deferUntilCommit` queued is drained once `begin` resolves, outside\n * the transaction and only on the outermost call — a savepoint has committed\n * nothing durable, so draining there would run work that a later rollback of\n * the enclosing transaction was meant to have prevented. See `drainAfterCommit`\n * for what that costs the caller.\n *\n * In development, an outermost transaction that stays open past\n * `options.slowTransactionThreshold` (2s by default, `false` to disable) warns\n * — see `watchForSlowTransaction`. Nothing here *prevents* a long transaction;\n * the warning exists because the cost of one is paid by unrelated queries\n * elsewhere in the process, which makes it hard to trace back.\n *\n * The threshold is passed in rather than read from `app(DatabaseManager)` here.\n * Every caller already holds the manager — it is where `pool` came from — and\n * taking it as an argument keeps this file free of the container, so a bare\n * `SQL` is still enough to call it. Its tests rely on that.\n *\n * `options.connection` is the name `pool` belongs to, and follows the same rule\n * for the same reason: the pool cannot be asked what it is called. Passing it\n * is what lets a nested `withTransaction` tell \"the same connection, so take a\n * savepoint\" from \"a different one, so refuse\" — omitting it means the default\n * connection, which is what a two-argument call always meant.\n *\n * The return type is asserted rather than inferred for one reason worth\n * knowing: Bun's `begin` unwraps a callback that resolves to an *array of\n * promises*, awaiting each. So `Model.transaction(async () => [a, b])` where\n * `a` and `b` are promises resolves to their values, not to the promises. That\n * is Bun's behaviour and is left alone; it is only surprising if unmentioned.\n */\nexport function withTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options?: {\n slowTransactionThreshold?: number | false;\n connection?: string;\n /**\n * Leave the scope's `settings` (#1158) to `fn`, which applies them with\n * `applyTransactionSettings()` after statements that have to come first\n * (`SET TRANSACTION READ ONLY`).\n */\n deferSettings?: boolean;\n /**\n * The connection's dialect. On `\"sqlite\"` an outermost transaction\n * queues behind the one already open on the same pool (#1362); see\n * `queuedOnSqlite`.\n */\n dialect?: string;\n },\n): Promise<T> {\n const current = liveScope();\n\n // THE SINGLE-CONNECTION ASSUMPTION, WHICH IS NOW CHECKED RATHER THAN PINNED.\n //\n // The savepoint branch below ignores `pool` entirely. That was correct while\n // there was one `DatabaseManager` and one `SQL` — the ambient handle and\n // whatever pool the caller passed were necessarily the same database — and\n // the note that stood here said what would happen when a second connection\n // became configurable (#327): a `DB.transaction` on B inside a\n // `Model.transaction` on A would savepoint on **A** and hand the callback A's\n // handle, so statements landed in the wrong database with no error at all.\n //\n // So the name is compared before the branch is taken, and a mismatch raises.\n // Refusing is the whole answer rather than half of one — there is no way to\n // make one transaction span two pools, and the alternatives are covered on\n // `CrossConnectionTransactionError`.\n //\n // A caller that passes no `connection` is treated as naming the default,\n // which is what `withTransaction(pool, fn)` meant before this argument\n // existed.\n const name = options?.connection ?? DEFAULT_CONNECTION;\n assertConnectionUsable(name);\n\n // `current?.tx` rather than `current`: since iteration 6 a scope can exist\n // with no open transaction — `Model.asSystem` enters one — and a savepoint\n // needs an actual handle, not merely a store.\n if (current?.tx) {\n // WHERE THE SHARED AFTER-COMMIT LIST IS PUT RIGHT.\n //\n // The savepoint's scope is a spread of this one, so it appends to the\n // transaction's list rather than to a list of its own — which is what makes\n // \"the outer transaction rolled back, so nothing runs\" free. The case that\n // is not free is this one: the savepoint rolls back and the transaction\n // goes on to commit. Its entries have to go, or a dispatch made inside a\n // block the database threw away runs anyway, which is the same wrong answer\n // as before with an extra step.\n //\n // A mark on the way in and a truncate on the way out, rather than tagging\n // each entry with its depth and dropping everything at or below the failing\n // one. Depth cannot tell two *siblings* apart: a savepoint that committed\n // and one that rolled back both left entries at the same depth, adjacent in\n // the list, and dropping by depth would discard the committed sibling's\n // work as well. The index is exact because the ORM issues one statement at\n // a time on a transaction handle — see `OrmScope.tx` — so nothing appends\n // between the mark and the failure but this savepoint's own subtree.\n const deferred = current.afterCommit;\n const mark = deferred?.length ?? 0;\n // The same mark for the writes the commit depends on. The savepoint waits\n // for its own before it releases, so one that failed rolls back only the\n // savepoint — which a caller that catches can survive, exactly as it\n // survives a statement that threw inside it — and is then forgotten\n // rather than failing the transaction a second time.\n const dependencies = current.commitDependsOn;\n const dependencyMark = dependencies?.length ?? 0;\n\n return current.tx\n .savepoint((sp) => {\n const nested = sp as TransactionSQL;\n return ormContext.run(\n { ...current, tx: nested, depth: current.depth + 1 },\n async () => {\n const result = await fn(nested);\n if (dependencies) {\n await awaitDependencies(dependencies, dependencyMark);\n }\n return result;\n },\n );\n })\n .catch((error: unknown) => {\n if (deferred) deferred.length = mark;\n if (dependencies) dependencies.length = dependencyMark;\n throw error;\n }) as Promise<T>;\n }\n\n if (options?.dialect === \"sqlite\") {\n return queuedOnSqlite(pool, (release) => openTransaction(pool, fn, options, current, name, release), options);\n }\n return openTransaction(pool, fn, options, current, name);\n}\n\n/**\n * The transactions waiting on each SQLite pool, as the promise the last one\n * queued settles (#1362). Bun's SQLite client runs every statement on one\n * connection, where a second `BEGIN` while a transaction is open fails with\n * \"cannot start a transaction within a transaction\". SQLite allows one writer\n * at a time anyway, so queueing changes the order, not the throughput.\n */\nconst sqliteQueues = new WeakMap<SQL, Promise<void>>();\n\n/**\n * A transaction on a SQLite pool waited, in the queue, for one it is itself\n * inside (#1362). It would wait forever: the open transaction can't commit\n * until this one, which it is waiting on, has run.\n *\n * Thrown, rather than hung, when a transaction that isn't nested through the\n * ORM's scope starts from inside an open one on the same connection, and is\n * still waiting on it 5 seconds later: a raw\n * `sql.begin` (a store's), or code that deliberately left the transaction's\n * ORM scope while still awaited by it (an in-process API call or channel\n * message, `ormContext.exit`). Run that work after the commit\n * (`afterCommit`), or inside the transaction, where it becomes a savepoint.\n */\nexport class TransactionQueueDeadlockError extends Error {\n constructor() {\n super(\n \"A SQLite transaction started from inside an open transaction on the same connection, \" +\n \"outside its scope (a raw `begin`, or an in-process call that left the transaction's scope \" +\n \"while the transaction waits on it). SQLite runs one transaction per connection, so it \" +\n \"would wait for the transaction that waits on it. Run it after the commit (`afterCommit`), \" +\n \"or inside the transaction.\",\n );\n this.name = \"TransactionQueueDeadlockError\";\n }\n}\n\n/** The transaction each SQLite pool's queue is running now: its token. */\nconst queueHolders = new WeakMap<SQL, object>();\n\n/**\n * The queued transactions the current async context is inside of. An ORM\n * scope exit (`ormContext.exit`) doesn't leave this one, which is the point:\n * code that left the ORM scope on purpose is still awaited by the\n * transaction around it.\n */\nconst insideQueued = new AsyncLocalStorage<ReadonlySet<object>>();\n\n/** How long a transaction waits in the queue before development warns. */\nconst QUEUE_WAIT_WARNING_MS = 5_000;\n\n/**\n * `begin` once the transactions queued on `pool` before it have let it go\n * (#1362). Exported for the stores that open their own transactions on an\n * app connection, so every transaction on the pool takes the same turns.\n *\n * `release` lets the next one go. The ORM calls it first thing after COMMIT,\n * before the after-commit callbacks: `begin` resolves only after those have\n * run, and one that opened a transaction would otherwise wait on the very\n * transaction that waits on it. Settling lets it go too, so a caller that\n * ignores `release` (a raw `sql.begin`, whose commit is its settle) holds the\n * queue until its promise settles, including any work it does after its own\n * commit. `begin` must not queue on the same pool again from inside (it\n * would wait for itself; see below).\n *\n * Savepoints never come here: they run inside the open transaction.\n *\n * A transaction queued from inside the one holding the pool (its async\n * context says so) is only a suspected deadlock: async context is inherited\n * by work the transaction never waits for too (a `setTimeout`, an un-awaited\n * call), which just waits its turn. So it queues like any other, and is\n * rejected with `TransactionQueueDeadlockError` only if, after 5 seconds, it\n * is still waiting on a transaction it is inside. In development any\n * transaction still waiting then warns (`slowTransactionThreshold: false`\n * turns the warning off).\n */\nexport function queuedOnSqlite<T>(\n pool: SQL,\n begin: (release: () => void) => Promise<T>,\n options: { slowTransactionThreshold?: number | false } = {},\n): Promise<T> {\n const inside = insideQueued.getStore();\n const token = {};\n let release!: () => void;\n const released = new Promise<void>((resolve) => {\n release = () => {\n if (queueHolders.get(pool) === token) queueHolders.delete(pool);\n resolve();\n };\n });\n const previous = sqliteQueues.get(pool) ?? Promise.resolve();\n sqliteQueues.set(pool, released);\n\n return new Promise<T>((resolve, reject) => {\n let abandoned = false;\n // Only where it can be shown: a stack per transaction is not free.\n const site =\n slowTransactionThreshold(options.slowTransactionThreshold) === null\n ? undefined\n : new Error(\"transaction queued here\");\n const timer = setTimeout(() => {\n // Still waiting. On a transaction it is inside: it can never get its\n // turn, so it fails, and lets the queue go when its turn would come.\n const holder = queueHolders.get(pool);\n if (holder && inside?.has(holder)) {\n abandoned = true;\n reject(new TransactionQueueDeadlockError());\n return;\n }\n if (site) warnQueueWait(site);\n }, QUEUE_WAIT_WARNING_MS);\n timer.unref?.();\n\n void previous.then(() => {\n clearTimeout(timer);\n if (abandoned) {\n release();\n return;\n }\n queueHolders.set(pool, token);\n const result = insideQueued.run(new Set([...(inside ?? []), token]), () => begin(release));\n result.then(release, release);\n result.then(resolve, reject);\n });\n });\n}\n\n/** Development's warning for a transaction still waiting in the queue. */\nfunction warnQueueWait(site: Error): void {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A SQLite transaction has waited ${QUEUE_WAIT_WARNING_MS}ms for the one open on its ` +\n `connection (SQLite runs one at a time per connection). Look for a long transaction, or ` +\n `one that waits on work started outside it.\\n${stack}\\n` +\n `(development only; database.slowTransactionThreshold: false switches it off)`,\n );\n}\n\n/** The outermost half of `withTransaction`: `BEGIN` on `pool`, `fn`, `COMMIT`, then the after-commit list. */\nfunction openTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options: { slowTransactionThreshold?: number | false; deferSettings?: boolean } | undefined,\n current: OrmScope | undefined,\n name: string,\n release?: () => void,\n): Promise<T> {\n // Only the outermost scope is watched. A savepoint reserves no connection of\n // its own — its lifetime is bounded by the transaction it sits in, which is\n // already being timed — so warning per depth would report one slow block as\n // several warnings and point at the innermost frame rather than the one\n // holding the connection.\n const stopWatching = watchForSlowTransaction(\n options?.slowTransactionThreshold,\n );\n\n // Built out here rather than inside the `begin` callback, because the drain\n // below needs it *after* that callback's scope is gone, and reading it off\n // the store then is exactly what is no longer possible.\n // A queued SQLite transaction lets the next one go first thing after its\n // commit, before the app's callbacks (`queuedOnSqlite`).\n const deferred: AfterCommitCallback[] = release ? [release] : [];\n const dependencies: Promise<unknown>[] = [];\n const applied = new Map<string, string>();\n const statementFailed = { value: false };\n\n // The `try` covers a *synchronous* throw from `begin` — a closed pool, say.\n // `.finally` alone would not: it is only attached once `begin` has returned a\n // promise, so a synchronous throw escapes with the timer still armed and\n // eventually warns about a transaction that never opened. `unref` keeps that\n // from holding the process, which makes it cosmetic rather than a leak, but\n // it is the same gap the `.finally` below exists to close.\n try {\n // Spread rather than replace: a `Model.transaction` inside a\n // `Model.asSystem` must not silently re-enable policies for its subtree.\n //\n // The connection goes into the scope alongside the handle, and the pair is\n // what makes the check at the top of this function possible: \"which\n // connection is this transaction on\" has to be answerable from the store,\n // because the handle itself does not say. It is also what makes an\n // unqualified query inside `DB.connection(\"analytics\").transaction(...)`\n // *join* the transaction instead of being refused by it — the query\n // inherits the name rather than defaulting to the hot path.\n return (\n pool\n .begin((tx) =>\n ormContext.run(\n {\n ...current,\n tx,\n depth: 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n // A fresh list per outermost transaction, assigned rather than\n // left to the spread. `current` holds no list today — the drain\n // clears the field before it runs anything — and assigning is\n // what keeps that from being load-bearing: a transaction opened\n // by a callback during a drain gets its own list either way,\n // rather than appending to the array it is being run out of.\n afterCommit: deferred,\n commitDependsOn: dependencies,\n appliedSettings: applied,\n statementFailed,\n },\n async () => {\n if (!options?.deferSettings) {\n await applySettings(tx, current?.settings, applied);\n }\n try {\n const result = await fn(tx);\n await awaitDependencies(dependencies, 0);\n // Throws \"current transaction is aborted\" when a failed statement\n // was swallowed on Postgres, so `begin` rolls back and rejects\n // instead of resolving over a `COMMIT` that rolled back.\n if (statementFailed.value) await tx.unsafe(\"select 1\");\n return result;\n } finally {\n // Done with it, before Bun sends COMMIT or ROLLBACK: work\n // that runs from now on is outside it (#1376).\n finishedLists.add(deferred);\n }\n },\n ),\n )\n // `finally` and not a `then`/`catch` pair: the connection is released on\n // rollback exactly as it is on commit, so a throwing callback must clear\n // the timer too or every failed transaction leaves a warning armed\n // against a connection that has already gone back to the pool.\n //\n // Before the drain, so that a slow after-commit listener is not\n // reported as a transaction that will not settle. The connection went\n // back to the pool at the commit; the warning is about holding it.\n .finally(stopWatching)\n // Only here, on the fulfilled path. A rejected `begin` rolled back, so\n // the scope and everything queued on it are discarded unread — which is\n // the whole of what `afterCommit` promises.\n .then(\n async (result) => {\n settledLists.set(deferred, \"committed\");\n await drainAfterCommit(deferred, current);\n return result;\n },\n (error: unknown) => {\n settledLists.set(deferred, \"rolled_back\");\n throw error;\n },\n ) as Promise<T>\n );\n } catch (error) {\n stopWatching();\n throw error;\n }\n}\n\n// --- session settings (#1158) ---------------------------------------------\n\n/** A custom Postgres setting's name: at least two dot-separated parts. */\nconst SETTING_NAME = /^[A-Za-z_][A-Za-z0-9_$]*(\\.[A-Za-z_][A-Za-z0-9_$]*)+$/;\n\n/** The value a setting can be given. `null` sets it to the empty string. */\nexport type SessionSettingValue = string | number | boolean | bigint | null;\n\n/**\n * A `withSettings` block tried to give a setting another value than the\n * block around it gave it (#1158). Refused rather than applied, because a\n * nested change would outlive the inner block: `SET LOCAL` survives\n * `RELEASE SAVEPOINT`, so the rest of the outer block would run as the inner\n * tenant.\n */\nexport class SessionSettingConflictError extends Error {\n constructor(\n readonly setting: string,\n readonly outer: string,\n readonly inner: string,\n ) {\n super(\n `DB.withSettings: \"${setting}\" is already \"${outer}\" in an enclosing withSettings block, and a nested block can't change it to \"${inner}\". Open a separate block outside the first one.`,\n );\n this.name = \"SessionSettingConflictError\";\n }\n}\n\n/** The settings of the ambient scope, or `undefined` when there are none. */\nexport function currentSettings(): Readonly<Record<string, string>> | undefined {\n const settings = liveScope()?.settings;\n return settings && Object.keys(settings).length > 0 ? settings : undefined;\n}\n\n/**\n * `set_config(name, value, true)` on `tx` for every setting not applied yet,\n * in one statement.\n */\nasync function applySettings(\n tx: TransactionSQL,\n settings: Readonly<Record<string, string>> | undefined,\n applied: Map<string, string>,\n): Promise<string[]> {\n if (!settings) return [];\n const pending = Object.entries(settings).filter(([name, value]) => applied.get(name) !== value);\n if (pending.length === 0) return [];\n const calls = pending.map((_, at) => `set_config($${at * 2 + 1}, $${at * 2 + 2}, true)`);\n await tx.unsafe(\n `select ${calls.join(\", \")}`,\n pending.flatMap(([name, value]) => [name, value]),\n );\n for (const [name, value] of pending) applied.set(name, value);\n return pending.map(([name]) => name);\n}\n\n/**\n * Apply the ambient scope's settings on the open transaction, for a caller\n * that opened it with `deferSettings` (`DB.readOnly`). @internal\n */\nexport async function applyTransactionSettings(): Promise<void> {\n const store = liveScope();\n if (store?.tx && store.appliedSettings) {\n await applySettings(store.tx, store.settings, store.appliedSettings);\n }\n}\n\n/**\n * Runs `fn` with Postgres session settings (#1158): every transaction opened\n * inside starts with `set_config(name, value, true)` for each, and so does the\n * implicit transaction a single ORM call or `DB.query` outside a transaction\n * is given. Inside an open transaction they are applied at once, and the ones\n * this block added are reset to `''` when it returns.\n *\n * Blocks nest: an inner block adds settings, and giving one the outer block\n * set another value throws `SessionSettingConflictError`.\n */\nexport async function runWithSettings<T>(\n settings: Record<string, SessionSettingValue>,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = liveScope();\n const outer = current?.settings ?? {};\n const merged: Record<string, string> = { ...outer };\n for (const [name, raw] of Object.entries(settings)) {\n if (!SETTING_NAME.test(name)) {\n throw new Error(\n `DB.withSettings: \"${name}\" is not a custom setting name. Use a prefix and a dot, like \"app.tenant_id\".`,\n );\n }\n const value = raw === null ? \"\" : String(raw);\n if (Object.hasOwn(outer, name) && outer[name] !== value) {\n throw new SessionSettingConflictError(name, outer[name]!, value);\n }\n merged[name] = value;\n }\n const scope: OrmScope = { ...current, depth: current?.depth ?? 0, settings: merged };\n\n const tx = current?.tx;\n const applied = current?.appliedSettings;\n if (!tx || !applied) return ormContext.run(scope, fn);\n\n return ormContext.run(scope, async () => {\n const added = await applySettings(tx, merged, applied);\n const reset = async () => {\n if (added.length === 0) return;\n const calls = added.map((_, at) => `set_config($${at + 1}, '', true)`);\n await tx.unsafe(`select ${calls.join(\", \")}`, added);\n for (const name of added) applied.delete(name);\n };\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n // The transaction may already be failing (an aborted transaction\n // refuses every statement): the rollback resets them anyway, and the\n // caller sees the original error.\n await reset().catch(() => {});\n throw error;\n }\n await reset();\n return result;\n });\n}\n"
6
+ ],
7
+ "mappings": ";yDACA,4BAAS,oBAgLF,IAAM,EAAa,IAAI,EAoB9B,SAAS,CAAS,EAAyB,CACzC,IAAM,EAAQ,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,QAAa,EAAM,cAAgB,OAAW,OAAO,EACvE,GAAI,CAAC,EAAc,IAAI,EAAM,WAAW,EAAG,OAAO,EAClD,MAAO,IACF,EACH,GAAI,OACJ,MAAO,EACP,YAAa,OACb,gBAAiB,OACjB,gBAAiB,OACjB,gBAAiB,MACnB,EAcK,SAAS,CAAkB,EAA+B,CAC/D,OAAO,EAAU,GAAG,GAUf,SAAS,CAAqB,EAAW,CAC9C,OAAO,EAAU,GAAG,YAAc,EAgB7B,SAAS,CAAkB,CAChC,EACA,EACY,CACZ,IAAM,EAAU,EAAU,EAC1B,GAAI,EAAsB,IAAM,EAAM,OAAO,EAAG,EAehD,OAFA,EAAuB,CAAI,EAEpB,EAAW,IAChB,IACK,EACH,MAAO,GAAS,OAAS,EACzB,WAAY,IAAS,EAAqB,OAAY,CACxD,EACA,CACF,EAiBK,SAAS,CAAsB,CAAC,EAAoB,CACzD,IAAM,EAAQ,EAAU,EACxB,GAAI,GAAO,KAAO,OAAW,OAE7B,IAAM,EAAO,EAAM,YAAc,EACjC,GAAI,IAAS,EAAM,OAEnB,MAAM,IAAI,EAAgC,EAAM,CAAI,EAsB/C,SAAS,CAAgB,CAAC,EAAwC,CAEvE,IAAM,EAAQ,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,QAAa,EAAM,cAAgB,OAAW,MAAO,GAYvE,IAAM,EAAU,EAAa,IAAI,EAAM,WAAW,EAClD,GAAI,IAAY,YAAa,MAAO,GACpC,GAAI,IAAY,cAAe,MAAO,GAGtC,OADA,EAAM,YAAY,KAAK,CAAQ,EACxB,GAOT,IAAM,EAAgB,IAAI,QAOpB,EAAe,IAAI,QAyBlB,SAAS,CAAW,CACzB,EACe,CACf,GAAI,EAAiB,CAAQ,EAAG,OAAO,QAAQ,QAAQ,EAEvD,IAAM,EAAS,CAAC,IAAmB,CACjC,QAAQ,MACN,kFAEA,CACF,GAEF,GAAI,CACF,OAAO,QAAQ,QAAQ,EAAS,CAAC,EAAE,MAAM,CAAM,EAC/C,MAAO,EAAO,CAEd,OADA,EAAO,CAAK,EACL,QAAQ,QAAQ,GAQpB,SAAS,CAAmB,CAAC,EAAuB,CACzD,IAAM,EAAQ,EAAU,EACxB,GAAI,GAAO,KAAO,QAAa,EAAM,KAAO,GAAU,EAAM,gBAC1D,EAAM,gBAAgB,MAAQ,GAqB3B,SAAS,CAAe,CAAC,EAAkC,CAChE,IAAM,EAAQ,EAAU,EACxB,GAAI,GAAO,KAAO,QAAa,EAAM,kBAAoB,OACvD,MAAO,GAGT,OADA,EAAM,gBAAgB,KAAK,CAAK,EACzB,GAQF,MAAM,UAAmC,KAAM,CACpD,WAAW,CAAC,EAAgB,CAC1B,MACE,mIAEK,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,IAC1D,CAAE,OAAM,CACV,EACA,KAAK,KAAO,6BAEhB,CAWA,eAAe,CAAiB,CAC9B,EACA,EACe,CACf,GAAI,EAAO,SAAW,EAAM,OAE5B,IAAM,GADU,MAAM,QAAQ,WAAW,EAAO,MAAM,CAAI,CAAC,GACpC,KACrB,CAAC,IAA8C,EAAQ,SAAW,UACpE,EACA,GAAI,EAAQ,MAAM,IAAI,EAA2B,EAAO,MAAM,EAIzD,SAAS,CAAgB,EAAkB,CAChD,IAAM,EAAQ,EAAU,EACxB,OAAO,GAAO,KAAO,OAAY,KAAO,EAAM,MAIzC,SAAS,CAAa,EAAY,CACvC,OAAO,EAAU,GAAG,SAAW,GAgB1B,SAAS,CAAc,CAAC,EAAkC,CAC/D,IAAM,EAAU,EAAU,EAC1B,OAAO,EAAW,IAAI,IAAK,EAAS,MAAO,GAAS,OAAS,EAAG,OAAQ,EAAK,EAAG,CAAE,EAO7E,SAAS,CAAW,CAAC,EAAwC,CAClE,OAAO,EAAU,GAAG,SAAS,IAAI,CAAK,EAQjC,SAAS,CAAiB,CAC/B,EACA,EACA,EACY,CACZ,IAAM,EAAU,EAAU,EACpB,EAAU,IAAI,IAAI,GAAS,OAAO,EAExC,OADA,EAAQ,IAAI,EAAO,CAAI,EAChB,EAAW,IAChB,IAAK,EAAS,MAAO,GAAS,OAAS,EAAG,SAAQ,EAClD,CACF,EAIK,SAAS,EAAY,EAAkC,CAC5D,OAAO,EAAU,GAAG,MA6Bf,SAAS,EAAY,CAAC,EAAe,EAAkC,CAC5E,IAAM,EAAU,EAAU,EAC1B,OAAO,EAAW,IAChB,IACK,EACH,MAAO,GAAS,OAAS,EACzB,OAAQ,GACR,MAAO,CAAE,KAAM,GAAQ,IAAK,CAC9B,EACA,CACF,EAkBK,SAAS,CAAwB,CACtC,EACe,CAIf,GAAI,mBAAyB,cAAe,OAAO,KAKnD,GAAI,IAAe,GAAO,OAAO,KAEjC,GAAI,IAAe,OAAW,OAAO,EACrC,GAAI,CAAC,OAAO,SAAS,CAAU,GAAK,GAAc,EAChD,OAAO,EAET,OAAO,EA+BT,SAAS,CAAuB,CAAC,EAAyC,CACxE,IAAM,EAAY,EAAyB,CAAU,EACrD,GAAI,IAAc,KAAM,MAAO,IAAM,GAErC,IAAM,EAAW,MAAM,yBAAyB,EAE1C,EAAQ,WAAW,IAAM,CAC7B,IAAM,EAAQ,EAAK,OAAO,MAAM;AAAA,CAAI,EAAE,MAAM,CAAC,EAAE,KAAK;AAAA,CAAI,GAAK,GAC7D,QAAQ,KACN,uDAAuD,WACrD,0EACA;AAAA,EACiC;AAAA,+GAGrC,GACC,CAAS,EAOZ,OAFA,EAAM,QAAQ,EAEP,IAAM,aAAa,CAAK,EA8BjC,eAAe,CAAgB,CAC7B,EACA,EACe,CACf,GAAI,EAAU,SAAW,EAAG,OAE5B,MAAM,EAAW,IACf,IACK,EACH,GAAI,OACJ,YAAa,OACb,gBAAiB,OACjB,MAAO,GAAS,OAAS,CAC3B,EACA,SAAY,CACV,QAAW,KAAY,EACrB,GAAI,CACF,MAAM,EAAS,EACf,MAAO,EAAO,CACd,QAAQ,MACN,qJAGA,CACF,GAIR,EAwDK,SAAS,EAAkB,CAChC,EACA,EACA,EAgBY,CACZ,IAAM,EAAU,EAAU,EAoBpB,EAAO,GAAS,YAAc,EAMpC,GALA,EAAuB,CAAI,EAKvB,GAAS,GAAI,CAmBf,IAAM,EAAW,EAAQ,YACnB,EAAO,GAAU,QAAU,EAM3B,EAAe,EAAQ,gBACvB,EAAiB,GAAc,QAAU,EAE/C,OAAO,EAAQ,GACZ,UAAU,CAAC,IAAO,CACjB,IAAM,EAAS,EACf,OAAO,EAAW,IAChB,IAAK,EAAS,GAAI,EAAQ,MAAO,EAAQ,MAAQ,CAAE,EACnD,SAAY,CACV,IAAM,EAAS,MAAM,EAAG,CAAM,EAC9B,GAAI,EACF,MAAM,EAAkB,EAAc,CAAc,EAEtD,OAAO,EAEX,EACD,EACA,MAAM,CAAC,IAAmB,CACzB,GAAI,EAAU,EAAS,OAAS,EAChC,GAAI,EAAc,EAAa,OAAS,EACxC,MAAM,EACP,EAGL,GAAI,GAAS,UAAY,SACvB,OAAO,EAAe,EAAM,CAAC,IAAY,EAAgB,EAAM,EAAI,EAAS,EAAS,EAAM,CAAO,EAAG,CAAO,EAE9G,OAAO,EAAgB,EAAM,EAAI,EAAS,EAAS,CAAI,EAUzD,IAAM,EAAe,IAAI,QAelB,MAAM,UAAsC,KAAM,CACvD,WAAW,EAAG,CACZ,MACE,2XAKF,EACA,KAAK,KAAO,gCAEhB,CAGA,IAAM,EAAe,IAAI,QAQnB,EAAe,IAAI,EAGnB,EAAwB,KA2BvB,SAAS,CAAiB,CAC/B,EACA,EACA,EAAyD,CAAC,EAC9C,CACZ,IAAM,EAAS,EAAa,SAAS,EAC/B,EAAQ,CAAC,EACX,EACE,EAAW,IAAI,QAAc,CAAC,IAAY,CAC9C,EAAU,IAAM,CACd,GAAI,EAAa,IAAI,CAAI,IAAM,EAAO,EAAa,OAAO,CAAI,EAC9D,EAAQ,GAEX,EACK,EAAW,EAAa,IAAI,CAAI,GAAK,QAAQ,QAAQ,EAG3D,OAFA,EAAa,IAAI,EAAM,CAAQ,EAExB,IAAI,QAAW,CAAC,EAAS,IAAW,CACzC,IAAI,EAAY,GAEV,EACJ,EAAyB,EAAQ,wBAAwB,IAAM,KAC3D,OACI,MAAM,yBAAyB,EACnC,EAAQ,WAAW,IAAM,CAG7B,IAAM,EAAS,EAAa,IAAI,CAAI,EACpC,GAAI,GAAU,GAAQ,IAAI,CAAM,EAAG,CACjC,EAAY,GACZ,EAAO,IAAI,CAA+B,EAC1C,OAEF,GAAI,EAAM,EAAc,CAAI,GAC3B,CAAqB,EACxB,EAAM,QAAQ,EAET,EAAS,KAAK,IAAM,CAEvB,GADA,aAAa,CAAK,EACd,EAAW,CACb,EAAQ,EACR,OAEF,EAAa,IAAI,EAAM,CAAK,EAC5B,IAAM,EAAS,EAAa,IAAI,IAAI,IAAI,CAAC,GAAI,GAAU,CAAC,EAAI,CAAK,CAAC,EAAG,IAAM,EAAM,CAAO,CAAC,EACzF,EAAO,KAAK,EAAS,CAAO,EAC5B,EAAO,KAAK,EAAS,CAAM,EAC5B,EACF,EAIH,SAAS,CAAa,CAAC,EAAmB,CACxC,IAAM,EAAQ,EAAK,OAAO,MAAM;AAAA,CAAI,EAAE,MAAM,CAAC,EAAE,KAAK;AAAA,CAAI,GAAK,GAC7D,QAAQ,KACN,0CAA0C;AAAA,EAEO;AAAA,6EAEnD,EAIF,SAAS,CAAkB,CACzB,EACA,EACA,EACA,EACA,EACA,EACY,CAMZ,IAAM,EAAe,EACnB,GAAS,wBACX,EAOM,EAAkC,EAAU,CAAC,CAAO,EAAI,CAAC,EACzD,EAAmC,CAAC,EACpC,EAAU,IAAI,IACd,EAAkB,CAAE,MAAO,EAAM,EAQvC,GAAI,CAWF,OACE,EACG,MAAM,CAAC,IACN,EAAW,IACT,IACK,EACH,KACA,MAAO,EACP,WAAY,IAAS,EAAqB,OAAY,EAOtD,YAAa,EACb,gBAAiB,EACjB,gBAAiB,EACjB,iBACF,EACA,SAAY,CACV,GAAI,CAAC,GAAS,cACZ,MAAM,EAAc,EAAI,GAAS,SAAU,CAAO,EAEpD,GAAI,CACF,IAAM,EAAS,MAAM,EAAG,CAAE,EAK1B,GAJA,MAAM,EAAkB,EAAc,CAAC,EAInC,EAAgB,MAAO,MAAM,EAAG,OAAO,UAAU,EACrD,OAAO,SACP,CAGA,EAAc,IAAI,CAAQ,GAGhC,CACF,EASC,QAAQ,CAAY,EAIpB,KACC,MAAO,IAAW,CAGhB,OAFA,EAAa,IAAI,EAAU,WAAW,EACtC,MAAM,EAAiB,EAAU,CAAO,EACjC,GAET,CAAC,IAAmB,CAElB,MADA,EAAa,IAAI,EAAU,aAAa,EAClC,EAEV,EAEJ,MAAO,EAAO,CAEd,MADA,EAAa,EACP,GAOV,IAAM,EAAe,wDAYd,MAAM,UAAoC,KAAM,CAE1C,QACA,MACA,MAHX,WAAW,CACA,EACA,EACA,EACT,CACA,MACE,qBAAqB,kBAAwB,iFAAqF,kDACpI,EANS,eACA,aACA,aAKT,KAAK,KAAO,8BAEhB,CAGO,SAAS,EAAe,EAAiD,CAC9E,IAAM,EAAW,EAAU,GAAG,SAC9B,OAAO,GAAY,OAAO,KAAK,CAAQ,EAAE,OAAS,EAAI,EAAW,OAOnE,eAAe,CAAa,CAC1B,EACA,EACA,EACmB,CACnB,GAAI,CAAC,EAAU,MAAO,CAAC,EACvB,IAAM,EAAU,OAAO,QAAQ,CAAQ,EAAE,OAAO,EAAE,EAAM,KAAW,EAAQ,IAAI,CAAI,IAAM,CAAK,EAC9F,GAAI,EAAQ,SAAW,EAAG,MAAO,CAAC,EAClC,IAAM,EAAQ,EAAQ,IAAI,CAAC,EAAG,IAAO,eAAe,EAAK,EAAI,OAAO,EAAK,EAAI,UAAU,EACvF,MAAM,EAAG,OACP,UAAU,EAAM,KAAK,IAAI,IACzB,EAAQ,QAAQ,EAAE,EAAM,KAAW,CAAC,EAAM,CAAK,CAAC,CAClD,EACA,QAAY,EAAM,KAAU,EAAS,EAAQ,IAAI,EAAM,CAAK,EAC5D,OAAO,EAAQ,IAAI,EAAE,KAAU,CAAI,EAOrC,eAAsB,EAAwB,EAAkB,CAC9D,IAAM,EAAQ,EAAU,EACxB,GAAI,GAAO,IAAM,EAAM,gBACrB,MAAM,EAAc,EAAM,GAAI,EAAM,SAAU,EAAM,eAAe,EAcvE,eAAsB,EAAkB,CACtC,EACA,EACY,CACZ,IAAM,EAAU,EAAU,EACpB,EAAQ,GAAS,UAAY,CAAC,EAC9B,EAAiC,IAAK,CAAM,EAClD,QAAY,EAAM,KAAQ,OAAO,QAAQ,CAAQ,EAAG,CAClD,GAAI,CAAC,EAAa,KAAK,CAAI,EACzB,MAAU,MACR,qBAAqB,gFACvB,EAEF,IAAM,EAAQ,IAAQ,KAAO,GAAK,OAAO,CAAG,EAC5C,GAAI,OAAO,OAAO,EAAO,CAAI,GAAK,EAAM,KAAU,EAChD,MAAM,IAAI,EAA4B,EAAM,EAAM,GAAQ,CAAK,EAEjE,EAAO,GAAQ,EAEjB,IAAM,EAAkB,IAAK,EAAS,MAAO,GAAS,OAAS,EAAG,SAAU,CAAO,EAE7E,EAAK,GAAS,GACd,EAAU,GAAS,gBACzB,GAAI,CAAC,GAAM,CAAC,EAAS,OAAO,EAAW,IAAI,EAAO,CAAE,EAEpD,OAAO,EAAW,IAAI,EAAO,SAAY,CACvC,IAAM,EAAQ,MAAM,EAAc,EAAI,EAAQ,CAAO,EAC/C,EAAQ,SAAY,CACxB,GAAI,EAAM,SAAW,EAAG,OACxB,IAAM,EAAQ,EAAM,IAAI,CAAC,EAAG,IAAO,eAAe,EAAK,cAAc,EACrE,MAAM,EAAG,OAAO,UAAU,EAAM,KAAK,IAAI,IAAK,CAAK,EACnD,QAAW,KAAQ,EAAO,EAAQ,OAAO,CAAI,GAE3C,EACJ,GAAI,CACF,EAAS,MAAM,EAAG,EAClB,MAAO,EAAO,CAKd,MADA,MAAM,EAAM,EAAE,MAAM,IAAM,EAAE,EACtB,EAGR,OADA,MAAM,EAAM,EACL,EACR",
8
+ "debugId": "80489B2923262AF164756E2164756E21",
9
+ "names": []
10
+ }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{kl as m}from"./chunk-6wv3k8ap.js";import{ml as H,nl as C,rl as A,tl as E}from"./chunk-ab5xsxyx.js";import{Wl as g}from"./chunk-2as2xfem.js";import{Dm as k}from"./chunk-49kkapvr.js";import{Zm as l}from"./chunk-4rs6w1gp.js";class V extends Error{lock;token;constructor(J,Y,Z="its lease ran out or another holder took it"){super(`Lost the lock "${J}" (token ${Y}): ${Z}.`);this.lock=J;this.token=Y;this.name="LockLostError"}}var d=60000,h=100,c=(J)=>new Promise((Y)=>setTimeout(Y,J));class T{store;name;owner;token;ttl;lost;controller=new AbortController;deadline;expiryTimer;renewTimer;done=!1;constructor(J,Y,Z,$,j,W){this.store=J;this.name=Y;this.owner=Z;this.token=$;this.ttl=j;this.lost=this.controller.signal,this.deadline=W+j,this.armExpiry()}get expired(){return this.lost.aborted||performance.now()>=this.deadline}async extend(J=this.ttl){if(this.lost.aborted)return!1;let Y=performance.now();if(!await this.store.extend(this.name,this.owner,this.token,J))return this.markLost(),!1;if(this.done)return!0;return this.deadline=Math.max(this.deadline,Y+J),this.armExpiry(),!0}async isHeld(){if(this.lost.aborted)return!1;let J=await this.store.held(this.name,this.owner,this.token);if(!J)this.markLost();return J}async fence(J){if(this.lost.aborted)throw new V(this.name,this.token);try{return await this.store.fence(this.name,this.owner,this.token,J)}catch(Y){if(Y instanceof V)this.markLost();throw Y}}async release(){if(this.stop(),this.lost.aborted)return!1;return this.store.release(this.name,this.owner,this.token)}startRenewing(){if(this.renewTimer||this.done)return;this.renewTimer=setInterval(()=>{this.extend().catch((J)=>{console.error(`[gemi] Could not renew the lock "${this.name}".`,J)})},Math.max(1,Math.floor(this.ttl/3))),this.renewTimer.unref?.()}markLost(J){if(this.stop(),!this.lost.aborted)this.controller.abort(new V(this.name,this.token,J))}stop(){this.done=!0,clearInterval(this.renewTimer),clearTimeout(this.expiryTimer),this.renewTimer=void 0,this.expiryTimer=void 0}armExpiry(){clearTimeout(this.expiryTimer),this.expiryTimer=setTimeout(()=>this.markLost("its lease ran out before it was renewed"),Math.max(0,this.deadline-performance.now())),this.expiryTimer.unref?.()}}class i{store;static token="locks";constructor(J){this.store=J}async acquire(J,Y={}){let Z=Y.ttl??d;if(!(Z>0))throw Error(`A lock's ttl must be a positive number of milliseconds; got ${Z}.`);let $=Bun.randomUUIDv7(),j=performance.now()+Math.max(0,Y.wait??0);for(;;){let W=performance.now(),z=await this.store.acquire(J,$,Z);if(z!==null){let X=new T(this.store,J,$,z,Z,W);if(Y.renew)X.startRenewing();return X}let G=j-performance.now();if(G<=0)return null;await c(Math.min(h,G))}}async run(J,Y,Z){let $=await this.acquire(J,{...Y,renew:Y.renew??!0});if(!$)return{acquired:!1};let j;try{j=await Z($)}catch(W){throw await $.release().catch(()=>{}),W}if($.expired)throw $.markLost(),$.lost.reason;return await $.release(),{acquired:!0,value:j}}}function VJ(J){return J}function S(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function O(J){let Y=new URLSearchParams;for(let[Z,$]of J)Y.append(Z,String($));return Y.toString()}function R(J){let Y=new Map;if(!J)return Y;let Z;try{Z=new URLSearchParams(J)}catch{return Y}for(let[$,j]of Z){let W=Number(j);if(j!==""&&Number.isSafeInteger(W)&&W>=0)Y.set($,W)}return Y}var{SQL:s}=globalThis.Bun;function t(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var o=async(J)=>{let Y=new s(J,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(Z,$,j)=>Y.listen(Z,$,j),close:()=>Y.close({timeout:1})}},a=async(J)=>{let Y;try{Y=(await import("./chunk-wskms8nf.js")).default}catch($){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:$})}let Z=Y(J,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:($,j,W)=>Z.listen($,j,W),close:()=>Z.end({timeout:1}).catch(()=>{})}},y=(J)=>t()?o(J):a(J);var r=/^[A-Za-z_][A-Za-z0-9_]*$/;class x{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor(J,Y={}){if(J.dialect!=="postgres"&&J.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${J.dialect}.`);let Z=Y.headsTable??"gemi_change_heads",$=Y.entriesTable??"gemi_changes",j=Y.notifyChannel??"gemi_changes";for(let z of[Z,$,j])if(!r.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let W=Y.retain??1000;if(!Number.isInteger(W)||W<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${W}.`);this.headsTable=Z,this.entriesTable=$,this.notifyChannel=j,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.url=J.url,this.retain=W,this.listener=Y.listener??y}async createTable(){for(let J of n(this.headsTable,this.entriesTable))await this.sql.unsafe(J)}joinsTransaction(){return this.transaction()!==void 0}publish(J,Y){let Z=this.transaction();if(!Z){let j=()=>this.sql.begin((z)=>this.append(z,J,Y));if(this.dialect!=="sqlite")return j();let W=this.sqliteTurn.then(j);return this.sqliteTurn=W.catch(()=>{}),W}let $=this.append(Z,J,Y);return E($),$}async append(J,Y,Z){let $=J.unsafe(`"${this.headsTable}"`),j=J.unsafe(`"${this.entriesTable}"`),[W]=await J`
2
+ import{kl as m}from"./chunk-6wv3k8ap.js";import{ml as H,nl as C,rl as A,tl as E}from"./chunk-mxqrmjha.js";import{Wl as g}from"./chunk-2as2xfem.js";import{Dm as k}from"./chunk-49kkapvr.js";import{Zm as l}from"./chunk-4rs6w1gp.js";class V extends Error{lock;token;constructor(J,Y,Z="its lease ran out or another holder took it"){super(`Lost the lock "${J}" (token ${Y}): ${Z}.`);this.lock=J;this.token=Y;this.name="LockLostError"}}var d=60000,h=100,c=(J)=>new Promise((Y)=>setTimeout(Y,J));class T{store;name;owner;token;ttl;lost;controller=new AbortController;deadline;expiryTimer;renewTimer;done=!1;constructor(J,Y,Z,$,j,W){this.store=J;this.name=Y;this.owner=Z;this.token=$;this.ttl=j;this.lost=this.controller.signal,this.deadline=W+j,this.armExpiry()}get expired(){return this.lost.aborted||performance.now()>=this.deadline}async extend(J=this.ttl){if(this.lost.aborted)return!1;let Y=performance.now();if(!await this.store.extend(this.name,this.owner,this.token,J))return this.markLost(),!1;if(this.done)return!0;return this.deadline=Math.max(this.deadline,Y+J),this.armExpiry(),!0}async isHeld(){if(this.lost.aborted)return!1;let J=await this.store.held(this.name,this.owner,this.token);if(!J)this.markLost();return J}async fence(J){if(this.lost.aborted)throw new V(this.name,this.token);try{return await this.store.fence(this.name,this.owner,this.token,J)}catch(Y){if(Y instanceof V)this.markLost();throw Y}}async release(){if(this.stop(),this.lost.aborted)return!1;return this.store.release(this.name,this.owner,this.token)}startRenewing(){if(this.renewTimer||this.done)return;this.renewTimer=setInterval(()=>{this.extend().catch((J)=>{console.error(`[gemi] Could not renew the lock "${this.name}".`,J)})},Math.max(1,Math.floor(this.ttl/3))),this.renewTimer.unref?.()}markLost(J){if(this.stop(),!this.lost.aborted)this.controller.abort(new V(this.name,this.token,J))}stop(){this.done=!0,clearInterval(this.renewTimer),clearTimeout(this.expiryTimer),this.renewTimer=void 0,this.expiryTimer=void 0}armExpiry(){clearTimeout(this.expiryTimer),this.expiryTimer=setTimeout(()=>this.markLost("its lease ran out before it was renewed"),Math.max(0,this.deadline-performance.now())),this.expiryTimer.unref?.()}}class i{store;static token="locks";constructor(J){this.store=J}async acquire(J,Y={}){let Z=Y.ttl??d;if(!(Z>0))throw Error(`A lock's ttl must be a positive number of milliseconds; got ${Z}.`);let $=Bun.randomUUIDv7(),j=performance.now()+Math.max(0,Y.wait??0);for(;;){let W=performance.now(),z=await this.store.acquire(J,$,Z);if(z!==null){let X=new T(this.store,J,$,z,Z,W);if(Y.renew)X.startRenewing();return X}let G=j-performance.now();if(G<=0)return null;await c(Math.min(h,G))}}async run(J,Y,Z){let $=await this.acquire(J,{...Y,renew:Y.renew??!0});if(!$)return{acquired:!1};let j;try{j=await Z($)}catch(W){throw await $.release().catch(()=>{}),W}if($.expired)throw $.markLost(),$.lost.reason;return await $.release(),{acquired:!0,value:j}}}function VJ(J){return J}function S(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function O(J){let Y=new URLSearchParams;for(let[Z,$]of J)Y.append(Z,String($));return Y.toString()}function R(J){let Y=new Map;if(!J)return Y;let Z;try{Z=new URLSearchParams(J)}catch{return Y}for(let[$,j]of Z){let W=Number(j);if(j!==""&&Number.isSafeInteger(W)&&W>=0)Y.set($,W)}return Y}var{SQL:s}=globalThis.Bun;function t(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var o=async(J)=>{let Y=new s(J,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(Z,$,j)=>Y.listen(Z,$,j),close:()=>Y.close({timeout:1})}},a=async(J)=>{let Y;try{Y=(await import("./chunk-wskms8nf.js")).default}catch($){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:$})}let Z=Y(J,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:($,j,W)=>Z.listen($,j,W),close:()=>Z.end({timeout:1}).catch(()=>{})}},y=(J)=>t()?o(J):a(J);var r=/^[A-Za-z_][A-Za-z0-9_]*$/;class x{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor(J,Y={}){if(J.dialect!=="postgres"&&J.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${J.dialect}.`);let Z=Y.headsTable??"gemi_change_heads",$=Y.entriesTable??"gemi_changes",j=Y.notifyChannel??"gemi_changes";for(let z of[Z,$,j])if(!r.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let W=Y.retain??1000;if(!Number.isInteger(W)||W<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${W}.`);this.headsTable=Z,this.entriesTable=$,this.notifyChannel=j,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.url=J.url,this.retain=W,this.listener=Y.listener??y}async createTable(){for(let J of n(this.headsTable,this.entriesTable))await this.sql.unsafe(J)}joinsTransaction(){return this.transaction()!==void 0}publish(J,Y){let Z=this.transaction();if(!Z){let j=()=>this.sql.begin((z)=>this.append(z,J,Y));if(this.dialect!=="sqlite")return j();let W=this.sqliteTurn.then(j);return this.sqliteTurn=W.catch(()=>{}),W}let $=this.append(Z,J,Y);return E($),$}async append(J,Y,Z){let $=J.unsafe(`"${this.headsTable}"`),j=J.unsafe(`"${this.entriesTable}"`),[W]=await J`
3
3
  INSERT INTO ${$} (channel, seq) VALUES (${Y}, 1)
4
4
  ON CONFLICT (channel) DO UPDATE SET seq = ${$}.seq + 1
5
5
  RETURNING seq
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ok as O}from"./chunk-8adbpxpm.js";import{Yk as S}from"./chunk-fhbre39m.js";import{Wl as E}from"./chunk-2as2xfem.js";import{um as U}from"./chunk-wj0q7tyn.js";class F{rows=new Map;async find(j,G){for(let Q of this.rows.values())if(Q.userId===j&&Q.provider===G)return{...Q};return null}async list(j){return[...this.rows.values()].filter((G)=>G.userId===j).map((G)=>({...G}))}async save(j,G,Q){let V=await this.find(j,G),W=new Date,Y={id:V?.id??Bun.randomUUIDv7(),userId:j,provider:G,...P(Q),needsReconnect:!1,revision:(V?.revision??0)+1,createdAt:V?.createdAt??W,updatedAt:W};return this.rows.set(Y.id,Y),{...Y}}async updateTokens(j,G,Q){let V=this.rows.get(j);if(!V||V.revision!==G)return null;let W=P(Q);W.providerAccountId??=V.providerAccountId;let Y={...V,...W,needsReconnect:!1,revision:G+1,updatedAt:new Date};return this.rows.set(j,Y),{...Y}}async markNeedsReconnect(j){let G=this.rows.get(j);if(G)this.rows.set(j,{...G,needsReconnect:!0,updatedAt:new Date})}async delete(j){this.rows.delete(j)}}class L{encrypter;table;sql;dialect;constructor(j,G,Q={}){this.encrypter=G;let V=Q.table??"gemi_oauth_connections";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The connections table name "${V}" is not a plain identifier.`);this.table=V,this.sql=j.sql,this.dialect=j.dialect}async createTable(){for(let j of q(this.dialect,this.table))await this.sql.unsafe(j)}async find(j,G){let Q=this.sql,V=await Q`
2
+ import{ok as O}from"./chunk-8adbpxpm.js";import{Yk as S}from"./chunk-psdcmh65.js";import{Wl as E}from"./chunk-2as2xfem.js";import{um as U}from"./chunk-wj0q7tyn.js";class F{rows=new Map;async find(j,G){for(let Q of this.rows.values())if(Q.userId===j&&Q.provider===G)return{...Q};return null}async list(j){return[...this.rows.values()].filter((G)=>G.userId===j).map((G)=>({...G}))}async save(j,G,Q){let V=await this.find(j,G),W=new Date,Y={id:V?.id??Bun.randomUUIDv7(),userId:j,provider:G,...P(Q),needsReconnect:!1,revision:(V?.revision??0)+1,createdAt:V?.createdAt??W,updatedAt:W};return this.rows.set(Y.id,Y),{...Y}}async updateTokens(j,G,Q){let V=this.rows.get(j);if(!V||V.revision!==G)return null;let W=P(Q);W.providerAccountId??=V.providerAccountId;let Y={...V,...W,needsReconnect:!1,revision:G+1,updatedAt:new Date};return this.rows.set(j,Y),{...Y}}async markNeedsReconnect(j){let G=this.rows.get(j);if(G)this.rows.set(j,{...G,needsReconnect:!0,updatedAt:new Date})}async delete(j){this.rows.delete(j)}}class L{encrypter;table;sql;dialect;constructor(j,G,Q={}){this.encrypter=G;let V=Q.table??"gemi_oauth_connections";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The connections table name "${V}" is not a plain identifier.`);this.table=V,this.sql=j.sql,this.dialect=j.dialect}async createTable(){for(let j of q(this.dialect,this.table))await this.sql.unsafe(j)}async find(j,G){let Q=this.sql,V=await Q`
3
3
  SELECT * FROM ${this.name(Q)} WHERE user_id = ${j} AND provider = ${G}
4
4
  `;return V[0]?this.decode(V[0]):null}async list(j){let G=this.sql;return(await G`
5
5
  SELECT * FROM ${this.name(G)} WHERE user_id = ${j} ORDER BY provider
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-fhbre39m.js";import{kl as Z1}from"./chunk-6wv3k8ap.js";import{Cl as v0,Dl as SZ,ml as fZ,nl as bZ,ol as TZ,ql as o,rl as tZ,tl as O0}from"./chunk-ab5xsxyx.js";import{Wl as DZ}from"./chunk-2as2xfem.js";import{rm as eZ,um as B0}from"./chunk-wj0q7tyn.js";import{Dm as w0}from"./chunk-49kkapvr.js";class C0{table;sql;dialect;connection;busyTimeout;configured;constructor(Z,$={}){let V=$.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The lock table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);this.table=V,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=$.busyTimeout??1000}async createTable(){await this.configure();for(let Z of H1(this.dialect,this.table))await this.sql.unsafe(Z)}async acquire(Z,$,V){await this.configure();let z=this.sql,X=this.now(z);if(await this.seed(z,Z),this.mysql){let G=await z`
2
+ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as Z1}from"./chunk-6wv3k8ap.js";import{Cl as v0,Dl as SZ,ml as fZ,nl as bZ,ol as TZ,ql as o,rl as tZ,tl as O0}from"./chunk-mxqrmjha.js";import{Wl as DZ}from"./chunk-2as2xfem.js";import{rm as eZ,um as B0}from"./chunk-wj0q7tyn.js";import{Dm as w0}from"./chunk-49kkapvr.js";class C0{table;sql;dialect;connection;busyTimeout;configured;constructor(Z,$={}){let V=$.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The lock table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);this.table=V,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=$.busyTimeout??1000}async createTable(){await this.configure();for(let Z of H1(this.dialect,this.table))await this.sql.unsafe(Z)}async acquire(Z,$,V){await this.configure();let z=this.sql,X=this.now(z);if(await this.seed(z,Z),this.mysql){let G=await z`
3
3
  UPDATE ${this.name(z)}
4
4
  SET owner = ${$}, token = token + 1, expires_at = ${X} + ${this.ms(z,V)},
5
5
  updated_at = ${X}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_h as KF}from"./chunk-vcmwp7pv.js";import{si as PF}from"./chunk-c3c37k46.js";import{Ai as x8,Bi as K8,Cj as QZ,Ei as _8,Fi as I8,Gi as xB,Hi as p5,Ji as $3,Ki as W8,Li as $2,Mi as k2,Ni as d,Pi as A8,Qi as b$,Ri as l2,Si as w2,Ti as q2,Ui as z6,Vi as S,Wi as _5,Xi as s8,Yi as LZ,Zi as S8,_i as L6,aj as R$,bj as a4,kj as M6,qj as H6,ti as B3,xi as EB,yi as V9,yj as E1,zi as U9}from"./chunk-h2cvg5r5.js";import{Ej as o1,Fj as f0,Gj as t1,Hj as O9}from"./chunk-2g1h9ktj.js";import{Mj as h,Pj as $Q,Qj as GZ}from"./chunk-ca1qwsjj.js";import{Rj as WZ,Sj as J2,Wj as YY,Xj as Y8,Yj as P}from"./chunk-0xmk4jyj.js";import{$j as dG,ck as i3}from"./chunk-j0bbh93g.js";import{gk as LY,jk as ZF}from"./chunk-8adbpxpm.js";import{Bk as E$,Gk as a1}from"./chunk-768yza4f.js";import{Uk as IG}from"./chunk-9a3wbbr6.js";import{Vk as BZ,Yk as eB,il as r3}from"./chunk-fhbre39m.js";import{kl as M$}from"./chunk-6wv3k8ap.js";import{Cl as H8,Fl as HF,Gl as TF,Hl as NF,ll as Q6,ml as v$,nl as g$,ol as M8,pl as LF,rl as y7,sl as MF}from"./chunk-ab5xsxyx.js";import{Wl as y$}from"./chunk-2as2xfem.js";import{$l as d5,em as u5}from"./chunk-mhvg8nnb.js";import{lm as c5,qm as u}from"./chunk-kbz5s9wb.js";import{rm as eZ,um as H}from"./chunk-wj0q7tyn.js";import{Cm as f5}from"./chunk-dh1wbntq.js";import{Rm as b5}from"./chunk-j5r7vm8a.js";import{Sm as z8,Um as RB}from"./chunk-358krc4n.js";import{Zm as i5}from"./chunk-4rs6w1gp.js";function W6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),bF=new Set([301,302,303,307,308]);class V1{kind;body;status;headers;[N2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return T2(J,"json"),new V1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return V1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!bF.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new V1("empty",void 0,J,Y)}static noContent($={}){return new V1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return T2(J,"text"),new V1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function T2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function i1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function EF($,Z,J={}){return V1.error($,Z,J)}function r0($){return typeof $==="string"?[$]:$}function Y6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function RF($){return"total"in $&&"partial"in $&&"body"in $}function P2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":I8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function kF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(RF($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function C8($,Z){if($ instanceof Response)return $;if(!$)return P2();let J=await kF($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return P2()}let{range:G}=Z;if(G){if(z<=0)return z3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=K8(G,z);if(!B)return z3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",_8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",Y6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:F,headers:V})}return new Response(W,{status:F,headers:V})}var wF=["content-type"];var K2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function qF($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function X3($,Z){let J=(Y)=>{throw Error(`CORS policy on ${Z}: ${Y}`)};if($===null||typeof $!=="object")J('expected an object such as { origins: "*" } or `false`.');let W=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(W!=="*"){if(!Array.isArray(W)||W.length===0)J('`origins` must be "*", an origin or a non-empty list of origins.');for(let Y of W){if(Y==="*")J('"*" goes on its own (`origins: "*"`), not in a list.');if(Y!=="null"&&!qF(Y))J(`"${Y}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(W==="*")J("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(W.includes("null"))J('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let Y of $.methods??[])if(!K2.test(Y))J(`"${Y}" is not a method.`);for(let Y of[...$.headers??[],...$.exposeHeaders??[]])if(!K2.test(Y))J(`"${Y}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))J("`maxAge` must be a whole number of seconds.");return{...$,origins:W}}function I2($,Z){return $.origins==="*"||$.origins.includes(Z)}function fF($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function C2($,Z,J){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":J),fF(Z,J))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function x2($,Z){let J=($.get("Vary")??"").split(",").map((Y)=>Y.trim()).filter(Boolean);if(J.includes("*"))return;let W=J.map((Y)=>Y.toLowerCase());for(let Y of Z)if(!W.includes(Y.toLowerCase()))J.push(Y);$.set("Vary",J.join(", "))}function _2($,Z,J){if(Z.origins!=="*")x2($,["Origin"]);if(!J||!I2(Z,J))return;if(C2($,Z,J),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function A2($,Z,J){let W=J.headers.get("Origin");try{return _2($.headers,Z,W),$}catch{let Y=new Headers($.headers);return _2(Y,Z,W),new Response($.body,{status:$.status,statusText:$.statusText,headers:Y})}}function S2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function b2($,Z){let J=new Headers,W=$.headers.get("Origin"),Y=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[Y];if(x2(J,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!W||!I2(j,W))return new Response(null,{status:204,headers:J});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(Y))return new Response(null,{status:204,headers:J});let G=(j.headers??wF).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:J});if(C2(J,j,W),J.set("Access-Control-Allow-Methods",X.join(", ")),G.length)J.set("Access-Control-Allow-Headers",G.join(", "));return J.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:J})}function vF($){return W6($)}function E2($,Z){if($.length===0)return $();return $(Z??new S)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!vF(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return E2(Z[this.methodName].bind(Z),$)}return E2(this.handler,$)}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,`a ${this.method} route`),this}}class f2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,"a proxy route"),this}async run(){let $=new S,Z=$.headers.toJSON();for(let J of k2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(q2($.rawRequest))throw new A8(w2($.rawRequest));throw J}}}class v2{constructor(...$){return new n(...$)}}class g2 extends n{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=x8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(i1(Y))return Y;return await C8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof S8)return z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class y2{constructor(...$){return new g2(...$)}}class m2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class C0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new m2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${R2($)}.`);return gF($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${R2($)}.`);return yF($)}file($,Z){return new v2("GET",$,Z)}stream($,Z){return new y2("GET",$,Z)}proxy($,Z={}){return new f2($,Z)}}function R2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function gF($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function yF($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends C0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var s1="access_token";function S$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function j6($,Z){let J=S$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var mF=/^[A-Za-z0-9_-]+$/,hF=/^:[A-Za-z_][A-Za-z0-9_]*$/,h2=/^[A-Za-z0-9_-]{1,128}$/,pF=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function p2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(hF.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!mF.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function G3($,Z={}){let J=UZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!h2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function c2($){if(typeof $!=="string"||$.length===0||$.length>64||!pF.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function d2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&h2.test(W[j]))}var U0="user";function DZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return G3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class X6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??b$("50mb"):b$(Z);return z6(this.req.rawRequest,J),{}}}function cF($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function dF($){return{"body-limit":X6.configure({uploadLimit:$})}}class n1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:b$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=b$($.uploadBodyLimit??"50mb"),this.builtinAliases=dF(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||l2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;z6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new S,J=this.aliases,W=[];for(let[Y,j]of cF($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:u2(z)})}}else if(W6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:u2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await uF(W.slice(j+1)),z}return Y})()}}function u2($){return $?.runsOnRefusal===!0}async function uF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class G6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...r0($)],this}events(...$){return this}}class o2{static __brand="ChannelRouter";channels={};public(){return new G6("public")}private($){return new G6("private",$)}async authorize($,Z,J={},W={}){try{nF(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!a2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=G3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new S($,z,"api",Z);return P.exit(()=>Q6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H(n1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await i2(X);if(!Q)return{ok:!1,code:"denied"};if(j=DZ(Q),Y.visibility==="private"&&Y.authorizer){if(await s2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await s2(Y.authorizer,X,z):await i2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(sF(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function lF($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;t2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function a2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function i2($){if(!P.getStore().user&&S$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function s2($,Z,J){if(iF($))return new $().authorize(Z,J);return $(Z,J)}function iF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function sF($){return $?.kind===o1||a1($)||E$($)}var n2=new WeakSet;function nF($){if(n2.has($))return;t2($),n2.add($)}function t2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!a2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(oF(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function oF($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class E8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class R8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function aF($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function tF($,Z){let J=aF($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class r2{static __brand="McpRouter";routes={};scopes;param($){return new E8($.as,$.input,$.bind)}fromTool($,Z={}){return new R8($,Z)}fromApiRoute($,Z,J){return new B6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(Y??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...N}=Y[U],K=O??(D?tF(W,D):W);if(B.has(K))throw Error(`${Q}: the audiences "${B.get(K)}" and "${U}" are both named "${K}". Give one its own name or casing.`);B.set(K,U);let _=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof _!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let x={...G,...N,description:_};if(z||M)x.params={...z,...M};if(X||T)x.files={...X,...T};V[K]=new B6($,Z,x)}return V}}function D0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class k8 extends f0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class S1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new k8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new k8($,Z)}}class e2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function w8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",Y6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class $9{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function Z9($,Z){if(i1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class J9{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=Z9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=r0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class W9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=Z9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new J9($,Z)}file($){return new $9($)}redirect($){return new e2($)}layout($,Z,J){return new W9($,Z,J)}}function rF($){return $}function eF(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function OZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function $V($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(u).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function ZV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(R).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=$V($,!W);if(W||!ZV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class Y9 extends Z0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await j6(H(R),J);if(!W)throw new R$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var v8="gemi_same_site",f8="private, no-cache, no-store, max-age=0, must-revalidate";class V6 extends Z0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(v8))return{};if(S$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(v8,"1"),new j9(`${W.pathname}${W.search}`)}}class j9 extends f0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=JV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":f8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":f8}},viewData:{status:200,data:{},headers:{"Cache-Control":f8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function JV($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class z9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var X9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class G9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...X9,...this.config.origins[Z]};if(Z==="null")delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...X9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var WV="Rate limit exceeded";class r1 extends f0{result;retryAfter;constructor($,Z=WV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?g8($):{}};this.payload={api:{status:429,data:{error:{...t1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function g8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(Q9("window",W),Q9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new r1(W,typeof J==="function"?J(W):J);return W}}function Q9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as U6}from"net";function e1($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return U6(j)===6?j:null}if(U6(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&U6(J[1])===4?J[1]:null}function B9($,{ipv6Prefix:Z=64}={}){if(!Number.isInteger(Z)||Z<0||Z>128)throw RangeError(`ipv6Prefix must be a whole number from 0 to 128, not ${Z}.`);let J=e1($);if(J===null||U6(J)===4)return J??$;let W=YV(J);if(W===null)return $;if(W.slice(0,5).every((z)=>z===0)&&W[5]===65535)return`${W[6]>>8}.${W[6]&255}.${W[7]>>8}.${W[7]&255}`;let Y=W.map((z,X)=>{let G=Math.min(Math.max(Z-X*16,0),16);return z&(65535<<16-G&65535)}),j=jV(Y);return Z===128?j:`${j}/${Z}`}function YV($){let Z=$.split("%")[0].toLowerCase(),J=/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(Z);if(J){let[Q,F,V,B]=J.slice(1).map(Number);Z=`${Z.slice(0,J.index)}${(Q<<8|F).toString(16)}:${(V<<8|B).toString(16)}`}let[W,Y]=Z.split("::"),j=(Q)=>Q===""?[]:Q.split(":").map((F)=>parseInt(F,16)),z=j(W),X=Y===void 0?[]:j(Y),G=Y===void 0?z:[...z,...Array.from({length:8-z.length-X.length},()=>0),...X];return G.length===8&&G.every((Q)=>Q>=0&&Q<=65535)?G:null}function jV($){let Z=-1,J=0;for(let Y=0;Y<8;Y++){if($[Y]!==0)continue;let j=Y;while(j<8&&$[j]===0)j++;if(j-Y>J)Z=Y,J=j-Y;Y=j}let W=$.map((Y)=>Y.toString(16));if(J<2)return W.join(":");return`${W.slice(0,Z).join(":")}::${W.slice(Z+J).join(":")}`}class D9 extends Z0{async run($,Z){let J=zV();if(!J)return{};let W=await J.consume(this.key(),{limit:F9($)??this.config.limit,window:F9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(g8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new r1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=V9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${O6(this.req)}:${this.req.routePath??"*"}`}}function zV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function D6($){let Z=U9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return e1(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function O6($,Z){return B9(D6($),Z)}function F9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class L9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new y8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new y8;return{}}}class y8 extends f0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:O9("csrf","Invalid CSRF token",403)}},view:{}}}class M9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class H9{all($,Z){return!0}}class m8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new LZ:new L6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new S,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof LZ:$ instanceof L6}}function XV($){return new m8($)}async function T6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await NV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return TV(z,Z,J,$.url)}async function TV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await Y.read();if(Q)break;if(z+F.byteLength>Z){if(!J)throw new H6(W,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function NV($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function N6($){return new TextDecoder("utf-8").decode($)}var PV={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function k$($){return $.replace(/[&<>"']/g,(Z)=>PV[Z])}var KV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function h8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return KV[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function p8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function T9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(h8($.slice(W)));return}if(Y>W)Z.text(h8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(p8($.slice(Y+2,j).trim())),W=j+1}else{let j=_V($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=p8(z.slice(0,G));if(Q){if(Z.open(Q,IV(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function _V($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function IV($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[p8(W[1])]=h8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var I9="http://www.sitemaps.org/schemas/sitemap/0.9",CV="http://www.w3.org/1999/xhtml",u8=`<?xml version="1.0" encoding="UTF-8"?>
2
+ import{_h as KF}from"./chunk-vcmwp7pv.js";import{si as PF}from"./chunk-c3c37k46.js";import{Ai as x8,Bi as K8,Cj as QZ,Ei as _8,Fi as I8,Gi as xB,Hi as p5,Ji as $3,Ki as W8,Li as $2,Mi as k2,Ni as d,Pi as A8,Qi as b$,Ri as l2,Si as w2,Ti as q2,Ui as z6,Vi as S,Wi as _5,Xi as s8,Yi as LZ,Zi as S8,_i as L6,aj as R$,bj as a4,kj as M6,qj as H6,ti as B3,xi as EB,yi as V9,yj as E1,zi as U9}from"./chunk-h2cvg5r5.js";import{Ej as o1,Fj as f0,Gj as t1,Hj as O9}from"./chunk-2g1h9ktj.js";import{Mj as h,Pj as $Q,Qj as GZ}from"./chunk-ca1qwsjj.js";import{Rj as WZ,Sj as J2,Wj as YY,Xj as Y8,Yj as P}from"./chunk-0xmk4jyj.js";import{$j as dG,ck as i3}from"./chunk-szyr67g7.js";import{gk as LY,jk as ZF}from"./chunk-8adbpxpm.js";import{Bk as E$,Gk as a1}from"./chunk-768yza4f.js";import{Uk as IG}from"./chunk-9a3wbbr6.js";import{Vk as BZ,Yk as eB,il as r3}from"./chunk-psdcmh65.js";import{kl as M$}from"./chunk-6wv3k8ap.js";import{Cl as H8,Fl as HF,Gl as TF,Hl as NF,ll as Q6,ml as v$,nl as g$,ol as M8,pl as LF,rl as y7,sl as MF}from"./chunk-mxqrmjha.js";import{Wl as y$}from"./chunk-2as2xfem.js";import{$l as d5,em as u5}from"./chunk-mhvg8nnb.js";import{lm as c5,qm as u}from"./chunk-kbz5s9wb.js";import{rm as eZ,um as H}from"./chunk-wj0q7tyn.js";import{Cm as f5}from"./chunk-dh1wbntq.js";import{Rm as b5}from"./chunk-j5r7vm8a.js";import{Sm as z8,Um as RB}from"./chunk-358krc4n.js";import{Zm as i5}from"./chunk-4rs6w1gp.js";function W6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),bF=new Set([301,302,303,307,308]);class V1{kind;body;status;headers;[N2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return T2(J,"json"),new V1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return V1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!bF.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new V1("empty",void 0,J,Y)}static noContent($={}){return new V1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return T2(J,"text"),new V1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function T2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function i1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function EF($,Z,J={}){return V1.error($,Z,J)}function r0($){return typeof $==="string"?[$]:$}function Y6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function RF($){return"total"in $&&"partial"in $&&"body"in $}function P2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":I8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function kF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(RF($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function C8($,Z){if($ instanceof Response)return $;if(!$)return P2();let J=await kF($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return P2()}let{range:G}=Z;if(G){if(z<=0)return z3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=K8(G,z);if(!B)return z3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",_8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",Y6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:F,headers:V})}return new Response(W,{status:F,headers:V})}var wF=["content-type"];var K2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function qF($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function X3($,Z){let J=(Y)=>{throw Error(`CORS policy on ${Z}: ${Y}`)};if($===null||typeof $!=="object")J('expected an object such as { origins: "*" } or `false`.');let W=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(W!=="*"){if(!Array.isArray(W)||W.length===0)J('`origins` must be "*", an origin or a non-empty list of origins.');for(let Y of W){if(Y==="*")J('"*" goes on its own (`origins: "*"`), not in a list.');if(Y!=="null"&&!qF(Y))J(`"${Y}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(W==="*")J("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(W.includes("null"))J('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let Y of $.methods??[])if(!K2.test(Y))J(`"${Y}" is not a method.`);for(let Y of[...$.headers??[],...$.exposeHeaders??[]])if(!K2.test(Y))J(`"${Y}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))J("`maxAge` must be a whole number of seconds.");return{...$,origins:W}}function I2($,Z){return $.origins==="*"||$.origins.includes(Z)}function fF($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function C2($,Z,J){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":J),fF(Z,J))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function x2($,Z){let J=($.get("Vary")??"").split(",").map((Y)=>Y.trim()).filter(Boolean);if(J.includes("*"))return;let W=J.map((Y)=>Y.toLowerCase());for(let Y of Z)if(!W.includes(Y.toLowerCase()))J.push(Y);$.set("Vary",J.join(", "))}function _2($,Z,J){if(Z.origins!=="*")x2($,["Origin"]);if(!J||!I2(Z,J))return;if(C2($,Z,J),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function A2($,Z,J){let W=J.headers.get("Origin");try{return _2($.headers,Z,W),$}catch{let Y=new Headers($.headers);return _2(Y,Z,W),new Response($.body,{status:$.status,statusText:$.statusText,headers:Y})}}function S2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function b2($,Z){let J=new Headers,W=$.headers.get("Origin"),Y=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[Y];if(x2(J,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!W||!I2(j,W))return new Response(null,{status:204,headers:J});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(Y))return new Response(null,{status:204,headers:J});let G=(j.headers??wF).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:J});if(C2(J,j,W),J.set("Access-Control-Allow-Methods",X.join(", ")),G.length)J.set("Access-Control-Allow-Headers",G.join(", "));return J.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:J})}function vF($){return W6($)}function E2($,Z){if($.length===0)return $();return $(Z??new S)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!vF(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return E2(Z[this.methodName].bind(Z),$)}return E2(this.handler,$)}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,`a ${this.method} route`),this}}class f2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,"a proxy route"),this}async run(){let $=new S,Z=$.headers.toJSON();for(let J of k2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(q2($.rawRequest))throw new A8(w2($.rawRequest));throw J}}}class v2{constructor(...$){return new n(...$)}}class g2 extends n{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=x8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(i1(Y))return Y;return await C8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof S8)return z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class y2{constructor(...$){return new g2(...$)}}class m2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class C0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new m2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${R2($)}.`);return gF($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${R2($)}.`);return yF($)}file($,Z){return new v2("GET",$,Z)}stream($,Z){return new y2("GET",$,Z)}proxy($,Z={}){return new f2($,Z)}}function R2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function gF($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function yF($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends C0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var s1="access_token";function S$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function j6($,Z){let J=S$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var mF=/^[A-Za-z0-9_-]+$/,hF=/^:[A-Za-z_][A-Za-z0-9_]*$/,h2=/^[A-Za-z0-9_-]{1,128}$/,pF=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function p2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(hF.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!mF.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function G3($,Z={}){let J=UZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!h2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function c2($){if(typeof $!=="string"||$.length===0||$.length>64||!pF.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function d2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&h2.test(W[j]))}var U0="user";function DZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return G3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class X6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??b$("50mb"):b$(Z);return z6(this.req.rawRequest,J),{}}}function cF($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function dF($){return{"body-limit":X6.configure({uploadLimit:$})}}class n1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:b$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=b$($.uploadBodyLimit??"50mb"),this.builtinAliases=dF(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||l2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;z6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new S,J=this.aliases,W=[];for(let[Y,j]of cF($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:u2(z)})}}else if(W6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:u2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await uF(W.slice(j+1)),z}return Y})()}}function u2($){return $?.runsOnRefusal===!0}async function uF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class G6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...r0($)],this}events(...$){return this}}class o2{static __brand="ChannelRouter";channels={};public(){return new G6("public")}private($){return new G6("private",$)}async authorize($,Z,J={},W={}){try{nF(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!a2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=G3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new S($,z,"api",Z);return P.exit(()=>Q6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H(n1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await i2(X);if(!Q)return{ok:!1,code:"denied"};if(j=DZ(Q),Y.visibility==="private"&&Y.authorizer){if(await s2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await s2(Y.authorizer,X,z):await i2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(sF(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function lF($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;t2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function a2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function i2($){if(!P.getStore().user&&S$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function s2($,Z,J){if(iF($))return new $().authorize(Z,J);return $(Z,J)}function iF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function sF($){return $?.kind===o1||a1($)||E$($)}var n2=new WeakSet;function nF($){if(n2.has($))return;t2($),n2.add($)}function t2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!a2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(oF(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function oF($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class E8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class R8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function aF($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function tF($,Z){let J=aF($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class r2{static __brand="McpRouter";routes={};scopes;param($){return new E8($.as,$.input,$.bind)}fromTool($,Z={}){return new R8($,Z)}fromApiRoute($,Z,J){return new B6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(Y??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...N}=Y[U],K=O??(D?tF(W,D):W);if(B.has(K))throw Error(`${Q}: the audiences "${B.get(K)}" and "${U}" are both named "${K}". Give one its own name or casing.`);B.set(K,U);let _=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof _!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let x={...G,...N,description:_};if(z||M)x.params={...z,...M};if(X||T)x.files={...X,...T};V[K]=new B6($,Z,x)}return V}}function D0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class k8 extends f0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class S1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new k8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new k8($,Z)}}class e2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function w8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",Y6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class $9{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function Z9($,Z){if(i1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class J9{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=Z9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=r0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class W9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=Z9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new J9($,Z)}file($){return new $9($)}redirect($){return new e2($)}layout($,Z,J){return new W9($,Z,J)}}function rF($){return $}function eF(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function OZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function $V($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(u).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function ZV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(R).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=$V($,!W);if(W||!ZV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class Y9 extends Z0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await j6(H(R),J);if(!W)throw new R$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var v8="gemi_same_site",f8="private, no-cache, no-store, max-age=0, must-revalidate";class V6 extends Z0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(v8))return{};if(S$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(v8,"1"),new j9(`${W.pathname}${W.search}`)}}class j9 extends f0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=JV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":f8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":f8}},viewData:{status:200,data:{},headers:{"Cache-Control":f8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function JV($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class z9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var X9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class G9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...X9,...this.config.origins[Z]};if(Z==="null")delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...X9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var WV="Rate limit exceeded";class r1 extends f0{result;retryAfter;constructor($,Z=WV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?g8($):{}};this.payload={api:{status:429,data:{error:{...t1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function g8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(Q9("window",W),Q9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new r1(W,typeof J==="function"?J(W):J);return W}}function Q9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as U6}from"net";function e1($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return U6(j)===6?j:null}if(U6(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&U6(J[1])===4?J[1]:null}function B9($,{ipv6Prefix:Z=64}={}){if(!Number.isInteger(Z)||Z<0||Z>128)throw RangeError(`ipv6Prefix must be a whole number from 0 to 128, not ${Z}.`);let J=e1($);if(J===null||U6(J)===4)return J??$;let W=YV(J);if(W===null)return $;if(W.slice(0,5).every((z)=>z===0)&&W[5]===65535)return`${W[6]>>8}.${W[6]&255}.${W[7]>>8}.${W[7]&255}`;let Y=W.map((z,X)=>{let G=Math.min(Math.max(Z-X*16,0),16);return z&(65535<<16-G&65535)}),j=jV(Y);return Z===128?j:`${j}/${Z}`}function YV($){let Z=$.split("%")[0].toLowerCase(),J=/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(Z);if(J){let[Q,F,V,B]=J.slice(1).map(Number);Z=`${Z.slice(0,J.index)}${(Q<<8|F).toString(16)}:${(V<<8|B).toString(16)}`}let[W,Y]=Z.split("::"),j=(Q)=>Q===""?[]:Q.split(":").map((F)=>parseInt(F,16)),z=j(W),X=Y===void 0?[]:j(Y),G=Y===void 0?z:[...z,...Array.from({length:8-z.length-X.length},()=>0),...X];return G.length===8&&G.every((Q)=>Q>=0&&Q<=65535)?G:null}function jV($){let Z=-1,J=0;for(let Y=0;Y<8;Y++){if($[Y]!==0)continue;let j=Y;while(j<8&&$[j]===0)j++;if(j-Y>J)Z=Y,J=j-Y;Y=j}let W=$.map((Y)=>Y.toString(16));if(J<2)return W.join(":");return`${W.slice(0,Z).join(":")}::${W.slice(Z+J).join(":")}`}class D9 extends Z0{async run($,Z){let J=zV();if(!J)return{};let W=await J.consume(this.key(),{limit:F9($)??this.config.limit,window:F9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(g8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new r1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=V9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${O6(this.req)}:${this.req.routePath??"*"}`}}function zV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function D6($){let Z=U9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return e1(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function O6($,Z){return B9(D6($),Z)}function F9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class L9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new y8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new y8;return{}}}class y8 extends f0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:O9("csrf","Invalid CSRF token",403)}},view:{}}}class M9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class H9{all($,Z){return!0}}class m8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new LZ:new L6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new S,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof LZ:$ instanceof L6}}function XV($){return new m8($)}async function T6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await NV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return TV(z,Z,J,$.url)}async function TV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await Y.read();if(Q)break;if(z+F.byteLength>Z){if(!J)throw new H6(W,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function NV($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function N6($){return new TextDecoder("utf-8").decode($)}var PV={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function k$($){return $.replace(/[&<>"']/g,(Z)=>PV[Z])}var KV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function h8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return KV[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function p8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function T9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(h8($.slice(W)));return}if(Y>W)Z.text(h8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(p8($.slice(Y+2,j).trim())),W=j+1}else{let j=_V($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=p8(z.slice(0,G));if(Q){if(Z.open(Q,IV(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function _V($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function IV($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[p8(W[1])]=h8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var I9="http://www.sitemaps.org/schemas/sitemap/0.9",CV="http://www.w3.org/1999/xhtml",u8=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `,N9=`<urlset xmlns="${I9}" xmlns:xhtml="${CV}">
4
4
  `,P9=`</urlset>
5
5
  `,w$=50000,Q3=52428800,K9=2048,xV=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),AV=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,SV="application/xml; charset=utf-8",_9=new TextEncoder;function l8($,Z){let J;try{J=new URL($)}catch{throw new j0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new j0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>K9)throw new j0(`Sitemap: ${Z} is over ${K9} characters: "${W.slice(0,80)}\u2026".`);return W}function C9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!AV.test($))throw new j0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function bV($){let Z=l8($.loc,"loc"),J=`<url><loc>${k$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${k$(C9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!xV.has($.changefreq))throw new j0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new j0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new j0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=l8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${k$(Y)}" href="${k$(j)}"/>`}return`${J}</url>
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Yj as l}from"./chunk-0xmk4jyj.js";import{ek as O,fk as E,gk as k}from"./chunk-8adbpxpm.js";import{Fk as R,Hk as i,Ik as C,Jk as M,Kk as Xz,vk as T}from"./chunk-768yza4f.js";import{Al as a}from"./chunk-ab5xsxyx.js";var $z=["every","none","some"],Vz=["is","isNot"];function g(z){return z==="many"?$z:Vz}function h(z,J){let W=Object.keys(z);return W.length>0&&W.every((Z)=>J.includes(Z))}var m="_count";function y(z){return Object.keys(z.relations).filter((J)=>z.relations[J]?.kind==="many").sort()}function N(z,J,W,Z){let X={model:z,operation:J,hasUser:W!=null};return Object.defineProperty(X,"user",{enumerable:!0,get(){if(W==null&&!Z)throw new R(z,J,"no-user");return W}}),X}class n{}class Qz extends n{}var qz=new Set(["findMany","findFirst","findFirstOrThrow","findUnique","findUniqueOrThrow","count","aggregate","groupBy","update","updateMany","delete","deleteMany"]),Yz=new Set(["create","createMany","upsert"]),jz=new Set(["update","updateMany","upsert"]),Lz=new Set(["update","updateMany"]),Kz=new Set(["create","createMany"]),p=new WeakMap;function Gz(z,J,W){if(typeof z!=="function")return z;let Z=p.get(z);if(Z!==void 0)return Z;let X;try{X=new z}catch($){throw new M(b(J),W,"constructor-threw",`${f(z)}, and constructing it threw:
2
+ import{Yj as l}from"./chunk-0xmk4jyj.js";import{ek as O,fk as E,gk as k}from"./chunk-8adbpxpm.js";import{Fk as R,Hk as i,Ik as C,Jk as M,Kk as Xz,vk as T}from"./chunk-768yza4f.js";import{Al as a}from"./chunk-mxqrmjha.js";var $z=["every","none","some"],Vz=["is","isNot"];function g(z){return z==="many"?$z:Vz}function h(z,J){let W=Object.keys(z);return W.length>0&&W.every((Z)=>J.includes(Z))}var m="_count";function y(z){return Object.keys(z.relations).filter((J)=>z.relations[J]?.kind==="many").sort()}function N(z,J,W,Z){let X={model:z,operation:J,hasUser:W!=null};return Object.defineProperty(X,"user",{enumerable:!0,get(){if(W==null&&!Z)throw new R(z,J,"no-user");return W}}),X}class n{}class Qz extends n{}var qz=new Set(["findMany","findFirst","findFirstOrThrow","findUnique","findUniqueOrThrow","count","aggregate","groupBy","update","updateMany","delete","deleteMany"]),Yz=new Set(["create","createMany","upsert"]),jz=new Set(["update","updateMany","upsert"]),Lz=new Set(["update","updateMany"]),Kz=new Set(["create","createMany"]),p=new WeakMap;function Gz(z,J,W){if(typeof z!=="function")return z;let Z=p.get(z);if(Z!==void 0)return Z;let X;try{X=new z}catch($){throw new M(b(J),W,"constructor-threw",`${f(z)}, and constructing it threw:
3
3
 
4
4
  ${$?.message??String($)}`,H,void 0,{cause:$})}return t(X,J,W),p.set(z,X),X}function S(z,J){return z.map((W,Z)=>Gz(W,J,Z))}var H=["before","scope","onCreate","onUpdate","redact"];var u=new WeakSet;function s(z,J){if(u.has(J))return;for(let W=0;W<J.length;W++)Uz(J[W],z,W);u.add(J)}function Uz(z,J,W){let Z=b(J),X=typeof z;if(z===null||Array.isArray(z)||X!=="object"&&X!=="function")throw new M(Z,W,"not-a-policy",o(z),H);if(X==="function"){if(!Mz(z))throw new M(Z,W,"not-constructable",f(z),H);return}t(z,J,W)}function t(z,J,W){let Z=b(J),X=0,$=[];for(let Y of H){let q=z[Y];if(q===void 0||q===null){if(Y in z)$.push(Y);continue}if(typeof q!=="function")throw new M(Z,W,"hook-not-callable",`'${Y}' that is ${o(q)} rather than a function`,H);X++}if(X>0)return;if($.length>0)throw new M(Z,W,"no-hooks",`It writes ${$.map((Y)=>`'${Y}'`).join(", ")} down and leaves ${$.length===1?"it":"them"} unset, which reads as `+"absent \u2014 so nothing is left to run.",H);let V=Fz(z),Q=Iz(V);throw new M(Z,W,"no-hooks",V.length===0?"It is empty.":`It spells ${Hz(V)}.`+(V.length===1&&V[0]==="default"?" A lone 'default' is a module namespace rather than the policy "+"inside it \u2014 put `entry.default` in the array, or import the "+"policy by name.":""),H,Q)}function Hz(z){let J=z.slice(0,8).map((W)=>`'${W}'`);return z.length>J.length?`${J.join(", ")} and ${z.length-J.length} more`:J.join(", ")}function Mz(z){try{return Reflect.construct(Bz,[],z),!0}catch{return!1}}var Bz=function(){};function Fz(z){let J=new Set,W=z;while(W!==null&&W!==Object.prototype){for(let Z of Object.getOwnPropertyNames(W))if(Z!=="constructor")J.add(Z);W=Object.getPrototypeOf(W)}return[...J]}function Iz(z){let J,W=2;for(let Z of z)for(let X of H){let $=Tz(Z.toLowerCase(),X.toLowerCase());if($<W)W=$,J={key:Z,hook:X}}return J}function Tz(z,J){if(z===J)return 0;let W=Array.from({length:J.length+1},(Z,X)=>X);for(let Z=1;Z<=z.length;Z++){let X=W[0];W[0]=Z;for(let $=1;$<=J.length;$++){let V=W[$];W[$]=Math.min(W[$]+1,W[$-1]+1,X+(z[Z-1]===J[$-1]?0:1)),X=V}}return W[J.length]}function o(z){if(z===null)return"null";if(z===void 0)return"undefined";if(typeof z==="string")return`the string ${JSON.stringify(z)}`;if(typeof z==="function")return f(z);if(Array.isArray(z))return"an array";if(typeof z==="object")return"an object";return`the ${typeof z} ${String(z)}`}function f(z){return z.name?`the function \`${z.name}\``:"an anonymous function"}function _(z){let J,W,Z,X=z;while(X&&X!==Function.prototype){if(Object.hasOwn(X,"$policy"))throw Error(`${X.name??"This model"} declares \`$policy\`, which is now \`$policies\` and takes a list. The old `+"name is not read, so this model is currently unpolicied \u2014 every "+"scope, onCreate and redact on it is being skipped.");if(Object.hasOwn(X,"$policies")&&X.$policies){let $=X.$policies;if($.length>0){let V=X;if(s(V,$),W===void 0&&J===void 0)W=$,Z=V;else J??=S(W,Z),W=void 0,J.unshift(...S($,V))}}X=Object.getPrototypeOf(X)}if(J!==void 0)return J;if(W===void 0)return Nz;return W.some(($)=>typeof $==="function")?S(W,Z):W}function r(z){let J=z;while(J&&J!==Function.prototype){if(Object.hasOwn(J,"$policies")&&J.$policies){let W=J.$policies;if(W.length>0)s(J,W)}J=Object.getPrototypeOf(J)}}function b(z){return z?.name??"This model"}var Nz=Object.freeze([]);function D(z,J,W,Z=[]){if(z.length===0)return W;let X=W,$;for(let V of z)if(V.before){if(V.before(J)===!1)throw new R(J.model,J.operation)}for(let V of z){if(!V.scope)continue;if(Kz.has(J.operation)){Sz(V,J);continue}let Q=V.scope(J);if(Q===void 0||Q===null)continue;if(Rz(J),Lz.has(J.operation)&&!V.onUpdate){let Y=Pz(Q);if(Y.length>0)($??=[]).push(...Y)}X=_z(X,Q)}if(Yz.has(J.operation)){for(let V of z)if(V.onCreate)X=Dz(X,J,V)}if(jz.has(J.operation)){for(let V of z)if(V.onUpdate)X=Az(X,J,V)}if($!==void 0)Cz($,J,X,Z);return X}function _z(z,J){let W=z?.where;if(W===void 0||W===null)return{...z,where:J};if(typeof W!=="object"||Array.isArray(W))return{...z,where:{AND:[W,J]}};let Z=W.AND,X=Z===void 0||Z===null?[]:Array.isArray(Z)?Z:[Z];return{...z,where:{...W,AND:[...X,J]}}}function Dz(z,J,W){let Z=(X)=>W.onCreate(J,{...X});if(J.operation==="createMany"){let X=z?.data;return{...z,data:Array.isArray(X)?X.map(Z):Z(X)}}if(J.operation==="upsert")return{...z,create:Z(z?.create)};return{...z,data:Z(z?.data)}}function Az(z,J,W){let Z=J.operation==="upsert"?"update":"data",X=z?.[Z];if(X===void 0||X===null)return z;return{...z,[Z]:W.onUpdate(J,{...X})}}function Cz(z,J,W,Z=[]){let X=W?.data;if(typeof X!=="object"||X===null)return;let $=z.filter((V)=>(V in X)&&!Z.includes(V));if($.length===0)return;throw new i(J.model,J.operation,[...new Set($)])}function Pz(z){if(typeof z!=="object"||z===null||Array.isArray(z))return[];let J=[];for(let W of Object.keys(z)){if(W==="AND"||W==="OR"||W==="NOT")continue;J.push(W)}return J}function Sz(z,J){if(z.onCreate)return;throw new T(J.operation,J.model,J.operation,`${J.model} has a policy that scopes reads but no 'onCreate', and ${J.operation} has no where clause for a scope to narrow. As written the policy would confine reads to the caller and let an insert name any value it likes. Add an onCreate that sets the scoped `+"column \u2014 or, if unscoped creates are intended, say so with an onCreate "+"that returns its data unchanged.")}function Rz(z){if(qz.has(z.operation))return;throw new T(z.operation,z.model,z.operation,`${z.model} has a policy with a scope, and ${z.operation} cannot carry one: its where clause compiles to an 'on conflict' target, which is a key rather than a filter. Running it would write outside the scope.
5
5
 
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{qa as c}from"../chunk-wgpg670d.js";import{qb as f,rb as o}from"../chunk-g6tqje74.js";import{he as A,ke as n,le as u,ve as r}from"../chunk-mt68n713.js";import"../chunk-w9v8bbp8.js";import"../chunk-8ccjtbm2.js";import{_j as g,ck as v}from"../chunk-j0bbh93g.js";import{nk as h}from"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-fhbre39m.js";import{kl as t}from"../chunk-6wv3k8ap.js";import"../chunk-ab5xsxyx.js";import"../chunk-2as2xfem.js";import{um as k}from"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-49kkapvr.js";import{Pm as a}from"../chunk-j5r7vm8a.js";import"../chunk-4rs6w1gp.js";function E(){let z=Promise.resolve(),J=Promise.resolve(),Y=(Q,G)=>new Promise(($)=>{Q.write(G,()=>$())});return{stdout:(Q)=>{z=Y(process.stdout,Q)},stderr:(Q)=>{J=Y(process.stderr,Q)},flush:async()=>{await Promise.all([z,J])}}}function x(z){let J=z.writers??E();return{args:z.args,options:z.options,argv:z.argv,line:(Y="")=>J.stdout(`${Y}
2
+ import{qa as c}from"../chunk-f0bz1q3t.js";import{qb as f,rb as o}from"../chunk-g6tqje74.js";import{he as A,ke as n,le as u,ve as r}from"../chunk-5na9khtz.js";import"../chunk-w9v8bbp8.js";import"../chunk-wt80ekv9.js";import{_j as g,ck as v}from"../chunk-szyr67g7.js";import{nk as h}from"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-psdcmh65.js";import{kl as t}from"../chunk-6wv3k8ap.js";import"../chunk-mxqrmjha.js";import"../chunk-2as2xfem.js";import{um as k}from"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-49kkapvr.js";import{Pm as a}from"../chunk-j5r7vm8a.js";import"../chunk-4rs6w1gp.js";function E(){let z=Promise.resolve(),J=Promise.resolve(),Y=(Q,G)=>new Promise(($)=>{Q.write(G,()=>$())});return{stdout:(Q)=>{z=Y(process.stdout,Q)},stderr:(Q)=>{J=Y(process.stderr,Q)},flush:async()=>{await Promise.all([z,J])}}}function x(z){let J=z.writers??E();return{args:z.args,options:z.options,argv:z.argv,line:(Y="")=>J.stdout(`${Y}
3
3
  `),error:(Y)=>J.stderr(`${Y}
4
4
  `),fail:(Y,Q=1)=>{throw new A(Y,Q)}}}import b from"path";var Gz=u("encryption:rotate").describe("Re-encrypt encrypted columns that are still under an older key").arg("model",{description:"The model to rotate. Omit to rotate every model with encrypted columns"}).option("batchSize",{type:"number",default:500,description:"Rows read and rewritten per batch"}).option("dryRun",{type:"boolean",description:"Count what would be re-encrypted, and write nothing"}).option("encryptPlaintext",{type:"boolean",description:"Also encrypt values that are not encrypted yet (a column just marked @gemi.encrypted)"}).handle(async({args:z,options:J,line:Y,fail:Q})=>{let G=z.model?[z.model]:[...new Set(h().map((B)=>B.split(".")[0]))],$=z.model?null:Jz();if(G.length===0&&!$){Y("No model has encrypted columns.");return}if($){let B=await $.rotateEncryption({dryRun:J.dryRun});Y(`OAuth connections: ${B.scanned} rows, ${B.rotated} ${J.dryRun?"to re-encrypt":"re-encrypted"}`)}let _=0;for(let B of G){let V=await c(B,{batchSize:J.batchSize,dryRun:J.dryRun,encryptPlaintext:J.encryptPlaintext});_+=V.plaintext,Y(`${V.model} (${V.fields.join(", ")}): ${V.scanned} rows, ${V.rotated} ${J.dryRun?"to re-encrypt":"re-encrypted"}`+(V.skipped>0?`, ${V.skipped} changed meanwhile (already current)`:"")+(V.plaintext>0?`, ${V.plaintext} not encrypted yet`:""))}if(_>0)Q(`${_} value${_===1?" is":"s are"} not encrypted. If the column was just marked @gemi.encrypted, run again with --encrypt-plaintext.`)});function Jz(){let z=k();if(!z.bound(v))return null;let J=z.make(v);if(Object.keys(J.providers).length===0)return null;let Y=J.store;return Y instanceof g?Y:null}var m=[Gz];function R(z){return z.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase()}function Qz(z){let J=new Map,Y=new Map;for(let Q of z){J.set(R(Q.name),Q),J.set(Q.name,Q);let G="alias"in Q?Q.alias:void 0;if(G)Y.set(G,Q)}return{byName:J,byAlias:Y}}function l(z){if(z==="--")return!0;if(!z.startsWith("-"))return!1;if(z==="-")return!1;if(/^-(\d|\.\d)/.test(z))return!1;return!0}function p(z,J){let{byName:Y,byAlias:Q}=Qz(z.options),G=[],$=[],_=new Map,B=!Y.has("help"),V=!Q.has("h"),F=!1,N=!1,W=(X)=>G.push(`Unknown option ${X} for command "${z.commandName}".`),T=(X,Z)=>{if(Z==="--help"||Z==="-h")N=!0;G.push(Z===void 0?`Option ${X} needs a value.`:`Option ${X} needs a value, but the next token is ${JSON.stringify(Z)}, which is another option. If that really is the value, write ${X}=${Z}.`)},j=0;while(j<J.length){let X=J[j];if(X==="--"){$.push(...J.slice(j+1));break}if(X.startsWith("--")){let Z=X.slice(2),K=Z.indexOf("="),M=K===-1?Z:Z.slice(0,K),O=K===-1?void 0:Z.slice(K+1),P=Y.get(M),D=!1;if(!P&&M.startsWith("no-")){let S=Y.get(M.slice(3));if(S&&S.type==="boolean")P=S,D=!0}if(!P&&M==="help"&&B){F=!0,j+=1;continue}if(!P){W(`--${M}`),j+=1;continue}if(P.type==="boolean"){if(O!==void 0&&O!=="true"&&O!=="false")G.push(`Option --${R(P.name)} is a flag and takes no value, but got ${JSON.stringify(O)}.`);else{let S=O===void 0?!0:O==="true";_.set(P.name,D?!S:S)}j+=1;continue}if(O!==void 0){_.set(P.name,O),j+=1;continue}let L=J[j+1];if(L===void 0||l(L)){T(`--${R(P.name)}`,L),j+=1;continue}_.set(P.name,L),j+=2;continue}if(X.startsWith("-")&&X.length>1){let Z=X.slice(1),K=!1;for(let M=0;M<Z.length;M+=1){let O=Q.get(Z[M]);if(!O){if(Z[M]==="h"&&V){F=!0;continue}W(`-${Z[M]}`);break}if(O.type==="boolean"){_.set(O.name,!0);continue}let P=Z.slice(M+1),D=P.startsWith("=")?P.slice(1):P;if(D!==""){_.set(O.name,D);break}let L=J[j+1];if(L===void 0||l(L)){T(`-${O.alias}`,L);break}_.set(O.name,L),K=!0;break}j+=K?2:1;continue}$.push(X),j+=1}let H={},I=0;for(let X of z.args){if(X.variadic){let K=$.slice(I);if(I=$.length,H[X.name]=K,X.required&&K.length===0)G.push(`Missing required argument <${X.name}...>. Command "${z.commandName}" needs at least one.`);continue}let Z=$[I];if(I+=1,Z!==void 0){H[X.name]=Z;continue}if(X.default!==void 0){H[X.name]=X.default;continue}if(X.required)G.push(`Missing required argument <${X.name}>.`);H[X.name]=void 0}if(I<$.length){let X=$.slice(I);G.push(`Unexpected argument${X.length===1?"":"s"} ${X.map((Z)=>JSON.stringify(Z)).join(", ")}. Command "${z.commandName}" takes ${z.args.length} argument${z.args.length===1?"":"s"}.`)}let U={};for(let X of z.options){let Z=_.get(X.name);if(X.type==="boolean"){U[X.name]=Z===void 0?X.default??!1:Boolean(Z);continue}if(Z===void 0){if(X.default!==void 0)U[X.name]=X.default;else if(X.required)G.push(`Missing required option --${R(X.name)}.`),U[X.name]=void 0;else U[X.name]=void 0;continue}let K=String(Z);if(X.type==="number"){let M=Number(K);if(K.trim()===""||!Number.isFinite(M))G.push(`Option --${R(X.name)} expects a number, but got ${JSON.stringify(K)}.`),U[X.name]=void 0;else U[X.name]=M;continue}U[X.name]=K}let q=F&&!N;if(G.length>0)return{ok:!1,help:q,errors:G};return{ok:!0,help:q,args:H,options:U}}function C(z,J=" "){let Y=z.reduce((Q,[G])=>Math.max(Q,G.length),0);return z.map(([Q,G])=>G===""?`${J}${Q}`:`${J}${Q.padEnd(Y)} ${G}`)}function d(z){let J=z.variadic?`${z.name}...`:z.name;return z.required?`<${J}>`:`[${J}]`}function Xz(z){let J=(G)=>z.options.some(G),Y=J((G)=>G.name==="help"||R(G.name)==="help"),Q=J((G)=>("alias"in G)&&G.alias==="h");if(Y&&Q)return[];if(Y)return[["-h","Show this message"]];return[[`${Q?"":"-h, "}--help`,"Show this message"]]}function w(z){let J=[],Y=z.args.map(d).join(" "),Q=["gemi run",z.commandName,z.options.length>0?"[options]":"",Y].filter(Boolean).join(" ");if(J.push(`Usage: ${Q}`),z.description)J.push("",z.description);if(z.args.length>0)J.push("","Arguments:"),J.push(...C(z.args.map((G)=>{let $=[G.description??"",G.default!==void 0?`(default: ${JSON.stringify(G.default)})`:""].filter(Boolean).join(" ");return[d(G),$]})));return J.push("","Options:"),J.push(...C([...z.options.map((G)=>{let $="alias"in G&&G.alias?`-${G.alias}, `:"",_=G.type==="boolean"?"":` <${G.type}>`,B=[G.description??"",G.default!==void 0?`(default: ${JSON.stringify(G.default)})`:"","required"in G&&G.required?"(required)":""].filter(Boolean).join(" ");return[`${$}--${R(G.name)}${_}`,B]}),...Xz(z)])),J.join(`
5
5
  `)}function i(z){return["Provided by gemi:","",...C(z.map((J)=>[J.commandName,J.description]))].join(`
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{$f as j,Bg as q,Mg as r,Ng as s,Og as t,Pg as u,Tf as a,Wf as c,Xf as e,Yf as f,Zf as h,_f as i,gg as k,hg as l,ig as m,jg as n,kg as o,lg as p,yh as v}from"../chunk-g6re0kkk.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{Bj as d}from"../chunk-h2cvg5r5.js";import"../chunk-2g1h9ktj.js";import{Mj as b,Qj as g}from"../chunk-ca1qwsjj.js";import"../chunk-0xmk4jyj.js";import"../chunk-j0bbh93g.js";import"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-fhbre39m.js";import"../chunk-6wv3k8ap.js";import"../chunk-ab5xsxyx.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import"../chunk-kbz5s9wb.js";import"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import"../chunk-4rs6w1gp.js";export{f as Url,d as Storage,r as Runs,j as Redis,a as Redirect,l as RateLimiter,e as Query,h as Meta,g as Log,m as Lock,c as Lang,s as Features,b as Facade,u as DB,n as Crypt,i as Cookie,o as Connections,t as ConnectionQueries,p as ChangeFeed,k as Cache,q as Broadcast,v as Auth};
2
+ import{$f as j,Bg as q,Mg as r,Ng as s,Og as t,Pg as u,Tf as a,Wf as c,Xf as e,Yf as f,Zf as h,_f as i,gg as k,hg as l,ig as m,jg as n,kg as o,lg as p,yh as v}from"../chunk-y89vn9da.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{Bj as d}from"../chunk-h2cvg5r5.js";import"../chunk-2g1h9ktj.js";import{Mj as b,Qj as g}from"../chunk-ca1qwsjj.js";import"../chunk-0xmk4jyj.js";import"../chunk-szyr67g7.js";import"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-psdcmh65.js";import"../chunk-6wv3k8ap.js";import"../chunk-mxqrmjha.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import"../chunk-kbz5s9wb.js";import"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import"../chunk-4rs6w1gp.js";export{f as Url,d as Storage,r as Runs,j as Redis,a as Redirect,l as RateLimiter,e as Query,h as Meta,g as Log,m as Lock,c as Lang,s as Features,b as Facade,u as DB,n as Crypt,i as Cookie,o as Connections,t as ConnectionQueries,p as ChangeFeed,k as Cache,q as Broadcast,v as Auth};
3
3
 
4
4
  //# debugId=F741325AA0CAAD4764756E2164756E21
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{$e as v,Ah as ca,Bh as da,Eh as ea,Fh as fa,Gh as ga,Hh as ha,Ih as ia,Jh as ja,Kh as ka,Lh as la,Mh as ma,Nh as na,Oh as oa,Ph as pa,Qh as qa,Rf as K,Rh as ra,Sf as L,Sh as sa,Th as ta,Uf as M,Uh as ua,Vf as N,Vh as va,Xg as aa,Ze as t,_e as u,af as w,bf as x,cf as E,hf as F,lf as G,mf as H,nf as I,of as J,zh as ba}from"../chunk-g6re0kkk.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{$i as C,Ai as e,Bi as f,Ci as g,Di as h,Ei as i,Fi as j,Ii as n,Ni as o,Oi as p,Pi as q,Qi as r,Vi as s,Xi as y,Yi as z,Zi as A,_i as B,aj as D,kj as O,lj as P,mj as Q,nj as R,oj as S,pj as T,qj as U,rj as V,sj as W,ti as a,tj as X,ui as b,uj as Y,vi as d,wj as Z,xj as _,yj as $}from"../chunk-h2cvg5r5.js";import{Fj as c}from"../chunk-2g1h9ktj.js";import"../chunk-ca1qwsjj.js";import{Tj as k,Uj as l,Vj as m}from"../chunk-0xmk4jyj.js";import"../chunk-j0bbh93g.js";import"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-fhbre39m.js";import"../chunk-6wv3k8ap.js";import"../chunk-ab5xsxyx.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import"../chunk-kbz5s9wb.js";import"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import"../chunk-4rs6w1gp.js";export{g as toRangeHeaderValue,v as toMiddlewareList,k as stateKey,$ as safeFetch,f as resolveRange,e as parseRangeHeader,h as parseContentRange,r as parseByteSize,ja as middlewareConfigDefaults,u as httpError,d as getCookies,j as formatUnsatisfiedContentRange,i as formatContentRange,ra as defineResourcePolicy,ia as defineMiddlewareConfig,n as cspNonce,w as createUnsatisfiableResponse,x as createStreamResponse,M as createFileResponse,I as clientIp,J as clientAddress,Z as classifyAddress,da as authorizeChannel,N as ViewRouter,o as ValidationError,W as TooManyRedirectsError,U as TooLargeError,T as TimeoutError,sa as SitemapError,ta as Sitemap,L as SameSiteBounceMiddleware,_ as SafeResponse,O as SafeFetchError,K as SAME_SITE_BOUNCE_PARAM,ua as RobotsTxt,va as Robots,qa as ResourcePolicy,b as ResourceController,m as RequestState,c as RequestBreakerError,H as RateLimitMiddleware,F as RateLimitExceededError,A as RangeNotSatisfiableError,oa as PoliciesServiceProvider,pa as Policies,q as PayloadTooLargeError,B as NotFoundError,X as NetworkError,l as MissingRequestStateError,G as Middleware,ga as McpToolDeclaration,ha as McpRouter,fa as McpRouteDeclaration,ea as McpModelParam,p as InvalidValidationRuleError,P as InvalidUrlError,z as InsufficientPermissionsError,Y as HttpStatusError,t as HttpResponse,s as HttpRequest,C as FileNotFoundError,S as DnsError,ma as CorsMiddleware,a as Controller,V as ContentTypeError,ca as ChannelRouter,ba as ChannelDeclaration,la as CacheMiddleware,na as CSRFMiddleware,aa as BodyLimitMiddleware,Q as BlockedHostError,R as BlockedAddressError,y as AuthorizationError,ka as AuthenticationMiddleware,D as AuthenticationError,E as ApiRouter};
2
+ import{$e as v,Ah as ca,Bh as da,Eh as ea,Fh as fa,Gh as ga,Hh as ha,Ih as ia,Jh as ja,Kh as ka,Lh as la,Mh as ma,Nh as na,Oh as oa,Ph as pa,Qh as qa,Rf as K,Rh as ra,Sf as L,Sh as sa,Th as ta,Uf as M,Uh as ua,Vf as N,Vh as va,Xg as aa,Ze as t,_e as u,af as w,bf as x,cf as E,hf as F,lf as G,mf as H,nf as I,of as J,zh as ba}from"../chunk-y89vn9da.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{$i as C,Ai as e,Bi as f,Ci as g,Di as h,Ei as i,Fi as j,Ii as n,Ni as o,Oi as p,Pi as q,Qi as r,Vi as s,Xi as y,Yi as z,Zi as A,_i as B,aj as D,kj as O,lj as P,mj as Q,nj as R,oj as S,pj as T,qj as U,rj as V,sj as W,ti as a,tj as X,ui as b,uj as Y,vi as d,wj as Z,xj as _,yj as $}from"../chunk-h2cvg5r5.js";import{Fj as c}from"../chunk-2g1h9ktj.js";import"../chunk-ca1qwsjj.js";import{Tj as k,Uj as l,Vj as m}from"../chunk-0xmk4jyj.js";import"../chunk-szyr67g7.js";import"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-psdcmh65.js";import"../chunk-6wv3k8ap.js";import"../chunk-mxqrmjha.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import"../chunk-kbz5s9wb.js";import"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import"../chunk-4rs6w1gp.js";export{g as toRangeHeaderValue,v as toMiddlewareList,k as stateKey,$ as safeFetch,f as resolveRange,e as parseRangeHeader,h as parseContentRange,r as parseByteSize,ja as middlewareConfigDefaults,u as httpError,d as getCookies,j as formatUnsatisfiedContentRange,i as formatContentRange,ra as defineResourcePolicy,ia as defineMiddlewareConfig,n as cspNonce,w as createUnsatisfiableResponse,x as createStreamResponse,M as createFileResponse,I as clientIp,J as clientAddress,Z as classifyAddress,da as authorizeChannel,N as ViewRouter,o as ValidationError,W as TooManyRedirectsError,U as TooLargeError,T as TimeoutError,sa as SitemapError,ta as Sitemap,L as SameSiteBounceMiddleware,_ as SafeResponse,O as SafeFetchError,K as SAME_SITE_BOUNCE_PARAM,ua as RobotsTxt,va as Robots,qa as ResourcePolicy,b as ResourceController,m as RequestState,c as RequestBreakerError,H as RateLimitMiddleware,F as RateLimitExceededError,A as RangeNotSatisfiableError,oa as PoliciesServiceProvider,pa as Policies,q as PayloadTooLargeError,B as NotFoundError,X as NetworkError,l as MissingRequestStateError,G as Middleware,ga as McpToolDeclaration,ha as McpRouter,fa as McpRouteDeclaration,ea as McpModelParam,p as InvalidValidationRuleError,P as InvalidUrlError,z as InsufficientPermissionsError,Y as HttpStatusError,t as HttpResponse,s as HttpRequest,C as FileNotFoundError,S as DnsError,ma as CorsMiddleware,a as Controller,V as ContentTypeError,ca as ChannelRouter,ba as ChannelDeclaration,la as CacheMiddleware,na as CSRFMiddleware,aa as BodyLimitMiddleware,Q as BlockedHostError,R as BlockedAddressError,y as AuthorizationError,ka as AuthenticationMiddleware,D as AuthenticationError,E as ApiRouter};
3
3
 
4
4
  //# debugId=74C09A0363F7972064756E2164756E21
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{ra as T}from"../chunk-7qhqqf0q.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-cwkf46bk.js";import{We as b,Xe as w}from"../chunk-g7exgg3k.js";import"../chunk-bhycdjcv.js";import{Wf as j}from"../chunk-g6re0kkk.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import"../chunk-h2cvg5r5.js";import"../chunk-2g1h9ktj.js";import"../chunk-ca1qwsjj.js";import"../chunk-0xmk4jyj.js";import"../chunk-j0bbh93g.js";import"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-fhbre39m.js";import"../chunk-6wv3k8ap.js";import"../chunk-ab5xsxyx.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import{lm as V,mm as X,nm as E,om as L,pm as R,qm as S}from"../chunk-kbz5s9wb.js";import"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import"../chunk-4rs6w1gp.js";import{createElement as J,Fragment as M,isValidElement as U}from"react";function $(q,B){let G=Object.values(B).some((z)=>typeof z==="function"&&U(z(""))),Q=/{{([^{}]+?)(?::([^{}\[\]]+?))?(?:\[(.*?)\])?}}/g;if(!G)return q.replace(Q,(W,O,_,Z)=>{let C=O.includes(":")?O.split(":")[0]:O,H=B[C];if(H===void 0)return W;if(typeof H==="function"){let K=H(Z!==void 0?Z:"");if(U(K))throw Error("JSX returned in string context");return String(K)}if(_)switch(_.toLowerCase()){case"number":return Number(H).toString();case"string":return String(H);case"boolean":return Boolean(H).toString();default:return String(H)}return String(H)});else{let z=[],W=0,O=null;while((O=Q.exec(q))!==null){let[_,Z,C,H]=O,F=O.index,K=Z.includes(":")?Z.split(":")[0]:Z;if(F>W)z.push(q.substring(W,F));let Y=B[K];if(Y===void 0)z.push(_);else if(typeof Y==="function"){let A=Y(H!==void 0?H:"");z.push(A)}else if(C)switch(C.toLowerCase()){case"number":z.push(Number(Y).toString());break;case"string":z.push(String(Y));break;case"boolean":z.push(Boolean(Y).toString());break;default:z.push(String(Y))}else z.push(String(Y));W=F+_.length}if(W<q.length)z.push(q.substring(W));return J(M,{},...z)}}class P{name;dictionary;constructor(q,B){this.name=q;this.dictionary=B}reference(q){if(typeof window<"u")throw Error("Cannot use reference in the browser");if(!this.dictionary?.[q])throw Error(`Translation not found for ${String(q)}`);return this.dictionary[q]}render(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B[0]};if(typeof window<"u")throw Error("Cannot use render in the browser");if(!this.dictionary?.[q]?.[G])throw Error(`Translation not found for ${String(q)} in ${String(G)}`);return $(this.dictionary[q][G],Q??{})}static create(q,B){return new P(q,B)}static text(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B?.[0]};if(!q?.[G])throw Error(`Translation not found for ${String(G)}`);return $(q[G],Q??{})}}async function N(q,B,...G){let{locale:Q=j.locale(),params:z}={params:{},...G[0]},O=(await q.load(String(Q)))[B];if(typeof O!=="string")throw Error(`Translation not found for "${B}" in "${String(Q)}" (dictionary ${q.id})`);return $(O,z??{})}export{w as translationConfigDefaults,N as translate,V as resolveLocale,X as negotiateLocale,L as isValidTimeZone,b as defineTranslationConfig,T as defineDictionary,R as createFormatter,S as Translator,D as TranslationServiceProvider,P as Dictionary,E as DEFAULT_TIME_ZONE};
2
+ import{ra as T}from"../chunk-7qhqqf0q.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-cwkf46bk.js";import{We as b,Xe as w}from"../chunk-g7exgg3k.js";import"../chunk-bhycdjcv.js";import{Wf as j}from"../chunk-y89vn9da.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import"../chunk-h2cvg5r5.js";import"../chunk-2g1h9ktj.js";import"../chunk-ca1qwsjj.js";import"../chunk-0xmk4jyj.js";import"../chunk-szyr67g7.js";import"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-psdcmh65.js";import"../chunk-6wv3k8ap.js";import"../chunk-mxqrmjha.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import{lm as V,mm as X,nm as E,om as L,pm as R,qm as S}from"../chunk-kbz5s9wb.js";import"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import"../chunk-4rs6w1gp.js";import{createElement as J,Fragment as M,isValidElement as U}from"react";function $(q,B){let G=Object.values(B).some((z)=>typeof z==="function"&&U(z(""))),Q=/{{([^{}]+?)(?::([^{}\[\]]+?))?(?:\[(.*?)\])?}}/g;if(!G)return q.replace(Q,(W,O,_,Z)=>{let C=O.includes(":")?O.split(":")[0]:O,H=B[C];if(H===void 0)return W;if(typeof H==="function"){let K=H(Z!==void 0?Z:"");if(U(K))throw Error("JSX returned in string context");return String(K)}if(_)switch(_.toLowerCase()){case"number":return Number(H).toString();case"string":return String(H);case"boolean":return Boolean(H).toString();default:return String(H)}return String(H)});else{let z=[],W=0,O=null;while((O=Q.exec(q))!==null){let[_,Z,C,H]=O,F=O.index,K=Z.includes(":")?Z.split(":")[0]:Z;if(F>W)z.push(q.substring(W,F));let Y=B[K];if(Y===void 0)z.push(_);else if(typeof Y==="function"){let A=Y(H!==void 0?H:"");z.push(A)}else if(C)switch(C.toLowerCase()){case"number":z.push(Number(Y).toString());break;case"string":z.push(String(Y));break;case"boolean":z.push(Boolean(Y).toString());break;default:z.push(String(Y))}else z.push(String(Y));W=F+_.length}if(W<q.length)z.push(q.substring(W));return J(M,{},...z)}}class P{name;dictionary;constructor(q,B){this.name=q;this.dictionary=B}reference(q){if(typeof window<"u")throw Error("Cannot use reference in the browser");if(!this.dictionary?.[q])throw Error(`Translation not found for ${String(q)}`);return this.dictionary[q]}render(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B[0]};if(typeof window<"u")throw Error("Cannot use render in the browser");if(!this.dictionary?.[q]?.[G])throw Error(`Translation not found for ${String(q)} in ${String(G)}`);return $(this.dictionary[q][G],Q??{})}static create(q,B){return new P(q,B)}static text(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B?.[0]};if(!q?.[G])throw Error(`Translation not found for ${String(G)}`);return $(q[G],Q??{})}}async function N(q,B,...G){let{locale:Q=j.locale(),params:z}={params:{},...G[0]},O=(await q.load(String(Q)))[B];if(typeof O!=="string")throw Error(`Translation not found for "${B}" in "${String(Q)}" (dictionary ${q.id})`);return $(O,z??{})}export{w as translationConfigDefaults,N as translate,V as resolveLocale,X as negotiateLocale,L as isValidTimeZone,b as defineTranslationConfig,T as defineDictionary,R as createFormatter,S as Translator,D as TranslationServiceProvider,P as Dictionary,E as DEFAULT_TIME_ZONE};
3
3
 
4
4
  //# debugId=07DB790F57444D9964756E2164756E21