gemi 0.90.0 → 0.91.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Schema.d.ts +5 -0
- package/dist/ai/Schema.d.ts.map +1 -1
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/{chunk-ecq15njr.js → chunk-087r45fw.js} +3 -3
- package/dist/{chunk-ecq15njr.js.map → chunk-087r45fw.js.map} +1 -1
- package/dist/{chunk-e6ngf60r.js → chunk-2dfar4d1.js} +2 -2
- package/dist/{chunk-e6ngf60r.js.map → chunk-2dfar4d1.js.map} +1 -1
- package/dist/chunk-2mrgrjy6.js +58 -0
- package/dist/chunk-2mrgrjy6.js.map +14 -0
- package/dist/{chunk-6a0grh04.js → chunk-3470jpmr.js} +2 -2
- package/dist/{chunk-6a0grh04.js.map → chunk-3470jpmr.js.map} +1 -1
- package/dist/{chunk-r1sj312m.js → chunk-4czqjqs7.js} +2 -2
- package/dist/{chunk-r1sj312m.js.map → chunk-4czqjqs7.js.map} +1 -1
- package/dist/{chunk-jbzxb75e.js → chunk-66g9yytx.js} +3 -3
- package/dist/{chunk-jbzxb75e.js.map → chunk-66g9yytx.js.map} +1 -1
- package/dist/{chunk-f64vhjgh.js → chunk-6mdw41s5.js} +3 -3
- package/dist/{chunk-f64vhjgh.js.map → chunk-6mdw41s5.js.map} +1 -1
- package/dist/{chunk-q6ydpt33.js → chunk-7bmctvep.js} +2 -2
- package/dist/{chunk-q6ydpt33.js.map → chunk-7bmctvep.js.map} +1 -1
- package/dist/chunk-7ct4y1zh.js +9 -0
- package/dist/chunk-7ct4y1zh.js.map +31 -0
- package/dist/{chunk-qht6qsvg.js → chunk-d33qcg5b.js} +2 -2
- package/dist/{chunk-qht6qsvg.js.map → chunk-d33qcg5b.js.map} +1 -1
- package/dist/chunk-ddbbxg9m.js +5 -0
- package/dist/{chunk-dk7818hj.js.map → chunk-ddbbxg9m.js.map} +1 -1
- package/dist/{chunk-ngq4n2b3.js → chunk-k5j65f2c.js} +2 -2
- package/dist/{chunk-ngq4n2b3.js.map → chunk-k5j65f2c.js.map} +1 -1
- package/dist/{chunk-bsbn7qtd.js → chunk-p0px3ym0.js} +2 -2
- package/dist/{chunk-bsbn7qtd.js.map → chunk-p0px3ym0.js.map} +1 -1
- package/dist/{chunk-2e9552jm.js → chunk-q18fb0cr.js} +2 -2
- package/dist/{chunk-2e9552jm.js.map → chunk-q18fb0cr.js.map} +1 -1
- package/dist/{chunk-3jf1rsbg.js → chunk-vqhcztw0.js} +2 -2
- package/dist/{chunk-3jf1rsbg.js.map → chunk-vqhcztw0.js.map} +1 -1
- package/dist/chunk-wc46df4w.js +5 -0
- package/dist/chunk-wc46df4w.js.map +10 -0
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/database/index.js +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/http/HttpRequest.d.ts +27 -2
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/validate.d.ts +1 -1
- package/dist/http/validate.d.ts.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/server/devFetch.d.ts +33 -0
- package/dist/server/devFetch.d.ts.map +1 -1
- package/dist/server/hmrRelay.d.ts +41 -0
- package/dist/server/hmrRelay.d.ts.map +1 -0
- package/dist/server/httpDev.d.ts +2 -1
- package/dist/server/httpDev.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-126mmhjj.js +0 -7
- package/dist/chunk-126mmhjj.js.map +0 -30
- package/dist/chunk-4v4v5wkh.js +0 -7
- package/dist/chunk-4v4v5wkh.js.map +0 -11
- package/dist/chunk-dk7818hj.js +0 -5
- package/dist/chunk-hdm74jbr.js +0 -55
- package/dist/chunk-hdm74jbr.js.map +0 -13
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Wb as T,Yb as D}from"./chunk-2dfar4d1.js";import{xg as C}from"./chunk-sh1cfx9j.js";import{Ig as I,Jg as Z,Kg as A}from"./chunk-kmebynhc.js";class R extends Error{code;constructor(G,H=1){super(G);this.code=H;this.name="CommandFailed"}}class K{static commandName="unset";static description="";static args=[];static options=[];run(G){}}function p(G){return G}function S(){return{commands:[],commandsDir:"app/commands"}}var Q=Symbol.for("gemi.console.builder");function x(G){if(G.trim()==="")throw Error("A command name cannot be empty.");if(/[{}]/.test(G)||/\s/.test(G))throw Error(`Invalid command name ${JSON.stringify(G)}. gemi does not parse a signature string; the name is the whole of it. Declare arguments with .arg() and flags with .option():
|
|
3
3
|
|
|
4
4
|
defineCommand("mail:send")
|
|
5
5
|
.arg("user", { required: true })
|
|
@@ -14,6 +14,6 @@ import{$b as D,Zb as T}from"./chunk-e6ngf60r.js";import{xg as C}from"./chunk-sh1
|
|
|
14
14
|
static event = UserRegistered;
|
|
15
15
|
|
|
16
16
|
If this is an abstract base its subclasses extend, move it out of the `+"listeners directory \u2014 the walk excludes gemi's `Listener` and "+"nothing else, so a base sitting beside its subclasses is registered and run like one of them.")}function v(G){for(let H of G){if(Object.getOwnPropertyDescriptor(H,"name")?.writable)continue;console.warn(`Event listener ${H.name} does not declare \`static name\`, so it is registered under its class name, which a production build renames. Nothing reads that name across a build boundary while the `+"listener is sync, which is why this is a warning \u2014 but adding "+`\`queued = true\` to it is refused at boot for the same reason, because the queue's key is that string. Add: static name = "${H.name}";`)}}function b(G){let H=new Set;for(let{event:P}of G){if(H.has(P))continue;if(Object.getOwnPropertyDescriptor(P,"name")?.writable)continue;H.add(P),console.warn(`Event ${P.name} does not declare \`static name\`, so it is dispatched under its class name. A production build minifies the code that dispatches it and renames the class, while discovery reads `+"the listener's copy from source and does not \u2014 so the dispatch would "+`reach no listener in production and nowhere else. Add: static name = "${P.name}";`)}}
|
|
17
|
-
export{R as
|
|
17
|
+
export{R as Eb,K as Fb,p as Gb,S as Hb,c as Ib,_ as Jb,o as Kb,W as Lb,i as Mb,B as Nb,M as Ob,U as Pb,JG as Qb,OG as Rb,QG as Sb,_G as Tb};
|
|
18
18
|
|
|
19
|
-
//# debugId=
|
|
19
|
+
//# debugId=ED9A72DAF2CDB2F964756E2164756E21
|
|
@@ -13,6 +13,6 @@
|
|
|
13
13
|
"import { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\n\nimport {\n discoverClasses,\n DiscoveryError,\n projectRoot,\n} from \"../support/discover\";\nimport { Command, type CommandClass } from \"../console/Command\";\nimport { commandConfigDefaults } from \"../console/config\";\nimport { isUnfinishedBuilder } from \"../console/builder\";\nimport { CronJob } from \"./cron/CronJob\";\nimport { scheduleConfigDefaults } from \"./cron/config\";\nimport { eventConfigDefaults } from \"./events/config\";\nimport type { EventClass } from \"./events/Event\";\nimport { Listener, type ListenerClass } from \"./events/Listener\";\nimport { Job } from \"./queue/Job\";\nimport { queueConfigDefaults } from \"./queue/config\";\n\n/**\n * Reading an application's jobs off the filesystem, for the two subsystems that\n * were asking every app to write its job list twice.\n *\n * Both functions here are the same call to `discoverClasses` with a different\n * base class, which is deliberate: one walk, one set of skip rules, one answer\n * to \"what does this app have\". They are exported from `gemi/services` rather\n * than kept private to the providers because the list stopped being something\n * an app could import — a test that used to walk the exported `jobs` array\n * needs somewhere to ask the same question, and so does a script.\n *\n * What the providers add on top of these is the decision of *whether* to ask,\n * which is the config's to make and not this file's.\n */\n\n/**\n * A directory the app named, resolved the way the app meant it.\n *\n * Relative paths hang off the project root rather than `process.cwd()` at the\n * moment of the call, because a config slice saying `app/jobs` means the app's\n * `app/jobs` and not whatever directory somebody happened to launch a script\n * from. Absolute paths are taken as given, which is what makes these callable\n * from a test that has no project around it.\n */\nfunction resolveDir(dir: string): string {\n return isAbsolute(dir) ? dir : join(projectRoot(), dir);\n}\n\n/**\n * Says something when the directory is missing *and so is the tree it lives in*.\n *\n * A missing directory has two readings and they want opposite responses. An app\n * that has never written a cron job has no `app/cron`, and warning about that on\n * every boot for the rest of its life is noise — the answer \"you have no cron\n * jobs\" is correct and uninteresting. But a deploy that ships `dist/` and\n * `node_modules/` without the source has no `app/cron` *and no `app/`*, and\n * there discovery quietly returns nothing while the app very much does have\n * jobs: the exact silence #322 and #323 exist to remove, reintroduced one layer\n * down and in production only.\n *\n * The parent directory is what tells them apart. If neither the directory nor\n * the one above it is there, the tree this was pointed into is not there\n * either, and that is worth a sentence.\n */\nfunction warnIfSourceIsMissing(\n resolved: string,\n subject: string,\n slice: string,\n) {\n if (existsSync(resolved) || existsSync(dirname(resolved))) return;\n\n console.warn(\n `No ${subject} were discovered: neither ${resolved} nor the directory ` +\n `above it exists, so this process cannot see the application's source. ` +\n `If this is a deploy that ships only the build output, list the classes ` +\n `explicitly in app/config/${slice}.ts so they travel with it.`,\n );\n}\n\n/**\n * The `Job` subclasses under `dir`, defaulting to the config slice's `app/jobs`.\n *\n * This is what a `queue` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array:\n * every job this application would register, in the order it would register\n * them.\n *\n * Every file underneath is imported, so calling this runs the app's job modules\n * — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverJobs(\n dir: string = queueConfigDefaults().jobsDir,\n): Promise<Array<new () => Job>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"queue jobs\", \"queue\");\n const jobs = await discoverClasses(resolved, Job);\n warnIfNameWillNotSurviveTheBuild(jobs);\n return jobs;\n}\n\n/**\n * Says something about a discovered job that never declared `static name`.\n *\n * This is the one hazard discovery introduces rather than removes, and it is\n * production-only. `gemi build` minifies the server entry, and app code\n * reachable from it — a controller, and every job class that controller\n * imports to dispatch — is bundled and minified with it. Minification renames\n * the class binding, and a class's implicit `.name` is that binding: a\n * `TestJob` in the bundle reports `\"D\"`. Discovery, meanwhile, imports\n * `app/jobs/TestJob.ts` from source at runtime, where it is still `\"TestJob\"`.\n * The queue is keyed by that name, so the two halves stop agreeing and the\n * dispatch is dropped — in production, and only there.\n *\n * A declared `static name = \"TestJob\"` is a string literal, which survives\n * minification intact, and the two halves agree again. `docs/jobs-and-queues.md`\n * has always called it required; before discovery an app could get away without\n * it, because the explicit `jobs` array was bundled too and both sides were\n * wrong in the same way.\n *\n * The check is exact rather than a guess: a `static name = \"...\"` class field\n * defines a *writable* own property, while the implicit class name is\n * non-writable. Cron is unaffected — `CronJob.name` is an instance field\n * holding a string literal, not the class binding.\n */\nfunction warnIfNameWillNotSurviveTheBuild(jobs: Array<new () => Job>) {\n for (const job of jobs) {\n if (Object.getOwnPropertyDescriptor(job, \"name\")?.writable) continue;\n\n console.warn(\n `Queued job ${job.name} does not declare \\`static name\\`, so it is ` +\n `registered under its class name. A production build minifies the ` +\n `class that dispatches it and renames it, while discovery reads this ` +\n `file from source and does not — so the dispatch would be dropped in ` +\n `production and nowhere else. Add: static name = \"${job.name}\";`,\n );\n }\n}\n\n/**\n * The `CronJob` subclasses under `dir`, defaulting to the config slice's\n * `app/cron`.\n *\n * This is what a `schedule` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array —\n * though after boot `app(Scheduler).jobs` is the better one, because it is what\n * the scheduler actually took rather than what this would find if asked again.\n *\n * Every file underneath is imported, so calling this runs the app's cron\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCronJobs(\n dir: string = scheduleConfigDefaults().jobsDir,\n): Promise<Array<new () => CronJob>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"cron jobs\", \"schedule\");\n return await discoverClasses(resolved, CronJob);\n}\n\n/**\n * The `Command` subclasses under `dir`, defaulting to the config slice's\n * `app/commands`.\n *\n * This is what a `commands`-less `command` slice resolves to, and what\n * `gemi run` lists. Unlike the two above it is not called during boot — a\n * command registry has one consumer, and importing every file under\n * `app/commands` into every server process would be a cost paid on every start\n * for code no request reaches.\n *\n * Every file underneath is imported, so calling this runs the app's command\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCommands(\n dir: string = commandConfigDefaults().commandsDir,\n): Promise<CommandClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"commands\", \"command\");\n\n const unfinished: string[] = [];\n\n const commands = await discoverClasses(\n resolved,\n Command,\n [],\n (value, file) => {\n if (isUnfinishedBuilder(value)) unfinished.push(file);\n },\n );\n\n refuseUnfinishedBuilders(unfinished);\n\n return commands as CommandClass[];\n}\n\n/**\n * Stops the walk for a builder chain that was never finished.\n *\n * This is the one silence the builder introduces, and it is the exact shape\n * #322 and #323 exist to remove. `defineCommand(...).arg(...)` without a\n * trailing `.handle(...)` is a plain object rather than a class, so\n * `discoverClasses` discards it along with every constant and helper a command\n * file happens to export — and the command disappears from `gemi run` with\n * nothing raised. The author sees a listing containing every command except the\n * one they just wrote.\n *\n * A throw rather than a warning, because there is no reading of an unfinished\n * builder under which the author meant it: the chain builds a description of a\n * command and then discards it.\n *\n * \"Unfinished\" is decided by `.handle()` clearing the brand, not by the export\n * still being a builder object. Those differ for the natural way to share\n * declarations —\n *\n * export const base = defineCommand(\"reindex\").option(\"verbose\", …);\n * export default base.handle(async () => {});\n *\n * — where `base` is a builder that *did* produce a command. Keying off the shape\n * alone made that file abort the whole of `gemi run`, taking every other command\n * in the project down with it, under a message that was untrue for it.\n */\nfunction refuseUnfinishedBuilders(files: string[]): void {\n if (files.length === 0) return;\n\n const subject =\n files.length === 1\n ? `${files[0]} exports a command builder that never called \\`.handle()\\``\n : `${files.length} files export a command builder that never called ` +\n `\\`.handle()\\`:\\n ${files.join(\"\\n \")}`;\n\n throw new DiscoveryError(\n `${subject}, so there is no command to run. \\`.handle()\\` is what turns ` +\n `the chain into a command — finish it:\\n\\n` +\n ` export default defineCommand(\"my-command\")\\n` +\n ` .handle(async ({ line }) => { line(\"hello\") })`,\n );\n}\n\n/**\n * The `Listener` subclasses under `dir`, defaulting to the config slice's\n * `app/listeners`.\n *\n * This is what an `events` config slice with no `listeners` key resolves to.\n * Call it directly to ask what an application would register: every listener,\n * in the order it would register them.\n *\n * Only listeners are walked. Event classes are never discovered — each is\n * imported by the listener that binds to it and by the code that dispatches it,\n * so there is nothing a walk over them would find that is not already in the\n * module graph.\n *\n * **Known residual, matching jobs and cron.** `discoverClasses` excludes the\n * `base` it is handed and not intermediates, so an abstract listener base\n * written in `listenersDir` and extended by its siblings is discovered and\n * registered alongside them — constructed, with its `handle` called, on every\n * dispatch of whatever event it declares. Keep shared bases outside the\n * directory.\n *\n * Every file underneath is imported, so calling this runs the app's listener\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n *\n * @throws DiscoveryError if a discovered listener declares no `static event`.\n */\nexport async function discoverListeners(\n dir: string = eventConfigDefaults().listenersDir,\n): Promise<ListenerClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"event listeners\", \"events\");\n\n const listeners = (await discoverClasses(\n resolved,\n Listener,\n )) as ListenerClass[];\n\n refuseListenersWithNoEvent(listeners);\n warnIfListenerNameWillNotSurviveTheBuild(listeners);\n warnIfEventNameWillNotSurviveTheBuild(listeners);\n\n return listeners;\n}\n\n/**\n * Stops the walk for a listener that binds to nothing.\n *\n * `static event` is declared as required on the base and the compiler still\n * cannot see it missing: every subclass inherits the declaration whether or not\n * it assigns to one, so `typeof SomeListener` type-checks either way. What the\n * author gets instead is a file that is imported, registered under no name, and\n * never called — the silence this whole module is arranged against.\n *\n * A throw rather than a warning, because there is no reading of a listener with\n * no event under which the author meant it. The usual cause is the residual\n * above: an abstract base sharing a gate between two listeners, sitting in\n * `listenersDir` where the walk finds it. Moving it out is the fix, and the\n * message says so — the alternative, excluding it by some guess about\n * abstractness, is how a discovery pass ends up quietly covering less than the\n * directory holds.\n */\nfunction refuseListenersWithNoEvent(listeners: ListenerClass[]): void {\n const orphans = listeners.filter((listener) => !listener.event);\n if (orphans.length === 0) return;\n\n throw new DiscoveryError(\n `${orphans\n .map((listener) => listener.name)\n .join(\", \")} declare no \\`static event\\`, so there is no event name to ` +\n `register them under and their \\`handle\\` would never run. Every ` +\n `listener binds to exactly one event:\\n\\n` +\n ` static event = UserRegistered;\\n\\n` +\n `If this is an abstract base its subclasses extend, move it out of the ` +\n `listeners directory — the walk excludes gemi's \\`Listener\\` and ` +\n `nothing else, so a base sitting beside its subclasses is registered ` +\n `and run like one of them.`,\n );\n}\n\n/**\n * Says something about a discovered listener that never declared `static name`.\n *\n * The hazard is `warnIfNameWillNotSurviveTheBuild`'s, one subsystem over: a\n * `static name = \"...\"` class field defines a *writable* own property while the\n * implicit class binding does not, and a minifier renames the binding while\n * leaving the string literal alone. The two spellings are indistinguishable by\n * value — both read `\"SendWelcomeEmail\"` in development — so the descriptor is\n * the only thing that tells them apart, and the difference only becomes visible\n * in a production build.\n *\n * A warning rather than a refusal, because a *sync* listener's name has no\n * second half to disagree with: every reader of it comes from this same\n * source-side walk, so a minified build and this walk cannot produce two\n * different strings for it. A **queued** listener does have one — the name is\n * the queue's key and it crosses a JSON boundary — and that case is refused\n * outright, by `jobForListener`, at the point the listener is registered with\n * the queue rather than here. This walk cannot tell the two apart without\n * constructing every listener it found; the registry constructs them anyway.\n */\nfunction warnIfListenerNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n for (const listener of listeners) {\n if (Object.getOwnPropertyDescriptor(listener, \"name\")?.writable) continue;\n\n console.warn(\n `Event listener ${listener.name} does not declare \\`static name\\`, so ` +\n `it is registered under its class name, which a production build ` +\n `renames. Nothing reads that name across a build boundary while the ` +\n `listener is sync, which is why this is a warning — but adding ` +\n `\\`queued = true\\` to it is refused at boot for the same reason, ` +\n `because the queue's key is that string. Add: static name = ` +\n `\"${listener.name}\";`,\n );\n }\n}\n\n/**\n * Says something about the *event* a discovered listener binds to, when that\n * event's name is the implicit class binding.\n *\n * This is the check that matters from the first dispatch, and it is the reason\n * `discoverListeners` reads `static event` at all. The registry is keyed by the\n * event's name; the dispatcher supplies that name from the class it constructs.\n * A production build minifies the server entry and the app code reachable from\n * it — the controller, and the event class it imports in order to dispatch —\n * while discovery imports `app/listeners/*.ts` from source, and those files\n * import `app/events/*.ts` from source too. Two module graphs, two class\n * objects, and an implicit `.name` that reads `\"UserRegistered\"` on one side\n * and `\"D\"` on the other. The dispatch then finds no listeners, which is legal,\n * normal, and completely silent.\n *\n * A declared `static name` is a string literal, which survives minification\n * intact, and the two halves agree again.\n *\n * Checked through the descriptor rather than the string, and not by comparing\n * `event.name` to anything: in development the two spellings produce the same\n * value, so a check on the string would be a tautology that passes forever.\n */\nfunction warnIfEventNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n const warned = new Set<EventClass>();\n\n for (const { event } of listeners) {\n if (warned.has(event)) continue;\n if (Object.getOwnPropertyDescriptor(event, \"name\")?.writable) continue;\n warned.add(event);\n\n console.warn(\n `Event ${event.name} does not declare \\`static name\\`, so it is ` +\n `dispatched under its class name. A production build minifies the ` +\n `code that dispatches it and renames the class, while discovery reads ` +\n `the listener's copy from source and does not — so the dispatch would ` +\n `reach no listener in production and nowhere else. Add: ` +\n `static name = \"${event.name}\";`,\n );\n }\n}\n"
|
|
14
14
|
],
|
|
15
15
|
"mappings": ";+JA4GO,AAAM,IAAsB,KAAM,CAG5B,KAFX,WAAW,CACT,EACS,EAAe,EACxB,CACA,MAAM,CAAO,EAFJ,YAGT,KAAK,KAAO,gBAEhB,CAYO,MAAM,CAAQ,OAKZ,aAAc,cAGd,aAAc,SAGd,MAA0B,CAAC,QAG3B,SAA2B,CAAC,EAWnC,GAAG,CAAC,EAA0B,EAChC,CC1GO,SAA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,yLAGb,6EACA,yEACkB,EAAM,QAC5B",
|
|
16
|
-
"debugId": "
|
|
16
|
+
"debugId": "ED9A72DAF2CDB2F964756E2164756E21",
|
|
17
17
|
"names": []
|
|
18
18
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
function j(h){return h}function p(){return{supportedLocales:[],defaultLocale:"en-US",prefetch:{},components:{},detectLocale:()=>null,onLocaleChange:(h)=>{console.log(`Locale changed to ${h}`)}}}
|
|
3
|
-
export{j as
|
|
3
|
+
export{j as bc,p as cc};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=CD5F56D57D3F900664756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import type { Dictionary } from \"./Dictionary\";\nimport type { HttpRequest } from \"../http/HttpRequest\";\n\n// Config key: `translation`. Derived from `I18nServiceProvider`.\nexport interface TranslationConfig {\n supportedLocales?: string[];\n defaultLocale?: string;\n /**\n * @deprecated Only for `Dictionary.create` dictionaries. A `defineDictionary`\n * dictionary needs no entry here — the component that reads it pulls it in,\n * and the bundler ships only the active locale.\n */\n prefetch?: Record<string, Array<Dictionary<any>>>;\n /** @deprecated Only for `Dictionary.create` dictionaries. See `prefetch`. */\n components?: Record<string, Dictionary<any>>;\n\n // Returning `null` falls back to gemi's own locale detection.\n detectLocale?: (req: HttpRequest) => string | null;\n onLocaleChange?: (locale: string) => Promise<void> | void;\n}\n\nexport function defineTranslationConfig(\n config: TranslationConfig,\n): TranslationConfig {\n return config;\n}\n\nexport function translationConfigDefaults(): Required<TranslationConfig> {\n return {\n supportedLocales: [],\n defaultLocale: \"en-US\",\n prefetch: {},\n components: {},\n detectLocale: () => null,\n onLocaleChange: (locale) => {\n console.log(`Locale changed to ${locale}`);\n },\n };\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAqBO,SAAS,CAAuB,CACrC,EACmB,CACnB,OAAO,EAGF,SAAS,CAAyB,EAAgC,CACvE,MAAO,CACL,iBAAkB,CAAC,EACnB,cAAe,QACf,SAAU,CAAC,EACX,WAAY,CAAC,EACb,aAAc,IAAM,KACpB,eAAgB,CAAC,IAAW,CAC1B,QAAQ,IAAI,qBAAqB,GAAQ,EAE7C",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "CD5F56D57D3F900664756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{vf as B,wf as e,xf as m}from"./chunk-xqyx8kzr.js";import{Af as C}from"./chunk-17nh5gfm.js";import{xg as _H}from"./chunk-sh1cfx9j.js";import{Kg as S}from"./chunk-kmebynhc.js";import{Rg as Q0}from"./chunk-fc28h7g2.js";class WH{static kind="controller";constructor(){}}class wH extends WH{}function o(H){let G=new Map;if(!H)return G;for(let Q of H.split(";")){let Z=Q.indexOf("=");if(Z===-1)continue;let X=Q.slice(0,Z).trim();if(!X)continue;G.set(X,Q.slice(Z+1).trim())}return G}function Y0(H){return o(H.headers.get("cookie"))}function j(H){if(!/^\d+$/.test(H))return null;let G=Number(H);return Number.isSafeInteger(G)?G:null}function KH(H){if(!H)return null;let G=H.trim();if(!/^bytes=/i.test(G))return null;let Z=G.slice(6).split(",").map((D)=>D.trim()).filter((D)=>D!=="");if(Z.length!==1)return null;let X=Z[0],$=X.indexOf("-");if($===-1)return null;let U=X.slice(0,$),W=X.slice($+1);if(U===""){let D=j(W);if(D===null)return null;return{kind:"suffix",suffixLength:D}}let K=j(U);if(K===null)return null;if(W==="")return{kind:"offset",start:K,end:null};let M=j(W);if(M===null||M<K)return null;return{kind:"offset",start:K,end:M}}function MH(H,G){if(!Number.isFinite(G)||G<=0)return null;let Q,Z;if(H.kind==="suffix"){if(H.suffixLength<=0)return null;Q=Math.max(0,G-H.suffixLength),Z=G-1}else{if(H.start>=G)return null;if(Q=H.start,Z=H.end===null?G-1:Math.min(H.end,G-1),Z<Q)return null}return{start:Q,end:Z,length:Z-Q+1}}function R0(H){if(H.kind==="suffix")return`bytes=-${H.suffixLength}`;return H.end===null?`bytes=${H.start}-`:`bytes=${H.start}-${H.end}`}function P0(H){if(!H)return null;let G=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(H.trim());if(!G)return null;let Q=j(G[1]),Z=j(G[2]),X=j(G[3]);if(Q===null||Z===null||X===null||Z<Q)return null;return{start:Q,end:Z,total:X}}function B0(H,G,Q){return`bytes ${H}-${G}/${Q}`}function TH(H){return`bytes */${H}`}class w extends B{errors={};constructor(H){super("Validation error");this.name="ValidationError",this.errors=H,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:H,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function EH(H){let[G,Q]=H.match(/\d+|\D+/g)??[];if(!G||!Q)return 0;let Z=Number.parseInt(G);switch(Q){case"B":return Z;case"KB":return Z*1024;case"MB":return Z*1024*1024;case"GB":return Z*1024*1024*1024;case"TB":return Z*1024*1024*1024*1024;default:return 0}}function NH(H){switch(H){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return H}}function YH(H){if(typeof H==="string"||Array.isArray(H))return H.length;return}function n(H){return typeof H==="number"&&!Number.isNaN(H)}var SH=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class J extends Error{name="InvalidValidationRuleError"}function y(H,G){let Q=G===void 0||G.trim()===""?Number.NaN:Number(G);if(Number.isNaN(Q))throw new J(`Validation rule "${H}:${G??""}" needs a number, e.g. "${H}:3"`);return Q}function DH(H){let G=H.indexOf(":"),Q=G===-1?H:H.slice(0,G),Z=G===-1?void 0:H.slice(G+1);switch(Q){case"required":return(X)=>{if(X instanceof Blob)return X.size>0;if(X===null||X===void 0)return!1;if(typeof X==="string"||Array.isArray(X))return X.length>0;return!0};case"string":return(X)=>typeof X==="string";case"boolean":return(X)=>typeof X==="boolean";case"number":return(X)=>n(X);case"password":return(X)=>{return typeof X==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(X)};case"min":{let X=y(Q,Z);return($)=>{let U=YH($);return U!==void 0&&U>=X}}case"max":{let X=y(Q,Z);return($)=>{let U=YH($);return U!==void 0&&U<=X}}case"gte":{let X=y(Q,Z);return($)=>n($)&&$>=X}case"lte":{let X=y(Q,Z);return($)=>n($)&&$<=X}case"email":return(X)=>{return typeof X==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X)};case"file":return(X)=>{return X instanceof Blob};case"fileType":{if(!Z)throw new J('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let X=NH(Z);return($)=>$ instanceof Blob&&$.type.startsWith(X)}case"fileSize":{let X=EH(Z??"");if(X===0&&!/^0+(B|KB|MB|GB|TB)$/.test(Z??""))throw new J(`Validation rule "fileSize:${Z??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return($)=>$ instanceof Blob&&$.size<=X}case"array":return(X)=>Array.isArray(X);case"object":return(X)=>typeof X==="object"&&X!==null&&!Array.isArray(X)&&!(X instanceof Blob);case"in":{let X=(Z??"").split(",").filter(($)=>$!=="");if(X.length===0)throw new J('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return($)=>typeof $==="string"&&X.includes($)}default:throw new J(`Unknown validation rule "${H}". Known rules: ${SH.join(", ")}`)}}var d=new WeakMap;function PH(H){return typeof H==="object"&&H!==null&&d.has(H)}function i(H){let G=d.get(H);if(!G)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return G}function b(H){let G=(H.optional||H.nullable)&&H.node.kind!=="json",Q=kH(yH(H.node),G),Z=[H.description,gH(H.node)].filter(Boolean).join(" ");return Z?{description:Z,...Q}:Q}function gH(H){let G=[];if(H.kind==="string"||H.kind==="enum"){let Q=H.checks;if(Q?.format)G.push(`Format: ${Q.format.name}.`);if(Q?.minLength!==void 0)G.push(`At least ${Q.minLength} characters.`);if(Q?.maxLength!==void 0)G.push(`At most ${Q.maxLength} characters.`)}else if(H.kind==="number"){let Q=H.checks;if(Q?.minimum!==void 0)G.push(`Minimum ${Q.minimum}.`);if(Q?.exclusiveMinimum!==void 0)G.push(`Greater than ${Q.exclusiveMinimum}.`);if(Q?.maximum!==void 0)G.push(`Maximum ${Q.maximum}.`);if(Q?.exclusiveMaximum!==void 0)G.push(`Less than ${Q.exclusiveMaximum}.`)}else if(H.kind==="array"){let Q=H.checks;if(Q?.minItems!==void 0)G.push(`At least ${Q.minItems} items.`);if(Q?.maxItems!==void 0)G.push(`At most ${Q.maxItems} items.`)}return G.join(" ")}function yH(H){switch(H.kind){case"string":return{type:"string"};case"number":return{type:H.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof H.value,const:H.value};case"enum":return{type:"string",enum:H.values};case"array":return{type:"array",items:b(H.item)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(H.shape).map(([G,Q])=>[G,b(Q)])),required:Object.keys(H.shape),additionalProperties:!1};case"union":return{anyOf:H.members.map(b)};case"json":return{}}}function kH(H,G){if(!G)return H;if(H.anyOf)return{...H,anyOf:[...H.anyOf,{type:"null"}]};if(H.enum||H.const!==void 0)return{anyOf:[H,{type:"null"}]};if(typeof H.type==="string")return{...H,type:[H.type,"null"]};return{anyOf:[H,{type:"null"}]}}function bH(H){if(H===null)return"null";if(Array.isArray(H))return"array";return typeof H}function fH(H,G){if(typeof G==="number"&&!Number.isFinite(G))return String(G);if(H.kind==="literal"||H.kind==="enum"){if(typeof G==="string"||typeof G==="number"||typeof G==="boolean")return JSON.stringify(G)}return bH(G)}function cH(H){let G=H.node,Q=(()=>{switch(G.kind){case"number":return G.checks?.integer?"integer":"number";case"string":case"boolean":return G.kind;case"literal":return JSON.stringify(G.value);case"enum":return`one of ${G.values.map((Z)=>JSON.stringify(Z)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value"}})();return H.optional||H.nullable?`${Q} or null`:Q}function vH(H){let G="";for(let Q of H)G+=typeof Q==="number"?`[${Q}]`:G?`.${Q}`:Q;return G}function pH(H){let G=vH(H);return G?`${G}: `:""}function t(H){return`${pH(H.path)}${H.message}`}function r(H,G){if(G===null||G===void 0)return H.optional||H.nullable?1:0;let Q=H.node;switch(Q.kind){case"string":return typeof G==="string"?1:0;case"number":return typeof G==="number"?1:0;case"boolean":return typeof G==="boolean"?1:0;case"literal":return G===Q.value?10:0;case"enum":return typeof G==="string"&&Q.values.includes(G)?10:0;case"array":return Array.isArray(G)?1:0;case"object":{if(typeof G!=="object"||Array.isArray(G))return 0;let Z=G,X=1;for(let[$,U]of Object.entries(Q.shape))X+=r(U,Z[$]);return X}case"union":return Q.members.reduce((Z,X)=>Math.max(Z,r(X,G)),0);case"json":return 1}}function x(H,G,Q,Z){if(H.optional&&(G===null||G===void 0))return{drop:!0,value:void 0};if(H.nullable&&G===null)return{drop:!1,value:null};return{drop:!1,value:hH(H,G,Q,Z)}}function hH(H,G,Q,Z){let X=H.node,$=()=>{let U=G===void 0?"required":X.kind==="literal"?"const":X.kind==="enum"&&typeof G==="string"?"enum":"type",W=U==="const"?{allowedValue:X.value}:U==="enum"?{allowedValues:X.values}:{};Z.push({path:Q,code:U,message:`expected ${cH(H)}, got ${fH(X,G)}`,params:W});return};switch(X.kind){case"string":if(typeof G!=="string")return $();return RH(X.checks,G,Q,Z),G;case"number":if(typeof G!=="number"||!Number.isFinite(G))return $();if(X.checks?.integer&&!Number.isInteger(G))return $();return mH(X.checks,G,Q,Z),G;case"boolean":return typeof G==="boolean"?G:$();case"literal":return G===X.value?G:$();case"enum":if(typeof G!=="string"||!X.values.includes(G))return $();return RH(X.checks,G,Q,Z),G;case"array":{if(!Array.isArray(G))return $();let U=G.map((M,D)=>{let q=x(X.item,M,[...Q,D],Z);return q.drop?void 0:q.value}),{minItems:W,maxItems:K}=X.checks??{};if(W!==void 0&&G.length<W)Z.push({path:Q,code:"minItems",message:`expected at least ${W} items, got ${G.length}`,params:{limit:W}});if(K!==void 0&&G.length>K)Z.push({path:Q,code:"maxItems",message:`expected at most ${K} items, got ${G.length}`,params:{limit:K}});return U}case"object":{if(typeof G!=="object"||G===null||Array.isArray(G))return $();let U=G,W={};for(let[K,M]of Object.entries(X.shape)){let D=x(M,U[K],[...Q,K],Z);if(!D.drop)W[K]=D.value}return W}case"union":{let U;for(let W of X.members){let K=[],M=x(W,G,Q,K);if(K.length===0)return M.drop?void 0:M.value;let D=r(W,G);if(!U||D>U.score)U={issues:K,score:D}}Z.push({path:Q,code:"anyOf",message:`no matching variant; closest: ${U.issues.map(t).join("; ")}`,params:{closest:U.issues}});return}case"json":if(G===void 0)return $();return f(G,Q,Z,new Set),G}}function dH(H){let G=0;for(let Q of H)G++;return G}function RH(H,G,Q,Z){if(!H)return;let{minLength:X,maxLength:$,format:U}=H;if(X!==void 0||$!==void 0){let W=dH(G);if(X!==void 0&&W<X)Z.push({path:Q,code:"minLength",message:`expected at least ${X} characters, got ${W}`,params:{limit:X}});if($!==void 0&&W>$)Z.push({path:Q,code:"maxLength",message:`expected at most ${$} characters, got ${W}`,params:{limit:$}})}if(U){let W=!1;try{W=U.test(G)===!0}catch{}if(!W)Z.push({path:Q,code:"format",message:`expected a string in format "${U.name}"`,params:{format:U.name}})}}function mH(H,G,Q,Z){if(!H)return;let X=($,U,W,K)=>{if(U===void 0||W(U))return;Z.push({path:Q,code:$,message:`expected ${K} ${U}, got ${G}`,params:{limit:U}})};X("minimum",H.minimum,($)=>G>=$,"at least"),X("exclusiveMinimum",H.exclusiveMinimum,($)=>G>$,"more than"),X("maximum",H.maximum,($)=>G<=$,"at most"),X("exclusiveMaximum",H.exclusiveMaximum,($)=>G<$,"less than")}function f(H,G,Q,Z,X=!0){let $=(W)=>{Q.push({path:G,code:"type",message:`expected a JSON value, got ${W}`,params:{}})};switch(typeof H){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(H))$(String(H));return;case"bigint":return $("a bigint");case"function":return $("a function");case"symbol":return $("a symbol")}if(H===null)return;let U=H;if(Z.has(U))return $("a circular reference");Z.add(U);try{let W=X?U.toJSON:void 0;if(typeof W==="function"){let K;try{K=W.call(U)}catch{return $("a toJSON that threw")}if(K===void 0)return $("a toJSON that returns undefined");return f(K,G,Q,Z,!1)}if(Array.isArray(H))H.forEach((K,M)=>f(K,[...G,M],Q,Z));else for(let[K,M]of Object.entries(U))f(M,[...G,K],Q,Z)}finally{Z.delete(U)}}function z(H){return c(H)}function c(H){let G={toJSONSchema:()=>b(H),parse(Q){let Z=[],X=x(H,Q,[],Z);if(Z.length>0)throw Error(Z.map(t).join("; "));return X.drop?void 0:X.value},safeParse(Q){let Z=[],X=x(H,Q,[],Z);if(Z.length>0)return{ok:!1,errors:Z.map(t)};return{ok:!0,value:X.drop?void 0:X.value}},validate(Q){let Z=[],X=x(H,Q,[],Z);if(Z.length>0)return{ok:!1,issues:Z};return{ok:!0,value:X.drop?void 0:X.value}},describe:(Q)=>c({...H,description:Q}),optional:()=>c({...H,optional:!0}),nullable:()=>c({...H,nullable:!0,optional:!1})};return d.set(G,H),G}function L(H){return{node:H,optional:!1,nullable:!1}}class BH extends Error{problems;constructor(H){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
|
|
3
|
+
${H.map((G)=>`- ${G}`).join(`
|
|
4
|
+
`)}`);this.name="JSONSchemaError",this.problems=H}}var uH=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),E={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function k(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}function v(H,G,Q,Z){let X=(T,Y=Q)=>{Z.push(Y?`${Y}: ${T}`:T);return},$=(T)=>Q?`${Q}.${T}`:T;if(!k(H))return X("expected a schema object");let U=new Set(G.ignoreKeywords??[]),W=(T)=>uH.has(T)||T.startsWith("x-")||U.has(T),K=!1,M=H.type;if(Array.isArray(M)){let T=M.filter((Y)=>Y!=="null");if(T.length!==1)return X(`type ${JSON.stringify(M)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,$("type"));K=T.length<M.length,M=T[0]}if(M!==void 0&&(typeof M!=="string"||!(M in E)))return X(`type ${JSON.stringify(M)} is not supported; expected one of ${Object.keys(E).join(", ")}`,$("type"));let D=new Set(["type","description","enum","const","anyOf",...M?E[M]:[]]),q=!1;for(let T of Object.keys(H)){if(D.has(T)||W(T))continue;q=!0;let Y=Object.entries(E).find(([,P])=>P.includes(T));X(Y&&Y[0]!==M?`"${T}" applies to type ${Y[0]}, and this schema is ${M?`type ${M}`:"untyped"}`:`"${T}" is not supported by s.fromJSONSchema`,$(T))}if(q)return;if(H.description!==void 0&&typeof H.description!=="string")return X("expected a string",$("description"));let g=H.description,F=(T)=>({node:T,optional:!1,nullable:K,...g?{description:g}:{}});if(H.anyOf!==void 0){if(M!==void 0||H.enum!==void 0||H.const!==void 0)return X("anyOf cannot be combined with type, enum or const here",$("anyOf"));if(!Array.isArray(H.anyOf)||H.anyOf.length===0)return X("expected a non-empty array",$("anyOf"));let T=[],Y=!1;if(H.anyOf.forEach((P,R)=>{if(k(P)&&P.type==="null"&&Object.keys(P).length===1){K=!0;return}let A=v(P,G,$(`anyOf[${R}]`),Z);if(A)T.push(A);else Y=!0}),Y)return;if(T.length===0)return X("anyOf has only null in it",$("anyOf"));if(T.length===1){let P=T[0];return{...P,nullable:P.nullable||K,...g?{description:g}:{}}}return F({kind:"union",members:T})}if(H.const!==void 0){let T=H.const;if(typeof T!=="string"&&typeof T!=="number"&&typeof T!=="boolean")return X("only a string, number or boolean const is supported",$("const"));if(M!==void 0&&typeof T!==(M==="integer"?"number":M))return X(`const ${JSON.stringify(T)} is not of type ${M}`,$("const"));return F({kind:"literal",value:T})}let O;if(M==="string"){if(O=oH(H,G,$,Z),O===null)return}if(H.enum!==void 0){if(!Array.isArray(H.enum)||H.enum.length===0)return X("expected a non-empty array",$("enum"));let T=H.enum.filter((R)=>R!==null);if(T.length<H.enum.length)K=!0;let Y=T.find((R)=>!(typeof R==="string"||typeof R==="number"||typeof R==="boolean")||M!==void 0&&typeof R!==(M==="integer"?"number":M));if(Y!==void 0||T.length===0)return X(M?`every value must be of type ${M}${T.length===0?", and there must be one":`; ${JSON.stringify(Y)} is not`}`:"only strings, numbers and booleans are supported",$("enum"));if(T.every((R)=>typeof R==="string"))return F({kind:"enum",values:[...new Set(T)],...O?{checks:O}:{}});let P=[...new Set(T)];if(P.length===1)return F({kind:"literal",value:P[0]});return F({kind:"union",members:P.map((R)=>L({kind:"literal",value:R}))})}switch(M){case void 0:return X("a schema needs a type, an enum, a const or an anyOf");case"string":return F({kind:"string",...O?{checks:O}:{}});case"number":case"integer":{let T=M==="integer"?{integer:!0}:{},Y=!1;for(let P of E.number){let R=H[P];if(R===void 0)continue;if(typeof R!=="number"||!Number.isFinite(R)){X("expected a number",$(P)),Y=!0;continue}T[P]=R}if(Y)return;return F({kind:"number",...Object.keys(T).length>0?{checks:T}:{}})}case"boolean":return F({kind:"boolean"});case"array":{if(!k(H.items))return X('an array needs "items" to be one schema (tuples are not supported)',$("items"));let T={},Y=!1;for(let R of["minItems","maxItems"]){let A=H[R];if(A===void 0)continue;if(typeof A!=="number"||!Number.isInteger(A)||A<0){X("expected a non-negative integer",$(R)),Y=!0;continue}T[R]=A}let P=v(H.items,G,$("items"),Z);if(!P||Y)return;return F({kind:"array",item:P,...Object.keys(T).length>0?{checks:T}:{}})}case"object":{let T=H.properties??{};if(!k(T))return X("expected an object",$("properties"));if(H.additionalProperties!==void 0&&H.additionalProperties!==!1)return X("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",$("additionalProperties"));let Y=H.required??[];if(!Array.isArray(Y)||!Y.every((V)=>typeof V==="string"))return X("expected an array of property names",$("required"));let P=Y.filter((V)=>!Object.hasOwn(T,V));if(P.length>0)return X(`lists properties the schema doesn't have: ${P.join(", ")}`,$("required"));let R={},A=!1;for(let[V,qH]of Object.entries(T)){let u=v(qH,G,$(`properties.${V}`),Z);if(!u){A=!0;continue}R[V]=Y.includes(V)?u:{...u,optional:!0}}if(A)return;return F({kind:"object",shape:R})}}return}function oH(H,G,Q,Z){let X={},$=!1;for(let U of["minLength","maxLength"]){let W=H[U];if(W===void 0)continue;if(typeof W!=="number"||!Number.isInteger(W)||W<0){Z.push(`${Q(U)}: expected a non-negative integer`),$=!0;continue}X[U]=W}if(H.format!==void 0){let U=H.format,W=typeof U==="string"?G.formats?.[U]:void 0;if(typeof U!=="string")Z.push(`${Q("format")}: expected a string`),$=!0;else if(!W||!Object.hasOwn(G.formats,U))Z.push(`${Q("format")}: unknown format ${JSON.stringify(U)}; pass a check for it in the formats option`),$=!0;else X.format={name:U,test:nH(W)}}if($)return null;return Object.keys(X).length>0?X:void 0}function nH(H){if(H===!0)return()=>!0;if(H instanceof RegExp)return(G)=>{return H.lastIndex=0,H.test(G)};return H}var J0={string:()=>z(L({kind:"string"})),number:()=>z(L({kind:"number"})),boolean:()=>z(L({kind:"boolean"})),literal:(H)=>z(L({kind:"literal",value:H})),enum:(H)=>z(L({kind:"enum",values:H})),object:(H)=>z(L({kind:"object",shape:Object.fromEntries(Object.entries(H).map(([G,Q])=>[G,i(Q)]))})),array:(H)=>z(L({kind:"array",item:i(H)})),union:(H)=>z(L({kind:"union",members:H.map(i)})),json:()=>z(L({kind:"json"})),fromJSONSchema:(H,G={})=>{let Q=[],Z=v(H,G,"",Q);if(!Z||Q.length>0)throw new BH(Q.length>0?Q:["unreadable schema"]);return z(Z)}};function C0(H){let G=d.get(H);if(G)return h(G.node);return p(H.toJSONSchema())}function p(H){if(!(H.type!==void 0||H.enum!==void 0||H.const!==void 0||H.anyOf!==void 0||H.properties!==void 0||H.items!==void 0))return!1;for(let Q of Object.values(H.properties??{}))if(!p(Q))return!1;if(H.items&&!p(H.items))return!1;for(let Q of H.anyOf??[])if(!p(Q))return!1;return!0}function h(H){switch(H.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(H.shape).every((G)=>h(G.node));case"array":return h(H.item.node);case"union":return H.members.every((G)=>h(G.node));case"json":return!1}}function AH(H){if(typeof H!=="string")return null;let[G]=H.split(";",1),Q=G.trim().toLowerCase();return Q===""?null:Q}function FH(H){if(H===null)return!1;if(H==="application/json")return!0;let G=H.indexOf("/");return G>0&&H.endsWith("+json")&&H.length>G+1+5}var l=new WeakMap;function O0(H,G){l.set(H,{clientAddress:G})}function zH(H){return l.has(H)}function j0(H){return l.get(H)?.clientAddress}var LH=new WeakMap;function I0(H,G){LH.set(H,G)}function JH(H){return LH.get(H)??null}var s=new WeakMap;function q0(H,G){let Q=s.get(H)??[];if(!Q.includes(G))s.set(H,[...Q,G])}function w0(H){return s.get(H)??[]}class I{data;constructor(H){this.data=H}get(H){return this.data[H]}has(H){return this.data[H]!==void 0}toJSON(){return this.data}}function CH(H){return typeof H==="object"&&H!==null&&!(H instanceof Blob)}function iH(H,G){if(!G.includes(".")||Object.hasOwn(H,G))return[{path:[G],value:H[G]}];let Q=[{path:[],value:H}];for(let Z of G.split(".")){let X=[];for(let{path:$,value:U}of Q){if(Z==="*"){if(Array.isArray(U))U.forEach((W,K)=>X.push({path:[...$,K],value:W}));else if(CH(U))for(let[W,K]of Object.entries(U))X.push({path:[...$,W],value:K});continue}if(Array.isArray(U)&&/^\d+$/.test(Z)){X.push({path:[...$,Number(Z)],value:U[Number(Z)]});continue}X.push({path:[...$,Z],value:CH(U)&&Object.hasOwn(U,Z)?U[Z]:void 0})}Q=X}return Q}function VH(H){return H.join(".")}class tH{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;constructor(H,G,Q,Z){if(!H){let K=C.getStore().req;this.params=K.params,this.rawRequest=K.rawRequest,this.kind=K.kind,this.routePath=K.routePath,this.domain=K.domain??null}else this.params=G,this.rawRequest=H,this.routePath=Z,this.kind=Q??"api",this.domain=JH(H);this.headers=this.rawRequest.headers;let X=o(this.rawRequest.headers.get("Cookie")),$=new URL(this.rawRequest.url),U=new Map;for(let[K,M]of $.searchParams)if(U.has(K)){let D=U.get(K);if(Array.isArray(D))D.push(M),U.set(K,D);else U.set(K,[D,M])}else U.set(K,M);let W=Object.fromEntries(U.entries());this.search=new I(W),this.cookies=X}locale(){return C.getStore().locale}ctx(){return C.getStore()}isModelOriginated(){return zH(this.rawRequest)}get signal(){return this.rawRequest.signal}range(){return KH(this.rawRequest.headers.get("Range"))}refine(H){return{}}async parseBody(){let H=AH(this.rawRequest.headers.get("Content-Type"));if(FH(H))return new I(await this.parseJsonBody());if(H==="application/x-www-form-urlencoded"||H==="multipart/form-data"){let G;try{G=await this.rawRequest.formData()}catch{throw new B("The request body could not be read as a form.")}let Q=new Map;for(let[Z,X]of G.entries())if(Q.has(Z)){let $=Q.get(Z);if(Array.isArray($))$.push(X);else Q.set(Z,[$,X])}else Q.set(Z,X);return new I(Object.fromEntries(Q.entries()))}return new I({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let H;try{H=await this.rawRequest.text()}catch{throw new B("The request body could not be read.")}if(H.trim()==="")return{};let G;try{G=JSON.parse(H)}catch{throw new B("The request body is not valid JSON.")}if(G===null||typeof G!=="object")throw new B("The request body must be a JSON object.");return G}validateInput(H){if(PH(this.schema))return this.validateWithSchema(H);let G=H.toJSON()??{},Q={},Z=Object.entries(this.schema).map(([X,$])=>({key:X,rules:Object.entries($).map(([U,W])=>({rule:U,message:W,check:typeof W==="function"?null:this.ruleFor(X,U)}))}));for(let{key:X,rules:$}of Z)for(let{path:U,value:W}of iH(G,X)){let K=this.checkField(W,$);if(K.length>0){let M=Q[VH(U)]??=[];for(let D of K)if(!M.includes(D))M.push(D)}}if(this.addRefinements(Q,G),Object.keys(Q).length>0)throw new w(Q);return H}checkField(H,G){let Q=G.some(({rule:$})=>$==="required"),Z=H===void 0||H===null||H==="",X=[];for(let{rule:$,message:U,check:W}of G){let K=U,M=!1;if(typeof U==="function")K=U(H),M=typeof K>"u";else M=W(H);if(M)continue;if(Z&&!Q)continue;if($==="required")return[String(K)];if(!X.includes(String(K)))X.push(String(K))}return X}validateWithSchema(H){let G=this.schema.validate(H.toJSON()),Q={};if("issues"in G)for(let X of G.issues){let $=VH(X.path),U=Q[$]??=[];if(!U.includes(X.message))U.push(X.message)}let Z="value"in G?new I(G.value):H;if(this.addRefinements(Q,Z.toJSON()),Object.keys(Q).length>0)throw new w(Q);return Z}addRefinements(H,G){for(let[Q,Z]of Object.entries(this.refine(G)??{})){let X=H[Q]??[];H[Q]=X.includes(Z)?X:[...X,Z]}}ruleFor(H,G){try{return DH(G)}catch(Q){if(Q instanceof J)throw new J(`${this.constructor.name}.schema.${H}: ${Q.message}`);throw Q}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let H=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(H)}}catch(G){if(!(G instanceof w))throw G;return{isValid:!1,errors:G.errors,input:H}}}}class rH extends B{error;constructor(H="Not authorized"){super(H);this.name="AuthorizationError",this.error=H,this.payload={api:{status:401,data:{error:m("authorization",this.error,401)}},view:{}}}}class a extends B{static apiStatus=403;error;constructor(H="Insufficient permissions"){super(H);this.name="InsufficientPermissionsError",this.error=H,this.payload={api:{status:a.apiStatus,data:{error:m("permission",this.error,a.apiStatus)}},view:{status:403}}}}class HH extends B{total;constructor(H){super("Range not satisfiable");this.total=H;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:e("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":TH(H),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class _ extends B{fileName;constructor(H){super("File not found");this.fileName=H;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:e("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{}}}}class lH extends B{constructor(H={}){super("Authentication error");this.name="AuthenticationError";let G=H.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:m("authentication","Authentication error",401)}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:G}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:G}}}}}class N{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return _H(this.getFacadeAccessor())}}class GH{async delete(H){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(H){let G=typeof H==="string"?{name:H}:H,Q=await this.fetch({name:G.name,bucket:G.bucket});if(!Q.ok)throw new _(G.name);let Z=Q.headers.get("Content-Type")??"application/octet-stream",X=Q.headers.get("ETag")??void 0,$=Q.headers.get("Last-Modified"),U=$?new Date($):void 0;if(G.range){let M=await Q.blob();return{body:M,start:0,end:M.size-1,total:M.size,partial:!1,type:Z,etag:X,lastModified:U,name:G.name}}let W=Number(Q.headers.get("Content-Length")),K=Number.isFinite(W)?W:0;return{body:Q.body,start:0,end:K-1,total:K,partial:!1,type:Z,etag:X,lastModified:U,name:G.name}}async size(H){let G=typeof H==="string"?H:H.name,Q=typeof H==="string"?void 0:H.bucket,Z=await this.fetch({name:G,bucket:Q});if(!Z.ok)throw new _(G);let X=Number(Z.headers.get("Content-Length"));if(Number.isFinite(X))return await Z.body?.cancel(),X;return(await Z.blob()).size}}function OH(H,G){if(!G)return H;let Q=H.getReader(),Z=!1,X,$=()=>{if(Z=!0,X)G.removeEventListener("abort",X)};return new ReadableStream({start(U){if(X=()=>{if(Z)return;$(),U.error(G.reason),Q.cancel(G.reason).catch(()=>{})},G.aborted)X();else G.addEventListener("abort",X,{once:!0})},async pull(U){let W;try{W=await Q.read()}catch(K){if(Z)return;$(),U.error(K);return}if(Z)return;if(W.done){$(),U.close();return}U.enqueue(W.value)},cancel(U){return $(),Q.cancel(U)}},{highWaterMark:0})}import{readdir as sH,unlink as aH}from"fs/promises";import{isAbsolute as eH,relative as H0,resolve as jH,sep as G0}from"path";class QH extends GH{configured;constructor(H){super();this.configured=H}get folderPath(){return this.configured??`${S()}/storage`}async put(H,{signal:G}={}){G?.throwIfAborted();let Q,Z;if(H instanceof Blob)Q=H,Z=`${Bun.randomUUIDv7()}.${H.type.split("/")[1].split(";")[0]}`;else Q=H.body,Z=H.name;let X=Q instanceof Buffer?Q:Q instanceof Blob||Q instanceof File?Buffer.from(await Q.arrayBuffer()):"",$=`${this.folderPath}/${Z}`;return G?.throwIfAborted(),await Bun.write($,X),Z}async fetch(H,{signal:G}={}){G?.throwIfAborted();let Q=process.env.BUCKET_NAME,Z;if(typeof H==="string")Z=H;else Q=H.bucket??Q,Z=H.name;if(!Z)throw Error("Object name has to be specified");let X=`${this.folderPath}/${Z}`,$=Bun.file(X),U=OH(Bun.file(X).stream(),G),W=new Date($.lastModified).toUTCString();return new Response(U,{headers:{"Content-Type":$.type,"Content-Length":String($.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":W}})}async read(H){let G=typeof H==="string"?{name:H}:H,{name:Q,range:Z=null}=G;if(!Q)throw Error("Object name has to be specified");let X=Bun.file(`${this.folderPath}/${Q}`);if(!await X.exists())throw new _(Q);let $=X.size,U=Z?MH(Z,$):null;if(Z&&!U)throw new HH($);let W=U?.start??0,K=U?U.end:$-1;return{body:U?X.slice(W,K+1):X,start:W,end:K,total:$,partial:Boolean(U),type:X.type||"application/octet-stream",lastModified:new Date(X.lastModified),name:Q}}async size(H){let G=typeof H==="string"?H:H.name,Q=Bun.file(`${this.folderPath}/${G}`);if(!await Q.exists())throw new _(G);return Q.size}async delete(H){let G=typeof H==="string"?H:H.name;if(!G)throw Error("Object name has to be specified");let Q=jH(this.folderPath),Z=jH(Q,G),X=H0(Q,Z);if(!X||X===".."||X.startsWith(`..${G0}`)||eH(X))throw Error(`Refusing to delete "${G}": it is outside the storage folder`);try{await aH(Z)}catch($){if($?.code==="ENOENT")return;throw $}}async list(){return await sH(this.folderPath)}}function $4(H){return H}function xH(){return{driver:new QH}}class XH{static token="filesystem";driver;constructor(H={}){this.driver=H.driver??xH().driver}}import{Buffer as X0}from"buffer";async function IH(H){try{return(await import("sharp")).default}catch(G){throw Error(`${H} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:G})}}class Z0 extends N{static getFacadeAccessor(){return XH}static async put(H,G={}){return this.getFacadeRoot().driver.put(H,G)}static async metadata(H){let G=X0.from(await H.arrayBuffer()),Q=await IH("Storage.metadata()");try{return await Q(G).metadata()}catch{return{}}}static async fetch(H,G={}){return G.signal?.throwIfAborted(),this.getFacadeRoot().driver.fetch(H,G)}static async read(H,G={}){let Q=typeof H==="string"?{name:H}:{...H},Z="range"in G?G.range??null:Q.range!==void 0?Q.range:C.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...Q,range:Z})}static list(H){return this.getFacadeRoot().driver.list(H)}static async delete(H){return this.getFacadeRoot().driver.delete(H)}}import{mkdir as ZH,readdir as $0,access as U0}from"fs/promises";async function $H(H){try{return await U0(H),!0}catch{return!1}}class UH{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${S()}/storage/logs`}constructor(H){this.config=H}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((H)=>{console.error("Log storage unavailable, file logging disabled",H)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let H=`${S()}/storage`;if(!await $H(H))await ZH(H);if(!await $H(this.logsDirPath))await ZH(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await $H(this.logsDirPath))await ZH(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let Q=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed(Q),this.fileSize=0,this.writerSize=0}let G=(await $0(this.logsDirPath)).sort().reverse()[0];if(G){let Q=Bun.file(`${this.logsDirPath}/${G}`);if(Q.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${G}`,this.writer=Q.writer(),this.writer.write(await Q.text()),this.writer.write(`
|
|
5
|
+
`),this.writer.flush(),this.fileSize=Q.size}if(!this.writer){let Q=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${Q}`;let Z=Bun.file(`${this.logsDirPath}/${Q}`);this.writer=Z.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(H,G,Q={}){if(!this.isReady)await this.boot();let Z=C.getStore(),X={};if(Z)X={url:Z.req.rawRequest.url,method:Z.req.rawRequest.method,headers:Z.req.rawRequest.headers,body:Z.req.rawRequest.body};let $={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:H,message:G,metadata:{...X,...Q}},U="";try{U=JSON.stringify($)}catch(W){console.log("Error parsing log object",W)}try{let W=this.config.onLogCreated($);if(W instanceof Promise)W.catch((K)=>console.error("Error in onLogCreated",K))}catch(W){console.error("Error in onLogCreated",W)}if(!this.writer)return;this.writerSize+=U.length,this.fileSize+=U.length;try{this.writer.write(U),this.writer.write(`
|
|
6
|
+
`),this.tryFlush()}catch(W){console.error("Error writing log",W)}}async tryFlush(){if(this.fileSize>this.config.maxFileSize){if(!this.isCreatingFile)await this.newLogFile()}if(this.writerSize>this.config.maxFileSize/2)await this.writer.flush(),this.writerSize=0,await this.newLogFile();else clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(async()=>{await this.writer.flush(),this.writerSize=0},100)}}class W0 extends N{static getFacadeAccessor(){return UH}static debug(H,G){this.getFacadeRoot().log("debug",H,G)}static info(H,G){this.getFacadeRoot().log("info",H,G)}static notice(H,G){this.getFacadeRoot().log("notice",H,G)}static warning(H,G){this.getFacadeRoot().log("warning",H,G)}static error(H,G){this.getFacadeRoot().log("error",H,G)}static critical(H,G){this.getFacadeRoot().log("critical",H,G)}static alert(H,G){this.getFacadeRoot().log("alert",H,G)}static emergency(H,G){this.getFacadeRoot().log("emergency",H,G)}}class K0{config;static token="redis";instance=null;constructor(H={}){this.config=H}get client(){return this.instance??=new(M0())(this.config.url,this.config.options)}set client(H){this.instance=H}close(){let H=this.instance;this.instance=null,H?.close()}}function M0(){let H=globalThis.Bun?.RedisClient;if(typeof H!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return H}
|
|
7
|
+
export{WH as Ie,wH as Je,Y0 as Ke,AH as Le,O0 as Me,j0 as Ne,KH as Oe,MH as Pe,R0 as Qe,P0 as Re,B0 as Se,TH as Te,I0 as Ue,JH as Ve,q0 as We,w0 as Xe,w as Ye,J as Ze,BH as _e,J0 as $e,C0 as af,tH as bf,rH as cf,a as df,HH as ef,_ as ff,lH as gf,N as hf,IH as if,GH as jf,OH as kf,QH as lf,$4 as mf,xH as nf,XH as of,Z0 as pf,UH as qf,W0 as rf,K0 as sf};
|
|
8
|
+
|
|
9
|
+
//# debugId=34F6DD823E73167364756E2164756E21
|