gemi 0.233.1 → 0.234.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/chunk-0hy5dsbt.js +5 -0
- package/dist/{chunk-rqzpxeb5.js.map → chunk-0hy5dsbt.js.map} +1 -1
- package/dist/{chunk-e30saw5t.js → chunk-17bva6b1.js} +2 -2
- package/dist/{chunk-e30saw5t.js.map → chunk-17bva6b1.js.map} +1 -1
- package/dist/{chunk-6fpjc2eg.js → chunk-17ewxwga.js} +3 -3
- package/dist/{chunk-6fpjc2eg.js.map → chunk-17ewxwga.js.map} +1 -1
- package/dist/{chunk-5p0gbwq1.js → chunk-1mb7kaxs.js} +3 -3
- package/dist/{chunk-5p0gbwq1.js.map → chunk-1mb7kaxs.js.map} +1 -1
- package/dist/{chunk-mcgcgm6g.js → chunk-1w6ra6jc.js} +1 -1
- package/dist/{chunk-qqe19gtm.js → chunk-1xz206e1.js} +3 -3
- package/dist/{chunk-qqe19gtm.js.map → chunk-1xz206e1.js.map} +1 -1
- package/dist/{chunk-wgxkr2jx.js → chunk-28yb0q82.js} +2 -2
- package/dist/{chunk-wgxkr2jx.js.map → chunk-28yb0q82.js.map} +1 -1
- package/dist/{chunk-j5fh6pjs.js → chunk-2j45vbs2.js} +2 -2
- package/dist/{chunk-j5fh6pjs.js.map → chunk-2j45vbs2.js.map} +1 -1
- package/dist/{chunk-mgvrfhy8.js → chunk-2kzysesp.js} +3 -3
- package/dist/{chunk-mgvrfhy8.js.map → chunk-2kzysesp.js.map} +1 -1
- package/dist/{chunk-tegjs0gg.js → chunk-2ver7cdt.js} +1 -1
- package/dist/{chunk-kfcz4qa8.js → chunk-3y1h3ncf.js} +2 -2
- package/dist/{chunk-kfcz4qa8.js.map → chunk-3y1h3ncf.js.map} +1 -1
- package/dist/{chunk-xprhym1t.js → chunk-406ef17s.js} +2 -2
- package/dist/{chunk-xprhym1t.js.map → chunk-406ef17s.js.map} +1 -1
- package/dist/{chunk-j7swq19b.js → chunk-4mha212g.js} +1 -1
- package/dist/{chunk-vnpfdr52.js → chunk-4n3jva4e.js} +2 -2
- package/dist/{chunk-vnpfdr52.js.map → chunk-4n3jva4e.js.map} +1 -1
- package/dist/{chunk-jrvqya5h.js → chunk-4vn8gyzy.js} +2 -2
- package/dist/{chunk-jrvqya5h.js.map → chunk-4vn8gyzy.js.map} +1 -1
- package/dist/{chunk-c5kd7eac.js → chunk-5exrgw07.js} +3 -3
- package/dist/{chunk-c5kd7eac.js.map → chunk-5exrgw07.js.map} +1 -1
- package/dist/chunk-69xg5wgz.js +10 -0
- package/dist/{chunk-1eha67ey.js.map → chunk-69xg5wgz.js.map} +5 -4
- package/dist/{chunk-mg9j9r9f.js → chunk-6v1fbe70.js} +2 -2
- package/dist/{chunk-mg9j9r9f.js.map → chunk-6v1fbe70.js.map} +1 -1
- package/dist/{chunk-q78n7dvm.js → chunk-74dzzd64.js} +2 -2
- package/dist/{chunk-q78n7dvm.js.map → chunk-74dzzd64.js.map} +1 -1
- package/dist/{chunk-3v8b2kdr.js → chunk-7fbnw7e2.js} +1 -1
- package/dist/{chunk-znh1mbqs.js → chunk-8476xvk9.js} +2 -2
- package/dist/{chunk-znh1mbqs.js.map → chunk-8476xvk9.js.map} +1 -1
- package/dist/{chunk-65wnm25z.js → chunk-8gz07168.js} +4 -4
- package/dist/{chunk-65wnm25z.js.map → chunk-8gz07168.js.map} +1 -1
- package/dist/{chunk-8q1n4087.js → chunk-8jc8x9tc.js} +2 -2
- package/dist/{chunk-8q1n4087.js.map → chunk-8jc8x9tc.js.map} +1 -1
- package/dist/{chunk-kpmp5hmc.js → chunk-8mpptpn5.js} +3 -3
- package/dist/{chunk-kpmp5hmc.js.map → chunk-8mpptpn5.js.map} +1 -1
- package/dist/{chunk-5sgwnrr8.js → chunk-8n40a2sn.js} +2 -2
- package/dist/{chunk-5sgwnrr8.js.map → chunk-8n40a2sn.js.map} +1 -1
- package/dist/{chunk-wedj46ec.js → chunk-8yb9jrj5.js} +2 -2
- package/dist/{chunk-wedj46ec.js.map → chunk-8yb9jrj5.js.map} +1 -1
- package/dist/{chunk-7ka1abkd.js → chunk-9jt5qj1b.js} +2 -2
- package/dist/{chunk-7ka1abkd.js.map → chunk-9jt5qj1b.js.map} +1 -1
- package/dist/{chunk-7g3r55sj.js → chunk-9kt24ctk.js} +2 -2
- package/dist/{chunk-7g3r55sj.js.map → chunk-9kt24ctk.js.map} +1 -1
- package/dist/{chunk-gd4qydsx.js → chunk-9sbhqscs.js} +3 -3
- package/dist/{chunk-gd4qydsx.js.map → chunk-9sbhqscs.js.map} +1 -1
- package/dist/{chunk-efnerp0c.js → chunk-a119av2z.js} +2 -2
- package/dist/{chunk-efnerp0c.js.map → chunk-a119av2z.js.map} +1 -1
- package/dist/{chunk-g0t49jec.js → chunk-aj9atkwk.js} +1 -1
- package/dist/{chunk-8hr7z8cc.js → chunk-at82qczv.js} +3 -3
- package/dist/{chunk-8hr7z8cc.js.map → chunk-at82qczv.js.map} +1 -1
- package/dist/{chunk-xmrd9460.js → chunk-byv7b79h.js} +2 -2
- package/dist/{chunk-xmrd9460.js.map → chunk-byv7b79h.js.map} +1 -1
- package/dist/{chunk-3q0sbk92.js → chunk-ca5kp6cn.js} +2 -2
- package/dist/{chunk-3q0sbk92.js.map → chunk-ca5kp6cn.js.map} +1 -1
- package/dist/{chunk-hd9yny4q.js → chunk-cb7mgx75.js} +4 -4
- package/dist/{chunk-hd9yny4q.js.map → chunk-cb7mgx75.js.map} +1 -1
- package/dist/{chunk-7y2g8wbb.js → chunk-ehtj7zs2.js} +2 -2
- package/dist/{chunk-7y2g8wbb.js.map → chunk-ehtj7zs2.js.map} +1 -1
- package/dist/{chunk-69q9tk74.js → chunk-ezea9fpd.js} +2 -2
- package/dist/{chunk-69q9tk74.js.map → chunk-ezea9fpd.js.map} +1 -1
- package/dist/{chunk-kspqqyv1.js → chunk-fbk79z21.js} +2 -2
- package/dist/{chunk-kspqqyv1.js.map → chunk-fbk79z21.js.map} +1 -1
- package/dist/{chunk-vjqpcet2.js → chunk-fqndtpwm.js} +3 -3
- package/dist/{chunk-vjqpcet2.js.map → chunk-fqndtpwm.js.map} +1 -1
- package/dist/{chunk-qgka1mvf.js → chunk-fs94x6ef.js} +3 -3
- package/dist/{chunk-qgka1mvf.js.map → chunk-fs94x6ef.js.map} +1 -1
- package/dist/{chunk-a2y481gh.js → chunk-g7hz0dmk.js} +2 -2
- package/dist/{chunk-a2y481gh.js.map → chunk-g7hz0dmk.js.map} +1 -1
- package/dist/{chunk-1v1ek1ey.js → chunk-gt9ftnhn.js} +2 -2
- package/dist/{chunk-1v1ek1ey.js.map → chunk-gt9ftnhn.js.map} +1 -1
- package/dist/{chunk-x6fa13e1.js → chunk-gvr7cwxn.js} +3 -3
- package/dist/{chunk-x6fa13e1.js.map → chunk-gvr7cwxn.js.map} +1 -1
- package/dist/{chunk-vrtt8nvm.js → chunk-h0dch3vh.js} +2 -2
- package/dist/{chunk-vrtt8nvm.js.map → chunk-h0dch3vh.js.map} +1 -1
- package/dist/{chunk-jqqyj6cr.js → chunk-h1wmpa03.js} +2 -2
- package/dist/{chunk-jqqyj6cr.js.map → chunk-h1wmpa03.js.map} +1 -1
- package/dist/{chunk-agc0e46c.js → chunk-h5wjk91m.js} +2 -2
- package/dist/{chunk-agc0e46c.js.map → chunk-h5wjk91m.js.map} +1 -1
- package/dist/{chunk-x1p31k7q.js → chunk-hgwkxn0g.js} +2 -2
- package/dist/{chunk-x1p31k7q.js.map → chunk-hgwkxn0g.js.map} +1 -1
- package/dist/{chunk-bs8bq053.js → chunk-hprgj13q.js} +2 -2
- package/dist/{chunk-bs8bq053.js.map → chunk-hprgj13q.js.map} +1 -1
- package/dist/{chunk-9bjggtdt.js → chunk-jssjfvsz.js} +2 -2
- package/dist/{chunk-9bjggtdt.js.map → chunk-jssjfvsz.js.map} +1 -1
- package/dist/{chunk-ct8eh241.js → chunk-k2mpxwh2.js} +2 -2
- package/dist/{chunk-30jcs49q.js.map → chunk-k2mpxwh2.js.map} +1 -1
- package/dist/{chunk-x8by5j7p.js → chunk-ka8dzc6q.js} +2 -2
- package/dist/{chunk-x8by5j7p.js.map → chunk-ka8dzc6q.js.map} +1 -1
- package/dist/{chunk-0zf4dy4y.js → chunk-kak3vc71.js} +2 -2
- package/dist/{chunk-0zf4dy4y.js.map → chunk-kak3vc71.js.map} +1 -1
- package/dist/{chunk-g0mxdh2x.js → chunk-kvtvx64t.js} +2 -2
- package/dist/{chunk-g0mxdh2x.js.map → chunk-kvtvx64t.js.map} +1 -1
- package/dist/{chunk-6j439skq.js → chunk-m2f4n0mq.js} +2 -2
- package/dist/{chunk-6j439skq.js.map → chunk-m2f4n0mq.js.map} +1 -1
- package/dist/{chunk-0zakpsep.js → chunk-m3fbewhz.js} +3 -3
- package/dist/{chunk-0zakpsep.js.map → chunk-m3fbewhz.js.map} +1 -1
- package/dist/{chunk-ejvamy3q.js → chunk-n4kz9vft.js} +1 -1
- package/dist/{chunk-vsr08sbe.js → chunk-n84v63hn.js} +2 -2
- package/dist/{chunk-vsr08sbe.js.map → chunk-n84v63hn.js.map} +1 -1
- package/dist/{chunk-m4wagwhr.js → chunk-naj8bmj5.js} +2 -2
- package/dist/{chunk-m4wagwhr.js.map → chunk-naj8bmj5.js.map} +1 -1
- package/dist/{chunk-6xt7w9bb.js → chunk-np6vee9d.js} +3 -3
- package/dist/{chunk-6xt7w9bb.js.map → chunk-np6vee9d.js.map} +1 -1
- package/dist/{chunk-bm4hjbbk.js → chunk-pfkbhqp7.js} +2 -2
- package/dist/{chunk-bm4hjbbk.js.map → chunk-pfkbhqp7.js.map} +1 -1
- package/dist/{chunk-ngbrbeg2.js → chunk-px9h2qgv.js} +3 -3
- package/dist/{chunk-ngbrbeg2.js.map → chunk-px9h2qgv.js.map} +1 -1
- package/dist/{chunk-0dp6jvrg.js → chunk-qvn0w2rt.js} +2 -2
- package/dist/{chunk-0dp6jvrg.js.map → chunk-qvn0w2rt.js.map} +1 -1
- package/dist/{chunk-c3jg93sn.js → chunk-sh2bd09k.js} +2 -2
- package/dist/{chunk-c3jg93sn.js.map → chunk-sh2bd09k.js.map} +1 -1
- package/dist/{chunk-dqb257xv.js → chunk-sv2mv2q2.js} +2 -2
- package/dist/{chunk-dqb257xv.js.map → chunk-sv2mv2q2.js.map} +1 -1
- package/dist/{chunk-ph7cjs7e.js → chunk-t2p5n8fe.js} +2 -2
- package/dist/{chunk-ph7cjs7e.js.map → chunk-t2p5n8fe.js.map} +1 -1
- package/dist/{chunk-11yrxwkt.js → chunk-t60krz4g.js} +2 -2
- package/dist/{chunk-11yrxwkt.js.map → chunk-t60krz4g.js.map} +1 -1
- package/dist/{chunk-30zs008n.js → chunk-t6x1r5n6.js} +3 -3
- package/dist/{chunk-30zs008n.js.map → chunk-t6x1r5n6.js.map} +1 -1
- package/dist/{chunk-rgcdf5pb.js → chunk-t929a66m.js} +2 -2
- package/dist/{chunk-rgcdf5pb.js.map → chunk-t929a66m.js.map} +1 -1
- package/dist/{chunk-30jcs49q.js → chunk-ts75gcfd.js} +2 -2
- package/dist/{chunk-ct8eh241.js.map → chunk-ts75gcfd.js.map} +1 -1
- package/dist/{chunk-t17vf1ep.js → chunk-w225pkpp.js} +2 -2
- package/dist/{chunk-t17vf1ep.js.map → chunk-w225pkpp.js.map} +1 -1
- package/dist/{chunk-c71dr883.js → chunk-x185900b.js} +3 -3
- package/dist/{chunk-c71dr883.js.map → chunk-x185900b.js.map} +1 -1
- package/dist/{chunk-djhr379j.js → chunk-x2dmgge8.js} +2 -2
- package/dist/{chunk-djhr379j.js.map → chunk-x2dmgge8.js.map} +1 -1
- package/dist/{chunk-76sp9knq.js → chunk-x6a5qxpa.js} +2 -2
- package/dist/{chunk-76sp9knq.js.map → chunk-x6a5qxpa.js.map} +1 -1
- package/dist/{chunk-607nk925.js → chunk-xtpx3f5t.js} +3 -3
- package/dist/{chunk-607nk925.js.map → chunk-xtpx3f5t.js.map} +1 -1
- package/dist/{chunk-b9gwjs4r.js → chunk-y2vayxcd.js} +2 -2
- package/dist/{chunk-b9gwjs4r.js.map → chunk-y2vayxcd.js.map} +1 -1
- package/dist/{chunk-xd4kvswv.js → chunk-y56xd7sv.js} +2 -2
- package/dist/{chunk-xd4kvswv.js.map → chunk-y56xd7sv.js.map} +1 -1
- package/dist/{chunk-xkrfxcm7.js → chunk-yahabnz4.js} +3 -3
- package/dist/{chunk-xkrfxcm7.js.map → chunk-yahabnz4.js.map} +1 -1
- package/dist/{chunk-keqjdy8q.js → chunk-z3tk66vh.js} +2 -2
- package/dist/{chunk-keqjdy8q.js.map → chunk-z3tk66vh.js.map} +1 -1
- package/dist/{chunk-jkhtybga.js → chunk-zm6b938z.js} +3 -3
- package/dist/{chunk-jkhtybga.js.map → chunk-zm6b938z.js.map} +1 -1
- package/dist/{chunk-7vkqcrfn.js → chunk-zt4hybgg.js} +2 -2
- package/dist/{chunk-7vkqcrfn.js.map → chunk-zt4hybgg.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +3 -4
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts +6 -0
- package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts.map +1 -1
- package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts +18 -0
- package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-1eha67ey.js +0 -10
- package/dist/chunk-rqzpxeb5.js +0 -5
- /package/dist/{chunk-mcgcgm6g.js.map → chunk-1w6ra6jc.js.map} +0 -0
- /package/dist/{chunk-tegjs0gg.js.map → chunk-2ver7cdt.js.map} +0 -0
- /package/dist/{chunk-j7swq19b.js.map → chunk-4mha212g.js.map} +0 -0
- /package/dist/{chunk-3v8b2kdr.js.map → chunk-7fbnw7e2.js.map} +0 -0
- /package/dist/{chunk-g0t49jec.js.map → chunk-aj9atkwk.js.map} +0 -0
- /package/dist/{chunk-ejvamy3q.js.map → chunk-n4kz9vft.js.map} +0 -0
|
@@ -5,6 +5,6 @@
|
|
|
5
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 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 ormContext.getStore()?.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 ormContext.getStore()?.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 = ormContext.getStore();\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 = ormContext.getStore();\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 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.\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 * 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 = ormContext.getStore();\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 = ormContext.getStore();\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 = ormContext.getStore();\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 ormContext.getStore()?.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 = ormContext.getStore();\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 ormContext.getStore()?.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 = ormContext.getStore();\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 ormContext.getStore()?.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 = ormContext.getStore();\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): Promise<T> {\n const current = ormContext.getStore();\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 // 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 const deferred: AfterCommitCallback[] = [];\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 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 },\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 = ormContext.getStore()?.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 = ormContext.getStore();\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 = ormContext.getStore();\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
6
|
],
|
|
7
7
|
"mappings": ";yDACA,4BAAS,oBAgLF,IAAM,EAAa,IAAI,EAavB,SAAS,CAAkB,EAA+B,CAC/D,OAAO,EAAW,SAAS,GAAG,GAUzB,SAAS,CAAqB,EAAW,CAC9C,OAAO,EAAW,SAAS,GAAG,YAAc,EAgBvC,SAAS,CAAkB,CAChC,EACA,EACY,CACZ,IAAM,EAAU,EAAW,SAAS,EACpC,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,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,OAAW,OAE7B,IAAM,EAAO,EAAM,YAA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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": "
|
|
8
|
+
"debugId": "65312690B0470E2464756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
class m{name;cron;withoutOverlapping=!1;onOneServer=!1;shouldRun(){return!0}callback(f){}onTick(){}onComplete(){}static exp(f){return f}}
|
|
3
|
-
export{m as
|
|
3
|
+
export{m as ue};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=923FAF3DC87869ED64756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"// A cron expression accepted by `Bun.cron`: a 5-field expression\n// (`minute hour day-of-month month day-of-week`, interpreted in UTC) or one of\n// the nicknames below. The `string & {}` member keeps arbitrary expressions\n// assignable while still surfacing the nicknames in editor autocomplete.\nexport type CronExpression =\n | \"@yearly\"\n | \"@annually\"\n | \"@monthly\"\n | \"@weekly\"\n | \"@daily\"\n | \"@midnight\"\n | \"@hourly\"\n | (string & {});\n\nimport type { HeldLock } from \"../lock/LockManager\";\n\nexport type WithoutOverlapping =\n | boolean\n | {\n /**\n * The lock's lease, in milliseconds: how long it outlives an instance\n * that died holding it. Renewed every third of this while the tick\n * runs, so it does not limit how long a tick may take. Default five\n * minutes.\n */\n expiresAfter?: number;\n };\n\nexport class CronJob {\n name: string;\n cron: CronExpression;\n\n /**\n * Skips a tick while an earlier tick of this job is still running, on this\n * instance or any other sharing the queue's storage. With the database\n * queue driver that is a lock row in `gemi_locks`; with the memory driver\n * it only covers this process.\n *\n * The lock is held across `onTick`, `callback` and `onComplete`, and handed\n * to `callback` as its argument. If its lease is lost while the tick runs\n * (the instance stalled past `expiresAfter`), `lock.lost` aborts and the\n * scheduler logs it. Writes that must not land after that go through\n * `lock.fence(...)`.\n *\n * It does not stop a second instance from running the same tick after the\n * first one finished; `onOneServer` does.\n */\n withoutOverlapping: WithoutOverlapping = false;\n\n /**\n * Runs each tick on one instance only, across every instance sharing the\n * queue's storage: the first to claim the tick's minute runs it, the others\n * skip it. Assumes the instances' clocks agree to well within a minute.\n */\n onOneServer = false;\n\n /**\n * Decides whether this tick happens at all. Evaluated once per tick, before\n * anything else; returning `false` skips `onTick`, `callback` and\n * `onComplete` alike.\n *\n * ### Why this is a member and not a line the job writes for itself\n *\n * A job that reports outward — mails a digest, opens a Sentry issue, pings a\n * channel — must not fire from a laptop, and the guard for that has to cover\n * the whole tick. There was nowhere to write it. gemi calls `onTick` and\n * `onComplete` *outside* `callback`, so a guard placed in a lifecycle hook\n * only stops the hook it lives in: an early `return` at the top of `callback`\n * leaves the job still announcing that it started and still announcing that\n * it finished, which for an outward-reporting job is most of the damage.\n *\n * The only construct that covered every hook was an abstract base class that\n * shadowed `callback` with the guard and renamed the real body to `run()` —\n * and that costs the app the framework's own vocabulary. A job then reads\n * `async run()` while every page of the documentation reads `async\n * callback()`, so the next person to follow the docs writes a `callback` the\n * base class never calls: no error, no output, a job that silently does\n * nothing. Forgetting *this* member fails the other way round — the job runs,\n * which is what it did before anyone asked for a gate.\n *\n * ### What it gates\n *\n * Work, not registration. A job whose gate returns `false` is still\n * scheduled, still holds its `Bun.cron` handle, and still appears in\n * `app(Scheduler).jobs` — \"is it scheduled\" and \"will it do anything\" are\n * different questions and the second one is answered per tick. That is also\n * why this is a method: a field would be read once, when the scheduler\n * constructs the job at boot, and would freeze whatever it saw then.\n *\n * A gate that throws is logged and treated as `false`. Cron work recurs, so\n * a skipped tick is recovered by the next one, while an email sent from the\n * wrong machine is not recovered at all.\n *\n * ### Composing with a base class\n *\n * Nothing here calls `super` for you. A subclass that overrides `shouldRun`\n * for its own reason silently replaces whatever its base was gating on, so\n * narrow rather than redefine:\n *\n * ```typescript\n * async shouldRun() {\n * return (await super.shouldRun()) && this.hasSubscribers();\n * }\n * ```\n *\n * A shared base should annotate its return type as written here rather than\n * let it be inferred: a base returning a plain `boolean` narrows the\n * signature its subclasses inherit, and the `await super` above then does not\n * typecheck against it.\n */\n shouldRun(): Promise<boolean> | boolean {\n return true;\n }\n\n /**\n * The tick's work. `lock` is the `withoutOverlapping` lock when the job\n * declares one.\n */\n callback(_lock?: HeldLock): Promise<void> | void {}\n onTick(): Promise<void> | void {}\n onComplete(): Promise<void> | void {}\n\n static exp(expression: CronExpression) {\n return expression;\n }\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AA4BO,MAAM,CAAQ,CACnB,KACA,KAiBA,mBAAyC,GAOzC,YAAc,GAwDd,SAAS,EAA+B,CACtC,MAAO,GAOT,QAAQ,CAAC,EAAwC,EACjD,MAAM,EAAyB,EAC/B,UAAU,EAAyB,QAE5B,IAAG,CAAC,EAA4B,CACrC,OAAO,EAEX",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "923FAF3DC87869ED64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -46,6 +46,6 @@ export { h } from ${JSON.stringify("virtual:gemi-island-runtime")};
|
|
|
46
46
|
import { hydrateRoot } from "react-dom/client";
|
|
47
47
|
export ${z}
|
|
48
48
|
`,Q='const d=document,c=JSON.parse(d.getElementById("gemi-islands").textContent),w=f=>(window.requestIdleCallback||setTimeout)(f),m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};for(const e of d.querySelectorAll("gemi-island")){const o=c.i[e.dataset.island];if(!o)continue;if(o.l=="eager")m(e,o);else if(o.l=="idle"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}';
|
|
49
|
-
export{B as
|
|
49
|
+
export{B as tm,F as um,G as vm,J as wm,M as xm,Q as ym};
|
|
50
50
|
|
|
51
|
-
//# debugId=
|
|
51
|
+
//# debugId=79D986F4880262D864756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * The browser side of islands, shared by the Vite plugin (which builds it), the\n * servers (which point the loader at it) and the tests.\n *\n * No imports: the Vite plugin is built on its own and the servers load it at\n * boot, so this file stays plain strings.\n */\n\n/**\n * The module that hydrates islands: React, `react-dom/client` and the small\n * `h(marker, Component)` below. A virtual module of gemi's Vite plugin that\n * every island entry imports, so the islands on a page share one copy of\n * React, in one chunk.\n */\nexport const ISLAND_RUNTIME_ID = \"virtual:gemi-island-runtime\";\n\n/** What `resolveId` turns `ISLAND_RUNTIME_ID` into (Vite's virtual-module convention). */\nexport const RESOLVED_ISLAND_RUNTIME_ID = `\\0${ISLAND_RUNTIME_ID}`;\n\n/**\n * The query that turns a module into its island entry: `Counter.tsx?gemi-island`\n * is a module of the plugin's that re-exports `Counter.tsx` as `m` next to the\n * runtime's `h`. It is what a static page imports for an island, and so it\n * is what the client manifest lists, keyed `app/…/Counter.tsx?gemi-island`,\n * with React and `react-dom/client` among its imports.\n */\nexport const ISLAND_ENTRY_QUERY = \"?gemi-island\";\n\n/** The island entry module for `file` (an absolute path or a root-relative URL). */\nexport function islandEntrySource(file: string) {\n return `import * as m from ${JSON.stringify(file)};\nexport { m };\nexport { h } from ${JSON.stringify(ISLAND_RUNTIME_ID)};\n`;\n}\n\n/**\n * `h(marker, Component)`: hydrates one `<gemi-island>` marker with the island's\n * component and the props the server serialised into `data-props`.\n *\n * The island's static children were rendered on the server into a\n * `<gemi-slot>` (the first one that belongs to this marker, not to an island\n * nested in it). They are handed back to the component as that same element\n * with the server's HTML, so hydration matches and React leaves them alone.\n *\n * `data-uid` is the `identifierPrefix` the server rendered the island with, so\n * `useId` agrees on both sides and two islands never share an id.\n *\n * When the page carries `#gemi-island-i18n` (its islands read the page's\n * locale or dictionaries, #1095), the dictionaries in it are seeded into the\n * dictionary registry through `__GEMI_DICT__` and the island's root gets the\n * locale and zone in `IslandI18nContext` (found on `globalThis`, where\n * `gemi/client` puts it), so `useDictionary` resolves synchronously, with the\n * strings the server rendered, and fetches nothing. An island that does not\n * import `gemi/client` has no such context to read, and is left as it was.\n *\n * The island's root reads queries through the cache the page's islands\n * share (found on `globalThis` under `gemi.islandQueries`, where `gemi/client`\n * puts it, #1155). When the page carries `#gemi-island-queries` (its islands\n * read queries the request prefetched), that `{ path: { variantKey: data } }`\n * payload seeds the cache first, so `useQuery` hydrates with the server's\n * data and does not refetch it.\n *\n * Written as a function body with `createElement` and `hydrateRoot` free, so a\n * test can run it against real React without a bundler.\n */\nexport const ISLAND_HYDRATE_SOURCE = `function h(marker, Component) {\n if (typeof Component !== \"function\" && (typeof Component !== \"object\" || Component === null)) {\n throw new Error(\"gemi: island module has no component export for \" + marker.outerHTML.slice(0, 80));\n }\n const json = marker.getAttribute(\"data-props\");\n const props = json ? JSON.parse(json) : {};\n let slot = null;\n for (const candidate of marker.querySelectorAll(\"gemi-slot\")) {\n if (candidate.closest(\"gemi-island\") === marker) {\n slot = candidate;\n break;\n }\n }\n const children = slot\n ? [createElement(\"gemi-slot\", {\n style: { display: \"contents\" },\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: { __html: slot.innerHTML },\n })]\n : [];\n let element = createElement(Component, props, ...children);\n const i18n = document.getElementById(\"gemi-island-i18n\");\n const context = globalThis[Symbol.for(\"gemi.islandI18n\")];\n if (i18n && context) {\n const payload = (i18n.p = i18n.p || JSON.parse(i18n.textContent));\n const dictionaries = (self.__GEMI_DICT__ = self.__GEMI_DICT__ || []);\n for (const entry of payload.dictionaries || []) dictionaries.push(entry);\n element = createElement(context.Provider, {\n value: { currentLocale: payload.currentLocale, defaultLocale: payload.defaultLocale, timeZone: payload.timeZone },\n }, element);\n }\n const cache = globalThis[Symbol.for(\"gemi.islandQueries\")];\n if (cache) {\n const queries = document.getElementById(\"gemi-island-queries\");\n if (queries) cache.seed((queries.p = queries.p || JSON.parse(queries.textContent)));\n element = createElement(cache.Provider, null, element);\n }\n return hydrateRoot(marker, element, {\n identifierPrefix: marker.getAttribute(\"data-uid\") || undefined,\n });\n}`;\n\n/** The runtime module's source, as the plugin serves and builds it. */\nexport const ISLAND_RUNTIME_SOURCE = `import { createElement } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nexport ${ISLAND_HYDRATE_SOURCE}\n`;\n\n/**\n * The island loader, inlined into a static document that uses islands.\n *\n * Kept byte-for-byte constant (the per-page island table travels in a\n * separate `<script type=\"application/json\">`, which a Content Security Policy\n * does not treat as script), so a strict policy can allow it by hash:\n * `script-src 'sha256-…'` with `ISLAND_LOADER_CSP_HASH`. Everything it loads\n * is a plain `import()` of a same-origin (or asset-base) file.\n *\n * The table is `{ i: [{ s: entry URL, e: export, l: load }] }` and each\n * marker's `data-island` indexes `i`. Per marker, on its schedule: import the\n * island's entry (the module as `m`, the runtime's `h`), then\n * `h(marker, m[export])`, which calls `hydrateRoot`. A failure is logged and\n * leaves the server-rendered markup in place.\n */\nexport const ISLAND_LOADER_SOURCE =\n 'const d=document,c=JSON.parse(d.getElementById(\"gemi-islands\").textContent),' +\n \"w=f=>(window.requestIdleCallback||setTimeout)(f),\" +\n \"m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};\" +\n 'for(const e of d.querySelectorAll(\"gemi-island\")){const o=c.i[e.dataset.island];if(!o)continue;' +\n 'if(o.l==\"eager\")m(e,o);else if(o.l==\"idle\"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));' +\n \"else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}\";\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAcO,IAAM,EAAoB,8BAGpB,EAA6B,kCAS7B,EAAqB,eAG3B,SAAS,CAAiB,CAAC,EAAc,CAC9C,MAAO,sBAAsB,KAAK,UAAU,CAAI;AAAA;AAAA,oBAE9B,KAAK,UAlBQ,6BAkBmB;AAAA,EAkC7C,IAAM,EAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GA2CxB,EAAwB;AAAA;AAAA,SAE5B;AAAA,EAkBI,EACX",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "79D986F4880262D864756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Hj as b}from"./chunk-30zs008n.js";class D extends Error{retryable;constructor(Q,V={}){super(Q,V.cause!==void 0?{cause:V.cause}:void 0);this.name="ToolError",this.retryable=V.retryable??!0}}var u={provider_error:"The model provider returned an error.",rate_limited:"The model provider is rate limiting requests. Try again shortly.",context_length_exceeded:"The conversation is too long for the model.",content_filtered:"The model provider's content filter blocked this request.",invalid_tool_input:"The model provider rejected the request.",tool_error:"A tool failed.",unknown:"The run failed unexpectedly."};function E(Q,V){if(V.source==="tool"){if(V.cause instanceof D)return Q;return{...Q,message:`The tool "${V.toolName}" failed with an unexpected error.`}}let Y=u[Q.code];return Y===void 0?Q:{...Q,message:Y}}function HQ(Q,V,Y,Z){let $;try{$=(Q??E)(V,Y)}catch(J){Z(J),$=E(V,Y)}return{code:$.code,message:$.message,...$.toolCallId!==void 0?{toolCallId:$.toolCallId}:{},retryable:$.retryable}}var S=new WeakMap;function LQ(Q,V){if(Q!==V)S.set(Q,V)}function UQ(Q){return S.get(Q)??Q}class _ extends D{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class T extends D{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function P(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new T("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var g="gemi_att_";function h(){return`${g}${crypto.randomUUID()}`}class A{store;storage;scope;lifetime;constructor(Q,V,Y,Z=null){this.store=Q;this.storage=V;this.scope=Y;this.lifetime=Z;P(Y)}withLifetime(Q){return new A(this.store,this.storage,this.scope,Q)}get scopeKey(){return this.scope.key}async get(Q){let V=await this.store.find(this.scope,Q);if(!V||V.scopeKey!==this.scope.key||x(V,Date.now()))throw new _(Q);return V}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,V){if(!V.objectName)throw new _(Q);return await this.storage.read({name:V.objectName})}async file(Q){let V=await this.get(Q),Z=(await this.readRecord(Q,V)).body,$=Z instanceof Blob?Z:Z?await new Response(Z).blob():new Blob([]);return new File([$],V.name,{type:V.mimeType})}async put(Q,V={}){let Y=h(),Z=V.mimeType??Q.type??"",$=V.name??(Q instanceof File?Q.name:Y),J=await this.storage.put({name:l(Y,$),body:Q,contentType:Z||void 0}),K={id:Y,scopeKey:this.scope.key,objectName:J,name:$,mimeType:Z||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:V.fileId?"both":"storage",...V.fileId?{fileId:V.fileId}:{},...this.lifetime?this.lifetime.next():{}};return await this.store.put(this.scope,K),this.lifetime?.onPut?.(K),K}}function x(Q,V){if(!Q.expiresAt)return!1;let Y=Date.parse(Q.expiresAt);return Number.isFinite(Y)&&Y<=V}function zQ(Q,V,Y=Date.now()){if(Q===null||Q===void 0)return null;if(Q==="turn")return{expiresAt:new Date(Y+V).toISOString(),deleteAfterTurn:!0};let Z=Q?.ttlMs;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=0)throw Error(`attachmentRetention() must answer "turn", { ttlMs } with a positive number of milliseconds, or null; it answered ${JSON.stringify(Q)}.`);return{expiresAt:new Date(Y+Z).toISOString()}}async function DQ(Q,V){if(Q.objectName){if(!V.storage.delete)throw Error(`Cannot delete attachment ${Q.id}: the controller's attachmentStorage has no delete().`);await V.storage.delete({name:Q.objectName})}if(Q.fileId){if(!V.provider?.deleteFile)throw Error(`Cannot delete the provider copy of attachment ${Q.id}: the agent's provider has no deleteFile().`);await V.provider.deleteFile(Q.fileId),await V.fileOwners?.delete?.(Q.fileId)}if(!V.store.delete)throw Error(`Cannot delete attachment ${Q.id}: the controller's attachment store has no delete().`);await V.store.delete({key:Q.scopeKey},Q.id)}function l(Q,V){let Y=/\.([A-Za-z0-9]{1,8})$/.exec(V);return`attachments/${Q}${Y?`.${Y[1].toLowerCase()}`:""}`}class w{rows=new Map;async put(Q,V){P(Q),this.rows.set(V.id,{...V,scopeKey:Q.key})}async find(Q,V){P(Q);let Y=this.rows.get(V);if(!Y||Y.scopeKey!==Q.key)return null;return Y}async delete(Q,V){P(Q);let Y=this.rows.get(V);if(Y&&Y.scopeKey===Q.key)this.rows.delete(V)}async expired(Q,V){let Y=[];for(let Z of this.rows.values()){if(Y.length>=V)break;if(x(Z,Q.getTime()))Y.push(Z)}return Y}get size(){return this.rows.size}}var FQ=new w;function p(Q){let V=new Set;for(let Y of Q)for(let Z of Y.content??[]){if(Z.type!=="tool-call")continue;for(let $ of Z.attachments??[])if($&&"shown"in $&&$.shown)V.add($.shown.messageId)}return V}function v(Q){if(Q.length===0)return[];let V=p(Q),Y=[0];for(let Z=1;Z<Q.length;Z++)if(m(Q[Z],V))Y.push(Z);return Y}function m(Q,V){if(Q.turn!==void 0)return Q.turn===Q.id;return Q.role==="user"&&!Q.joined&&!V.has(Q.id)}function f(Q){if(Q.turn!==void 0)return Q.turn===Q.id?void 0:Q.turn;return Q.joined}function RQ(Q){let V=v(Q),Y=V.map(()=>[]),Z=new Map,$=-1;return Q.forEach((J,K)=>{if(V[$+1]===K)$++;let B=f(J),H=B!==void 0?Z.get(B):void 0;Y[H??$].push(J),Z.set(J.id,H??$)}),Y}function c(Q,V,Y){let Z=(K)=>{let B=0;while(B+1<V.length&&V[B+1]<=K)B++;return B},$=new Map(Q.map((K,B)=>[K.id,B])),J=Y;for(let K=Q.length-1;K>=V[J];K--){let B=f(Q[K]),H=B!==void 0?$.get(B):void 0;if(H!==void 0&&H<V[J])J=Z(H)}return J}function d(Q){try{return JSON.stringify(Q).length}catch{return 0}}var i=4,n=10,o="[Earlier turns of this conversation are not shown.]";function CQ(Q,V={}){let Y=[...Q],Z=v(Y),$=s(V),J=R(V.maxTurns)??1/0,K=Math.max(1,Math.floor(R(V.step)??n));if(Z.length<=1||J>=Z.length&&$===1/0)return{messages:Y,start:0,omittedTurns:0,omittedMessages:0};let B=Array.from({length:Y.length+1},()=>0);if($!==1/0)for(let X=Y.length-1;X>=0;X--)B[X]=B[X+1]+d(Y[X]);let H=(X)=>Z.length-X<=J&&B[Z[X]]<=$,G=-1;for(let X=0;X<Z.length;X+=K)if(H(X)){G=X;break}if(G<0){for(let X=0;X<Z.length;X++)if(H(X)){G=X;break}}if(G<0)G=Z.length-1;if(G=c(Y,Z,G),G===0)return{messages:Y,start:0,omittedTurns:0,omittedMessages:0};let L=Z[G],U=Y.slice(0,L),F=U.filter((X)=>X.role==="system"),q=a(U,Y.slice(L)),W={turns:G,messages:U.length-F.length},M=typeof V.note==="function"?V.note(W):V.note===void 0?o:V.note;if(M){let X=q[0];q[0]={...X,content:[{type:"text",text:M},...X.content]}}return{messages:[...F,...q],start:L,omittedTurns:W.turns,omittedMessages:W.messages}}function R(Q){return typeof Q==="number"&&Q>0?Q:void 0}function s(Q){let V=R(Q.maxBytes)??1/0,Y=R(Q.maxTokens);return Math.min(V,Y===void 0?1/0:Y*i)}function k(Q,V){let Y=Array.isArray(Q?.namespaces)?Q.namespaces:[],Z=Array.isArray(Q?.loaded)?Q.loaded:[];return V.namespace?Y.includes(V.namespace):Z.includes(String(V.name))}function j(Q){return Array.isArray(Q.toolSearches)?Q.toolSearches:[]}function a(Q,V){let Y=[];for(let G of Q)for(let L of G.content??[])if(L.type==="tool-call")Y.push(...j(L));if(Y.length===0)return V;let Z=[],$=new Set,J;if(V.forEach((G,L)=>{(G.content??[]).forEach((U,F)=>{if(U.type!=="tool-call"||U.partial)return;if(Z.push(...j(U)),Z.some((W)=>k(W,U)))return;let q=Y.filter((W)=>k(W,U));if(q.length===0)return;for(let W of q)$.add(W);J??={message:L,part:F}})}),!J)return V;let K=Y.filter((G)=>$.has(G)),B=[...V],H=B[J.message];return B[J.message]={...H,content:H.content.map((G,L)=>L===J.part&&G.type==="tool-call"?{...G,toolSearches:[...K,...j(G)]}:G)},B}class O extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function OQ(Q,V){if(V.aborted)return Promise.reject(new O);return new Promise((Y,Z)=>{let $=()=>Z(new O);V.addEventListener("abort",$,{once:!0}),Q.then(Y,Z).finally(()=>V.removeEventListener("abort",$))})}function IQ(Q){switch(Q.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}function NQ(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function MQ(Q,V){if(!V)return Q;let Y={inputTokens:Q.inputTokens+(V.inputTokens??0),outputTokens:Q.outputTokens+(V.outputTokens??0),totalTokens:Q.totalTokens+(V.totalTokens??0)};for(let Z of r)if(V[Z]!==void 0||Q[Z]!==void 0)Y[Z]=(Q[Z]??0)+(V[Z]??0);return Y}var r=["reasoningTokens","cachedInputTokens","cacheWriteInputTokens","imageInputTokens","imageOutputTokens","audioInputTokens","cachedAudioInputTokens","audioOutputTokens"];function t(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let V=[],Y=!1,Z=!1;for(let K of Q){if(Y){if(Z)Z=!1;else if(K==="\\")Z=!0;else if(K==='"')Y=!1;continue}if(K==='"')Y=!0;else if(K==="{")V.push("}");else if(K==="[")V.push("]");else if(K==="}"||K==="]")V.pop()}let $=Q;if(Y)$+='"';$=$.replace(/[,:]\s*$/,"");let J=V.reverse().join("");try{return JSON.parse($+J)}catch{try{return JSON.parse($.replace(/,?\s*"[^"]*"\s*$/,"")+J)}catch{return{}}}}function EQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:b(Q)}}function SQ(Q,V){let Y=Q.safeParse(t(V));if(Y.ok===!0)return{ok:!0,value:Y.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Y.errors.join(", ")}`,retryable:!0}}}function TQ(Q){if(Q.length>0)Q[0];return Q}function AQ(Q,V,Y){let Z=Q.content[Q.content.length-1];if(Z&&Z.type===V){Z.text=(Z.text??"")+Y;return}Q.content.push(V==="text"?{type:"text",text:Y}:{type:"reasoning",text:Y})}function xQ(Q,V,Y,Z){let $=Q.content[Q.content.length-1];if($&&$.type==="reasoning"&&$.id===V&&!$.providerMetadata){if($.text=($.text??"")+Y,Z)$.providerMetadata=Z;return}Q.content.push({type:"reasoning",...V?{id:V}:{},text:Y,...Z?{providerMetadata:Z}:{}})}class y extends Error{status;body;requestId;retryAfter;constructor(Q,V,Y,Z){super(`Provider request failed with status ${Q}: ${YQ(V)}`);if(this.name="ProviderHttpError",this.status=Q,this.body=V,this.requestId=Y,Z!==void 0)this.retryAfter=Z}}class C extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}class e extends C{constructor(Q){super(Q);this.name="ProviderStreamIdleError",this.message=`Provider stream sent nothing for ${Q}ms (streamIdleTimeoutMs)`}}class QQ extends C{constructor(Q){super(Q);this.name="ProviderStreamDurationError",this.message=`Provider stream was still going after ${Q}ms (streamMaxDurationMs)`}}class I extends Error{limit;detail;constructor(Q,V,Y="",Z=Q+1){super(`Provider streamed more than ${Q} characters of arguments for "${V}" without finishing the call (maxToolArgumentChars)`);this.name="ProviderToolArgumentsTooLongError",this.limit=Q,this.detail={tool:V,toolCallId:Y,limit:Q,chars:Z}}}class VQ extends I{constructor(Q,V,Y,Z,$){super(Q,V,Y,Z);this.name="ProviderToolArgumentsRunawayError",this.message=`Provider streamed more than ${Q} characters of white space in the arguments for "${V}" before they were whole JSON (maxToolArgumentWhitespace)`,this.detail.whitespace=$}}function YQ(Q){let V=N(Q);if(V?.message)return V.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function N(Q){if(!Q||typeof Q!=="object")return null;let V=Q,Z=V.error&&typeof V.error==="object"?V.error:Q;if(typeof Z.message!=="string"&&typeof Z.code!=="string"&&typeof Z.type!=="string")return null;let $=Z.innererror?.code??Z.code;return{message:Z.message,type:Z.type,code:$,param:Z.param}}function kQ(Q){if(!Q||typeof Q!=="object")return{};let V=Q,{status:Y,requestId:Z}=V,$=ZQ(V.body),J=z(V.providerType)??$.providerType,K=z(V.providerCode)??$.providerCode,B=z(V.providerParam)??$.providerParam;return{...typeof Y==="number"&&Y>=100&&Y<=599?{status:Y}:{},...typeof Z==="string"&&Z?{requestId:Z}:{},...J?{providerType:J}:{},...K?{providerCode:K}:{},...B?{providerParam:B}:{}}}function ZQ(Q){let V=N(Q),Y=z(V?.type),Z=z(V?.code),$=z(V?.param);return{...Y?{providerType:Y}:{},...Z?{providerCode:Z}:{},...$?{providerParam:$}:{}}}function z(Q){return typeof Q==="string"&&Q?Q:void 0}function vQ(Q){if(Q instanceof C||Q instanceof I)return{code:"provider_error",message:Q.message,retryable:!0};if(XQ(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof y)return $Q(Q.status,N(Q.body),Q.message,Q.retryAfter);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function $Q(Q,V,Y,Z){let $=V?.message??Y,J=(V?.code??"").toLowerCase(),K=(V?.type??"").toLowerCase(),B=`${J} ${K} ${$}`.toLowerCase().replace(/https?:\/\/\S+/g,"");if(Q===429){if(!JQ.has(J)&&(J==="insufficient_quota"||B.includes("quota")))return{code:"rate_limited",message:$,retryable:!1};let G=Z??KQ($);return{code:"rate_limited",message:$,retryable:!0,...G!==void 0?{retryAfter:G}:{}}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:$,retryable:!0};if(BQ(B))return{code:"context_length_exceeded",message:$,retryable:!1};if(GQ(B))return{code:"content_filtered",message:$,retryable:!1};if(V?.param?.startsWith("tools")||B.includes("invalid schema for function"))return{code:"invalid_tool_input",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!1}}var JQ=new Set(["ratelimitreached","rate_limit_exceeded","too_many_requests"]);function KQ(Q){let V=/retry after (\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s)\b/i.exec(Q);if(!V)return;let Y=Number(V[1]);return/^m(s|illi)/i.test(V[2])?Y:Y*1000}function BQ(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")||Q.includes("prompt is too long")||Q.includes("request_too_large")}function GQ(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")||Q.includes("moderation_blocked")||Q.includes("rejected by the safety system")||Q.includes("safety_violations")}function XQ(Q){if(!Q||typeof Q!=="object")return!1;let V=Q;return V.name==="AbortError"||V.code==="ABORT_ERR"}
|
|
3
|
-
export{O as
|
|
2
|
+
import{Ij as b}from"./chunk-t6x1r5n6.js";class D extends Error{retryable;constructor(Q,V={}){super(Q,V.cause!==void 0?{cause:V.cause}:void 0);this.name="ToolError",this.retryable=V.retryable??!0}}var u={provider_error:"The model provider returned an error.",rate_limited:"The model provider is rate limiting requests. Try again shortly.",context_length_exceeded:"The conversation is too long for the model.",content_filtered:"The model provider's content filter blocked this request.",invalid_tool_input:"The model provider rejected the request.",tool_error:"A tool failed.",unknown:"The run failed unexpectedly."};function E(Q,V){if(V.source==="tool"){if(V.cause instanceof D)return Q;return{...Q,message:`The tool "${V.toolName}" failed with an unexpected error.`}}let Y=u[Q.code];return Y===void 0?Q:{...Q,message:Y}}function HQ(Q,V,Y,Z){let $;try{$=(Q??E)(V,Y)}catch(J){Z(J),$=E(V,Y)}return{code:$.code,message:$.message,...$.toolCallId!==void 0?{toolCallId:$.toolCallId}:{},retryable:$.retryable}}var S=new WeakMap;function LQ(Q,V){if(Q!==V)S.set(Q,V)}function UQ(Q){return S.get(Q)??Q}class _ extends D{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class T extends D{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function P(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new T("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var g="gemi_att_";function h(){return`${g}${crypto.randomUUID()}`}class A{store;storage;scope;lifetime;constructor(Q,V,Y,Z=null){this.store=Q;this.storage=V;this.scope=Y;this.lifetime=Z;P(Y)}withLifetime(Q){return new A(this.store,this.storage,this.scope,Q)}get scopeKey(){return this.scope.key}async get(Q){let V=await this.store.find(this.scope,Q);if(!V||V.scopeKey!==this.scope.key||x(V,Date.now()))throw new _(Q);return V}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,V){if(!V.objectName)throw new _(Q);return await this.storage.read({name:V.objectName})}async file(Q){let V=await this.get(Q),Z=(await this.readRecord(Q,V)).body,$=Z instanceof Blob?Z:Z?await new Response(Z).blob():new Blob([]);return new File([$],V.name,{type:V.mimeType})}async put(Q,V={}){let Y=h(),Z=V.mimeType??Q.type??"",$=V.name??(Q instanceof File?Q.name:Y),J=await this.storage.put({name:l(Y,$),body:Q,contentType:Z||void 0}),K={id:Y,scopeKey:this.scope.key,objectName:J,name:$,mimeType:Z||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:V.fileId?"both":"storage",...V.fileId?{fileId:V.fileId}:{},...this.lifetime?this.lifetime.next():{}};return await this.store.put(this.scope,K),this.lifetime?.onPut?.(K),K}}function x(Q,V){if(!Q.expiresAt)return!1;let Y=Date.parse(Q.expiresAt);return Number.isFinite(Y)&&Y<=V}function zQ(Q,V,Y=Date.now()){if(Q===null||Q===void 0)return null;if(Q==="turn")return{expiresAt:new Date(Y+V).toISOString(),deleteAfterTurn:!0};let Z=Q?.ttlMs;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=0)throw Error(`attachmentRetention() must answer "turn", { ttlMs } with a positive number of milliseconds, or null; it answered ${JSON.stringify(Q)}.`);return{expiresAt:new Date(Y+Z).toISOString()}}async function DQ(Q,V){if(Q.objectName){if(!V.storage.delete)throw Error(`Cannot delete attachment ${Q.id}: the controller's attachmentStorage has no delete().`);await V.storage.delete({name:Q.objectName})}if(Q.fileId){if(!V.provider?.deleteFile)throw Error(`Cannot delete the provider copy of attachment ${Q.id}: the agent's provider has no deleteFile().`);await V.provider.deleteFile(Q.fileId),await V.fileOwners?.delete?.(Q.fileId)}if(!V.store.delete)throw Error(`Cannot delete attachment ${Q.id}: the controller's attachment store has no delete().`);await V.store.delete({key:Q.scopeKey},Q.id)}function l(Q,V){let Y=/\.([A-Za-z0-9]{1,8})$/.exec(V);return`attachments/${Q}${Y?`.${Y[1].toLowerCase()}`:""}`}class w{rows=new Map;async put(Q,V){P(Q),this.rows.set(V.id,{...V,scopeKey:Q.key})}async find(Q,V){P(Q);let Y=this.rows.get(V);if(!Y||Y.scopeKey!==Q.key)return null;return Y}async delete(Q,V){P(Q);let Y=this.rows.get(V);if(Y&&Y.scopeKey===Q.key)this.rows.delete(V)}async expired(Q,V){let Y=[];for(let Z of this.rows.values()){if(Y.length>=V)break;if(x(Z,Q.getTime()))Y.push(Z)}return Y}get size(){return this.rows.size}}var FQ=new w;function p(Q){let V=new Set;for(let Y of Q)for(let Z of Y.content??[]){if(Z.type!=="tool-call")continue;for(let $ of Z.attachments??[])if($&&"shown"in $&&$.shown)V.add($.shown.messageId)}return V}function v(Q){if(Q.length===0)return[];let V=p(Q),Y=[0];for(let Z=1;Z<Q.length;Z++)if(m(Q[Z],V))Y.push(Z);return Y}function m(Q,V){if(Q.turn!==void 0)return Q.turn===Q.id;return Q.role==="user"&&!Q.joined&&!V.has(Q.id)}function f(Q){if(Q.turn!==void 0)return Q.turn===Q.id?void 0:Q.turn;return Q.joined}function RQ(Q){let V=v(Q),Y=V.map(()=>[]),Z=new Map,$=-1;return Q.forEach((J,K)=>{if(V[$+1]===K)$++;let B=f(J),H=B!==void 0?Z.get(B):void 0;Y[H??$].push(J),Z.set(J.id,H??$)}),Y}function c(Q,V,Y){let Z=(K)=>{let B=0;while(B+1<V.length&&V[B+1]<=K)B++;return B},$=new Map(Q.map((K,B)=>[K.id,B])),J=Y;for(let K=Q.length-1;K>=V[J];K--){let B=f(Q[K]),H=B!==void 0?$.get(B):void 0;if(H!==void 0&&H<V[J])J=Z(H)}return J}function d(Q){try{return JSON.stringify(Q).length}catch{return 0}}var i=4,n=10,o="[Earlier turns of this conversation are not shown.]";function CQ(Q,V={}){let Y=[...Q],Z=v(Y),$=s(V),J=R(V.maxTurns)??1/0,K=Math.max(1,Math.floor(R(V.step)??n));if(Z.length<=1||J>=Z.length&&$===1/0)return{messages:Y,start:0,omittedTurns:0,omittedMessages:0};let B=Array.from({length:Y.length+1},()=>0);if($!==1/0)for(let X=Y.length-1;X>=0;X--)B[X]=B[X+1]+d(Y[X]);let H=(X)=>Z.length-X<=J&&B[Z[X]]<=$,G=-1;for(let X=0;X<Z.length;X+=K)if(H(X)){G=X;break}if(G<0){for(let X=0;X<Z.length;X++)if(H(X)){G=X;break}}if(G<0)G=Z.length-1;if(G=c(Y,Z,G),G===0)return{messages:Y,start:0,omittedTurns:0,omittedMessages:0};let L=Z[G],U=Y.slice(0,L),F=U.filter((X)=>X.role==="system"),q=a(U,Y.slice(L)),W={turns:G,messages:U.length-F.length},M=typeof V.note==="function"?V.note(W):V.note===void 0?o:V.note;if(M){let X=q[0];q[0]={...X,content:[{type:"text",text:M},...X.content]}}return{messages:[...F,...q],start:L,omittedTurns:W.turns,omittedMessages:W.messages}}function R(Q){return typeof Q==="number"&&Q>0?Q:void 0}function s(Q){let V=R(Q.maxBytes)??1/0,Y=R(Q.maxTokens);return Math.min(V,Y===void 0?1/0:Y*i)}function k(Q,V){let Y=Array.isArray(Q?.namespaces)?Q.namespaces:[],Z=Array.isArray(Q?.loaded)?Q.loaded:[];return V.namespace?Y.includes(V.namespace):Z.includes(String(V.name))}function j(Q){return Array.isArray(Q.toolSearches)?Q.toolSearches:[]}function a(Q,V){let Y=[];for(let G of Q)for(let L of G.content??[])if(L.type==="tool-call")Y.push(...j(L));if(Y.length===0)return V;let Z=[],$=new Set,J;if(V.forEach((G,L)=>{(G.content??[]).forEach((U,F)=>{if(U.type!=="tool-call"||U.partial)return;if(Z.push(...j(U)),Z.some((W)=>k(W,U)))return;let q=Y.filter((W)=>k(W,U));if(q.length===0)return;for(let W of q)$.add(W);J??={message:L,part:F}})}),!J)return V;let K=Y.filter((G)=>$.has(G)),B=[...V],H=B[J.message];return B[J.message]={...H,content:H.content.map((G,L)=>L===J.part&&G.type==="tool-call"?{...G,toolSearches:[...K,...j(G)]}:G)},B}class O extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function OQ(Q,V){if(V.aborted)return Promise.reject(new O);return new Promise((Y,Z)=>{let $=()=>Z(new O);V.addEventListener("abort",$,{once:!0}),Q.then(Y,Z).finally(()=>V.removeEventListener("abort",$))})}function IQ(Q){switch(Q.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}function NQ(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function MQ(Q,V){if(!V)return Q;let Y={inputTokens:Q.inputTokens+(V.inputTokens??0),outputTokens:Q.outputTokens+(V.outputTokens??0),totalTokens:Q.totalTokens+(V.totalTokens??0)};for(let Z of r)if(V[Z]!==void 0||Q[Z]!==void 0)Y[Z]=(Q[Z]??0)+(V[Z]??0);return Y}var r=["reasoningTokens","cachedInputTokens","cacheWriteInputTokens","imageInputTokens","imageOutputTokens","audioInputTokens","cachedAudioInputTokens","audioOutputTokens"];function t(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let V=[],Y=!1,Z=!1;for(let K of Q){if(Y){if(Z)Z=!1;else if(K==="\\")Z=!0;else if(K==='"')Y=!1;continue}if(K==='"')Y=!0;else if(K==="{")V.push("}");else if(K==="[")V.push("]");else if(K==="}"||K==="]")V.pop()}let $=Q;if(Y)$+='"';$=$.replace(/[,:]\s*$/,"");let J=V.reverse().join("");try{return JSON.parse($+J)}catch{try{return JSON.parse($.replace(/,?\s*"[^"]*"\s*$/,"")+J)}catch{return{}}}}function EQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:b(Q)}}function SQ(Q,V){let Y=Q.safeParse(t(V));if(Y.ok===!0)return{ok:!0,value:Y.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Y.errors.join(", ")}`,retryable:!0}}}function TQ(Q){if(Q.length>0)Q[0];return Q}function AQ(Q,V,Y){let Z=Q.content[Q.content.length-1];if(Z&&Z.type===V){Z.text=(Z.text??"")+Y;return}Q.content.push(V==="text"?{type:"text",text:Y}:{type:"reasoning",text:Y})}function xQ(Q,V,Y,Z){let $=Q.content[Q.content.length-1];if($&&$.type==="reasoning"&&$.id===V&&!$.providerMetadata){if($.text=($.text??"")+Y,Z)$.providerMetadata=Z;return}Q.content.push({type:"reasoning",...V?{id:V}:{},text:Y,...Z?{providerMetadata:Z}:{}})}class y extends Error{status;body;requestId;retryAfter;constructor(Q,V,Y,Z){super(`Provider request failed with status ${Q}: ${YQ(V)}`);if(this.name="ProviderHttpError",this.status=Q,this.body=V,this.requestId=Y,Z!==void 0)this.retryAfter=Z}}class C extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}class e extends C{constructor(Q){super(Q);this.name="ProviderStreamIdleError",this.message=`Provider stream sent nothing for ${Q}ms (streamIdleTimeoutMs)`}}class QQ extends C{constructor(Q){super(Q);this.name="ProviderStreamDurationError",this.message=`Provider stream was still going after ${Q}ms (streamMaxDurationMs)`}}class I extends Error{limit;detail;constructor(Q,V,Y="",Z=Q+1){super(`Provider streamed more than ${Q} characters of arguments for "${V}" without finishing the call (maxToolArgumentChars)`);this.name="ProviderToolArgumentsTooLongError",this.limit=Q,this.detail={tool:V,toolCallId:Y,limit:Q,chars:Z}}}class VQ extends I{constructor(Q,V,Y,Z,$){super(Q,V,Y,Z);this.name="ProviderToolArgumentsRunawayError",this.message=`Provider streamed more than ${Q} characters of white space in the arguments for "${V}" before they were whole JSON (maxToolArgumentWhitespace)`,this.detail.whitespace=$}}function YQ(Q){let V=N(Q);if(V?.message)return V.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function N(Q){if(!Q||typeof Q!=="object")return null;let V=Q,Z=V.error&&typeof V.error==="object"?V.error:Q;if(typeof Z.message!=="string"&&typeof Z.code!=="string"&&typeof Z.type!=="string")return null;let $=Z.innererror?.code??Z.code;return{message:Z.message,type:Z.type,code:$,param:Z.param}}function kQ(Q){if(!Q||typeof Q!=="object")return{};let V=Q,{status:Y,requestId:Z}=V,$=ZQ(V.body),J=z(V.providerType)??$.providerType,K=z(V.providerCode)??$.providerCode,B=z(V.providerParam)??$.providerParam;return{...typeof Y==="number"&&Y>=100&&Y<=599?{status:Y}:{},...typeof Z==="string"&&Z?{requestId:Z}:{},...J?{providerType:J}:{},...K?{providerCode:K}:{},...B?{providerParam:B}:{}}}function ZQ(Q){let V=N(Q),Y=z(V?.type),Z=z(V?.code),$=z(V?.param);return{...Y?{providerType:Y}:{},...Z?{providerCode:Z}:{},...$?{providerParam:$}:{}}}function z(Q){return typeof Q==="string"&&Q?Q:void 0}function vQ(Q){if(Q instanceof C||Q instanceof I)return{code:"provider_error",message:Q.message,retryable:!0};if(XQ(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof y)return $Q(Q.status,N(Q.body),Q.message,Q.retryAfter);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function $Q(Q,V,Y,Z){let $=V?.message??Y,J=(V?.code??"").toLowerCase(),K=(V?.type??"").toLowerCase(),B=`${J} ${K} ${$}`.toLowerCase().replace(/https?:\/\/\S+/g,"");if(Q===429){if(!JQ.has(J)&&(J==="insufficient_quota"||B.includes("quota")))return{code:"rate_limited",message:$,retryable:!1};let G=Z??KQ($);return{code:"rate_limited",message:$,retryable:!0,...G!==void 0?{retryAfter:G}:{}}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:$,retryable:!0};if(BQ(B))return{code:"context_length_exceeded",message:$,retryable:!1};if(GQ(B))return{code:"content_filtered",message:$,retryable:!1};if(V?.param?.startsWith("tools")||B.includes("invalid schema for function"))return{code:"invalid_tool_input",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!1}}var JQ=new Set(["ratelimitreached","rate_limit_exceeded","too_many_requests"]);function KQ(Q){let V=/retry after (\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s)\b/i.exec(Q);if(!V)return;let Y=Number(V[1]);return/^m(s|illi)/i.test(V[2])?Y:Y*1000}function BQ(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")||Q.includes("prompt is too long")||Q.includes("request_too_large")}function GQ(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")||Q.includes("moderation_blocked")||Q.includes("rejected by the safety system")||Q.includes("safety_violations")}function XQ(Q){if(!Q||typeof Q!=="object")return!1;let V=Q;return V.name==="AbortError"||V.code==="ABORT_ERR"}
|
|
3
|
+
export{O as qd,OQ as rd,IQ as sd,NQ as td,MQ as ud,t as vd,EQ as wd,SQ as xd,TQ as yd,AQ as zd,xQ as Ad,D as Bd,E as Cd,HQ as Dd,LQ as Ed,UQ as Fd,_ as Gd,T as Hd,g as Id,h as Jd,A as Kd,zQ as Ld,DQ as Md,l as Nd,w as Od,FQ as Pd,y as Qd,C as Rd,e as Sd,QQ as Td,I as Ud,VQ as Vd,kQ as Wd,ZQ as Xd,vQ as Yd,p as Zd,v as _d,RQ as $d,d as ae,n as be,o as ce,CQ as de};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=2DB216492CE128A864756E2164756E21
|
|
@@ -9,6 +9,6 @@
|
|
|
9
9
|
"import type { AgentError, ProviderErrorDetail, ToolArgumentsTooLong } from \"../types\";\n\n/**\n * A non-2xx response, carried as an exception so the retry loop and\n * `normalizeError` can both read it.\n *\n * The body is kept parsed-if-possible and raw-if-not: OpenAI and Azure both\n * answer `{ error: { message, type, code } }` on a good day, and an HTML error\n * page from a proxy on a bad one, and the bad day is exactly when the text\n * matters.\n */\nexport class ProviderHttpError extends Error {\n readonly status: number;\n readonly body: unknown;\n readonly requestId?: string;\n /** The response's `Retry-After`, in milliseconds, when it had one. */\n readonly retryAfter?: number;\n\n constructor(status: number, body: unknown, requestId?: string, retryAfter?: number) {\n super(`Provider request failed with status ${status}: ${describeBody(body)}`);\n this.name = \"ProviderHttpError\";\n this.status = status;\n this.body = body;\n this.requestId = requestId;\n if (retryAfter !== undefined) this.retryAfter = retryAfter;\n }\n}\n\n/**\n * The request ran out of time. Its own class because it must not read as a\n * user abort: `stop()` means the person is done, and a timeout means the\n * network was, and only one of those is worth trying again.\n */\nexport class ProviderTimeoutError extends Error {\n readonly timeoutMs: number;\n\n constructor(timeoutMs: number) {\n super(`Provider request timed out after ${timeoutMs}ms`);\n this.name = \"ProviderTimeoutError\";\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * A streamed answer that started and then sent nothing, not even a keepalive,\n * for `streamIdleTimeoutMs` (#1167). A `ProviderTimeoutError`, so it reads the\n * same everywhere: retryable `provider_error`, never an abort. The attempt was\n * aborted, so its connection is released.\n */\nexport class ProviderStreamIdleError extends ProviderTimeoutError {\n constructor(timeoutMs: number) {\n super(timeoutMs);\n this.name = \"ProviderStreamIdleError\";\n this.message = `Provider stream sent nothing for ${timeoutMs}ms (streamIdleTimeoutMs)`;\n }\n}\n\n/**\n * A streamed answer still going after `streamMaxDurationMs` (#1169): the one\n * bound a stream that keeps trickling cannot get around, because no chunk\n * resets it. A `ProviderTimeoutError`, so it is a retryable `provider_error`\n * and never an abort. The attempt was aborted, so its connection is released.\n */\nexport class ProviderStreamDurationError extends ProviderTimeoutError {\n constructor(timeoutMs: number) {\n super(timeoutMs);\n this.name = \"ProviderStreamDurationError\";\n this.message = `Provider stream was still going after ${timeoutMs}ms (streamMaxDurationMs)`;\n }\n}\n\n/**\n * One tool call streamed more argument text than `maxToolArgumentChars`\n * without finishing (#1169), which is what a degenerate generation inside the\n * arguments looks like. Retryable: the call never completed and never ran, so\n * asking again costs a request, and the next sample usually ends normally.\n */\nexport class ProviderToolArgumentsTooLongError extends Error {\n readonly limit: number;\n /** The cut call (#1259), carried onto the provider's `error` event. */\n readonly detail: ToolArgumentsTooLong;\n\n constructor(limit: number, toolName: string, toolCallId = \"\", chars = limit + 1) {\n super(\n `Provider streamed more than ${limit} characters of arguments for \"${toolName}\" without finishing the call (maxToolArgumentChars)`,\n );\n this.name = \"ProviderToolArgumentsTooLongError\";\n this.limit = limit;\n this.detail = { tool: toolName, toolCallId, limit, chars };\n }\n}\n\n/**\n * One tool call's arguments ran into more white space outside strings than\n * `maxToolArgumentWhitespace` (#1334) before they were whole JSON: the model\n * stopped writing the call and kept streaming spaces and line breaks, an\n * event every fraction of a second, which no idle limit catches. A cut call\n * like `ProviderToolArgumentsTooLongError` (the same retries, the same\n * `toolArgumentsTooLong` on the error event), with `whitespace` on its detail\n * and a message that names the cause.\n */\nexport class ProviderToolArgumentsRunawayError extends ProviderToolArgumentsTooLongError {\n constructor(limit: number, toolName: string, toolCallId: string, chars: number, whitespace: number) {\n super(limit, toolName, toolCallId, chars);\n this.name = \"ProviderToolArgumentsRunawayError\";\n this.message = `Provider streamed more than ${limit} characters of white space in the arguments for \"${toolName}\" before they were whole JSON (maxToolArgumentWhitespace)`;\n this.detail.whitespace = whitespace;\n }\n}\n\nfunction describeBody(body: unknown): string {\n const detail = errorBody(body);\n if (detail?.message) return detail.message;\n if (typeof body === \"string\") return body.slice(0, 500);\n return \"no error body\";\n}\n\ntype OpenAIErrorBody = { message?: string; type?: string; code?: string; param?: string };\n\nfunction errorBody(body: unknown): OpenAIErrorBody | null {\n if (!body || typeof body !== \"object\") return null;\n const wrapper = body as { error?: unknown };\n const inner = wrapper.error && typeof wrapper.error === \"object\" ? wrapper.error : body;\n const e = inner as OpenAIErrorBody & { innererror?: { code?: string } };\n if (typeof e.message !== \"string\" && typeof e.code !== \"string\" && typeof e.type !== \"string\") {\n return null;\n }\n // Azure hides the interesting code one level down when its content filter\n // fires, and the outer code is the useless `content_filter`.\n const code = e.innererror?.code ?? e.code;\n return { message: e.message, type: e.type, code, param: e.param };\n}\n\n/**\n * The HTTP status, request id and error body detail of a provider failure,\n * read off what was thrown or off an `error` event — server-side detail for\n * `AgentRunResult.error`, never for a frame.\n *\n * By shape rather than by `instanceof ProviderHttpError`, so a custom provider\n * whose SDK throws its own error class with a `status` gets the same detail.\n * A `status` outside 100–599 is not an HTTP status and is ignored.\n *\n * `providerType`, `providerCode` and `providerParam` (#1302) are taken as set\n * on the object (an `error` event carries them that way), and otherwise read\n * from a `body` in the provider's error shape, as `ProviderHttpError` has.\n */\nexport function httpErrorDetail(error: unknown): ProviderErrorDetail {\n if (!error || typeof error !== \"object\") return {};\n const e = error as {\n status?: unknown;\n requestId?: unknown;\n providerType?: unknown;\n providerCode?: unknown;\n providerParam?: unknown;\n body?: unknown;\n };\n const { status, requestId } = e;\n const body = streamErrorDetail(e.body);\n const providerType = nonEmpty(e.providerType) ?? body.providerType;\n const providerCode = nonEmpty(e.providerCode) ?? body.providerCode;\n const providerParam = nonEmpty(e.providerParam) ?? body.providerParam;\n return {\n ...(typeof status === \"number\" && status >= 100 && status <= 599 ? { status } : {}),\n ...(typeof requestId === \"string\" && requestId ? { requestId } : {}),\n ...(providerType ? { providerType } : {}),\n ...(providerCode ? { providerCode } : {}),\n ...(providerParam ? { providerParam } : {}),\n };\n}\n\n/**\n * The `type`, `code` and `param` of a provider's error object: a response\n * body, or one it streamed (Anthropic's `error` frame, the Responses API's\n * `response.failed`), for the `error` event that reports it.\n */\nexport function streamErrorDetail(raw: unknown): ProviderErrorDetail {\n const body = errorBody(raw);\n const providerType = nonEmpty(body?.type);\n const providerCode = nonEmpty(body?.code);\n const providerParam = nonEmpty(body?.param);\n return {\n ...(providerType ? { providerType } : {}),\n ...(providerCode ? { providerCode } : {}),\n ...(providerParam ? { providerParam } : {}),\n };\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\n/**\n * Provider failures onto `AgentErrorCode`.\n *\n * The contract an app is buying here is that it can branch on `rate_limited`\n * without knowing whose rate limit it was, and on `retryable` without knowing\n * which of the two APIs answered. So `retryable` is set from what is actually\n * true of the failure — a 429 from a spent quota is not retryable no matter\n * what its status code says, and neither is a request that will be too long\n * again next time.\n */\nexport function normalizeProviderError(error: unknown): AgentError {\n if (error instanceof ProviderTimeoutError || error instanceof ProviderToolArgumentsTooLongError) {\n return { code: \"provider_error\", message: error.message, retryable: true };\n }\n\n if (isAbort(error)) {\n return { code: \"aborted\", message: \"The request was aborted.\", retryable: false };\n }\n\n if (error instanceof ProviderHttpError) {\n return fromStatus(error.status, errorBody(error.body), error.message, error.retryAfter);\n }\n\n // `fetch` rejects with a TypeError for DNS failures, refused connections and\n // dropped sockets. Every one of those is worth another attempt.\n if (error instanceof TypeError) {\n return {\n code: \"provider_error\",\n message: `Could not reach the provider: ${error.message}`,\n retryable: true,\n };\n }\n\n if (error instanceof Error) {\n return { code: \"provider_error\", message: error.message, retryable: false };\n }\n\n return { code: \"unknown\", message: String(error), retryable: false };\n}\n\nfunction fromStatus(\n status: number,\n body: OpenAIErrorBody | null,\n fallbackMessage: string,\n retryAfterHeader?: number,\n): AgentError {\n const message = body?.message ?? fallbackMessage;\n const code = (body?.code ?? \"\").toLowerCase();\n const type = (body?.type ?? \"\").toLowerCase();\n // URLs are dropped before matching: Azure's ordinary rate-limit 429 ends\n // with \"visit: https://aka.ms/oai/quotaincrease\", and a link in a message is\n // advice, not the diagnosis.\n const haystack = `${code} ${type} ${message}`.toLowerCase().replace(/https?:\\/\\/\\S+/g, \"\");\n\n if (status === 429) {\n // A spent quota answers 429 and will answer 429 for the rest of the month.\n // Retrying it is how a run turns one billing problem into `maxRetries`\n // billing problems and a much later error message. A code that names a\n // rate limit is believed over any wording, though: Azure's\n // `RateLimitReached` asks for a retry in so many seconds.\n const outOfCredit =\n !RATE_LIMIT_CODES.has(code) && (code === \"insufficient_quota\" || haystack.includes(\"quota\"));\n if (outOfCredit) return { code: \"rate_limited\", message, retryable: false };\n const retryAfter = retryAfterHeader ?? retryAfterFromMessage(message);\n return {\n code: \"rate_limited\",\n message,\n retryable: true,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n };\n }\n\n if (status >= 500 || status === 408 || status === 409) {\n return { code: \"provider_error\", message, retryable: true };\n }\n\n if (isContextLength(haystack)) {\n return { code: \"context_length_exceeded\", message, retryable: false };\n }\n\n if (isContentFilter(haystack)) {\n return { code: \"content_filtered\", message, retryable: false };\n }\n\n // A schema the API refused. It is our request that is wrong, so the run\n // should surface it as a tool problem rather than a generic outage.\n if (body?.param?.startsWith(\"tools\") || haystack.includes(\"invalid schema for function\")) {\n return { code: \"invalid_tool_input\", message, retryable: false };\n }\n\n return { code: \"provider_error\", message, retryable: false };\n}\n\n/** Body codes that say \"too many requests right now\", never \"out of credit\". */\nconst RATE_LIMIT_CODES = new Set([\"ratelimitreached\", \"rate_limit_exceeded\", \"too_many_requests\"]);\n\n/**\n * \"Please retry after 30 seconds\", as Azure words it in a 429 that may come\n * without a `Retry-After` header. Milliseconds, or undefined when the message\n * does not say.\n */\nexport function retryAfterFromMessage(message: string): number | undefined {\n const match = /retry after (\\d+(?:\\.\\d+)?)\\s*(milliseconds?|ms|seconds?|secs?|s)\\b/i.exec(message);\n if (!match) return undefined;\n const value = Number(match[1]);\n return /^m(s|illi)/i.test(match[2]!) ? value : value * 1000;\n}\n\nfunction isContextLength(haystack: string): boolean {\n return (\n haystack.includes(\"context_length_exceeded\") ||\n haystack.includes(\"maximum context length\") ||\n haystack.includes(\"context window\") ||\n haystack.includes(\"reduce the length\") ||\n // Anthropic: 400 \"prompt is too long: 1050000 tokens > 1000000 maximum\",\n // and 413 `request_too_large` for a body over the byte limit. Neither\n // works on a retry; both want a shorter history.\n haystack.includes(\"prompt is too long\") ||\n haystack.includes(\"request_too_large\")\n );\n}\n\nfunction isContentFilter(haystack: string): boolean {\n return (\n haystack.includes(\"content_filter\") ||\n haystack.includes(\"content_policy_violation\") ||\n haystack.includes(\"responsibleaipolicyviolation\") ||\n haystack.includes(\"content management policy\") ||\n // The image models' refusal: `code: \"moderation_blocked\"`, \"Your request\n // was rejected by the safety system ... safety_violations=[...]\".\n haystack.includes(\"moderation_blocked\") ||\n haystack.includes(\"rejected by the safety system\") ||\n haystack.includes(\"safety_violations\")\n );\n}\n\nfunction isAbort(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const e = error as { name?: string; code?: string };\n return e.name === \"AbortError\" || e.code === \"ABORT_ERR\";\n}\n"
|
|
10
10
|
],
|
|
11
11
|
"mappings": ";yCAgBO,MAAM,UAAkB,KAAM,CAE1B,UAET,WAAW,CAAC,EAAiB,EAAoD,CAAC,EAAG,CACnF,MAAM,EAAS,EAAQ,QAAU,OAAY,CAAE,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AoB,sBAAuB,mBAAmB,CAAC,EAO1F,SAAS,EAAqB,CAAC,EAAqC,CACzE,IAAM,EAAQ,uEAAuE,KAAK,CAAO,EACjG,GAAI,CAAC,EAAO,OACZ,IAAM,EAAQ,OAAO,EAAM,EAAE,EAC7B,MAAO,cAAc,KAAK,EAAM,EAAG,EAAI,EAAQ,EAAQ,KAGzD,SAAS,EAAe,CAAC,EAA2B,CAClD,OACE,EAAS,SAAS,yBAAyB,GAC3C,EAAS,SAAS,wBAAwB,GAC1C,EAAS,SAAS,gBAAgB,GAClC,EAAS,SAAS,mBAAmB,GAIrC,EAAS,SAAS,oBAAoB,GACtC,EAAS,SAAS,mBAAmB,EAIzC,SAAS,EAAe,CAAC,EAA2B,CAClD,OACE,EAAS,SAAS,gBAAgB,GAClC,EAAS,SAAS,0BAA0B,GAC5C,EAAS,SAAS,8BAA8B,GAChD,EAAS,SAAS,2BAA2B,GAG7C,EAAS,SAAS,oBAAoB,GACtC,EAAS,SAAS,+BAA+B,GACjD,EAAS,SAAS,mBAAmB,EAIzC,SAAS,EAAO,CAAC,EAAyB,CACxC,GAAI,CAAC,GAAS,OAAO,IAAU,SAAU,MAAO,GAChD,IAAM,EAAI,EACV,OAAO,EAAE,OAAS,cAAgB,EAAE,OAAS",
|
|
12
|
-
"debugId": "
|
|
12
|
+
"debugId": "2DB216492CE128A864756E2164756E21",
|
|
13
13
|
"names": []
|
|
14
14
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{W as J}from"./chunk-
|
|
2
|
+
import{W as J}from"./chunk-4n3jva4e.js";import{Sm as I}from"./chunk-ts75gcfd.js";var Z=I((Q)=>{var K=J(),L=(b)=>{return{setHttpHandler(j){b.httpHandler=j},httpHandler(){return b.httpHandler},updateHttpClientConfig(j,w){b.httpHandler?.updateHttpClientConfig(j,w)},httpHandlerConfigs(){return b.httpHandler.httpHandlerConfigs()}}},M=(b)=>{return{httpHandler:b.httpHandler()}};class B{name;kind;values;constructor({name:b,kind:j=K.FieldPosition.HEADER,values:w=[]}){this.name=b,this.kind=j,this.values=w}add(b){this.values.push(b)}set(b){this.values=b}remove(b){this.values=this.values.filter((j)=>j!==b)}toString(){return this.values.map((b)=>b.includes(",")||b.includes(" ")?`"${b}"`:b).join(", ")}get(){return this.values}}class D{entries={};encoding;constructor({fields:b=[],encoding:j="utf-8"}){b.forEach(this.setField.bind(this)),this.encoding=j}setField(b){this.entries[b.name.toLowerCase()]=b}getField(b){return this.entries[b.toLowerCase()]}removeField(b){delete this.entries[b.toLowerCase()]}getByType(b){return Object.values(this.entries).filter((j)=>j.kind===b)}}class z{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(b){this.method=b.method||"GET",this.hostname=b.hostname||"localhost",this.port=b.port,this.query=b.query||{},this.headers=b.headers||{},this.body=b.body,this.protocol=b.protocol?b.protocol.slice(-1)!==":"?`${b.protocol}:`:b.protocol:"https:",this.path=b.path?b.path.charAt(0)!=="/"?`/${b.path}`:b.path:"/",this.username=b.username,this.password=b.password,this.fragment=b.fragment}static clone(b){let j=new z({...b,headers:{...b.headers}});if(j.query)j.query=O(j.query);return j}static isInstance(b){if(!b)return!1;let j=b;return"method"in j&&"protocol"in j&&"hostname"in j&&"path"in j&&typeof j.query==="object"&&typeof j.headers==="object"}clone(){return z.clone(this)}}function O(b){return Object.keys(b).reduce((j,w)=>{let A=b[w];return{...j,[w]:Array.isArray(A)?[...A]:A}},{})}class G{statusCode;reason;headers;body;constructor(b){this.statusCode=b.statusCode,this.reason=b.reason,this.headers=b.headers||{},this.body=b.body}static isInstance(b){if(!b)return!1;let j=b;return typeof j.statusCode==="number"&&typeof j.headers==="object"}}function P(b){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(b)}Q.Field=B;Q.Fields=D;Q.HttpRequest=z;Q.HttpResponse=G;Q.getHttpHandlerExtensionConfiguration=L;Q.isValidHostname=P;Q.resolveHttpHandlerRuntimeConfig=M});
|
|
3
3
|
export{Z as Q};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=B2475FFD726DA98664756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"'use strict';\n\nvar types = require('@smithy/types');\n\nconst getHttpHandlerExtensionConfiguration = (runtimeConfig) => {\n return {\n setHttpHandler(handler) {\n runtimeConfig.httpHandler = handler;\n },\n httpHandler() {\n return runtimeConfig.httpHandler;\n },\n updateHttpClientConfig(key, value) {\n runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);\n },\n httpHandlerConfigs() {\n return runtimeConfig.httpHandler.httpHandlerConfigs();\n },\n };\n};\nconst resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {\n return {\n httpHandler: httpHandlerExtensionConfiguration.httpHandler(),\n };\n};\n\nclass Field {\n name;\n kind;\n values;\n constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) {\n this.name = name;\n this.kind = kind;\n this.values = values;\n }\n add(value) {\n this.values.push(value);\n }\n set(values) {\n this.values = values;\n }\n remove(value) {\n this.values = this.values.filter((v) => v !== value);\n }\n toString() {\n return this.values.map((v) => (v.includes(\",\") || v.includes(\" \") ? `\"${v}\"` : v)).join(\", \");\n }\n get() {\n return this.values;\n }\n}\n\nclass Fields {\n entries = {};\n encoding;\n constructor({ fields = [], encoding = \"utf-8\" }) {\n fields.forEach(this.setField.bind(this));\n this.encoding = encoding;\n }\n setField(field) {\n this.entries[field.name.toLowerCase()] = field;\n }\n getField(name) {\n return this.entries[name.toLowerCase()];\n }\n removeField(name) {\n delete this.entries[name.toLowerCase()];\n }\n getByType(kind) {\n return Object.values(this.entries).filter((field) => field.kind === kind);\n }\n}\n\nclass HttpRequest {\n method;\n protocol;\n hostname;\n port;\n path;\n query;\n headers;\n username;\n password;\n fragment;\n body;\n constructor(options) {\n this.method = options.method || \"GET\";\n this.hostname = options.hostname || \"localhost\";\n this.port = options.port;\n this.query = options.query || {};\n this.headers = options.headers || {};\n this.body = options.body;\n this.protocol = options.protocol\n ? options.protocol.slice(-1) !== \":\"\n ? `${options.protocol}:`\n : options.protocol\n : \"https:\";\n this.path = options.path ? (options.path.charAt(0) !== \"/\" ? `/${options.path}` : options.path) : \"/\";\n this.username = options.username;\n this.password = options.password;\n this.fragment = options.fragment;\n }\n static clone(request) {\n const cloned = new HttpRequest({\n ...request,\n headers: { ...request.headers },\n });\n if (cloned.query) {\n cloned.query = cloneQuery(cloned.query);\n }\n return cloned;\n }\n static isInstance(request) {\n if (!request) {\n return false;\n }\n const req = request;\n return (\"method\" in req &&\n \"protocol\" in req &&\n \"hostname\" in req &&\n \"path\" in req &&\n typeof req[\"query\"] === \"object\" &&\n typeof req[\"headers\"] === \"object\");\n }\n clone() {\n return HttpRequest.clone(this);\n }\n}\nfunction cloneQuery(query) {\n return Object.keys(query).reduce((carry, paramName) => {\n const param = query[paramName];\n return {\n ...carry,\n [paramName]: Array.isArray(param) ? [...param] : param,\n };\n }, {});\n}\n\nclass HttpResponse {\n statusCode;\n reason;\n headers;\n body;\n constructor(options) {\n this.statusCode = options.statusCode;\n this.reason = options.reason;\n this.headers = options.headers || {};\n this.body = options.body;\n }\n static isInstance(response) {\n if (!response)\n return false;\n const resp = response;\n return typeof resp.statusCode === \"number\" && typeof resp.headers === \"object\";\n }\n}\n\nfunction isValidHostname(hostname) {\n const hostPattern = /^[a-z0-9][a-z0-9\\.\\-]*[a-z0-9]$/;\n return hostPattern.test(hostname);\n}\n\nexports.Field = Field;\nexports.Fields = Fields;\nexports.HttpRequest = HttpRequest;\nexports.HttpResponse = HttpResponse;\nexports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;\nexports.isValidHostname = isValidHostname;\nexports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";qGAEA,FAAI,MAEE,EAAuC,CAAC,IAAkB,CAC5D,MAAO,CACH,cAAc,CAAC,EAAS,CACpB,EAAc,YA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B,KAAK,WAAa,EAAQ,WAC1B,KAAK,OAAS,EAAQ,OACtB,KAAK,QAAU,EAAQ,SAAW,CAAC,EACnC,KAAK,KAAO,EAAQ,WAEjB,WAAU,CAAC,EAAU,CACxB,GAAI,CAAC,EACD,MAAO,GACX,IAAM,EAAO,EACb,OAAO,OAAO,EAAK,aAAe,UAAY,OAAO,EAAK,UAAY,SAE9E,CAEA,SAAS,CAAe,CAAC,EAAU,CAE/B,MADoB,kCACD,KAAK,CAAQ,EAG5B,QAAQ,EACR,SAAS,EACT,cAAc,EACd,eAAe,EACf,uCAAuC,EACvC,kBAAkB,EAClB,kCAAkC",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "B2475FFD726DA98664756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
function H(z){if(z===401)return"authentication";if(z===403)return"permission";if(z===404)return"not_found";if(z===416)return"range_not_satisfiable";if(z===429)return"rate_limit";if(z>=500)return"server_error";return"form_error"}var N="GEMI_REQUEST_BREAKER_ERROR";class J extends Error{static legacyStringPayload=!1;kind=N;payload;constructor(z,C={}){super(z);let D=C.status??400;this.payload={api:{status:D,data:{error:L(C.kind??H(D),z??"",D)},...C.headers?{headers:C.headers}:{}},view:{status:D}}}}function L(z,C,D){return{kind:z,message:C,status:D}}function X(z,C,D){return J.legacyStringPayload?C:L(z,C,D)}
|
|
3
|
-
export{H as
|
|
3
|
+
export{H as Aj,N as Bj,J as Cj,L as Dj,X as Ej};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=83CC724CFD8B358A64756E2164756E21
|
|
@@ -6,6 +6,6 @@
|
|
|
6
6
|
"import { refusalKindForStatus, type Refusal, type RefusalKind } from \"./refusal\";\n\nexport const GEMI_REQUEST_BREAKER_ERROR = \"GEMI_REQUEST_BREAKER_ERROR\";\n\nexport type RequestBreakerOptions = {\n /** The answer's status. 400 when absent. */\n status?: number;\n /**\n * What the client's guards classify it as. Absent, it follows from\n * `status`: 401 `authentication`, 403 `permission`, 404 `not_found`, 429\n * `rate_limit`, 5xx `server_error`, any other status `form_error`.\n */\n kind?: Exclude<RefusalKind, \"validation_error\">;\n /** Extra headers for the API answer. */\n headers?: Record<string, string>;\n};\n\nexport class RequestBreakerError extends Error {\n /**\n * Answer the refusals that were bare strings before 0.88 — authentication,\n * authorization, permission, CSRF and a 500 — with that string again,\n * instead of `{ kind, message, status }`.\n *\n * For a shipped native client that reads `body.error` as a string and cannot\n * be rolled forward in the same deploy as the server. Set it once at boot,\n * and remove the line when the clients read `body.error.message`:\n *\n * ```ts\n * RequestBreakerError.legacyStringPayload = true;\n * ```\n *\n * gemi's own web client reads either shape. Refusals that were already\n * objects (404, 429, a policy 403) stay objects.\n */\n static legacyStringPayload = false;\n\n public kind = GEMI_REQUEST_BREAKER_ERROR;\n public payload: {\n api: Record<string, any>;\n view: Record<string, any>;\n /**\n * What a `.json` view navigation answers, when that differs from `api`.\n * Absent, it gets `api` — right for most breakers, but not for one that\n * must be a 401 to an API client and a redirect to the client router.\n */\n viewData?: Record<string, any>;\n };\n\n /**\n * A refusal that answers `{ error: { kind, message, status } }` with\n * `status`, so the client's guards classify it without a payload of your\n * own. A subclass that sets `payload` itself replaces this.\n *\n * ```ts\n * throw new RequestBreakerError(\"This slug is taken\", { status: 409 });\n * // → 409 { error: { kind: \"form_error\", message: \"This slug is taken\", status: 409 } }\n * ```\n */\n constructor(message?: string, options: RequestBreakerOptions = {}) {\n super(message);\n const status = options.status ?? 400;\n this.payload = {\n api: {\n status,\n data: {\n error: refusal(options.kind ?? refusalKindForStatus(status), message ?? \"\", status),\n },\n ...(options.headers ? { headers: options.headers } : {}),\n },\n view: { status },\n };\n }\n}\n\n/** A refusal's `error` field. */\nexport function refusal<K extends Exclude<RefusalKind, \"validation_error\">>(\n kind: K,\n message: string,\n status: number,\n): Refusal<K> {\n return { kind, message, status };\n}\n\n/**\n * A refusal that was a bare string before 0.88: the object, or the string\n * under `RequestBreakerError.legacyStringPayload`.\n *\n * @internal\n */\nexport function stringEraRefusal<K extends Exclude<RefusalKind, \"validation_error\">>(\n kind: K,\n message: string,\n status: number,\n): Refusal<K> | string {\n return RequestBreakerError.legacyStringPayload ? message : refusal(kind, message, status);\n}\n"
|
|
7
7
|
],
|
|
8
8
|
"mappings": ";AA0DO,SAAS,CAAoB,CAAC,EAA0D,CAC7F,GAAI,IAAW,IAAK,MAAO,iBAC3B,GAAI,IAAW,IAAK,MAAO,aAC3B,GAAI,IAAW,IAAK,MAAO,YAC3B,GAAI,IAAW,IAAK,MAAO,wBAC3B,GAAI,IAAW,IAAK,MAAO,aAC3B,GAAI,GAAU,IAAK,MAAO,eAC1B,MAAO,aC/DF,IAAM,EAA6B,6BAenC,MAAM,UAA4B,KAAM,OAiBtC,qBAAsB,GAEtB,KAAO,EACP,QAqBP,WAAW,CAAC,EAAkB,EAAiC,CAAC,EAAG,CACjE,MAAM,CAAO,EACb,IAAM,EAAS,EAAQ,QAAU,IACjC,KAAK,QAAU,CACb,IAAK,CACH,SACA,KAAM,CACJ,MAAO,EAAQ,EAAQ,MAAQ,EAAqB,CAAM,EAAG,GAAW,GAAI,CAAM,CACpF,KACI,EAAQ,QAAU,CAAE,QAAS,EAAQ,OAAQ,EAAI,CAAC,CACxD,EACA,KAAM,CAAE,QAAO,CACjB,EAEJ,CAGO,SAAS,CAA2D,CACzE,EACA,EACA,EACY,CACZ,MAAO,CAAE,OAAM,UAAS,QAAO,EAS1B,SAAS,CAAoE,CAClF,EACA,EACA,EACqB,CACrB,OAAO,EAAoB,oBAAsB,EAAU,EAAQ,EAAM,EAAS,CAAM",
|
|
9
|
-
"debugId": "
|
|
9
|
+
"debugId": "83CC724CFD8B358A64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Sm as t,Vm as A}from"./chunk-ts75gcfd.js";var o=t((b)=>{var i=(r)=>typeof ArrayBuffer==="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]";b.isArrayBuffer=i});var y=t((g)=>{var m=o(),f=A("buffer"),B=(r,e=0,u=r.byteLength-e)=>{if(!m.isArrayBuffer(r))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof r} (${r})`);return f.Buffer.from(r,e,u)},a=(r,e)=>{if(typeof r!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof r} (${r})`);return e?f.Buffer.from(r,e):f.Buffer.from(r)};g.fromArrayBuffer=B;g.fromString=a});var x=t((w)=>{var n=y(),s=(r)=>{let e=n.fromString(r,"utf8");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT)},h=(r)=>{if(typeof r==="string")return s(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(r)},p=(r)=>{if(typeof r==="string")return r;if(typeof r!=="object"||typeof r.byteOffset!=="number"||typeof r.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return n.fromArrayBuffer(r.buffer,r.byteOffset,r.byteLength).toString("utf8")};w.fromUtf8=s;w.toUint8Array=h;w.toUtf8=p});
|
|
3
3
|
export{o as R,y as S,x as T};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=E7172C11EBD333DC64756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"'use strict';\n\nvar utilBufferFrom = require('@smithy/util-buffer-from');\n\nconst fromUtf8 = (input) => {\n const buf = utilBufferFrom.fromString(input, \"utf8\");\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n};\n\nconst toUint8Array = (data) => {\n if (typeof data === \"string\") {\n return fromUtf8(data);\n }\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n }\n return new Uint8Array(data);\n};\n\nconst toUtf8 = (input) => {\n if (typeof input === \"string\") {\n return input;\n }\n if (typeof input !== \"object\" || typeof input.byteOffset !== \"number\" || typeof input.byteLength !== \"number\") {\n throw new Error(\"@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.\");\n }\n return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString(\"utf8\");\n};\n\nexports.fromUtf8 = fromUtf8;\nexports.toUint8Array = toUint8Array;\nexports.toUtf8 = toUtf8;\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";+DAEA,IAAM,EAAgB,CAAC,IAAS,OAAO,cAAgB,YAAc,aAAe,aAChF,OAAO,UAAU,SAAS,KAAK,CAAG,IAAM,uBAEpC,gBAAgB,kBCHxB,IAAI,MACA,cAEE,EAAkB,CAAC,EAAO,EAAS,EAAG,EAAS,EAAM,WAAa,IAAW,CAC/E,GAAI,CAAC,EAAc,cAAc,CAAK,EAClC,MAAU,UAAU,2DAA2D,OAAO,MAAU,IAAQ,EAE5G,OAAO,EAAO,OAAO,KAAK,EAAO,EAAQ,CAAM,GAE7C,EAAa,CAAC,EAAO,IAAa,CACpC,GAAI,OAAO,IAAU,SACjB,MAAU,UAAU,8DAA8D,OAAO,MAAU,IAAQ,EAE/G,OAAO,EAAW,EAAO,OAAO,KAAK,EAAO,CAAQ,EAAI,EAAO,OAAO,KAAK,CAAK,GAG5E,kBAAkB,EAClB,aAAa,kBCjBrB,IAAI,MAEE,EAAW,CAAC,IAAU,CACxB,IAAM,EAAM,EAAe,WAAW,EAAO,MAAM,EACnD,OAAO,IAAI,WAAW,EAAI,OAAQ,EAAI,WAAY,EAAI,WAAa,WAAW,iBAAiB,GAG7F,EAAe,CAAC,IAAS,CAC3B,GAAI,OAAO,IAAS,SAChB,OAAO,EAAS,CAAI,EAExB,GAAI,YAAY,OAAO,CAAI,EACvB,OAAO,IAAI,WAAW,EAAK,OAAQ,EAAK,WAAY,EAAK,WAAa,WAAW,iBAAiB,EAEtG,OAAO,IAAI,WAAW,CAAI,GAGxB,EAAS,CAAC,IAAU,CACtB,GAAI,OAAO,IAAU,SACjB,OAAO,EAEX,GAAI,OAAO,IAAU,UAAY,OAAO,EAAM,aAAe,UAAY,OAAO,EAAM,aAAe,SACjG,MAAU,MAAM,8EAA8E,EAElG,OAAO,EAAe,gBAAgB,EAAM,OAAQ,EAAM,WAAY,EAAM,UAAU,EAAE,SAAS,MAAM,GAGnG,WAAW,EACX,eAAe,EACf,SAAS",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "E7172C11EBD333DC64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{V as A}from"./chunk-
|
|
2
|
+
import{V as A}from"./chunk-hprgj13q.js";import"./chunk-4n3jva4e.js";import{X as T}from"./chunk-sh2bd09k.js";import{Y as y}from"./chunk-x6a5qxpa.js";import{Rm as r}from"./chunk-ts75gcfd.js";var u=r(A(),1);var i=r(y(),1),E=r(A(),1);import{exec as d}from"child_process";import{promisify as I}from"util";var x=r(T(),1),_=(c,n,e)=>{if(n.Version!==1)throw Error(`Profile ${c} credential_process did not return Version 1.`);if(n.AccessKeyId===void 0||n.SecretAccessKey===void 0)throw Error(`Profile ${c} credential_process returned invalid credentials.`);if(n.Expiration){let w=new Date;if(new Date(n.Expiration)<w)throw Error(`Profile ${c} credential_process returned expired credentials.`)}let s=n.AccountId;if(!s&&e?.[c]?.aws_account_id)s=e[c].aws_account_id;let t={accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,...n.SessionToken&&{sessionToken:n.SessionToken},...n.Expiration&&{expiration:new Date(n.Expiration)},...n.CredentialScope&&{credentialScope:n.CredentialScope},...s&&{accountId:s}};return x.setCredentialFeature(t,"CREDENTIALS_PROCESS","w"),t};var K=async(c,n,e)=>{let s=n[c];if(n[c]){let t=s.credential_process;if(t!==void 0){let w=I(E.externalDataInterceptor?.getTokenRecord?.().exec??d);try{let{stdout:o}=await w(t),S;try{S=JSON.parse(o.trim())}catch{throw Error(`Profile ${c} credential_process returned invalid JSON.`)}return _(c,S,n)}catch(o){throw new i.CredentialsProviderError(o.message,{logger:e})}}else throw new i.CredentialsProviderError(`Profile ${c} did not contain credential_process.`,{logger:e})}else throw new i.CredentialsProviderError(`Profile ${c} could not be found in shared credentials file.`,{logger:e})};var R=(c={})=>async({callerClientConfig:n}={})=>{c.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let e=await u.parseKnownFiles(c);return K(u.getProfileName({profile:c.profile??n?.profile}),e,c.logger)};export{R as fromProcess};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=9297BA5015C0706E64756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"C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AyB,EAAM,QAAS,CAAE,QAAO,CAAC,GAIhE,WAAM,IAAI,2BAAyB,WAAW,wCAAmD,CAAE,QAAO,CAAC,EAI/G,WAAM,IAAI,2BAAyB,WAAW,mDAA8D,CACxG,QACJ,CAAC,GD/BF,IAAM,EAAc,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CAC7E,EAAK,QAAQ,MAAM,oDAAoD,EACvE,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAA0B,iBAAe,CAC5C,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAK,MAAM",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "9297BA5015C0706E64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{W as re}from"./chunk-
|
|
2
|
+
import{W as re}from"./chunk-4n3jva4e.js";import{Sm as _,Vm as a}from"./chunk-ts75gcfd.js";var I=_((b)=>{Object.defineProperty(b,"__esModule",{value:!0});b.getHomeDir=void 0;var W=a("os"),V=a("path"),x={},G=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},U=()=>{let{HOME:e,USERPROFILE:t,HOMEPATH:r,HOMEDRIVE:o=`C:${V.sep}`}=process.env;if(e)return e;if(t)return t;if(r)return`${o}${r}`;let i=G();if(!x[i])x[i]=(0,W.homedir)();return x[i]};b.getHomeDir=U});var P=_((j)=>{Object.defineProperty(j,"__esModule",{value:!0});j.getSSOTokenFilepath=void 0;var X=a("crypto"),B=a("path"),J=I(),z=(e)=>{let r=(0,X.createHash)("sha1").update(e).digest("hex");return(0,B.join)((0,J.getHomeDir)(),".aws","sso","cache",`${r}.json`)};j.getSSOTokenFilepath=z});var R=_((C)=>{Object.defineProperty(C,"__esModule",{value:!0});C.getSSOTokenFromFile=C.tokenIntercept=void 0;var Q=a("fs/promises"),Y=P();C.tokenIntercept={};var Z=async(e)=>{if(C.tokenIntercept[e])return C.tokenIntercept[e];let t=(0,Y.getSSOTokenFilepath)(e),r=await(0,Q.readFile)(t,"utf8");return JSON.parse(r)};C.getSSOTokenFromFile=Z});var k=_((L)=>{Object.defineProperty(L,"__esModule",{value:!0});L.readFile=L.fileIntercept=L.filePromises=void 0;var ee=a("fs/promises");L.filePromises={};L.fileIntercept={};var te=(e,t)=>{if(L.fileIntercept[e]!==void 0)return L.fileIntercept[e];if(!L.filePromises[e]||t?.ignoreCache)L.filePromises[e]=(0,ee.readFile)(e,"utf8");return L.filePromises[e]};L.readFile=te});var ye=_((c)=>{var l=I(),O=P(),y=R(),g=a("path"),S=re(),f=k(),q="AWS_PROFILE",$="default",oe=(e)=>e.profile||process.env[q]||$,p=".",ie=(e)=>Object.entries(e).filter(([t])=>{let r=t.indexOf(p);if(r===-1)return!1;return Object.values(S.IniSectionType).includes(t.substring(0,r))}).reduce((t,[r,o])=>{let i=r.indexOf(p),n=r.substring(0,i)===S.IniSectionType.PROFILE?r.substring(i+1):r;return t[n]=o,t},{...e.default&&{default:e.default}}),ne="AWS_CONFIG_FILE",M=()=>process.env[ne]||g.join(l.getHomeDir(),".aws","config"),se="AWS_SHARED_CREDENTIALS_FILE",ce=()=>process.env[se]||g.join(l.getHomeDir(),".aws","credentials"),ae=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,le=["__proto__","profile __proto__"],T=(e)=>{let t={},r,o;for(let i of e.split(/\r?\n/)){let n=i.split(/(^|\s)[;#]/)[0].trim();if(n[0]==="["&&n[n.length-1]==="]"){r=void 0,o=void 0;let s=n.substring(1,n.length-1),u=ae.exec(s);if(u){let[,d,,m]=u;if(Object.values(S.IniSectionType).includes(d))r=[d,m].join(p)}else r=s;if(le.includes(s))throw Error(`Found invalid profile name "${s}"`)}else if(r){let s=n.indexOf("=");if(![0,-1].includes(s)){let[u,d]=[n.substring(0,s).trim(),n.substring(s+1).trim()];if(d==="")o=u;else{if(o&&i.trimStart()===i)o=void 0;t[r]=t[r]||{};let m=o?[o,u].join(p):u;t[r][m]=d}}}}return t},A=()=>({}),K=async(e={})=>{let{filepath:t=ce(),configFilepath:r=M()}=e,o=l.getHomeDir(),i="~/",n=t;if(t.startsWith("~/"))n=g.join(o,t.slice(2));let h=r;if(r.startsWith("~/"))h=g.join(o,r.slice(2));let s=await Promise.all([f.readFile(h,{ignoreCache:e.ignoreCache}).then(T).then(ie).catch(A),f.readFile(n,{ignoreCache:e.ignoreCache}).then(T).catch(A)]);return{configFile:s[0],credentialsFile:s[1]}},pe=(e)=>Object.entries(e).filter(([t])=>t.startsWith(S.IniSectionType.SSO_SESSION+p)).reduce((t,[r,o])=>({...t,[r.substring(r.indexOf(p)+1)]:o}),{}),ue=()=>({}),fe=async(e={})=>f.readFile(e.configFilepath??M()).then(T).then(pe).catch(ue),de=(...e)=>{let t={};for(let r of e)for(let[o,i]of Object.entries(r))if(t[o]!==void 0)Object.assign(t[o],i);else t[o]=i;return t},_e=async(e)=>{let t=await K(e);return de(t.configFile,t.credentialsFile)},Fe={getFileRecord(){return f.fileIntercept},interceptFile(e,t){f.fileIntercept[e]=Promise.resolve(t)},getTokenRecord(){return y.tokenIntercept},interceptToken(e,t){y.tokenIntercept[e]=t}};c.getSSOTokenFromFile=y.getSSOTokenFromFile;c.readFile=f.readFile;c.CONFIG_PREFIX_SEPARATOR=p;c.DEFAULT_PROFILE=$;c.ENV_PROFILE=q;c.externalDataInterceptor=Fe;c.getProfileName=oe;c.loadSharedConfigFiles=K;c.loadSsoSessionData=fe;c.parseKnownFiles=_e;Object.prototype.hasOwnProperty.call(l,"__proto__")&&!Object.prototype.hasOwnProperty.call(c,"__proto__")&&Object.defineProperty(c,"__proto__",{enumerable:!0,value:l.__proto__});Object.keys(l).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(c,e))c[e]=l[e]});Object.prototype.hasOwnProperty.call(O,"__proto__")&&!Object.prototype.hasOwnProperty.call(c,"__proto__")&&Object.defineProperty(c,"__proto__",{enumerable:!0,value:O.__proto__});Object.keys(O).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(c,e))c[e]=O[e]})});
|
|
3
3
|
export{ye as V};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=F86D6236EB905B1A64756E2164756E21
|
|
@@ -9,6 +9,6 @@
|
|
|
9
9
|
"'use strict';\n\nvar getHomeDir = require('./getHomeDir');\nvar getSSOTokenFilepath = require('./getSSOTokenFilepath');\nvar getSSOTokenFromFile = require('./getSSOTokenFromFile');\nvar path = require('path');\nvar types = require('@smithy/types');\nvar readFile = require('./readFile');\n\nconst ENV_PROFILE = \"AWS_PROFILE\";\nconst DEFAULT_PROFILE = \"default\";\nconst getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE;\n\nconst CONFIG_PREFIX_SEPARATOR = \".\";\n\nconst getConfigData = (data) => Object.entries(data)\n .filter(([key]) => {\n const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);\n if (indexOfSeparator === -1) {\n return false;\n }\n return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator));\n})\n .reduce((acc, [key, value]) => {\n const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);\n const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;\n acc[updatedKey] = value;\n return acc;\n}, {\n ...(data.default && { default: data.default }),\n});\n\nconst ENV_CONFIG_PATH = \"AWS_CONFIG_FILE\";\nconst getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path.join(getHomeDir.getHomeDir(), \".aws\", \"config\");\n\nconst ENV_CREDENTIALS_PATH = \"AWS_SHARED_CREDENTIALS_FILE\";\nconst getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path.join(getHomeDir.getHomeDir(), \".aws\", \"credentials\");\n\nconst prefixKeyRegex = /^([\\w-]+)\\s([\"'])?([\\w-@\\+\\.%:/]+)\\2$/;\nconst profileNameBlockList = [\"__proto__\", \"profile __proto__\"];\nconst parseIni = (iniData) => {\n const map = {};\n let currentSection;\n let currentSubSection;\n for (const iniLine of iniData.split(/\\r?\\n/)) {\n const trimmedLine = iniLine.split(/(^|\\s)[;#]/)[0].trim();\n const isSection = trimmedLine[0] === \"[\" && trimmedLine[trimmedLine.length - 1] === \"]\";\n if (isSection) {\n currentSection = undefined;\n currentSubSection = undefined;\n const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);\n const matches = prefixKeyRegex.exec(sectionName);\n if (matches) {\n const [, prefix, , name] = matches;\n if (Object.values(types.IniSectionType).includes(prefix)) {\n currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR);\n }\n }\n else {\n currentSection = sectionName;\n }\n if (profileNameBlockList.includes(sectionName)) {\n throw new Error(`Found invalid profile name \"${sectionName}\"`);\n }\n }\n else if (currentSection) {\n const indexOfEqualsSign = trimmedLine.indexOf(\"=\");\n if (![0, -1].includes(indexOfEqualsSign)) {\n const [name, value] = [\n trimmedLine.substring(0, indexOfEqualsSign).trim(),\n trimmedLine.substring(indexOfEqualsSign + 1).trim(),\n ];\n if (value === \"\") {\n currentSubSection = name;\n }\n else {\n if (currentSubSection && iniLine.trimStart() === iniLine) {\n currentSubSection = undefined;\n }\n map[currentSection] = map[currentSection] || {};\n const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;\n map[currentSection][key] = value;\n }\n }\n }\n }\n return map;\n};\n\nconst swallowError$1 = () => ({});\nconst loadSharedConfigFiles = async (init = {}) => {\n const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init;\n const homeDir = getHomeDir.getHomeDir();\n const relativeHomeDirPrefix = \"~/\";\n let resolvedFilepath = filepath;\n if (filepath.startsWith(relativeHomeDirPrefix)) {\n resolvedFilepath = path.join(homeDir, filepath.slice(2));\n }\n let resolvedConfigFilepath = configFilepath;\n if (configFilepath.startsWith(relativeHomeDirPrefix)) {\n resolvedConfigFilepath = path.join(homeDir, configFilepath.slice(2));\n }\n const parsedFiles = await Promise.all([\n readFile.readFile(resolvedConfigFilepath, {\n ignoreCache: init.ignoreCache,\n })\n .then(parseIni)\n .then(getConfigData)\n .catch(swallowError$1),\n readFile.readFile(resolvedFilepath, {\n ignoreCache: init.ignoreCache,\n })\n .then(parseIni)\n .catch(swallowError$1),\n ]);\n return {\n configFile: parsedFiles[0],\n credentialsFile: parsedFiles[1],\n };\n};\n\nconst getSsoSessionData = (data) => Object.entries(data)\n .filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR))\n .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {});\n\nconst swallowError = () => ({});\nconst loadSsoSessionData = async (init = {}) => readFile.readFile(init.configFilepath ?? getConfigFilepath())\n .then(parseIni)\n .then(getSsoSessionData)\n .catch(swallowError);\n\nconst mergeConfigFiles = (...files) => {\n const merged = {};\n for (const file of files) {\n for (const [key, values] of Object.entries(file)) {\n if (merged[key] !== undefined) {\n Object.assign(merged[key], values);\n }\n else {\n merged[key] = values;\n }\n }\n }\n return merged;\n};\n\nconst parseKnownFiles = async (init) => {\n const parsedFiles = await loadSharedConfigFiles(init);\n return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);\n};\n\nconst externalDataInterceptor = {\n getFileRecord() {\n return readFile.fileIntercept;\n },\n interceptFile(path, contents) {\n readFile.fileIntercept[path] = Promise.resolve(contents);\n },\n getTokenRecord() {\n return getSSOTokenFromFile.tokenIntercept;\n },\n interceptToken(id, contents) {\n getSSOTokenFromFile.tokenIntercept[id] = contents;\n },\n};\n\nexports.getSSOTokenFromFile = getSSOTokenFromFile.getSSOTokenFromFile;\nexports.readFile = readFile.readFile;\nexports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR;\nexports.DEFAULT_PROFILE = DEFAULT_PROFILE;\nexports.ENV_PROFILE = ENV_PROFILE;\nexports.externalDataInterceptor = externalDataInterceptor;\nexports.getProfileName = getProfileName;\nexports.loadSharedConfigFiles = loadSharedConfigFiles;\nexports.loadSsoSessionData = loadSsoSessionData;\nexports.parseKnownFiles = parseKnownFiles;\nObject.prototype.hasOwnProperty.call(getHomeDir, '__proto__') &&\n !Object.prototype.hasOwnProperty.call(exports, '__proto__') &&\n Object.defineProperty(exports, '__proto__', {\n enumerable: true,\n value: getHomeDir['__proto__']\n });\n\nObject.keys(getHomeDir).forEach(function (k) {\n if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = getHomeDir[k];\n});\nObject.prototype.hasOwnProperty.call(getSSOTokenFilepath, '__proto__') &&\n !Object.prototype.hasOwnProperty.call(exports, '__proto__') &&\n Object.defineProperty(exports, '__proto__', {\n enumerable: true,\n value: getSSOTokenFilepath['__proto__']\n });\n\nObject.keys(getSSOTokenFilepath).forEach(function (k) {\n if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = getSSOTokenFilepath[k];\n});\n"
|
|
10
10
|
],
|
|
11
11
|
"mappings": ";8GACA,CAAO,eAAe,EAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EACpD,aAAkB,OAC1B,IAAM,UACA,YACA,EAAe,CAAC,EAChB,EAAqB,IAAM,CAC7B,GAAI,SAAW,QAAQ,QACnB,MAAO,GAAG,QAAQ,QAAQ,IAE9B,MAAO,WAEL,EAAa,IAAM,CACrB,IAAQ,OAAM,cAAa,WAAU,YAAY,KAAK,EAAO,OAAU,QAAQ,IAC/E,GAAI,EACA,OAAO,EACX,GAAI,EACA,OAAO,EACX,GAAI,EACA,MAAO,GAAG,IAAY,IAC1B,IAAM,EAAkB,EAAmB,EAC3C,GAAI,CAAC,EAAa,GACd,EAAa,IAAoB,EAAG,EAAK,SAAS,EACtD,OAAO,EAAa,IAEhB,aAAa,kBCxBrB,OAAO,eAAe,EAAS,aA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