From c0082b2ddb4bf9b52b7c9c47f84f822fa561192c Mon Sep 17 00:00:00 2001 From: Koji Wakayama Date: Sun, 9 Aug 2026 09:16:21 +0200 Subject: [PATCH 1/7] test(cli): serialize the tests that change the process directory `cli/commands/skills/validate.test.ts` failed once on main, on a commit that touched only CSP, and passed on the next run. It resolves a relative path through `Deno.chdir`, and five CLI test files do the same. The working directory is process-global, so when a shard groups two of them the second `chdir` lands while the first is still awaiting, and the first resolves against the wrong directory. Which files a shard groups decides whether it happens, which is why it fails rarely and somewhere unrelated to the change under test. Adds `withCwd`, which queues callers so at most one holds the directory at a time and each is restored before the next begins, and moves the test that failed onto it. The other four files still call `Deno.chdir` directly, so the race is narrowed rather than closed. `webhook/handler.test.ts` has grown its own queue for this, which says the hazard was already felt -- and also why a per-file queue is not the answer, since it orders only its own callers while every other file races it. I tried moving that file onto the shared helper and it broke a test that passes in isolation and fails in the full suite, so it is left alone rather than half-understood. `router.test.ts`, `app/operations/project-creation.test.ts` and `commands/schedule/handler.test.ts` set the directory in setup and restore it in a distant `finally`, which means restructuring each test rather than swapping a helper. Noted here so the next person does not read one migration as the whole job. --- cli/commands/skills/validate.test.ts | 13 ++------ src/testing/cwd.ts | 46 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 11 deletions(-) create mode 100644 src/testing/cwd.ts diff --git a/cli/commands/skills/validate.test.ts b/cli/commands/skills/validate.test.ts index 0bafe696ff..375229b8a0 100644 --- a/cli/commands/skills/validate.test.ts +++ b/cli/commands/skills/validate.test.ts @@ -1,3 +1,4 @@ +import { withCwd } from "#veryfront/testing/cwd.ts"; import "#veryfront/schemas/_test-setup.ts"; import { assertEquals } from "#veryfront/testing/assert.ts"; import { describe, it } from "#veryfront/testing/bdd.ts"; @@ -25,16 +26,6 @@ async function withTempSkill( } } -async function withTempCwd(dir: string, fn: () => Promise): Promise { - const previous = Deno.cwd(); - try { - Deno.chdir(dir); - await fn(); - } finally { - Deno.chdir(previous); - } -} - describe("Skills Validate", () => { it("accepts a project skill with SKILL.md frontmatter", async () => { await withTempSkill({ @@ -66,7 +57,7 @@ description: Review code changes. Review the submitted changes. `, }, async (dir) => { - await withTempCwd(dir, async () => { + await withCwd(dir, async () => { const issues = await validateSkillDirectory("."); assertEquals(issues, []); }); diff --git a/src/testing/cwd.ts b/src/testing/cwd.ts new file mode 100644 index 0000000000..69e25c0125 --- /dev/null +++ b/src/testing/cwd.ts @@ -0,0 +1,46 @@ +/** + * Serialized access to the process working directory in tests. + * + * `Deno.chdir` mutates state shared by every test in the process, and the CLI + * suite has several files that need it -- each one resolving a relative path + * the way the command under test would. Run two of them at once and the second + * `chdir` lands while the first is still awaiting, so the first resolves its + * path against the wrong directory. That is a race by construction: it depends + * on which files a shard happens to group, so it fails rarely, somewhere + * unrelated to whatever change is being tested. + * + * Every caller queues here instead, so at most one has the working directory at + * a time and each is restored before the next begins. + * + * @module testing/cwd + */ + +/** Tail of the queue. Each caller awaits the previous one before it chdirs. */ +let queue: Promise = Promise.resolve(); + +/** + * Run `fn` with the process working directory set to `dir`. + * + * Waits for any other caller to finish first, and restores the previous + * directory afterwards even if `fn` throws. + * + * @param dir directory to enter + * @param fn work to run inside it + * @returns whatever `fn` returns + */ +export function withCwd(dir: string, fn: () => Promise | T): Promise { + const run = queue.then(async () => { + const previous = Deno.cwd(); + try { + Deno.chdir(dir); + return await fn(); + } finally { + Deno.chdir(previous); + } + }); + + // The queue advances whether or not this caller succeeded, so one failure + // does not strand everyone behind it. + queue = run.then(() => {}, () => {}); + return run; +} From a7fe6d72ffefd52a07f7f82a6a8f648d92a6c69d Mon Sep 17 00:00:00 2001 From: Koji Wakayama Date: Sun, 9 Aug 2026 11:26:48 +0200 Subject: [PATCH 2/7] test(cli): reject nested withCwd instead of deadlocking A nested call waited for the queue, which waited for the outer call, which waited for the inner one, so the suite hung rather than failed. Reentrancy is not the fix either: the inner chdir would move the directory out from under the outer caller, which is the hazard this helper exists to prevent. It now rejects with a named error. Adds the tests the helper should have had when it was introduced: restore, serialization of overlapping callers, the nested rejection, and the queue still advancing after a caller throws. --- src/testing/cwd.test.ts | 69 +++++++++++++++++++++++++++++++++++++++++ src/testing/cwd.ts | 17 ++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/testing/cwd.test.ts diff --git a/src/testing/cwd.test.ts b/src/testing/cwd.test.ts new file mode 100644 index 0000000000..006bfc4483 --- /dev/null +++ b/src/testing/cwd.test.ts @@ -0,0 +1,69 @@ +import { describe, it } from "#veryfront/testing/bdd.ts"; +import { assert, assertEquals, assertRejects } from "#veryfront/testing/assert.ts"; +import { withCwd } from "./cwd.ts"; + +describe("testing/cwd", () => { + it("restores the previous directory", async () => { + const before = Deno.cwd(); + const temp = await Deno.makeTempDir(); + try { + await withCwd(temp, () => assert(Deno.cwd() !== before)); + assertEquals(Deno.cwd(), before); + } finally { + await Deno.remove(temp, { recursive: true }); + } + }); + + it("serializes overlapping callers", async () => { + const temp = await Deno.makeTempDir(); + const order: string[] = []; + try { + await Promise.all([ + withCwd(temp, async () => { + order.push("a:start"); + await new Promise((r) => setTimeout(r, 5)); + order.push("a:end"); + }), + withCwd(temp, () => void order.push("b")), + ]); + assertEquals(order, ["a:start", "a:end", "b"], "b must not run inside a"); + } finally { + await Deno.remove(temp, { recursive: true }); + } + }); + + it("rejects a nested call instead of deadlocking", async () => { + // The inner call would wait for the queue, which waits for the outer call, + // which waits for the inner one. Failing fast turns a hung suite into a + // named error. + const temp = await Deno.makeTempDir(); + try { + await assertRejects( + () => withCwd(temp, () => withCwd(temp, () => {})), + Error, + "cannot be nested", + ); + // The queue still works afterwards. + await withCwd(temp, () => assertEquals(typeof Deno.cwd(), "string")); + } finally { + await Deno.remove(temp, { recursive: true }); + } + }); + + it("releases the queue when a caller throws", async () => { + const temp = await Deno.makeTempDir(); + try { + await assertRejects( + () => + withCwd(temp, () => { + throw new Error("boom"); + }), + Error, + "boom", + ); + await withCwd(temp, () => assertEquals(typeof Deno.cwd(), "string")); + } finally { + await Deno.remove(temp, { recursive: true }); + } + }); +}); diff --git a/src/testing/cwd.ts b/src/testing/cwd.ts index 69e25c0125..8323649575 100644 --- a/src/testing/cwd.ts +++ b/src/testing/cwd.ts @@ -18,6 +18,9 @@ /** Tail of the queue. Each caller awaits the previous one before it chdirs. */ let queue: Promise = Promise.resolve(); +/** Whether a caller currently holds the directory. */ +let held = false; + /** * Run `fn` with the process working directory set to `dir`. * @@ -29,12 +32,26 @@ let queue: Promise = Promise.resolve(); * @returns whatever `fn` returns */ export function withCwd(dir: string, fn: () => Promise | T): Promise { + // Fail fast rather than enqueue: a nested call would wait for the queue, + // which waits for the outer call, which waits for this one. Reentrancy is + // not the answer either -- the inner chdir would move the directory out from + // under the outer caller, which is the exact hazard this exists to prevent. + if (held) { + return Promise.reject( + new Error( + "withCwd cannot be nested: the inner call would move the directory the outer call is using.", + ), + ); + } + const run = queue.then(async () => { const previous = Deno.cwd(); + held = true; try { Deno.chdir(dir); return await fn(); } finally { + held = false; Deno.chdir(previous); } }); From bdb432e8160f2ccb11c32fb0a668da468e15e52d Mon Sep 17 00:00:00 2001 From: Koji Wakayama Date: Sun, 9 Aug 2026 11:47:01 +0200 Subject: [PATCH 3/7] test(cli): tell a nested withCwd call from an independent one The nested-call guard I added used a process-global flag, which rejects any caller that arrives while another callback is awaiting -- and that caller is usually an independent test, for which queueing is exactly the right answer. Worse than the deadlock it replaced, and my own serialization test could not see it: both calls were made synchronously before either body ran, so the flag was still clear. Ownership is tracked by async context now, so only code running inside a callback is treated as nested. The regression test starts a callback, waits for it to signal, then calls from outside while it is still awaiting, and asserts the second caller runs after the first rather than being rejected. It fails against the global-flag version. --- src/testing/cwd.test.ts | 31 +++++++++++++++++++++++++++++++ src/testing/cwd.ts | 21 +++++++++++++++------ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/src/testing/cwd.test.ts b/src/testing/cwd.test.ts index 006bfc4483..eda5f671ad 100644 --- a/src/testing/cwd.test.ts +++ b/src/testing/cwd.test.ts @@ -32,6 +32,37 @@ describe("testing/cwd", () => { } }); + it("queues an independent caller that arrives mid-callback", async () => { + // The caller that matters is the one that appears *while* another callback + // is awaiting. A global "someone holds it" flag rejects that caller, which + // is worse than the deadlock it prevents: queueing is exactly what it + // should do. + const temp = await Deno.makeTempDir(); + const order: string[] = []; + let started!: () => void; + const hasStarted = new Promise((r) => (started = r)); + let open!: () => void; + const gate = new Promise((r) => (open = r)); + + try { + const first = withCwd(temp, async () => { + order.push("first:start"); + started(); + await gate; + order.push("first:end"); + }); + + await hasStarted; + const second = withCwd(temp, () => void order.push("second")); + open(); + + await Promise.all([first, second]); + assertEquals(order, ["first:start", "first:end", "second"]); + } finally { + await Deno.remove(temp, { recursive: true }); + } + }); + it("rejects a nested call instead of deadlocking", async () => { // The inner call would wait for the queue, which waits for the outer call, // which waits for the inner one. Failing fast turns a hung suite into a diff --git a/src/testing/cwd.ts b/src/testing/cwd.ts index 8323649575..407733ed18 100644 --- a/src/testing/cwd.ts +++ b/src/testing/cwd.ts @@ -15,11 +15,22 @@ * @module testing/cwd */ +import { AsyncLocalStorage } from "node:async_hooks"; + /** Tail of the queue. Each caller awaits the previous one before it chdirs. */ let queue: Promise = Promise.resolve(); -/** Whether a caller currently holds the directory. */ -let held = false; +/** + * Marks the execution context of a running callback. + * + * A global "someone holds it" flag cannot tell a nested call from an + * independent one that simply arrived while a callback was awaiting -- and + * rejecting the latter is worse than the deadlock it was meant to prevent, + * because queueing is exactly what an independent caller should do. Async + * context distinguishes them: only code running inside a callback sees the + * store. + */ +const insideCallback = new AsyncLocalStorage(); /** * Run `fn` with the process working directory set to `dir`. @@ -36,7 +47,7 @@ export function withCwd(dir: string, fn: () => Promise | T): Promise { // which waits for the outer call, which waits for this one. Reentrancy is // not the answer either -- the inner chdir would move the directory out from // under the outer caller, which is the exact hazard this exists to prevent. - if (held) { + if (insideCallback.getStore()) { return Promise.reject( new Error( "withCwd cannot be nested: the inner call would move the directory the outer call is using.", @@ -46,12 +57,10 @@ export function withCwd(dir: string, fn: () => Promise | T): Promise { const run = queue.then(async () => { const previous = Deno.cwd(); - held = true; try { Deno.chdir(dir); - return await fn(); + return await insideCallback.run(true, fn); } finally { - held = false; Deno.chdir(previous); } }); From 3b2bd32575e0d13b8d986f2b3ac859056c7edcb7 Mon Sep 17 00:00:00 2001 From: Koji Wakayama Date: Sun, 9 Aug 2026 12:17:31 +0200 Subject: [PATCH 4/7] fix(errors): register a slug for the nested working-directory contract `withCwd` rejected nested calls with a generic `Error`, which left the contract resting on message text -- callers wanting to distinguish it from any other failure had to substring-match the wording. Registers `nested-cwd-scope` under GENERAL so the condition has a name that survives rewording. Both count assertions move with it: the total and the per-category one, which is easy to miss because the failure names only the category. The RSC client bundle is regenerated because the error registry is reachable from it, so any registry entry changes its bytes. --- src/errors/error-registry.test.ts | 6 +++--- src/errors/error-registry/general.ts | 11 +++++++++++ src/errors/index.ts | 1 + .../services/rsc/endpoints/rsc-bundles.generated.ts | 4 ++-- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/errors/error-registry.test.ts b/src/errors/error-registry.test.ts index ee5b3c443f..3af4286f17 100644 --- a/src/errors/error-registry.test.ts +++ b/src/errors/error-registry.test.ts @@ -29,9 +29,9 @@ describe("error-registry", () => { assertEquals(slugs.length, uniqueSlugs.size, "Duplicate slugs detected"); }); - it("should have 105 registered errors", () => { + it("should have 106 registered errors", () => { const slugs = getAllSlugs(); - assertEquals(slugs.length, 105); + assertEquals(slugs.length, 106); }); }); @@ -324,7 +324,7 @@ describe("error-registry", () => { DEV: 5, DEPLOY: 12, AGENT: 8, - GENERAL: 12, + GENERAL: 13, }; for ( diff --git a/src/errors/error-registry/general.ts b/src/errors/error-registry/general.ts index 5d80bfcbb9..aaba25a956 100644 --- a/src/errors/error-registry/general.ts +++ b/src/errors/error-registry/general.ts @@ -99,6 +99,16 @@ export const PROJECT_SOURCE_EMPTY = defineError({ suggestion: "Add project files or run 'veryfront init'", }); +/** A scope that owns the process working directory was opened inside another one. */ +export const NESTED_CWD_SCOPE = defineError({ + slug: "nested-cwd-scope", + category: "GENERAL", + status: 500, + title: "Working directory scope nested inside another", + suggestion: + "Do the inner work directly in the outer scope's callback instead of opening a second one", +}); + // ============================================================================= // Registry exports // ============================================================================= @@ -121,4 +131,5 @@ export const GENERAL_REGISTRY = { "security-violation": SECURITY_VIOLATION, "input-validation-failed": INPUT_VALIDATION_FAILED, "project-source-empty": PROJECT_SOURCE_EMPTY, + "nested-cwd-scope": NESTED_CWD_SCOPE, } as const; diff --git a/src/errors/index.ts b/src/errors/index.ts index 90b4b31cbb..f2393a7e88 100644 --- a/src/errors/index.ts +++ b/src/errors/index.ts @@ -102,6 +102,7 @@ export { MIDDLEWARE_ERROR, // MODULE MODULE_NOT_FOUND, + NESTED_CWD_SCOPE, NETWORK_ERROR, NOT_SUPPORTED, ORCHESTRATION_ERROR, diff --git a/src/server/services/rsc/endpoints/rsc-bundles.generated.ts b/src/server/services/rsc/endpoints/rsc-bundles.generated.ts index 1f8ea5e85b..dbbe909d44 100644 --- a/src/server/services/rsc/endpoints/rsc-bundles.generated.ts +++ b/src/server/services/rsc/endpoints/rsc-bundles.generated.ts @@ -7,7 +7,7 @@ */ export const CLIENT_BOOT_BUNDLE: string = - 'var ht=Object.defineProperty;var _t=(e,t,r)=>t in e?ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var E=(e,t,r)=>_t(e,typeof t!="symbol"?t+"":t,r);var Ls=Array.prototype.at,Us=Array.prototype.filter,xt=Array.prototype.join,Hs=Array.prototype.map,vs=Array.prototype.pop,Tt=Array.prototype.push,ks=Array.prototype.sort,Ae=Reflect.apply;function G(e,t){return Ae(xt,e,[t])}function w(e,t){Ae(Tt,e,[t])}var St="3.2.3",At=Object.entries;function Ct(e){let t=[];if(e?.external?.length&&w(t,`external=${G(e.external,",")}`),w(t,`target=${e?.target??"es2022"}`),e?.deps){let r=[],n=At(e.deps);for(let o=0;ot||r?.(n,...o)}debug(t,...r){this.log(0,console.debug,`[${this.prefix}] DEBUG: ${t}`,...r)}info(t,...r){this.log(1,console.log,`[${this.prefix}] ${t}`,...r)}warn(t,...r){this.log(2,console.warn,`[${this.prefix}] WARN: ${t}`,...r)}error(t,...r){this.log(3,console.error,`[${this.prefix}] ERROR: ${t}`,...r)}};function $t(){if(typeof window>"u")return 2;let e=globalThis;return e.__VERYFRONT_DEV__||e.__RSC_DEV__?e.__VERYFRONT_DEBUG__||e.__RSC_DEBUG__?0:1:2}var z=$t(),g=new C("RSC",z),di=new C("PREFETCH",z),gi=new C("HYDRATE",z),fi=new C("VERYFRONT",z);var Vt="veryfront-hydration-data";function ue(e){try{let t=[...e.querySelectorAll(`[id="${Vt}"]`)];if(t.length!==1)return null;let r=e.body;if(!r)return null;let n=t[0];return r.firstElementChild!==n&&n.parentElement!==r||n.tagName?.toLowerCase()!=="script"||n.getAttribute("type")?.trim().toLowerCase()!=="application/json"?null:n}catch{return null}}function b(e=document){try{let t=ue(e);return t?JSON.parse(t.textContent||"{}"):null}catch(t){return g.debug("hydration data parse failed",t),null}}function Y(e,t){if(!t?.startsWith("on:"))return!1;try{let r=ue(e);if(!r)return!1;let n=JSON.parse(r.textContent||"{}");return n.dependencyPinningCacheKey=t,r.textContent=JSON.stringify(n),!0}catch(r){return g.debug("hydration dependency snapshot seed failed",r),!1}}function W(e){return e?.clientModuleStrategy?e.clientModuleStrategy:e?.dev?"fs":"rsc-module"}function Ft(e,t){if(!t)return e;let r=e.includes("?")?"&":"?";return`${e}${r}v=${encodeURIComponent(t)}`}function K(e,t){if(!t?.startsWith("on:"))return e;let r=e.indexOf("#"),n=r===-1?"":e.slice(r),o=r===-1?e:e.slice(0,r),i=o.indexOf("?"),a=i===-1?o:o.slice(0,i),c=new URLSearchParams(i===-1?"":o.slice(i+1));c.set("pins",t);let u=c.toString();return`${a}${u?`?${u}`:""}${n}`}function Gt(e,t){return Ft(`${De}${ae(e)}.js`,t)}function Bt(e,t,r){let n=t?`&v=${encodeURIComponent(t)}`:"";return K(`${P}module?rel=${encodeURIComponent(e)}${n}`,r)}function U(e){let t=e?.dependencyPinningCacheKey;return t?.startsWith("on:")?{[j]:t}:{}}function jt(e){return e.replace(/^\\/+_vf_modules\\//,"").replace(/^\\/+/,"").replace(/\\.js$/,"")}var zt=/\\.(tsx|ts|jsx|mdx|js)$/;function Yt(e){let t=jt(e),r=[e,t];return zt.test(t)||r.push(`${t}.tsx`,`${t}.ts`,`${t}.jsx`,`${t}.mdx`,`${t}.js`),Array.from(new Set(r))}function Wt(e,t){if(!e)return null;for(let r of Yt(t)){let n=e[r];if(n)return n}return null}function X(e){if(e.strategy==="fs"){let r=e.absPath??e.rel;return r?K(Gt(r,e.version),e.dependencyPinningCacheKey):null}let t=Wt(e.releaseAssetModules,e.rel);return t||Bt(e.rel,e.version,e.dependencyPinningCacheKey)}function q(e=document,t=M){let r=ce(e);return{react:B("react",r)?"react":be(t),reactDomClient:B("react-dom/client",r)?"react-dom/client":Oe(t)}}function we(e=document){let t=ce(e);return B("veryfront/router",t)?"veryfront/router":null}var Kt=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function Xt(e,...t){let r=Object.create(null),n=e.charAt(0).toUpperCase()+e.slice(1);for(let o of t)for(let[i,a]of Object.entries(o)){if(typeof a!="object"||a===null||!Object.hasOwn(a,"slug"))throw new Error(`${n} entry "${i}" must define a slug`);let c=a.slug;if(typeof c!="string")throw new Error(`${n} entry "${i}" must define a string slug`);if(c!==i)throw new Error(`${n} key "${i}" does not match entry slug "${c}"`);if(Object.hasOwn(r,i))throw new Error(`Duplicate ${e} slug "${i}"`);r[i]=a}return Object.freeze(r)}function Me(...e){for(let t of e)for(let r of Object.values(t)){if(typeof r.slug!="string"||r.slug.length<3||r.slug.length>40||!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(r.slug))throw new TypeError(`Registered error slug must be 3-40 characters of lowercase kebab-case, got "${r.slug}"`);if(typeof r.category!="string"||!Kt.has(r.category))throw new TypeError(`Registered error has unknown category "${r.category}"`);if(!Number.isInteger(r.status)||r.status<400||r.status>=600)throw new RangeError(`Registered error status must be an integer from 400 through 599, got ${r.status}`);if(typeof r.title!="string"||r.title.trim().length===0)throw new TypeError("Registered error title must be a non-empty string");if(r.suggestion!==void 0&&(typeof r.suggestion!="string"||r.suggestion.trim().length===0))throw new TypeError("Registered error suggestion must be non-empty when provided")}return Xt("error registry",...e)}var J={reset:"\\x1B[0m",dim:"\\x1B[2m",gray:"\\x1B[90m",red:"\\x1B[31m",green:"\\x1B[32m",yellow:"\\x1B[33m",blue:"\\x1B[34m",magenta:"\\x1B[35m",cyan:"\\x1B[36m"},Ci={debug:J.gray,info:J.green,warn:J.yellow,error:J.red};var m="[REDACTED]",y=Reflect.apply,qt=Array.prototype.pop,Jt=Array.prototype.push;var Oi=Array.prototype,Ii=BigInt.prototype.toString,ve=Map,Zt=Map.prototype.delete,Qt=Map.prototype.get,er=Map.prototype.keys,tr=Map.prototype.set;var _=Object.getOwnPropertyDescriptor,rr=Object.getPrototypeOf,Ni=Object.hasOwn,Di=Object.prototype,nr=Set,or=decodeURIComponent,A=URL,wi=Number.isFinite,Mi=Number.isInteger,de=RegExp.prototype.exec,sr=_(RegExp.prototype,"global").get,ir=_(RegExp.prototype,"unicode").get,ar=String.prototype.charCodeAt,cr=String.prototype.includes,lr=String.prototype.indexOf,Pe=String.prototype.slice,ke=String.prototype.startsWith,$e=String.prototype.toLowerCase,ur=Set.prototype.add,Pi=Set.prototype.delete,dr=Set.prototype.has,gr=rr(new ve().keys()).next,fr=_(Map.prototype,"size").get,Li=_(A.prototype,"host").get,Ui=_(A.prototype,"origin").get,pr=_(A.prototype,"password").get,Hi=_(A.prototype,"pathname").get,vi=_(A.prototype,"protocol").get,yr=_(A.prototype,"username").get,mr=/[^a-z0-9]/g,Er=/([a-z0-9])([A-Z])/g,Rr=/([A-Z])([A-Z][a-z])/g,hr=/\\b(?:sk-[A-Za-z0-9._-]{8,}|gh[po]_[A-Za-z0-9._-]{8,}|xox[baprs]-[A-Za-z0-9._-]{8,}|eyJ[A-Za-z0-9._-]{8,})\\b/g;function h(e,t,r){let n=y(sr,t,[]),o=y(ir,t,[]),i=0,a=!1,c="";t.lastIndex=0;try{for(;;){let u=y(de,t,[e]);if(u===null)break;let l=u[0],d=u.index;if(c+=S(e,i,d),c+=typeof r=="string"?r:r(u),i=d+l.length,a=!0,!n)break;l.length===0&&(t.lastIndex=_r(e,d,o))}}finally{t.lastIndex=0}return a?c+S(e,i):e}function ge(e){let t=y($e,e,[]);return h(t,mr,"")}function O(e,t){return y(ar,e,[t])}function _r(e,t,r){let n=t+1;if(!r||n>=e.length)return n;let o=O(e,t);if(o<55296||o>56319)return n;let i=O(e,n);return i>=56320&&i<=57343?t+2:n}function S(e,t,r){return r===void 0?y(Pe,e,[t]):y(Pe,e,[t,r])}function xr(e){let t=[],r=0;for(let n=0;n<=e.length;n++){let o=n===e.length?-1:O(e,n);o>=97&&o<=122||o>=48&&o<=57||(n>r&&(t[t.length]=S(e,r,n)),r=n+1)}return t}var Z=["password","passwd","pwd","passphrase","secret","clientsecret","token","apikey","accesskey","privatekey","credential","authheader","authorization","cookie","bearer","jwt","connectionstring","signature","sessionid","sid","otp","mfa","pin","salt","xsrf","csrf"],Tr=512,Sr=128,H=new ve;var Ar=256;function Cr(e){let t=e.length<=Sr;if(t){let o=y(Qt,H,[e]);if(o!==void 0)return o}let r=ge(e),n=r==="auth";for(let o=0;!n&&o=Tr){let i=y(er,H,[]),a=y(gr,i,[]).value;a!==void 0&&y(Zt,H,[a])}y(tr,H,[e,n])}return n}var Le=["access_token","accesstoken","refresh_token","api_key","apikey","code","token","secret","client_secret","password","passwd","pwd","state","sig","signature","auth","x-amz-credential","x-amz-signature","x-amz-security-token","x-goog-credential","x-goog-signature"],Ve=new nr;for(let e=0;e=65&&t<=90||t>=97&&t<=122}function Fe(e){return Dr(e)||e==="_"||e==="$"}function wr(e){if(!e)return!1;let t=O(e,0);return Fe(e)||t>=48&&t<=57||e==="."||e==="-"}function Ge(e,t){let r=t,n=e[r]===\'"\'||e[r]==="\'"?e[r++]:"";if(!Fe(e[r]))return!1;for(r++;wr(e[r]);)r++;if(n){if(e[r]!==n)return!1;r++}for(;e[r]===" "||e[r]==="\t";)r++;return e[r]===":"||e[r]==="="}function Be(e){return e==="\\r"||e===`\n`||e==="}"||e==="]"||Nr(e)}function je(e,t){let r=t;for(;r=e.length||Ge(e,r)}function Mr(e,t){let r=t,n=!0;if(y(ke,e,[m,t])){let d=t+m.length;if(Ue(e,d))return{end:d,replacement:m};r=d,n=!1}let o=n&&(e[r]===\'"\'||e[r]==="\'"||e[r]==="`")?e[r]:"",i=!1,a=()=>o?`${o}${m}${i?o:""}`:m,c=[],u="",l=-1;for(let d=r;d0&&(f==="}"||f==="]")){if(c[c.length-1]!==f)return{end:e.length,replacement:a()};if(y(qt,c,[]),d++,c.length===0&&Ue(e,d))return{end:d,replacement:a()};continue}if(c.length>0||!Be(f)){d++;continue}let R=d;if(d=je(e,d),d>=e.length||Ge(e,d))return{end:R,replacement:a()}}return{end:e.length,replacement:a()}}function He(e,t,r,n){let o=0,i="";for(let a=y(de,t,[e]);a;a=y(de,t,[e])){let c=a[r];if(!Pr(c))continue;let u=t.lastIndex,l=n===void 0?void 0:a[n],d=u+m.length;if((l==="?"||l==="&"||l===";")&&y(ke,e,[m,u])&&e[d]==="#")continue;let f=Mr(e,u);i+=S(e,o,a.index),i+=a[0],i+=f.replacement,o=f.end,t.lastIndex=f.end}return o===0?e:i+S(e,o)}function Pr(e){if(e.length>Ar)return!0;let t=h(e,Rr,i=>`${i[1]} ${i[2]}`),r=h(t,Er,i=>`${i[1]} ${i[2]}`),n=y($e,r,[]),o=xr(n);for(let i=0;i{let n=r[1],o=r[2],i=y(lr,o,[":"]);if(i===-1)return`${n}${m}@`;let a=S(o,0,i);return`${n}${a}:${m}@`});return t=h(t,Or,r=>{let n=r[1],o=r[2],i=r[3];return Lr(n,o,i)?r[0]:`${n}${o}:${m}@`}),t=h(t,/([?#&;])([-a-z0-9_.%\\[\\]]+)=([^&#;\\s]*)/gi,r=>{let n=r[1],o=r[2],i=Ur(o);return y(dr,Ve,[ge(i)])||Cr(i)?`${n}${o}=${m}`:r[0]}),t=h(t,/(^|[^a-z0-9_-])((?:set-cookie|cookie)\\s*:\\s*)[^\\r\\n]*/gi,r=>`${r[1]}${r[2]}${m}`),t=h(t,/\\b(authorization\\s*[:=]\\s*)[^\\r\\n]*/gi,r=>`${r[1]}${m}`),t=h(t,/\\b(bearer|basic)(\\s+)(?:"[^"\\r\\n]*"|\'[^\'\\r\\n]*\'|[a-z0-9._~+/=-]+)/gi,r=>`${r[1]}${r[2]}${m}`),t=h(t,hr,m),t=He(t,/(["\'])([_$a-z][a-z0-9_.$-]*)\\1(\\s*[:=]\\s*)/gi,2),t=He(t,/(^|[^a-z0-9_.$-])([_$a-z][a-z0-9_.$-]*)(\\s*[:=]\\s*)/gi,2,1),t}var Hr=2048;var Gi=64*1024,vr=256,kr="https://veryfront.com/docs/errors/",ze="...[truncated]",pe="unknown-error";function Ye(e,t){if(e.length<=t)return e;let r=Math.max(0,t-ze.length);return`${$r(e,r)}${ze}`}function $r(e,t){let r=e.slice(0,t),n=r.charCodeAt(r.length-1);return n>=55296&&n<=56319&&(r=r.slice(0,-1)),r}function Vr(e){let t="";for(let r=0;r=55296&&n<=56319){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=e.slice(r,r+2),r++):t+="\\uFFFD";continue}t+=n>=56320&&n<=57343?"\\uFFFD":e.charAt(r)}return t}function I(e){return typeof e!="string"?m:Ye(fe(e),Hr)}function Fr(e){let t=typeof e=="string"?fe(e):pe,r=Ye(t||pe,vr),n=Vr(r);return n==="."||n===".."?pe:n}function Q(e){let t=encodeURIComponent(Fr(e));return`${kr}${t}`}var Xe=Reflect.apply,Gr=Object.freeze,Br=Object.getOwnPropertyDescriptors,We=Number.isFinite,qe=new WeakSet,jr=WeakSet.prototype.add,zr=WeakSet.prototype.has,Yr=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function s(e){let t={...e},r={...t,create(n){let o=n?.message,i=n?.detail,a=n?.cause,c=n?.instance,u=n?.context,l=n?.status??t.status;return new ye(o||i||t.title,{slug:t.slug,category:t.category,status:l,title:t.title,suggestion:t.suggestion,exitCode:t.exitCode,detail:i,cause:a,instance:c,context:u})}};return Gr(r)}var ye=class extends Error{constructor(r,n){super(r);E(this,"slug");E(this,"category");E(this,"status");E(this,"title");E(this,"suggestion");E(this,"exitCode");E(this,"detail");E(this,"cause");E(this,"instance");E(this,"context");Xe(jr,qe,[this]),this.name="VeryfrontError",this.slug=n.slug,this.category=n.category,this.status=n.status,this.title=n.title,this.suggestion=n.suggestion,this.exitCode=n.exitCode,this.detail=n.detail,this.cause=n.cause,this.instance=n.instance,this.context=n.context}toRFC9457(){let r=Ke(this);return r?{type:Q(r.slug),title:I(r.title),status:r.status,detail:r.detail===void 0?void 0:I(r.detail),instance:r.instance===void 0?void 0:I(r.instance),category:r.category,suggestion:r.suggestion===void 0?void 0:I(r.suggestion),cause:typeof r.cause=="string"?I(r.cause):void 0}:{type:Q("unknown-error"),title:"Unknown/unclassified error",status:500,category:"GENERAL"}}getDocsUrl(){let r=Ke(this);return Q(r?.slug??"unknown-error")}};function Je(e){return typeof e=="object"&&e!==null&&Xe(zr,qe,[e])===!0}function Ke(e){return Je(e)?Wr(e):null}function Wr(e){try{if(!Je(e))return null;let t=Br(e),r=ne=>{let D=t[ne];return D&&"value"in D?D.value:void 0},n=r("slug"),o=r("category"),i=r("status"),a=r("title"),c=r("message"),u=r("suggestion"),l=r("exitCode"),d=r("detail"),f=r("cause"),R=r("instance"),$=r("context"),x=r("stack");return typeof n!="string"||!Yr.has(o)||typeof i!="number"||!We(i)||typeof a!="string"||typeof c!="string"||u!==void 0&&typeof u!="string"||l!==void 0&&(typeof l!="number"||!We(l))||d!==void 0&&typeof d!="string"||R!==void 0&&typeof R!="string"||x!==void 0&&typeof x!="string"?null:{slug:n,category:o,status:i,title:a,message:c,suggestion:u,exitCode:l,detail:d,cause:f,instance:R,context:$,stack:x}}catch{return null}}var Kr=s({slug:"config-not-found",category:"CONFIG",status:404,title:"Configuration file not found",suggestion:"Create veryfront.config.js, veryfront.config.ts, or veryfront.config.mjs in the project root"}),Xr=s({slug:"config-invalid",category:"CONFIG",status:400,title:"Invalid configuration format",suggestion:"Check the reported configuration path and validation details"}),qr=s({slug:"config-parse-error",category:"CONFIG",status:400,title:"Failed to parse configuration",suggestion:"Ensure your configuration file contains valid JavaScript or TypeScript"}),Jr=s({slug:"config-validation-error",category:"CONFIG",status:422,title:"Configuration validation failed",suggestion:"Check the configuration against the schema requirements"}),Zr=s({slug:"config-type-error",category:"CONFIG",status:400,title:"Configuration type mismatch",suggestion:"Ensure configuration values match expected types"}),Qr=s({slug:"import-map-invalid",category:"CONFIG",status:400,title:"Invalid import map configuration",suggestion:"Check your import map syntax and paths"}),en=s({slug:"cors-config-invalid",category:"CONFIG",status:400,title:"Invalid CORS configuration",suggestion:"Review CORS settings in your configuration"}),tn=s({slug:"config-validation-failed",category:"CONFIG",status:400,title:"Configuration validation failed",suggestion:"Check configuration values against requirements"}),rn=s({slug:"webhook-config-invalid",category:"CONFIG",status:400,title:"Invalid webhook configuration",suggestion:"Check webhook definition fields, target settings, and eventFilter conditions"}),nn=s({slug:"schedule-config-invalid",category:"CONFIG",status:400,title:"Invalid schedule configuration",suggestion:"Check schedule definition fields, cron expression, target settings, and positive-integer limits"}),on=s({slug:"trigger-config-invalid",category:"CONFIG",status:400,title:"Invalid trigger configuration",suggestion:"Check trigger ID format (lowercase, alphanumeric, dots/slashes/hyphens) and ensure all input values are JSON-serializable"}),Ze={"config-not-found":Kr,"config-invalid":Xr,"config-parse-error":qr,"config-validation-error":Jr,"config-type-error":Zr,"import-map-invalid":Qr,"cors-config-invalid":en,"config-validation-failed":tn,"webhook-config-invalid":rn,"schedule-config-invalid":nn,"trigger-config-invalid":on};var sn=s({slug:"build-failed",category:"BUILD",status:500,title:"Build process failed",suggestion:"Check the build output for specific errors"}),an=s({slug:"bundle-error",category:"BUILD",status:500,title:"Bundle generation failed",suggestion:"Review bundler output for details"}),cn=s({slug:"typescript-error",category:"BUILD",status:500,title:"TypeScript compilation error",suggestion:"Fix TypeScript errors shown in the output"}),ln=s({slug:"mdx-compile-error",category:"BUILD",status:500,title:"MDX compilation failed",suggestion:"Check your MDX file syntax"}),un=s({slug:"asset-optimization-error",category:"BUILD",status:500,title:"Asset optimization failed",suggestion:"Check asset file formats and paths"}),dn=s({slug:"ssg-generation-error",category:"BUILD",status:500,title:"Static site generation failed",suggestion:"Review SSG configuration and data fetching"}),gn=s({slug:"sourcemap-error",category:"BUILD",status:500,title:"Source map generation failed",suggestion:"Check source map configuration"}),fn=s({slug:"compilation-error",category:"BUILD",status:500,title:"Compilation failed",suggestion:"Review compiler output for specific errors"}),Qe={"build-failed":sn,"bundle-error":an,"typescript-error":cn,"mdx-compile-error":ln,"asset-optimization-error":un,"ssg-generation-error":dn,"sourcemap-error":gn,"compilation-error":fn};var pn=s({slug:"hydration-mismatch",category:"RUNTIME",status:500,title:"Client/server hydration mismatch",suggestion:"Ensure server and client render the same content"}),yn=s({slug:"render-error",category:"RUNTIME",status:500,title:"Component render failed",suggestion:"Check component for runtime errors"}),mn=s({slug:"component-error",category:"RUNTIME",status:500,title:"Component execution error",suggestion:"Review component logic and props"}),En=s({slug:"layout-not-found",category:"RUNTIME",status:404,title:"Layout component not found",suggestion:"Ensure layout file exists at the expected path"}),Rn=s({slug:"page-not-found",category:"RUNTIME",status:404,title:"Page component not found",suggestion:"Check that the page file exists in the routes directory"}),hn=s({slug:"api-error",category:"RUNTIME",status:500,title:"API route handler error",suggestion:"Review API route handler for errors"}),_n=s({slug:"middleware-error",category:"RUNTIME",status:500,title:"Middleware execution error",suggestion:"Check middleware function for errors"}),xn=s({slug:"trigger-target-not-found",category:"RUNTIME",status:404,title:"Trigger target not found",suggestion:"Ensure the referenced task or workflow ID is registered in the project"}),Tn=s({slug:"trigger-execution-failed",category:"RUNTIME",status:500,title:"Trigger target execution failed",suggestion:"Check the task or workflow for errors and review the trigger input"}),Sn=s({slug:"trigger-not-supported",category:"RUNTIME",status:501,title:"Trigger target type not supported in local runtime",suggestion:"Use a workflow or task target for local trigger runs; agent targets require the Cloud runtime"}),et={"hydration-mismatch":pn,"render-error":yn,"component-error":mn,"layout-not-found":En,"page-not-found":Rn,"api-error":hn,"middleware-error":_n,"trigger-target-not-found":xn,"trigger-execution-failed":Tn,"trigger-not-supported":Sn};var An=s({slug:"route-conflict",category:"ROUTE",status:409,title:"Conflicting route definitions",suggestion:"Rename or reorganize conflicting route files"}),Cn=s({slug:"invalid-route-file",category:"ROUTE",status:400,title:"Invalid route file structure",suggestion:"Ensure route file exports required functions"}),bn=s({slug:"route-handler-invalid",category:"ROUTE",status:400,title:"Invalid route handler export",suggestion:"Export a valid handler function from the route file"}),On=s({slug:"dynamic-route-error",category:"ROUTE",status:500,title:"Dynamic route parsing failed",suggestion:"Check dynamic route segment syntax"}),In=s({slug:"route-params-error",category:"ROUTE",status:400,title:"Route parameters invalid",suggestion:"Validate route parameter values"}),Nn=s({slug:"api-route-error",category:"ROUTE",status:500,title:"API route definition error",suggestion:"Review API route configuration"}),tt={"route-conflict":An,"invalid-route-file":Cn,"route-handler-invalid":bn,"dynamic-route-error":On,"route-params-error":In,"api-route-error":Nn};var Dn=s({slug:"module-not-found",category:"MODULE",status:404,title:"Module could not be resolved",suggestion:"Check the import path and ensure the module is installed"}),wn=s({slug:"import-resolution-error",category:"MODULE",status:500,title:"Import path resolution failed",suggestion:"Verify import paths and module configuration"}),Mn=s({slug:"circular-dependency",category:"MODULE",status:500,title:"Circular dependency detected",suggestion:"Refactor imports to break the circular dependency"}),Pn=s({slug:"invalid-import",category:"MODULE",status:400,title:"Invalid import statement",suggestion:"Fix import syntax or path"}),Ln=s({slug:"dependency-missing",category:"MODULE",status:404,title:"Required dependency not installed",suggestion:"Install the missing dependency with your package manager"}),Un=s({slug:"version-mismatch",category:"MODULE",status:409,title:"Dependency version mismatch",suggestion:"Update dependencies to compatible versions"}),Hn=s({slug:"lockfile-format-mismatch",category:"MODULE",status:409,title:"Lockfile format is not supported",suggestion:"Upgrade Veryfront or migrate the lockfile before modifying it"}),vn=s({slug:"lockfile-read-error",category:"MODULE",status:500,title:"Lockfile could not be read safely",suggestion:"Check file access or restore a valid lockfile before retrying"}),rt={"module-not-found":Dn,"import-resolution-error":wn,"circular-dependency":Mn,"invalid-import":Pn,"dependency-missing":Ln,"version-mismatch":Un,"lockfile-format-mismatch":Hn,"lockfile-read-error":vn};var kn=s({slug:"port-in-use",category:"SERVER",status:409,title:"Server port already in use",suggestion:"Use a different port or stop the process using this port"}),$n=s({slug:"server-start-error",category:"SERVER",status:500,title:"Server failed to start",suggestion:"Check server configuration and port availability"}),Vn=s({slug:"cache-error",category:"SERVER",status:500,title:"Cache operation failed",suggestion:"Clear the cache and try again"}),Fn=s({slug:"file-watch-error",category:"SERVER",status:500,title:"File watcher error",suggestion:"Restart the development server"}),Gn=s({slug:"request-error",category:"SERVER",status:500,title:"HTTP request handling error",suggestion:"Check request handler and middleware"}),Bn=s({slug:"service-overloaded",category:"SERVER",status:503,title:"Service overloaded",suggestion:"Reduce load or scale up resources"}),jn=s({slug:"project-execution-unavailable",category:"SERVER",status:503,title:"Project execution unavailable",suggestion:"Route the project to a dedicated isolated runtime"}),zn=s({slug:"semaphore-timeout",category:"SERVER",status:503,title:"Semaphore acquire timeout",suggestion:"Reduce concurrency or increase the semaphore acquire timeout"}),Yn=s({slug:"circuit-breaker-open",category:"SERVER",status:503,title:"Circuit breaker is open",suggestion:"Wait for the breaker reset timeout before retrying"}),Wn=s({slug:"cache-path-mismatch",category:"SERVER",status:500,title:"Cache path mismatch",suggestion:"Clear the cache directory and rebuild"}),Kn=s({slug:"network-error",category:"SERVER",status:502,title:"Network operation failed",suggestion:"Check network connectivity and retry"}),Xn=s({slug:"api-client-error",category:"SERVER",status:500,title:"API client request failed",suggestion:"Check API connectivity and authentication"}),qn=s({slug:"token-storage-error",category:"SERVER",status:500,title:"Token storage operation failed",suggestion:"Check token storage backend and credentials"}),Jn=s({slug:"cache-invariant-violation",category:"SERVER",status:500,title:"Cache path invariant violated",suggestion:"Clear the cache and rebuild"}),Zn=s({slug:"release-not-found",category:"SERVER",status:404,title:"No active release found",suggestion:"Deploy the project to create a release for this environment"}),Qn=s({slug:"fallback-exhausted",category:"SERVER",status:500,title:"Primary and fallback operations both failed",suggestion:"Check service availability and connectivity"}),eo=s({slug:"rag-store-corrupt",category:"SERVER",status:500,title:"RAG store file is corrupt",suggestion:"Repair or move the store file aside, then retry; it was not overwritten"}),to=s({slug:"rag-store-unavailable",category:"SERVER",status:500,title:"RAG store file is unavailable",suggestion:"Check storage availability, permissions, and concurrent operations, then retry"}),nt={"port-in-use":kn,"server-start-error":$n,"cache-error":Vn,"file-watch-error":Fn,"request-error":Gn,"service-overloaded":Bn,"project-execution-unavailable":jn,"semaphore-timeout":zn,"circuit-breaker-open":Yn,"cache-path-mismatch":Wn,"network-error":Kn,"api-client-error":Xn,"token-storage-error":qn,"cache-invariant-violation":Jn,"release-not-found":Zn,"fallback-exhausted":Qn,"rag-store-corrupt":eo,"rag-store-unavailable":to};var ro=s({slug:"client-boundary-violation",category:"BOUNDARY",status:400,title:"Client boundary rule violation",suggestion:"Add \'use client\' directive or move code to a client component"}),no=s({slug:"server-only-in-client",category:"BOUNDARY",status:400,title:"Server-only code in client component",suggestion:"Move server-only code to a server component"}),oo=s({slug:"client-only-in-server",category:"BOUNDARY",status:400,title:"Client-only code in server component",suggestion:"Move client-only code to a client component"}),so=s({slug:"invalid-use-client",category:"BOUNDARY",status:400,title:"Invalid \'use client\' directive",suggestion:"Place \'use client\' at the top of the file"}),io=s({slug:"invalid-use-server",category:"BOUNDARY",status:400,title:"Invalid \'use server\' directive",suggestion:"Place \'use server\' at the top of the file or function"}),ao=s({slug:"rsc-payload-error",category:"BOUNDARY",status:500,title:"RSC payload serialization error",suggestion:"Ensure props are serializable (no functions, symbols, etc.)"}),co=s({slug:"ssr-output-limit-exceeded",category:"BOUNDARY",status:500,title:"SSR output limit exceeded",suggestion:"Reduce the rendered HTML size or split the response into smaller pages"}),ot={"client-boundary-violation":ro,"server-only-in-client":no,"client-only-in-server":oo,"invalid-use-client":so,"invalid-use-server":io,"rsc-payload-error":ao,"ssr-output-limit-exceeded":co};var lo=s({slug:"hmr-error",category:"DEV",status:500,title:"Hot module replacement error",suggestion:"Restart the development server"}),uo=s({slug:"dev-server-error",category:"DEV",status:500,title:"Development server error",suggestion:"Check the dev server logs and restart"}),go=s({slug:"fast-refresh-error",category:"DEV",status:500,title:"Fast refresh failed",suggestion:"Save the file again or restart the dev server"}),fo=s({slug:"error-overlay-error",category:"DEV",status:500,title:"Error overlay failed",suggestion:"Check browser console for details"}),po=s({slug:"source-map-error",category:"DEV",status:500,title:"Source map loading error",suggestion:"Rebuild or clear cache"}),st={"hmr-error":lo,"dev-server-error":uo,"fast-refresh-error":go,"error-overlay-error":fo,"source-map-error":po};var yo=s({slug:"deployment-error",category:"DEPLOY",status:500,title:"Deployment process failed",suggestion:"Check deployment logs for details"}),mo=s({slug:"platform-error",category:"DEPLOY",status:500,title:"Platform-specific error",suggestion:"Check platform documentation and requirements"}),Eo=s({slug:"env-var-missing",category:"DEPLOY",status:500,title:"Required environment variable missing",suggestion:"Set the required environment variable"}),Ro=s({slug:"production-build-required",category:"DEPLOY",status:400,title:"Production build required",suggestion:"Run \'veryfront build\' before deploying"}),ho=s({slug:"environment-not-found",category:"DEPLOY",status:404,title:"Deployment environment not found",suggestion:"Check environment names with: veryfront config"}),_o=s({slug:"release-missing-version",category:"DEPLOY",status:500,title:"Release has no version",suggestion:"Try again or check the build logs in Studio"}),xo=s({slug:"release-build-timeout",category:"DEPLOY",status:408,title:"Release build timed out",suggestion:"Try again or check the build logs in Studio"}),To=s({slug:"deployment-verification-timeout",category:"DEPLOY",status:408,title:"Deployment verification timed out",suggestion:"Try again or check the deployment status in Studio"}),So=s({slug:"push-receipt-missing",category:"DEPLOY",status:400,title:"Push receipt not found",suggestion:"Run: veryfront push --branch main first"}),Ao=s({slug:"source-digest-mismatch",category:"DEPLOY",status:409,title:"Release source digest mismatch",suggestion:"Run veryfront push again to re-upload source files"}),Co=s({slug:"preview-hostname-too-long",category:"DEPLOY",status:400,title:"Preview hostname too long",suggestion:"Use a shorter project slug or branch name"}),bo=s({slug:"branch-not-found",category:"DEPLOY",status:404,title:"Branch not found",suggestion:"List branches in Studio or push a new one with: veryfront push --branch "}),it={"deployment-error":yo,"platform-error":mo,"env-var-missing":Eo,"production-build-required":Ro,"environment-not-found":ho,"release-missing-version":_o,"release-build-timeout":xo,"deployment-verification-timeout":To,"push-receipt-missing":So,"source-digest-mismatch":Ao,"preview-hostname-too-long":Co,"branch-not-found":bo};var Oo=s({slug:"agent-error",category:"AGENT",status:500,title:"Agent operation error",suggestion:"Check agent configuration and logs"}),Io=s({slug:"agent-not-found",category:"AGENT",status:404,title:"Agent not found",suggestion:"Verify the agent ID exists"}),No=s({slug:"agent-timeout",category:"AGENT",status:408,title:"Agent operation timed out",suggestion:"Increase timeout or simplify the request"}),Do=s({slug:"agent-intent-error",category:"AGENT",status:400,title:"Agent intent parsing error",suggestion:"Rephrase the request more clearly"}),wo=s({slug:"orchestration-error",category:"AGENT",status:500,title:"Multi-agent orchestration error",suggestion:"Check agent coordination logic"}),Mo=s({slug:"cost-limit-exceeded",category:"AGENT",status:429,title:"Cost limit exceeded",suggestion:"Wait for the budget period to reset or increase the limit"}),Po=s({slug:"tool-id-conflict",category:"AGENT",status:409,title:"Tool ID conflict",suggestion:"Use a unique tool ID or rename one of the conflicting tools"}),Lo=s({slug:"durable-run-event-persistence-failed",category:"AGENT",status:500,title:"Durable run event persistence failed",suggestion:"Correct invalid or oversized event data, or retry after durable event storage recovers"}),at={"agent-error":Oo,"agent-not-found":Io,"agent-timeout":No,"agent-intent-error":Do,"orchestration-error":wo,"cost-limit-exceeded":Mo,"tool-id-conflict":Po,"durable-run-event-persistence-failed":Lo};var Uo=s({slug:"unknown-error",category:"GENERAL",status:500,title:"Unknown/unclassified error",suggestion:"Check logs for more details"}),Ho=s({slug:"authentication-required",category:"GENERAL",status:401,title:"Authentication required",suggestion:"Set VERYFRONT_API_TOKEN or run \'veryfront login\'"}),vo=s({slug:"permission-denied",category:"GENERAL",status:403,title:"File/resource permission denied",suggestion:"Check file permissions and access rights"}),ko=s({slug:"file-not-found",category:"GENERAL",status:404,title:"File not found",suggestion:"Verify the file path exists"}),$o=s({slug:"resource-not-found",category:"GENERAL",status:404,title:"Requested resource not found",suggestion:"Verify the referenced resource ID or name exists"}),Vo=s({slug:"invalid-argument",category:"GENERAL",status:400,title:"Invalid function argument",suggestion:"Check argument types and values",exitCode:2}),Fo=s({slug:"timeout-error",category:"GENERAL",status:408,title:"Operation timed out",suggestion:"Increase timeout or optimize the operation"}),Go=s({slug:"initialization-error",category:"GENERAL",status:500,title:"Initialization failed",suggestion:"Check initialization requirements and dependencies"}),Bo=s({slug:"not-supported",category:"GENERAL",status:501,title:"Feature not supported",suggestion:"Check documentation for supported features"}),me=s({slug:"security-violation",category:"GENERAL",status:403,title:"Security violation detected",suggestion:"Check for path traversal or unauthorized access attempts"}),jo=s({slug:"input-validation-failed",category:"GENERAL",status:400,title:"Input validation failed",suggestion:"Check request input against validation rules"}),zo=s({slug:"project-source-empty",category:"GENERAL",status:400,title:"Project source is empty",suggestion:"Add project files or run \'veryfront init\'"}),ct={"unknown-error":Uo,"authentication-required":Ho,"permission-denied":vo,"file-not-found":ko,"resource-not-found":$o,"invalid-argument":Vo,"timeout-error":Fo,"initialization-error":Go,"not-supported":Bo,"security-violation":me,"input-validation-failed":jo,"project-source-empty":zo};var Da=Me(Ze,Qe,et,tt,rt,nt,ot,st,it,at,ct);var Yo=[{source:String.raw`]*>[\\s\\S]*?<\\/script>`,flags:"gi",name:"inline script"},{source:String.raw`javascript:`,flags:"gi",name:"javascript: URL"},{source:String.raw`\\bon\\w+\\s*=`,flags:"gi",name:"event handler attribute"},{source:String.raw`data:\\s*text\\/html`,flags:"gi",name:"data: HTML URL"}];function Wo(){return Yo.map(({source:e,flags:t,name:r})=>({pattern:new RegExp(e,t),name:r}))}function Ko(){let e=globalThis;return e.__VERYFRONT_DEV__===!0||e.Deno?.env?.get?.("VERYFRONT_ENV")==="development"}function v(e,t={}){let{allowInlineScripts:r=!1,strict:n=!1,warn:o=!0}=t;for(let{pattern:i,name:a}of Wo())if(!(r&&a==="inline script")&&(i.lastIndex=0,!!i.test(e)&&(o&&console.warn(`[Security] Suspicious ${a} detected in server HTML`),n||!Ko())))throw me.create({detail:`Potentially unsafe HTML: ${a} detected`});return e}function k(e,t){let r=t==="root"?L:`rsc-slot-${t}`,n=e.getElementById(r);if(n)return n;let o=e.createElement("div");return o.id=r,e.body.appendChild(o),o}function Xo(e,t){if(t.type!=="slot")return;let r=k(e,t.id);r.innerHTML=v(String(t.html??""))}function lt(e,t){let r=t.split(`\n`),n=r.pop()??"";for(let o of r){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch(u){g.debug("[client-dom] malformed NDJSON line",{line:i,error:u instanceof Error?u.message:String(u)});continue}if(!a||typeof a!="object")continue;let c=a;if(c.type==="slot"){Xo(e,c);try{Zo(e,c.id||"root")}catch(u){g.debug("[client-dom] hydration optional failed",u)}}}return n}function qo(e){return new Promise((t,r)=>{let n=()=>r(new DOMException("aborted","AbortError"));if(e.aborted){n();return}e.addEventListener("abort",n,{once:!0})})}async function ut(e,t=document,r){let n="body"in e?e:null,o=n?.body??e;if(!o)return;n&&Y(t,n.headers.get(j));let i=o.getReader(),a=new TextDecoder,c="",u=!1;try{for(;;){if(r?.aborted)throw new DOMException("aborted","AbortError");let l=i.read(),{done:d,value:f}=r?await Promise.race([l,qo(r)]):await l;if(d){u=!0;break}c+=a.decode(f,{stream:!0}),c=lt(t,c)}c&<(t,`${c}\n`)}catch(l){throw l instanceof Error&&l.name==="AbortError"||g.debug("[client-dom] consumeNdjsonStream error",l),l}finally{try{await i.cancel()}catch(l){u||g.debug("[client-dom] reader.cancel failed",l)}try{i.releaseLock()}catch(l){g.debug("[client-dom] reader.releaseLock failed",l)}if(typeof o.cancel=="function")try{await o.cancel()}catch(l){g.debug("[client-dom] stream.cancel failed",l)}if(typeof n?.body?.cancel=="function")try{await n.body.cancel()}catch(l){g.debug("[client-dom] response.body.cancel failed",l)}}}function Jo(e,t){let r=k(e,t),n=[],o=i=>{let a=i;a.dataset?.clientRef&&n.push(a);for(let c of i.children)o(c)};return o(r),n}function Zo(e,t){let r=Jo(e,t);for(let n of r){let o=n.dataset?.clientRef;o&&(n.dataset.hydrated="true",g.debug("[client-dom] marked for hydration",o))}}var Qo=new Set(["server","client","html","fragment"]);function dt(e){if(!e)return[];try{let t=JSON.parse(e);return ts(t)?t.nodes:[]}catch{return[]}}async function Re(e,t,r){return await Promise.all(e.map(n=>es(n,t,r)))}async function es(e,t,r){if(e.type==="html")return e.text??e.html??"";let n=await Re(e.children??[],t,r);if(e.type==="fragment"||e.type==="server"&&!e.component)return t.createElement(t.Fragment,{},...n);if(e.type==="server")return t.createElement(e.component,e.props??{},...n);let o=await r(e.component);return o?t.createElement(o,e.props??{},...n):null}function ts(e){return!Ee(e)||e.version!==1||!Array.isArray(e.nodes)?!1:e.nodes.every(t=>gt(t,0))}function gt(e,t){return t>100||!Ee(e)||!Qo.has(e.type)||e.type==="html"&&typeof e.html!="string"&&typeof e.text!="string"||e.type==="client"&&typeof e.component!="string"||e.type==="server"&&e.component!==void 0&&typeof e.component!="string"||e.props!==void 0&&!Ee(e.props)?!1:e.children===void 0?!0:Array.isArray(e.children)&&e.children.every(r=>gt(r,t+1))}function Ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rs(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e))t[r]=Array.isArray(n)?n.join("/"):n;return t}async function ee(e,t,r=document){try{let n=we(r);if(!n)return e;let i=(await import(n)).wrapForHydration;return typeof i!="function"?e:i(e,{params:rs(t?.params),frontmatter:t?.frontmatter??{},data:t?.props??{}})}catch(n){return g.debug("router provider wrap failed",n),e}}var ns="Unknown dependency snapshot",os="export default null; // Unknown dependency snapshot",he="__VF_DEPENDENCY_SNAPSHOT_RECOVERY_STARTED__";function ss(){return globalThis}async function is(e){if(e.status!==409)return!1;try{let t=(await e.clone().text()).trim();return t===ns||t===os}catch{return!1}}async function N(e,t=()=>globalThis.location.reload()){if(!await is(e))return!1;let r=ss();if(r[he])return!0;r[he]=!0;try{t()}catch{return delete r[he],!1}return!0}async function te(e,t=globalThis.fetch,r=()=>globalThis.location.reload()){try{let n=new URL(e,"http://veryfront.local").searchParams.getAll("pins");if(n.length!==1||!n[0]?.startsWith("on:"))return!1;let o=await t(e,{cache:"no-store"});return await N(o,r)}catch{return!1}}var as=100;function cs(e,t){if(globalThis.__VF_CLIENT_MOD_CACHE??(globalThis.__VF_CLIENT_MOD_CACHE=new Map),globalThis.__VF_CLIENT_MOD_CACHE.size>=as){let r=globalThis.__VF_CLIENT_MOD_CACHE.keys().next().value;r&&globalThis.__VF_CLIENT_MOD_CACHE.delete(r)}globalThis.__VF_CLIENT_MOD_CACHE.set(e,t)}function ft(e){let t=e.match(/^\\/app\\/(.+)#([\\w$.-]+)$/);if(t)return{rel:`/${t[1]||""}`,exportName:t[2]||"default"};let r=e.match(/^(\\/_veryfront\\/[^#]+)#([\\w$.-]+)$/);return r?{moduleUrl:r[1],exportName:r[2]||"default"}:(g.debug("hydrate: unrecognised client ref format, skipping",{ref:e}),null)}function ls(e){let t=e.dataset?.rscProps;if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch(r){return g.debug("hydrate: invalid client boundary props, using empty props",r),{}}}function us(e){return dt(e.dataset?.rscChildren)}function ds(e){return"/_veryfront/rsc/manifest"}function gs(e){return U(e)}async function fs(e=document){try{let t=b(e),r=await fetch(ds(t),{headers:gs(t)});return r.ok?await r.json():(await N(r),null)}catch{return null}}async function pt(e,t,r,n={}){let o=ps(e,t,r,n.releaseAssetModules),i=t.moduleUrl??t.rel;if(!i)return null;let a=`${i}#${e.hash??""}`;try{let c=globalThis.__VF_CLIENT_MOD_CACHE?.get(a);if(c)return c}catch(c){g.debug("hydrate: cache get failed",c)}if(!o)return null;try{let c=await(n.importModule??(u=>import(u)))(o);try{cs(a,c)}catch(u){g.debug("hydrate: cache set failed",u)}return c}catch(c){return g.debug("hydrate: failed to import module",{moduleUrl:o,error:c}),await(n.recoverSnapshotFailure??te)(o),null}}function ps(e,t,r,n){if(t.moduleUrl)return K(t.moduleUrl,e.dependencyPinningCacheKey);if(!t.rel)return null;let o=e.graphIds?.client.find(i=>i.rel===t.rel)?.path;return X({strategy:r,rel:t.rel,absPath:o,version:e.hash,dependencyPinningCacheKey:e.dependencyPinningCacheKey,releaseAssetModules:n})}function ys(e){let t=Array.from(e.querySelectorAll("[data-client-ref]")),r=new Set(t);return t.filter(n=>{let o=n.parentElement;for(;o;){if(r.has(o))return!1;o=o.parentElement}return!0})}async function yt(e=document){let t=null;try{t=await fs(e)}catch(l){g.debug("hydrate: fetch manifest failed",l)}if(!t){g.debug("hydrate: no manifest");return}let r=ys(e);try{let l=globalThis.__VF_MANIFEST_HASH;if(!r.some(f=>f.dataset?.hydrated!=="true")&&l&&t.hash&&l===t.hash)return}catch(l){g.debug("hydrate: hmr hash read failed",l)}if(r.length===0){try{globalThis.__VF_MANIFEST_HASH=t.hash??""}catch(l){g.debug("hydrate: set hash failed",l)}return}let n=b(e),o=W(n),i=n?.releaseAssetModules;try{if(globalThis.__VF_TEST_MODE__){globalThis.__VF_HYDRATE_CALLED=!0,globalThis.__VF_MANIFEST_HASH=t.hash??"";return}}catch(l){g.debug("hydrate: test mode flags failed",l)}let a=q(e,n?.reactVersion),[{default:c},{createRoot:u}]=await Promise.all([import(a.react),import(a.reactDomClient)]);for(let l of r){let d=l.dataset?.clientRef??"";if(!d||l.dataset?.hydrated==="true")continue;let f=ft(d);if(!f)continue;let R=await pt(t,f,o,{releaseAssetModules:i});if(!R)continue;let $=R[f.exportName]??R.default;if(typeof $=="function")try{let x=u(l),ne=ls(l),D=us(l),mt=await Re(D,{Fragment:c.Fragment,createElement(V,oe,...F){return c.createElement(V,oe,...F)}},async V=>{let oe=t.modules.find(Rt=>Rt.id===V),F=t.components?.[V],Te=oe?.clientRef??(F?`${F}#default`:void 0);if(!Te)return null;let se=ft(Te);if(!se)return null;let ie=await pt(t,se,o,{releaseAssetModules:i});if(!ie)return null;let Se=ie[se.exportName]??ie.default;return typeof Se=="function"?Se:null}),Et=await ee(c.createElement($,ne,...mt),n,e);x.render(Et),l.dataset.hydrated="true"}catch(x){g.warn("hydrate: render failed",x)}}try{globalThis.__VF_MANIFEST_HASH=t.hash??""}catch(l){g.debug("hydrate: set hash failed (post)",l)}}var _e="data-vf-react-head-owner";var ms=2*1024*1024,cc=ms*2;var lc=64*1024,uc=1024*1024,dc=1024*1024;var gc=new TextEncoder;async function Es(){let e=b(document),t=q(document,e?.reactVersion),[r,n]=await Promise.all([import(t.react),import(t.reactDomClient)]);return{React:r,ReactDOM:n}}var Rs=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE"]);function xe(e){let t=e.getAttribute("style")??"";return e.hasAttribute("data-veryfront-head")||e.hasAttribute("hidden")||/(?:^|;)\\s*display\\s*:\\s*none(?:\\s*;|$)/i.test(t)||Rs.has(e.tagName.toUpperCase())}function hs(e,t){return e.find(r=>r.tagName.toUpperCase()==="DIV"&&!!r.getAttribute("class")?.trim()&&!xe(r))??t}function _s(e,t){return e===t}function xs(e,t){let r=document.createElement("div");r.setAttribute("data-veryfront-hydration-root","page");let n=e.find(o=>!xe(o));n?.parentNode===t?t.insertBefore(r,n):t.appendChild(r);for(let o of e)!xe(o)&&o.parentNode===t&&r.appendChild(o);return r}function Ts(e,t){for(let r of e){let n=[...r.hasAttribute(_e)?[r]:[],...r.querySelectorAll(`[${_e}]`)];for(let o of n)t.contains(o)||o.remove()}}function Ss(e,t,r=document){return!!t?.pagePath&&typeof e?.__veryfrontRenderPage=="function"&&!!r.getElementById("root")}function As(e,t){return t?.pagePath?!1:!!e.getElementById(L)}function Cs(e=import.meta.url){try{return new URL(e,"http://veryfront.local").searchParams.get("hydrate")==="1"}catch{return!1}}function bs(e){return e==="rsc-module"}function Os(e,t){return e?e.startsWith("?")?e:`?${e}`:""}function Is(e,t,r){return X({strategy:t,rel:e,releaseAssetModules:r?.releaseAssetModules,dependencyPinningCacheKey:r?.dependencyPinningCacheKey})}async function Ns(e,t){try{let r=await fetch(P+"stream"+e,{headers:U(t)});if(!r.ok)return await N(r)?"snapshot-conflict":"failure";if(!r.body)return"failure";let n=new AbortController;return addEventListener("pagehide",()=>n.abort(),{once:!0}),await ut(r,document,n.signal),"success"}catch(r){return g.debug("tryStream failed",r),"failure"}}async function re(){try{await yt(document)}catch(e){g.debug("hydration failed",e)}}async function Ds(e,t,r){try{let{React:n,ReactDOM:o}=await Es(),i=Is(e,t,r);if(!i)return!1;g.debug("Loading component from:",i);let a;try{a=await import(i)}catch(R){throw await te(i),R}let c=a.default;if(typeof c!="function")return g.debug("Page component is not a function"),!1;let u=Array.from(document.body.children),l=hs(u,document.body),d=_s(l,document.body)?xs(u,document.body):l;Ts(u,d);let f=await ee(n.createElement(c,{}),r);return bs(t)?o.createRoot(d).render(f):o.hydrateRoot(d,f,{identifierPrefix:"vf",onRecoverableError:()=>{}}),g.debug("Page component hydrated successfully"),!0}catch(n){return g.error("Page hydration failed",n),!1}}async function ws(e,t){try{let r=await fetch(P+"payload"+e,{headers:U(t)});if(!r.ok)return await N(r)?"snapshot-conflict":"failure";let n=await r.json();if(Y(document,n?.dependencyPinningCacheKey),n?.slots){for(let[o,i]of Object.entries(n.slots))k(document,o).innerHTML=v(String(i||""));return"success"}return k(document,L).innerHTML=v(String(n?.html||"")),"success"}catch(r){return g.debug("payload fetch failed",r),"failure"}}async function Ms(){try{let e=b(document),t=Os(globalThis.window?.location.search??"",e?.dependencyPinningCacheKey);if(Cs()){await re();return}let r=e?.pagePath,n=W(e);if(r){if(Ss(globalThis.window,e,document)){g.debug("Page renderer owns hydration");return}g.debug("Found page component in hydration data:",r),await Ds(r,n,e)&&g.debug("Client component hydrated successfully");return}if(!As(document,e))return;let o=await Ns(t,e);if(o==="snapshot-conflict")return;if(o==="success"){await re();return}let i=await ws(t,e);if(i==="snapshot-conflict")return;if(i==="success"){await re();return}await re()}catch(e){g.error("boot failed",e)}}if(typeof document<"u"){let e=()=>{Ms()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{Ms as boot,Is as buildPageHydrationModuleUrl,Os as buildRSCTransportQuery,Ts as retireAbandonedHeadOwnerMarkers,hs as selectHydrationRoot,As as shouldAttemptRSCTransport,Cs as shouldHydrateOnly,bs as shouldRenderPageComponent,Ss as shouldUsePageRendererHydration,_s as shouldWrapPageHydrationRoot};\n'; + 'var ht=Object.defineProperty;var _t=(e,t,r)=>t in e?ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var E=(e,t,r)=>_t(e,typeof t!="symbol"?t+"":t,r);var Us=Array.prototype.at,Hs=Array.prototype.filter,xt=Array.prototype.join,vs=Array.prototype.map,ks=Array.prototype.pop,Tt=Array.prototype.push,$s=Array.prototype.sort,Ae=Reflect.apply;function G(e,t){return Ae(xt,e,[t])}function w(e,t){Ae(Tt,e,[t])}var St="3.2.3",At=Object.entries;function Ct(e){let t=[];if(e?.external?.length&&w(t,`external=${G(e.external,",")}`),w(t,`target=${e?.target??"es2022"}`),e?.deps){let r=[],n=At(e.deps);for(let o=0;ot||r?.(n,...o)}debug(t,...r){this.log(0,console.debug,`[${this.prefix}] DEBUG: ${t}`,...r)}info(t,...r){this.log(1,console.log,`[${this.prefix}] ${t}`,...r)}warn(t,...r){this.log(2,console.warn,`[${this.prefix}] WARN: ${t}`,...r)}error(t,...r){this.log(3,console.error,`[${this.prefix}] ERROR: ${t}`,...r)}};function $t(){if(typeof window>"u")return 2;let e=globalThis;return e.__VERYFRONT_DEV__||e.__RSC_DEV__?e.__VERYFRONT_DEBUG__||e.__RSC_DEBUG__?0:1:2}var z=$t(),g=new C("RSC",z),gi=new C("PREFETCH",z),fi=new C("HYDRATE",z),pi=new C("VERYFRONT",z);var Vt="veryfront-hydration-data";function ue(e){try{let t=[...e.querySelectorAll(`[id="${Vt}"]`)];if(t.length!==1)return null;let r=e.body;if(!r)return null;let n=t[0];return r.firstElementChild!==n&&n.parentElement!==r||n.tagName?.toLowerCase()!=="script"||n.getAttribute("type")?.trim().toLowerCase()!=="application/json"?null:n}catch{return null}}function b(e=document){try{let t=ue(e);return t?JSON.parse(t.textContent||"{}"):null}catch(t){return g.debug("hydration data parse failed",t),null}}function Y(e,t){if(!t?.startsWith("on:"))return!1;try{let r=ue(e);if(!r)return!1;let n=JSON.parse(r.textContent||"{}");return n.dependencyPinningCacheKey=t,r.textContent=JSON.stringify(n),!0}catch(r){return g.debug("hydration dependency snapshot seed failed",r),!1}}function W(e){return e?.clientModuleStrategy?e.clientModuleStrategy:e?.dev?"fs":"rsc-module"}function Ft(e,t){if(!t)return e;let r=e.includes("?")?"&":"?";return`${e}${r}v=${encodeURIComponent(t)}`}function K(e,t){if(!t?.startsWith("on:"))return e;let r=e.indexOf("#"),n=r===-1?"":e.slice(r),o=r===-1?e:e.slice(0,r),i=o.indexOf("?"),a=i===-1?o:o.slice(0,i),c=new URLSearchParams(i===-1?"":o.slice(i+1));c.set("pins",t);let u=c.toString();return`${a}${u?`?${u}`:""}${n}`}function Gt(e,t){return Ft(`${De}${ae(e)}.js`,t)}function Bt(e,t,r){let n=t?`&v=${encodeURIComponent(t)}`:"";return K(`${P}module?rel=${encodeURIComponent(e)}${n}`,r)}function U(e){let t=e?.dependencyPinningCacheKey;return t?.startsWith("on:")?{[j]:t}:{}}function jt(e){return e.replace(/^\\/+_vf_modules\\//,"").replace(/^\\/+/,"").replace(/\\.js$/,"")}var zt=/\\.(tsx|ts|jsx|mdx|js)$/;function Yt(e){let t=jt(e),r=[e,t];return zt.test(t)||r.push(`${t}.tsx`,`${t}.ts`,`${t}.jsx`,`${t}.mdx`,`${t}.js`),Array.from(new Set(r))}function Wt(e,t){if(!e)return null;for(let r of Yt(t)){let n=e[r];if(n)return n}return null}function X(e){if(e.strategy==="fs"){let r=e.absPath??e.rel;return r?K(Gt(r,e.version),e.dependencyPinningCacheKey):null}let t=Wt(e.releaseAssetModules,e.rel);return t||Bt(e.rel,e.version,e.dependencyPinningCacheKey)}function q(e=document,t=M){let r=ce(e);return{react:B("react",r)?"react":be(t),reactDomClient:B("react-dom/client",r)?"react-dom/client":Oe(t)}}function we(e=document){let t=ce(e);return B("veryfront/router",t)?"veryfront/router":null}var Kt=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function Xt(e,...t){let r=Object.create(null),n=e.charAt(0).toUpperCase()+e.slice(1);for(let o of t)for(let[i,a]of Object.entries(o)){if(typeof a!="object"||a===null||!Object.hasOwn(a,"slug"))throw new Error(`${n} entry "${i}" must define a slug`);let c=a.slug;if(typeof c!="string")throw new Error(`${n} entry "${i}" must define a string slug`);if(c!==i)throw new Error(`${n} key "${i}" does not match entry slug "${c}"`);if(Object.hasOwn(r,i))throw new Error(`Duplicate ${e} slug "${i}"`);r[i]=a}return Object.freeze(r)}function Me(...e){for(let t of e)for(let r of Object.values(t)){if(typeof r.slug!="string"||r.slug.length<3||r.slug.length>40||!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(r.slug))throw new TypeError(`Registered error slug must be 3-40 characters of lowercase kebab-case, got "${r.slug}"`);if(typeof r.category!="string"||!Kt.has(r.category))throw new TypeError(`Registered error has unknown category "${r.category}"`);if(!Number.isInteger(r.status)||r.status<400||r.status>=600)throw new RangeError(`Registered error status must be an integer from 400 through 599, got ${r.status}`);if(typeof r.title!="string"||r.title.trim().length===0)throw new TypeError("Registered error title must be a non-empty string");if(r.suggestion!==void 0&&(typeof r.suggestion!="string"||r.suggestion.trim().length===0))throw new TypeError("Registered error suggestion must be non-empty when provided")}return Xt("error registry",...e)}var J={reset:"\\x1B[0m",dim:"\\x1B[2m",gray:"\\x1B[90m",red:"\\x1B[31m",green:"\\x1B[32m",yellow:"\\x1B[33m",blue:"\\x1B[34m",magenta:"\\x1B[35m",cyan:"\\x1B[36m"},bi={debug:J.gray,info:J.green,warn:J.yellow,error:J.red};var m="[REDACTED]",y=Reflect.apply,qt=Array.prototype.pop,Jt=Array.prototype.push;var Ii=Array.prototype,Ni=BigInt.prototype.toString,ve=Map,Zt=Map.prototype.delete,Qt=Map.prototype.get,er=Map.prototype.keys,tr=Map.prototype.set;var _=Object.getOwnPropertyDescriptor,rr=Object.getPrototypeOf,Di=Object.hasOwn,wi=Object.prototype,nr=Set,or=decodeURIComponent,A=URL,Mi=Number.isFinite,Pi=Number.isInteger,de=RegExp.prototype.exec,sr=_(RegExp.prototype,"global").get,ir=_(RegExp.prototype,"unicode").get,ar=String.prototype.charCodeAt,cr=String.prototype.includes,lr=String.prototype.indexOf,Pe=String.prototype.slice,ke=String.prototype.startsWith,$e=String.prototype.toLowerCase,ur=Set.prototype.add,Li=Set.prototype.delete,dr=Set.prototype.has,gr=rr(new ve().keys()).next,fr=_(Map.prototype,"size").get,Ui=_(A.prototype,"host").get,Hi=_(A.prototype,"origin").get,pr=_(A.prototype,"password").get,vi=_(A.prototype,"pathname").get,ki=_(A.prototype,"protocol").get,yr=_(A.prototype,"username").get,mr=/[^a-z0-9]/g,Er=/([a-z0-9])([A-Z])/g,Rr=/([A-Z])([A-Z][a-z])/g,hr=/\\b(?:sk-[A-Za-z0-9._-]{8,}|gh[po]_[A-Za-z0-9._-]{8,}|xox[baprs]-[A-Za-z0-9._-]{8,}|eyJ[A-Za-z0-9._-]{8,})\\b/g;function h(e,t,r){let n=y(sr,t,[]),o=y(ir,t,[]),i=0,a=!1,c="";t.lastIndex=0;try{for(;;){let u=y(de,t,[e]);if(u===null)break;let l=u[0],d=u.index;if(c+=S(e,i,d),c+=typeof r=="string"?r:r(u),i=d+l.length,a=!0,!n)break;l.length===0&&(t.lastIndex=_r(e,d,o))}}finally{t.lastIndex=0}return a?c+S(e,i):e}function ge(e){let t=y($e,e,[]);return h(t,mr,"")}function O(e,t){return y(ar,e,[t])}function _r(e,t,r){let n=t+1;if(!r||n>=e.length)return n;let o=O(e,t);if(o<55296||o>56319)return n;let i=O(e,n);return i>=56320&&i<=57343?t+2:n}function S(e,t,r){return r===void 0?y(Pe,e,[t]):y(Pe,e,[t,r])}function xr(e){let t=[],r=0;for(let n=0;n<=e.length;n++){let o=n===e.length?-1:O(e,n);o>=97&&o<=122||o>=48&&o<=57||(n>r&&(t[t.length]=S(e,r,n)),r=n+1)}return t}var Z=["password","passwd","pwd","passphrase","secret","clientsecret","token","apikey","accesskey","privatekey","credential","authheader","authorization","cookie","bearer","jwt","connectionstring","signature","sessionid","sid","otp","mfa","pin","salt","xsrf","csrf"],Tr=512,Sr=128,H=new ve;var Ar=256;function Cr(e){let t=e.length<=Sr;if(t){let o=y(Qt,H,[e]);if(o!==void 0)return o}let r=ge(e),n=r==="auth";for(let o=0;!n&&o=Tr){let i=y(er,H,[]),a=y(gr,i,[]).value;a!==void 0&&y(Zt,H,[a])}y(tr,H,[e,n])}return n}var Le=["access_token","accesstoken","refresh_token","api_key","apikey","code","token","secret","client_secret","password","passwd","pwd","state","sig","signature","auth","x-amz-credential","x-amz-signature","x-amz-security-token","x-goog-credential","x-goog-signature"],Ve=new nr;for(let e=0;e=65&&t<=90||t>=97&&t<=122}function Fe(e){return Dr(e)||e==="_"||e==="$"}function wr(e){if(!e)return!1;let t=O(e,0);return Fe(e)||t>=48&&t<=57||e==="."||e==="-"}function Ge(e,t){let r=t,n=e[r]===\'"\'||e[r]==="\'"?e[r++]:"";if(!Fe(e[r]))return!1;for(r++;wr(e[r]);)r++;if(n){if(e[r]!==n)return!1;r++}for(;e[r]===" "||e[r]==="\t";)r++;return e[r]===":"||e[r]==="="}function Be(e){return e==="\\r"||e===`\n`||e==="}"||e==="]"||Nr(e)}function je(e,t){let r=t;for(;r=e.length||Ge(e,r)}function Mr(e,t){let r=t,n=!0;if(y(ke,e,[m,t])){let d=t+m.length;if(Ue(e,d))return{end:d,replacement:m};r=d,n=!1}let o=n&&(e[r]===\'"\'||e[r]==="\'"||e[r]==="`")?e[r]:"",i=!1,a=()=>o?`${o}${m}${i?o:""}`:m,c=[],u="",l=-1;for(let d=r;d0&&(f==="}"||f==="]")){if(c[c.length-1]!==f)return{end:e.length,replacement:a()};if(y(qt,c,[]),d++,c.length===0&&Ue(e,d))return{end:d,replacement:a()};continue}if(c.length>0||!Be(f)){d++;continue}let R=d;if(d=je(e,d),d>=e.length||Ge(e,d))return{end:R,replacement:a()}}return{end:e.length,replacement:a()}}function He(e,t,r,n){let o=0,i="";for(let a=y(de,t,[e]);a;a=y(de,t,[e])){let c=a[r];if(!Pr(c))continue;let u=t.lastIndex,l=n===void 0?void 0:a[n],d=u+m.length;if((l==="?"||l==="&"||l===";")&&y(ke,e,[m,u])&&e[d]==="#")continue;let f=Mr(e,u);i+=S(e,o,a.index),i+=a[0],i+=f.replacement,o=f.end,t.lastIndex=f.end}return o===0?e:i+S(e,o)}function Pr(e){if(e.length>Ar)return!0;let t=h(e,Rr,i=>`${i[1]} ${i[2]}`),r=h(t,Er,i=>`${i[1]} ${i[2]}`),n=y($e,r,[]),o=xr(n);for(let i=0;i{let n=r[1],o=r[2],i=y(lr,o,[":"]);if(i===-1)return`${n}${m}@`;let a=S(o,0,i);return`${n}${a}:${m}@`});return t=h(t,Or,r=>{let n=r[1],o=r[2],i=r[3];return Lr(n,o,i)?r[0]:`${n}${o}:${m}@`}),t=h(t,/([?#&;])([-a-z0-9_.%\\[\\]]+)=([^&#;\\s]*)/gi,r=>{let n=r[1],o=r[2],i=Ur(o);return y(dr,Ve,[ge(i)])||Cr(i)?`${n}${o}=${m}`:r[0]}),t=h(t,/(^|[^a-z0-9_-])((?:set-cookie|cookie)\\s*:\\s*)[^\\r\\n]*/gi,r=>`${r[1]}${r[2]}${m}`),t=h(t,/\\b(authorization\\s*[:=]\\s*)[^\\r\\n]*/gi,r=>`${r[1]}${m}`),t=h(t,/\\b(bearer|basic)(\\s+)(?:"[^"\\r\\n]*"|\'[^\'\\r\\n]*\'|[a-z0-9._~+/=-]+)/gi,r=>`${r[1]}${r[2]}${m}`),t=h(t,hr,m),t=He(t,/(["\'])([_$a-z][a-z0-9_.$-]*)\\1(\\s*[:=]\\s*)/gi,2),t=He(t,/(^|[^a-z0-9_.$-])([_$a-z][a-z0-9_.$-]*)(\\s*[:=]\\s*)/gi,2,1),t}var Hr=2048;var Bi=64*1024,vr=256,kr="https://veryfront.com/docs/errors/",ze="...[truncated]",pe="unknown-error";function Ye(e,t){if(e.length<=t)return e;let r=Math.max(0,t-ze.length);return`${$r(e,r)}${ze}`}function $r(e,t){let r=e.slice(0,t),n=r.charCodeAt(r.length-1);return n>=55296&&n<=56319&&(r=r.slice(0,-1)),r}function Vr(e){let t="";for(let r=0;r=55296&&n<=56319){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=e.slice(r,r+2),r++):t+="\\uFFFD";continue}t+=n>=56320&&n<=57343?"\\uFFFD":e.charAt(r)}return t}function I(e){return typeof e!="string"?m:Ye(fe(e),Hr)}function Fr(e){let t=typeof e=="string"?fe(e):pe,r=Ye(t||pe,vr),n=Vr(r);return n==="."||n===".."?pe:n}function Q(e){let t=encodeURIComponent(Fr(e));return`${kr}${t}`}var Xe=Reflect.apply,Gr=Object.freeze,Br=Object.getOwnPropertyDescriptors,We=Number.isFinite,qe=new WeakSet,jr=WeakSet.prototype.add,zr=WeakSet.prototype.has,Yr=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function s(e){let t={...e},r={...t,create(n){let o=n?.message,i=n?.detail,a=n?.cause,c=n?.instance,u=n?.context,l=n?.status??t.status;return new ye(o||i||t.title,{slug:t.slug,category:t.category,status:l,title:t.title,suggestion:t.suggestion,exitCode:t.exitCode,detail:i,cause:a,instance:c,context:u})}};return Gr(r)}var ye=class extends Error{constructor(r,n){super(r);E(this,"slug");E(this,"category");E(this,"status");E(this,"title");E(this,"suggestion");E(this,"exitCode");E(this,"detail");E(this,"cause");E(this,"instance");E(this,"context");Xe(jr,qe,[this]),this.name="VeryfrontError",this.slug=n.slug,this.category=n.category,this.status=n.status,this.title=n.title,this.suggestion=n.suggestion,this.exitCode=n.exitCode,this.detail=n.detail,this.cause=n.cause,this.instance=n.instance,this.context=n.context}toRFC9457(){let r=Ke(this);return r?{type:Q(r.slug),title:I(r.title),status:r.status,detail:r.detail===void 0?void 0:I(r.detail),instance:r.instance===void 0?void 0:I(r.instance),category:r.category,suggestion:r.suggestion===void 0?void 0:I(r.suggestion),cause:typeof r.cause=="string"?I(r.cause):void 0}:{type:Q("unknown-error"),title:"Unknown/unclassified error",status:500,category:"GENERAL"}}getDocsUrl(){let r=Ke(this);return Q(r?.slug??"unknown-error")}};function Je(e){return typeof e=="object"&&e!==null&&Xe(zr,qe,[e])===!0}function Ke(e){return Je(e)?Wr(e):null}function Wr(e){try{if(!Je(e))return null;let t=Br(e),r=ne=>{let D=t[ne];return D&&"value"in D?D.value:void 0},n=r("slug"),o=r("category"),i=r("status"),a=r("title"),c=r("message"),u=r("suggestion"),l=r("exitCode"),d=r("detail"),f=r("cause"),R=r("instance"),$=r("context"),x=r("stack");return typeof n!="string"||!Yr.has(o)||typeof i!="number"||!We(i)||typeof a!="string"||typeof c!="string"||u!==void 0&&typeof u!="string"||l!==void 0&&(typeof l!="number"||!We(l))||d!==void 0&&typeof d!="string"||R!==void 0&&typeof R!="string"||x!==void 0&&typeof x!="string"?null:{slug:n,category:o,status:i,title:a,message:c,suggestion:u,exitCode:l,detail:d,cause:f,instance:R,context:$,stack:x}}catch{return null}}var Kr=s({slug:"config-not-found",category:"CONFIG",status:404,title:"Configuration file not found",suggestion:"Create veryfront.config.js, veryfront.config.ts, or veryfront.config.mjs in the project root"}),Xr=s({slug:"config-invalid",category:"CONFIG",status:400,title:"Invalid configuration format",suggestion:"Check the reported configuration path and validation details"}),qr=s({slug:"config-parse-error",category:"CONFIG",status:400,title:"Failed to parse configuration",suggestion:"Ensure your configuration file contains valid JavaScript or TypeScript"}),Jr=s({slug:"config-validation-error",category:"CONFIG",status:422,title:"Configuration validation failed",suggestion:"Check the configuration against the schema requirements"}),Zr=s({slug:"config-type-error",category:"CONFIG",status:400,title:"Configuration type mismatch",suggestion:"Ensure configuration values match expected types"}),Qr=s({slug:"import-map-invalid",category:"CONFIG",status:400,title:"Invalid import map configuration",suggestion:"Check your import map syntax and paths"}),en=s({slug:"cors-config-invalid",category:"CONFIG",status:400,title:"Invalid CORS configuration",suggestion:"Review CORS settings in your configuration"}),tn=s({slug:"config-validation-failed",category:"CONFIG",status:400,title:"Configuration validation failed",suggestion:"Check configuration values against requirements"}),rn=s({slug:"webhook-config-invalid",category:"CONFIG",status:400,title:"Invalid webhook configuration",suggestion:"Check webhook definition fields, target settings, and eventFilter conditions"}),nn=s({slug:"schedule-config-invalid",category:"CONFIG",status:400,title:"Invalid schedule configuration",suggestion:"Check schedule definition fields, cron expression, target settings, and positive-integer limits"}),on=s({slug:"trigger-config-invalid",category:"CONFIG",status:400,title:"Invalid trigger configuration",suggestion:"Check trigger ID format (lowercase, alphanumeric, dots/slashes/hyphens) and ensure all input values are JSON-serializable"}),Ze={"config-not-found":Kr,"config-invalid":Xr,"config-parse-error":qr,"config-validation-error":Jr,"config-type-error":Zr,"import-map-invalid":Qr,"cors-config-invalid":en,"config-validation-failed":tn,"webhook-config-invalid":rn,"schedule-config-invalid":nn,"trigger-config-invalid":on};var sn=s({slug:"build-failed",category:"BUILD",status:500,title:"Build process failed",suggestion:"Check the build output for specific errors"}),an=s({slug:"bundle-error",category:"BUILD",status:500,title:"Bundle generation failed",suggestion:"Review bundler output for details"}),cn=s({slug:"typescript-error",category:"BUILD",status:500,title:"TypeScript compilation error",suggestion:"Fix TypeScript errors shown in the output"}),ln=s({slug:"mdx-compile-error",category:"BUILD",status:500,title:"MDX compilation failed",suggestion:"Check your MDX file syntax"}),un=s({slug:"asset-optimization-error",category:"BUILD",status:500,title:"Asset optimization failed",suggestion:"Check asset file formats and paths"}),dn=s({slug:"ssg-generation-error",category:"BUILD",status:500,title:"Static site generation failed",suggestion:"Review SSG configuration and data fetching"}),gn=s({slug:"sourcemap-error",category:"BUILD",status:500,title:"Source map generation failed",suggestion:"Check source map configuration"}),fn=s({slug:"compilation-error",category:"BUILD",status:500,title:"Compilation failed",suggestion:"Review compiler output for specific errors"}),Qe={"build-failed":sn,"bundle-error":an,"typescript-error":cn,"mdx-compile-error":ln,"asset-optimization-error":un,"ssg-generation-error":dn,"sourcemap-error":gn,"compilation-error":fn};var pn=s({slug:"hydration-mismatch",category:"RUNTIME",status:500,title:"Client/server hydration mismatch",suggestion:"Ensure server and client render the same content"}),yn=s({slug:"render-error",category:"RUNTIME",status:500,title:"Component render failed",suggestion:"Check component for runtime errors"}),mn=s({slug:"component-error",category:"RUNTIME",status:500,title:"Component execution error",suggestion:"Review component logic and props"}),En=s({slug:"layout-not-found",category:"RUNTIME",status:404,title:"Layout component not found",suggestion:"Ensure layout file exists at the expected path"}),Rn=s({slug:"page-not-found",category:"RUNTIME",status:404,title:"Page component not found",suggestion:"Check that the page file exists in the routes directory"}),hn=s({slug:"api-error",category:"RUNTIME",status:500,title:"API route handler error",suggestion:"Review API route handler for errors"}),_n=s({slug:"middleware-error",category:"RUNTIME",status:500,title:"Middleware execution error",suggestion:"Check middleware function for errors"}),xn=s({slug:"trigger-target-not-found",category:"RUNTIME",status:404,title:"Trigger target not found",suggestion:"Ensure the referenced task or workflow ID is registered in the project"}),Tn=s({slug:"trigger-execution-failed",category:"RUNTIME",status:500,title:"Trigger target execution failed",suggestion:"Check the task or workflow for errors and review the trigger input"}),Sn=s({slug:"trigger-not-supported",category:"RUNTIME",status:501,title:"Trigger target type not supported in local runtime",suggestion:"Use a workflow or task target for local trigger runs; agent targets require the Cloud runtime"}),et={"hydration-mismatch":pn,"render-error":yn,"component-error":mn,"layout-not-found":En,"page-not-found":Rn,"api-error":hn,"middleware-error":_n,"trigger-target-not-found":xn,"trigger-execution-failed":Tn,"trigger-not-supported":Sn};var An=s({slug:"route-conflict",category:"ROUTE",status:409,title:"Conflicting route definitions",suggestion:"Rename or reorganize conflicting route files"}),Cn=s({slug:"invalid-route-file",category:"ROUTE",status:400,title:"Invalid route file structure",suggestion:"Ensure route file exports required functions"}),bn=s({slug:"route-handler-invalid",category:"ROUTE",status:400,title:"Invalid route handler export",suggestion:"Export a valid handler function from the route file"}),On=s({slug:"dynamic-route-error",category:"ROUTE",status:500,title:"Dynamic route parsing failed",suggestion:"Check dynamic route segment syntax"}),In=s({slug:"route-params-error",category:"ROUTE",status:400,title:"Route parameters invalid",suggestion:"Validate route parameter values"}),Nn=s({slug:"api-route-error",category:"ROUTE",status:500,title:"API route definition error",suggestion:"Review API route configuration"}),tt={"route-conflict":An,"invalid-route-file":Cn,"route-handler-invalid":bn,"dynamic-route-error":On,"route-params-error":In,"api-route-error":Nn};var Dn=s({slug:"module-not-found",category:"MODULE",status:404,title:"Module could not be resolved",suggestion:"Check the import path and ensure the module is installed"}),wn=s({slug:"import-resolution-error",category:"MODULE",status:500,title:"Import path resolution failed",suggestion:"Verify import paths and module configuration"}),Mn=s({slug:"circular-dependency",category:"MODULE",status:500,title:"Circular dependency detected",suggestion:"Refactor imports to break the circular dependency"}),Pn=s({slug:"invalid-import",category:"MODULE",status:400,title:"Invalid import statement",suggestion:"Fix import syntax or path"}),Ln=s({slug:"dependency-missing",category:"MODULE",status:404,title:"Required dependency not installed",suggestion:"Install the missing dependency with your package manager"}),Un=s({slug:"version-mismatch",category:"MODULE",status:409,title:"Dependency version mismatch",suggestion:"Update dependencies to compatible versions"}),Hn=s({slug:"lockfile-format-mismatch",category:"MODULE",status:409,title:"Lockfile format is not supported",suggestion:"Upgrade Veryfront or migrate the lockfile before modifying it"}),vn=s({slug:"lockfile-read-error",category:"MODULE",status:500,title:"Lockfile could not be read safely",suggestion:"Check file access or restore a valid lockfile before retrying"}),rt={"module-not-found":Dn,"import-resolution-error":wn,"circular-dependency":Mn,"invalid-import":Pn,"dependency-missing":Ln,"version-mismatch":Un,"lockfile-format-mismatch":Hn,"lockfile-read-error":vn};var kn=s({slug:"port-in-use",category:"SERVER",status:409,title:"Server port already in use",suggestion:"Use a different port or stop the process using this port"}),$n=s({slug:"server-start-error",category:"SERVER",status:500,title:"Server failed to start",suggestion:"Check server configuration and port availability"}),Vn=s({slug:"cache-error",category:"SERVER",status:500,title:"Cache operation failed",suggestion:"Clear the cache and try again"}),Fn=s({slug:"file-watch-error",category:"SERVER",status:500,title:"File watcher error",suggestion:"Restart the development server"}),Gn=s({slug:"request-error",category:"SERVER",status:500,title:"HTTP request handling error",suggestion:"Check request handler and middleware"}),Bn=s({slug:"service-overloaded",category:"SERVER",status:503,title:"Service overloaded",suggestion:"Reduce load or scale up resources"}),jn=s({slug:"project-execution-unavailable",category:"SERVER",status:503,title:"Project execution unavailable",suggestion:"Route the project to a dedicated isolated runtime"}),zn=s({slug:"semaphore-timeout",category:"SERVER",status:503,title:"Semaphore acquire timeout",suggestion:"Reduce concurrency or increase the semaphore acquire timeout"}),Yn=s({slug:"circuit-breaker-open",category:"SERVER",status:503,title:"Circuit breaker is open",suggestion:"Wait for the breaker reset timeout before retrying"}),Wn=s({slug:"cache-path-mismatch",category:"SERVER",status:500,title:"Cache path mismatch",suggestion:"Clear the cache directory and rebuild"}),Kn=s({slug:"network-error",category:"SERVER",status:502,title:"Network operation failed",suggestion:"Check network connectivity and retry"}),Xn=s({slug:"api-client-error",category:"SERVER",status:500,title:"API client request failed",suggestion:"Check API connectivity and authentication"}),qn=s({slug:"token-storage-error",category:"SERVER",status:500,title:"Token storage operation failed",suggestion:"Check token storage backend and credentials"}),Jn=s({slug:"cache-invariant-violation",category:"SERVER",status:500,title:"Cache path invariant violated",suggestion:"Clear the cache and rebuild"}),Zn=s({slug:"release-not-found",category:"SERVER",status:404,title:"No active release found",suggestion:"Deploy the project to create a release for this environment"}),Qn=s({slug:"fallback-exhausted",category:"SERVER",status:500,title:"Primary and fallback operations both failed",suggestion:"Check service availability and connectivity"}),eo=s({slug:"rag-store-corrupt",category:"SERVER",status:500,title:"RAG store file is corrupt",suggestion:"Repair or move the store file aside, then retry; it was not overwritten"}),to=s({slug:"rag-store-unavailable",category:"SERVER",status:500,title:"RAG store file is unavailable",suggestion:"Check storage availability, permissions, and concurrent operations, then retry"}),nt={"port-in-use":kn,"server-start-error":$n,"cache-error":Vn,"file-watch-error":Fn,"request-error":Gn,"service-overloaded":Bn,"project-execution-unavailable":jn,"semaphore-timeout":zn,"circuit-breaker-open":Yn,"cache-path-mismatch":Wn,"network-error":Kn,"api-client-error":Xn,"token-storage-error":qn,"cache-invariant-violation":Jn,"release-not-found":Zn,"fallback-exhausted":Qn,"rag-store-corrupt":eo,"rag-store-unavailable":to};var ro=s({slug:"client-boundary-violation",category:"BOUNDARY",status:400,title:"Client boundary rule violation",suggestion:"Add \'use client\' directive or move code to a client component"}),no=s({slug:"server-only-in-client",category:"BOUNDARY",status:400,title:"Server-only code in client component",suggestion:"Move server-only code to a server component"}),oo=s({slug:"client-only-in-server",category:"BOUNDARY",status:400,title:"Client-only code in server component",suggestion:"Move client-only code to a client component"}),so=s({slug:"invalid-use-client",category:"BOUNDARY",status:400,title:"Invalid \'use client\' directive",suggestion:"Place \'use client\' at the top of the file"}),io=s({slug:"invalid-use-server",category:"BOUNDARY",status:400,title:"Invalid \'use server\' directive",suggestion:"Place \'use server\' at the top of the file or function"}),ao=s({slug:"rsc-payload-error",category:"BOUNDARY",status:500,title:"RSC payload serialization error",suggestion:"Ensure props are serializable (no functions, symbols, etc.)"}),co=s({slug:"ssr-output-limit-exceeded",category:"BOUNDARY",status:500,title:"SSR output limit exceeded",suggestion:"Reduce the rendered HTML size or split the response into smaller pages"}),ot={"client-boundary-violation":ro,"server-only-in-client":no,"client-only-in-server":oo,"invalid-use-client":so,"invalid-use-server":io,"rsc-payload-error":ao,"ssr-output-limit-exceeded":co};var lo=s({slug:"hmr-error",category:"DEV",status:500,title:"Hot module replacement error",suggestion:"Restart the development server"}),uo=s({slug:"dev-server-error",category:"DEV",status:500,title:"Development server error",suggestion:"Check the dev server logs and restart"}),go=s({slug:"fast-refresh-error",category:"DEV",status:500,title:"Fast refresh failed",suggestion:"Save the file again or restart the dev server"}),fo=s({slug:"error-overlay-error",category:"DEV",status:500,title:"Error overlay failed",suggestion:"Check browser console for details"}),po=s({slug:"source-map-error",category:"DEV",status:500,title:"Source map loading error",suggestion:"Rebuild or clear cache"}),st={"hmr-error":lo,"dev-server-error":uo,"fast-refresh-error":go,"error-overlay-error":fo,"source-map-error":po};var yo=s({slug:"deployment-error",category:"DEPLOY",status:500,title:"Deployment process failed",suggestion:"Check deployment logs for details"}),mo=s({slug:"platform-error",category:"DEPLOY",status:500,title:"Platform-specific error",suggestion:"Check platform documentation and requirements"}),Eo=s({slug:"env-var-missing",category:"DEPLOY",status:500,title:"Required environment variable missing",suggestion:"Set the required environment variable"}),Ro=s({slug:"production-build-required",category:"DEPLOY",status:400,title:"Production build required",suggestion:"Run \'veryfront build\' before deploying"}),ho=s({slug:"environment-not-found",category:"DEPLOY",status:404,title:"Deployment environment not found",suggestion:"Check environment names with: veryfront config"}),_o=s({slug:"release-missing-version",category:"DEPLOY",status:500,title:"Release has no version",suggestion:"Try again or check the build logs in Studio"}),xo=s({slug:"release-build-timeout",category:"DEPLOY",status:408,title:"Release build timed out",suggestion:"Try again or check the build logs in Studio"}),To=s({slug:"deployment-verification-timeout",category:"DEPLOY",status:408,title:"Deployment verification timed out",suggestion:"Try again or check the deployment status in Studio"}),So=s({slug:"push-receipt-missing",category:"DEPLOY",status:400,title:"Push receipt not found",suggestion:"Run: veryfront push --branch main first"}),Ao=s({slug:"source-digest-mismatch",category:"DEPLOY",status:409,title:"Release source digest mismatch",suggestion:"Run veryfront push again to re-upload source files"}),Co=s({slug:"preview-hostname-too-long",category:"DEPLOY",status:400,title:"Preview hostname too long",suggestion:"Use a shorter project slug or branch name"}),bo=s({slug:"branch-not-found",category:"DEPLOY",status:404,title:"Branch not found",suggestion:"List branches in Studio or push a new one with: veryfront push --branch "}),it={"deployment-error":yo,"platform-error":mo,"env-var-missing":Eo,"production-build-required":Ro,"environment-not-found":ho,"release-missing-version":_o,"release-build-timeout":xo,"deployment-verification-timeout":To,"push-receipt-missing":So,"source-digest-mismatch":Ao,"preview-hostname-too-long":Co,"branch-not-found":bo};var Oo=s({slug:"agent-error",category:"AGENT",status:500,title:"Agent operation error",suggestion:"Check agent configuration and logs"}),Io=s({slug:"agent-not-found",category:"AGENT",status:404,title:"Agent not found",suggestion:"Verify the agent ID exists"}),No=s({slug:"agent-timeout",category:"AGENT",status:408,title:"Agent operation timed out",suggestion:"Increase timeout or simplify the request"}),Do=s({slug:"agent-intent-error",category:"AGENT",status:400,title:"Agent intent parsing error",suggestion:"Rephrase the request more clearly"}),wo=s({slug:"orchestration-error",category:"AGENT",status:500,title:"Multi-agent orchestration error",suggestion:"Check agent coordination logic"}),Mo=s({slug:"cost-limit-exceeded",category:"AGENT",status:429,title:"Cost limit exceeded",suggestion:"Wait for the budget period to reset or increase the limit"}),Po=s({slug:"tool-id-conflict",category:"AGENT",status:409,title:"Tool ID conflict",suggestion:"Use a unique tool ID or rename one of the conflicting tools"}),Lo=s({slug:"durable-run-event-persistence-failed",category:"AGENT",status:500,title:"Durable run event persistence failed",suggestion:"Correct invalid or oversized event data, or retry after durable event storage recovers"}),at={"agent-error":Oo,"agent-not-found":Io,"agent-timeout":No,"agent-intent-error":Do,"orchestration-error":wo,"cost-limit-exceeded":Mo,"tool-id-conflict":Po,"durable-run-event-persistence-failed":Lo};var Uo=s({slug:"unknown-error",category:"GENERAL",status:500,title:"Unknown/unclassified error",suggestion:"Check logs for more details"}),Ho=s({slug:"authentication-required",category:"GENERAL",status:401,title:"Authentication required",suggestion:"Set VERYFRONT_API_TOKEN or run \'veryfront login\'"}),vo=s({slug:"permission-denied",category:"GENERAL",status:403,title:"File/resource permission denied",suggestion:"Check file permissions and access rights"}),ko=s({slug:"file-not-found",category:"GENERAL",status:404,title:"File not found",suggestion:"Verify the file path exists"}),$o=s({slug:"resource-not-found",category:"GENERAL",status:404,title:"Requested resource not found",suggestion:"Verify the referenced resource ID or name exists"}),Vo=s({slug:"invalid-argument",category:"GENERAL",status:400,title:"Invalid function argument",suggestion:"Check argument types and values",exitCode:2}),Fo=s({slug:"timeout-error",category:"GENERAL",status:408,title:"Operation timed out",suggestion:"Increase timeout or optimize the operation"}),Go=s({slug:"initialization-error",category:"GENERAL",status:500,title:"Initialization failed",suggestion:"Check initialization requirements and dependencies"}),Bo=s({slug:"not-supported",category:"GENERAL",status:501,title:"Feature not supported",suggestion:"Check documentation for supported features"}),me=s({slug:"security-violation",category:"GENERAL",status:403,title:"Security violation detected",suggestion:"Check for path traversal or unauthorized access attempts"}),jo=s({slug:"input-validation-failed",category:"GENERAL",status:400,title:"Input validation failed",suggestion:"Check request input against validation rules"}),zo=s({slug:"project-source-empty",category:"GENERAL",status:400,title:"Project source is empty",suggestion:"Add project files or run \'veryfront init\'"}),Yo=s({slug:"nested-cwd-scope",category:"GENERAL",status:500,title:"Working directory scope nested inside another",suggestion:"Do the inner work directly in the outer scope\'s callback instead of opening a second one"}),ct={"unknown-error":Uo,"authentication-required":Ho,"permission-denied":vo,"file-not-found":ko,"resource-not-found":$o,"invalid-argument":Vo,"timeout-error":Fo,"initialization-error":Go,"not-supported":Bo,"security-violation":me,"input-validation-failed":jo,"project-source-empty":zo,"nested-cwd-scope":Yo};var wa=Me(Ze,Qe,et,tt,rt,nt,ot,st,it,at,ct);var Wo=[{source:String.raw`]*>[\\s\\S]*?<\\/script>`,flags:"gi",name:"inline script"},{source:String.raw`javascript:`,flags:"gi",name:"javascript: URL"},{source:String.raw`\\bon\\w+\\s*=`,flags:"gi",name:"event handler attribute"},{source:String.raw`data:\\s*text\\/html`,flags:"gi",name:"data: HTML URL"}];function Ko(){return Wo.map(({source:e,flags:t,name:r})=>({pattern:new RegExp(e,t),name:r}))}function Xo(){let e=globalThis;return e.__VERYFRONT_DEV__===!0||e.Deno?.env?.get?.("VERYFRONT_ENV")==="development"}function v(e,t={}){let{allowInlineScripts:r=!1,strict:n=!1,warn:o=!0}=t;for(let{pattern:i,name:a}of Ko())if(!(r&&a==="inline script")&&(i.lastIndex=0,!!i.test(e)&&(o&&console.warn(`[Security] Suspicious ${a} detected in server HTML`),n||!Xo())))throw me.create({detail:`Potentially unsafe HTML: ${a} detected`});return e}function k(e,t){let r=t==="root"?L:`rsc-slot-${t}`,n=e.getElementById(r);if(n)return n;let o=e.createElement("div");return o.id=r,e.body.appendChild(o),o}function qo(e,t){if(t.type!=="slot")return;let r=k(e,t.id);r.innerHTML=v(String(t.html??""))}function lt(e,t){let r=t.split(`\n`),n=r.pop()??"";for(let o of r){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch(u){g.debug("[client-dom] malformed NDJSON line",{line:i,error:u instanceof Error?u.message:String(u)});continue}if(!a||typeof a!="object")continue;let c=a;if(c.type==="slot"){qo(e,c);try{Qo(e,c.id||"root")}catch(u){g.debug("[client-dom] hydration optional failed",u)}}}return n}function Jo(e){return new Promise((t,r)=>{let n=()=>r(new DOMException("aborted","AbortError"));if(e.aborted){n();return}e.addEventListener("abort",n,{once:!0})})}async function ut(e,t=document,r){let n="body"in e?e:null,o=n?.body??e;if(!o)return;n&&Y(t,n.headers.get(j));let i=o.getReader(),a=new TextDecoder,c="",u=!1;try{for(;;){if(r?.aborted)throw new DOMException("aborted","AbortError");let l=i.read(),{done:d,value:f}=r?await Promise.race([l,Jo(r)]):await l;if(d){u=!0;break}c+=a.decode(f,{stream:!0}),c=lt(t,c)}c&<(t,`${c}\n`)}catch(l){throw l instanceof Error&&l.name==="AbortError"||g.debug("[client-dom] consumeNdjsonStream error",l),l}finally{try{await i.cancel()}catch(l){u||g.debug("[client-dom] reader.cancel failed",l)}try{i.releaseLock()}catch(l){g.debug("[client-dom] reader.releaseLock failed",l)}if(typeof o.cancel=="function")try{await o.cancel()}catch(l){g.debug("[client-dom] stream.cancel failed",l)}if(typeof n?.body?.cancel=="function")try{await n.body.cancel()}catch(l){g.debug("[client-dom] response.body.cancel failed",l)}}}function Zo(e,t){let r=k(e,t),n=[],o=i=>{let a=i;a.dataset?.clientRef&&n.push(a);for(let c of i.children)o(c)};return o(r),n}function Qo(e,t){let r=Zo(e,t);for(let n of r){let o=n.dataset?.clientRef;o&&(n.dataset.hydrated="true",g.debug("[client-dom] marked for hydration",o))}}var es=new Set(["server","client","html","fragment"]);function dt(e){if(!e)return[];try{let t=JSON.parse(e);return rs(t)?t.nodes:[]}catch{return[]}}async function Re(e,t,r){return await Promise.all(e.map(n=>ts(n,t,r)))}async function ts(e,t,r){if(e.type==="html")return e.text??e.html??"";let n=await Re(e.children??[],t,r);if(e.type==="fragment"||e.type==="server"&&!e.component)return t.createElement(t.Fragment,{},...n);if(e.type==="server")return t.createElement(e.component,e.props??{},...n);let o=await r(e.component);return o?t.createElement(o,e.props??{},...n):null}function rs(e){return!Ee(e)||e.version!==1||!Array.isArray(e.nodes)?!1:e.nodes.every(t=>gt(t,0))}function gt(e,t){return t>100||!Ee(e)||!es.has(e.type)||e.type==="html"&&typeof e.html!="string"&&typeof e.text!="string"||e.type==="client"&&typeof e.component!="string"||e.type==="server"&&e.component!==void 0&&typeof e.component!="string"||e.props!==void 0&&!Ee(e.props)?!1:e.children===void 0?!0:Array.isArray(e.children)&&e.children.every(r=>gt(r,t+1))}function Ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ns(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e))t[r]=Array.isArray(n)?n.join("/"):n;return t}async function ee(e,t,r=document){try{let n=we(r);if(!n)return e;let i=(await import(n)).wrapForHydration;return typeof i!="function"?e:i(e,{params:ns(t?.params),frontmatter:t?.frontmatter??{},data:t?.props??{}})}catch(n){return g.debug("router provider wrap failed",n),e}}var os="Unknown dependency snapshot",ss="export default null; // Unknown dependency snapshot",he="__VF_DEPENDENCY_SNAPSHOT_RECOVERY_STARTED__";function is(){return globalThis}async function as(e){if(e.status!==409)return!1;try{let t=(await e.clone().text()).trim();return t===os||t===ss}catch{return!1}}async function N(e,t=()=>globalThis.location.reload()){if(!await as(e))return!1;let r=is();if(r[he])return!0;r[he]=!0;try{t()}catch{return delete r[he],!1}return!0}async function te(e,t=globalThis.fetch,r=()=>globalThis.location.reload()){try{let n=new URL(e,"http://veryfront.local").searchParams.getAll("pins");if(n.length!==1||!n[0]?.startsWith("on:"))return!1;let o=await t(e,{cache:"no-store"});return await N(o,r)}catch{return!1}}var cs=100;function ls(e,t){if(globalThis.__VF_CLIENT_MOD_CACHE??(globalThis.__VF_CLIENT_MOD_CACHE=new Map),globalThis.__VF_CLIENT_MOD_CACHE.size>=cs){let r=globalThis.__VF_CLIENT_MOD_CACHE.keys().next().value;r&&globalThis.__VF_CLIENT_MOD_CACHE.delete(r)}globalThis.__VF_CLIENT_MOD_CACHE.set(e,t)}function ft(e){let t=e.match(/^\\/app\\/(.+)#([\\w$.-]+)$/);if(t)return{rel:`/${t[1]||""}`,exportName:t[2]||"default"};let r=e.match(/^(\\/_veryfront\\/[^#]+)#([\\w$.-]+)$/);return r?{moduleUrl:r[1],exportName:r[2]||"default"}:(g.debug("hydrate: unrecognised client ref format, skipping",{ref:e}),null)}function us(e){let t=e.dataset?.rscProps;if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch(r){return g.debug("hydrate: invalid client boundary props, using empty props",r),{}}}function ds(e){return dt(e.dataset?.rscChildren)}function gs(e){return"/_veryfront/rsc/manifest"}function fs(e){return U(e)}async function ps(e=document){try{let t=b(e),r=await fetch(gs(t),{headers:fs(t)});return r.ok?await r.json():(await N(r),null)}catch{return null}}async function pt(e,t,r,n={}){let o=ys(e,t,r,n.releaseAssetModules),i=t.moduleUrl??t.rel;if(!i)return null;let a=`${i}#${e.hash??""}`;try{let c=globalThis.__VF_CLIENT_MOD_CACHE?.get(a);if(c)return c}catch(c){g.debug("hydrate: cache get failed",c)}if(!o)return null;try{let c=await(n.importModule??(u=>import(u)))(o);try{ls(a,c)}catch(u){g.debug("hydrate: cache set failed",u)}return c}catch(c){return g.debug("hydrate: failed to import module",{moduleUrl:o,error:c}),await(n.recoverSnapshotFailure??te)(o),null}}function ys(e,t,r,n){if(t.moduleUrl)return K(t.moduleUrl,e.dependencyPinningCacheKey);if(!t.rel)return null;let o=e.graphIds?.client.find(i=>i.rel===t.rel)?.path;return X({strategy:r,rel:t.rel,absPath:o,version:e.hash,dependencyPinningCacheKey:e.dependencyPinningCacheKey,releaseAssetModules:n})}function ms(e){let t=Array.from(e.querySelectorAll("[data-client-ref]")),r=new Set(t);return t.filter(n=>{let o=n.parentElement;for(;o;){if(r.has(o))return!1;o=o.parentElement}return!0})}async function yt(e=document){let t=null;try{t=await ps(e)}catch(l){g.debug("hydrate: fetch manifest failed",l)}if(!t){g.debug("hydrate: no manifest");return}let r=ms(e);try{let l=globalThis.__VF_MANIFEST_HASH;if(!r.some(f=>f.dataset?.hydrated!=="true")&&l&&t.hash&&l===t.hash)return}catch(l){g.debug("hydrate: hmr hash read failed",l)}if(r.length===0){try{globalThis.__VF_MANIFEST_HASH=t.hash??""}catch(l){g.debug("hydrate: set hash failed",l)}return}let n=b(e),o=W(n),i=n?.releaseAssetModules;try{if(globalThis.__VF_TEST_MODE__){globalThis.__VF_HYDRATE_CALLED=!0,globalThis.__VF_MANIFEST_HASH=t.hash??"";return}}catch(l){g.debug("hydrate: test mode flags failed",l)}let a=q(e,n?.reactVersion),[{default:c},{createRoot:u}]=await Promise.all([import(a.react),import(a.reactDomClient)]);for(let l of r){let d=l.dataset?.clientRef??"";if(!d||l.dataset?.hydrated==="true")continue;let f=ft(d);if(!f)continue;let R=await pt(t,f,o,{releaseAssetModules:i});if(!R)continue;let $=R[f.exportName]??R.default;if(typeof $=="function")try{let x=u(l),ne=us(l),D=ds(l),mt=await Re(D,{Fragment:c.Fragment,createElement(V,oe,...F){return c.createElement(V,oe,...F)}},async V=>{let oe=t.modules.find(Rt=>Rt.id===V),F=t.components?.[V],Te=oe?.clientRef??(F?`${F}#default`:void 0);if(!Te)return null;let se=ft(Te);if(!se)return null;let ie=await pt(t,se,o,{releaseAssetModules:i});if(!ie)return null;let Se=ie[se.exportName]??ie.default;return typeof Se=="function"?Se:null}),Et=await ee(c.createElement($,ne,...mt),n,e);x.render(Et),l.dataset.hydrated="true"}catch(x){g.warn("hydrate: render failed",x)}}try{globalThis.__VF_MANIFEST_HASH=t.hash??""}catch(l){g.debug("hydrate: set hash failed (post)",l)}}var _e="data-vf-react-head-owner";var Es=2*1024*1024,lc=Es*2;var uc=64*1024,dc=1024*1024,gc=1024*1024;var fc=new TextEncoder;async function Rs(){let e=b(document),t=q(document,e?.reactVersion),[r,n]=await Promise.all([import(t.react),import(t.reactDomClient)]);return{React:r,ReactDOM:n}}var hs=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE"]);function xe(e){let t=e.getAttribute("style")??"";return e.hasAttribute("data-veryfront-head")||e.hasAttribute("hidden")||/(?:^|;)\\s*display\\s*:\\s*none(?:\\s*;|$)/i.test(t)||hs.has(e.tagName.toUpperCase())}function _s(e,t){return e.find(r=>r.tagName.toUpperCase()==="DIV"&&!!r.getAttribute("class")?.trim()&&!xe(r))??t}function xs(e,t){return e===t}function Ts(e,t){let r=document.createElement("div");r.setAttribute("data-veryfront-hydration-root","page");let n=e.find(o=>!xe(o));n?.parentNode===t?t.insertBefore(r,n):t.appendChild(r);for(let o of e)!xe(o)&&o.parentNode===t&&r.appendChild(o);return r}function Ss(e,t){for(let r of e){let n=[...r.hasAttribute(_e)?[r]:[],...r.querySelectorAll(`[${_e}]`)];for(let o of n)t.contains(o)||o.remove()}}function As(e,t,r=document){return!!t?.pagePath&&typeof e?.__veryfrontRenderPage=="function"&&!!r.getElementById("root")}function Cs(e,t){return t?.pagePath?!1:!!e.getElementById(L)}function bs(e=import.meta.url){try{return new URL(e,"http://veryfront.local").searchParams.get("hydrate")==="1"}catch{return!1}}function Os(e){return e==="rsc-module"}function Is(e,t){return e?e.startsWith("?")?e:`?${e}`:""}function Ns(e,t,r){return X({strategy:t,rel:e,releaseAssetModules:r?.releaseAssetModules,dependencyPinningCacheKey:r?.dependencyPinningCacheKey})}async function Ds(e,t){try{let r=await fetch(P+"stream"+e,{headers:U(t)});if(!r.ok)return await N(r)?"snapshot-conflict":"failure";if(!r.body)return"failure";let n=new AbortController;return addEventListener("pagehide",()=>n.abort(),{once:!0}),await ut(r,document,n.signal),"success"}catch(r){return g.debug("tryStream failed",r),"failure"}}async function re(){try{await yt(document)}catch(e){g.debug("hydration failed",e)}}async function ws(e,t,r){try{let{React:n,ReactDOM:o}=await Rs(),i=Ns(e,t,r);if(!i)return!1;g.debug("Loading component from:",i);let a;try{a=await import(i)}catch(R){throw await te(i),R}let c=a.default;if(typeof c!="function")return g.debug("Page component is not a function"),!1;let u=Array.from(document.body.children),l=_s(u,document.body),d=xs(l,document.body)?Ts(u,document.body):l;Ss(u,d);let f=await ee(n.createElement(c,{}),r);return Os(t)?o.createRoot(d).render(f):o.hydrateRoot(d,f,{identifierPrefix:"vf",onRecoverableError:()=>{}}),g.debug("Page component hydrated successfully"),!0}catch(n){return g.error("Page hydration failed",n),!1}}async function Ms(e,t){try{let r=await fetch(P+"payload"+e,{headers:U(t)});if(!r.ok)return await N(r)?"snapshot-conflict":"failure";let n=await r.json();if(Y(document,n?.dependencyPinningCacheKey),n?.slots){for(let[o,i]of Object.entries(n.slots))k(document,o).innerHTML=v(String(i||""));return"success"}return k(document,L).innerHTML=v(String(n?.html||"")),"success"}catch(r){return g.debug("payload fetch failed",r),"failure"}}async function Ps(){try{let e=b(document),t=Is(globalThis.window?.location.search??"",e?.dependencyPinningCacheKey);if(bs()){await re();return}let r=e?.pagePath,n=W(e);if(r){if(As(globalThis.window,e,document)){g.debug("Page renderer owns hydration");return}g.debug("Found page component in hydration data:",r),await ws(r,n,e)&&g.debug("Client component hydrated successfully");return}if(!Cs(document,e))return;let o=await Ds(t,e);if(o==="snapshot-conflict")return;if(o==="success"){await re();return}let i=await Ms(t,e);if(i==="snapshot-conflict")return;if(i==="success"){await re();return}await re()}catch(e){g.error("boot failed",e)}}if(typeof document<"u"){let e=()=>{Ps()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{Ps as boot,Ns as buildPageHydrationModuleUrl,Is as buildRSCTransportQuery,Ss as retireAbandonedHeadOwnerMarkers,_s as selectHydrationRoot,Cs as shouldAttemptRSCTransport,bs as shouldHydrateOnly,Os as shouldRenderPageComponent,As as shouldUsePageRendererHydration,xs as shouldWrapPageHydrationRoot};\n'; export const CLIENT_DOM_BUNDLE: string = - 'var Nt=Object.defineProperty;var bt=(e,r,t)=>r in e?Nt(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var m=(e,r,t)=>bt(e,typeof r!="symbol"?r+"":r,t);var Dt=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function Ut(e,...r){let t=Object.create(null),n=e.charAt(0).toUpperCase()+e.slice(1);for(let s of r)for(let[i,a]of Object.entries(s)){if(typeof a!="object"||a===null||!Object.hasOwn(a,"slug"))throw new Error(`${n} entry "${i}" must define a slug`);let c=a.slug;if(typeof c!="string")throw new Error(`${n} entry "${i}" must define a string slug`);if(c!==i)throw new Error(`${n} key "${i}" does not match entry slug "${c}"`);if(Object.hasOwn(t,i))throw new Error(`Duplicate ${e} slug "${i}"`);t[i]=a}return Object.freeze(t)}function F(...e){for(let r of e)for(let t of Object.values(r)){if(typeof t.slug!="string"||t.slug.length<3||t.slug.length>40||!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(t.slug))throw new TypeError(`Registered error slug must be 3-40 characters of lowercase kebab-case, got "${t.slug}"`);if(typeof t.category!="string"||!Dt.has(t.category))throw new TypeError(`Registered error has unknown category "${t.category}"`);if(!Number.isInteger(t.status)||t.status<400||t.status>=600)throw new RangeError(`Registered error status must be an integer from 400 through 599, got ${t.status}`);if(typeof t.title!="string"||t.title.trim().length===0)throw new TypeError("Registered error title must be a non-empty string");if(t.suggestion!==void 0&&(typeof t.suggestion!="string"||t.suggestion.trim().length===0))throw new TypeError("Registered error suggestion must be non-empty when provided")}return Ut("error registry",...e)}var C={reset:"\\x1B[0m",dim:"\\x1B[2m",gray:"\\x1B[90m",red:"\\x1B[31m",green:"\\x1B[32m",yellow:"\\x1B[33m",blue:"\\x1B[34m",magenta:"\\x1B[35m",cyan:"\\x1B[36m"},Wn={debug:C.gray,info:C.green,warn:C.yellow,error:C.red};var E="[REDACTED]",p=Reflect.apply,Lt=Array.prototype.pop,wt=Array.prototype.push;var qn=Array.prototype,Xn=BigInt.prototype.toString,B=Map,vt=Map.prototype.delete,Pt=Map.prototype.get,Mt=Map.prototype.keys,kt=Map.prototype.set;var h=Object.getOwnPropertyDescriptor,$t=Object.getPrototypeOf,Jn=Object.hasOwn,Zn=Object.prototype,Vt=Set,Gt=decodeURIComponent,_=URL,Qn=Number.isFinite,to=Number.isInteger,w=RegExp.prototype.exec,Ft=h(RegExp.prototype,"global").get,Ht=h(RegExp.prototype,"unicode").get,jt=String.prototype.charCodeAt,zt=String.prototype.includes,Yt=String.prototype.indexOf,H=String.prototype.slice,W=String.prototype.startsWith,K=String.prototype.toLowerCase,Bt=Set.prototype.add,eo=Set.prototype.delete,Wt=Set.prototype.has,Kt=$t(new B().keys()).next,qt=h(Map.prototype,"size").get,ro=h(_.prototype,"host").get,no=h(_.prototype,"origin").get,Xt=h(_.prototype,"password").get,oo=h(_.prototype,"pathname").get,so=h(_.prototype,"protocol").get,Jt=h(_.prototype,"username").get,Zt=/[^a-z0-9]/g,Qt=/([a-z0-9])([A-Z])/g,te=/([A-Z])([A-Z][a-z])/g,ee=/\\b(?:sk-[A-Za-z0-9._-]{8,}|gh[po]_[A-Za-z0-9._-]{8,}|xox[baprs]-[A-Za-z0-9._-]{8,}|eyJ[A-Za-z0-9._-]{8,})\\b/g;function y(e,r,t){let n=p(Ft,r,[]),s=p(Ht,r,[]),i=0,a=!1,c="";r.lastIndex=0;try{for(;;){let l=p(w,r,[e]);if(l===null)break;let u=l[0],g=l.index;if(c+=x(e,i,g),c+=typeof t=="string"?t:t(l),i=g+u.length,a=!0,!n)break;u.length===0&&(r.lastIndex=re(e,g,s))}}finally{r.lastIndex=0}return a?c+x(e,i):e}function v(e){let r=p(K,e,[]);return y(r,Zt,"")}function S(e,r){return p(jt,e,[r])}function re(e,r,t){let n=r+1;if(!t||n>=e.length)return n;let s=S(e,r);if(s<55296||s>56319)return n;let i=S(e,n);return i>=56320&&i<=57343?r+2:n}function x(e,r,t){return t===void 0?p(H,e,[r]):p(H,e,[r,t])}function ne(e){let r=[],t=0;for(let n=0;n<=e.length;n++){let s=n===e.length?-1:S(e,n);s>=97&&s<=122||s>=48&&s<=57||(n>t&&(r[r.length]=x(e,t,n)),t=n+1)}return r}var N=["password","passwd","pwd","passphrase","secret","clientsecret","token","apikey","accesskey","privatekey","credential","authheader","authorization","cookie","bearer","jwt","connectionstring","signature","sessionid","sid","otp","mfa","pin","salt","xsrf","csrf"],oe=512,se=128,A=new B;var ie=256;function ae(e){let r=e.length<=se;if(r){let s=p(Pt,A,[e]);if(s!==void 0)return s}let t=v(e),n=t==="auth";for(let s=0;!n&&s=oe){let i=p(Mt,A,[]),a=p(Kt,i,[]).value;a!==void 0&&p(vt,A,[a])}p(kt,A,[e,n])}return n}var j=["access_token","accesstoken","refresh_token","api_key","apikey","code","token","secret","client_secret","password","passwd","pwd","state","sig","signature","auth","x-amz-credential","x-amz-signature","x-amz-security-token","x-goog-credential","x-goog-signature"],q=new Vt;for(let e=0;e=65&&r<=90||r>=97&&r<=122}function X(e){return de(e)||e==="_"||e==="$"}function pe(e){if(!e)return!1;let r=S(e,0);return X(e)||r>=48&&r<=57||e==="."||e==="-"}function J(e,r){let t=r,n=e[t]===\'"\'||e[t]==="\'"?e[t++]:"";if(!X(e[t]))return!1;for(t++;pe(e[t]);)t++;if(n){if(e[t]!==n)return!1;t++}for(;e[t]===" "||e[t]==="\t";)t++;return e[t]===":"||e[t]==="="}function Z(e){return e==="\\r"||e===`\n`||e==="}"||e==="]"||ge(e)}function Q(e,r){let t=r;for(;t=e.length||J(e,t)}function fe(e,r){let t=r,n=!0;if(p(W,e,[E,r])){let g=r+E.length;if(z(e,g))return{end:g,replacement:E};t=g,n=!1}let s=n&&(e[t]===\'"\'||e[t]==="\'"||e[t]==="`")?e[t]:"",i=!1,a=()=>s?`${s}${E}${i?s:""}`:E,c=[],l="",u=-1;for(let g=t;g0&&(f==="}"||f==="]")){if(c[c.length-1]!==f)return{end:e.length,replacement:a()};if(p(Lt,c,[]),g++,c.length===0&&z(e,g))return{end:g,replacement:a()};continue}if(c.length>0||!Z(f)){g++;continue}let T=g;if(g=Q(e,g),g>=e.length||J(e,g))return{end:T,replacement:a()}}return{end:e.length,replacement:a()}}function Y(e,r,t,n){let s=0,i="";for(let a=p(w,r,[e]);a;a=p(w,r,[e])){let c=a[t];if(!Ee(c))continue;let l=r.lastIndex,u=n===void 0?void 0:a[n],g=l+E.length;if((u==="?"||u==="&"||u===";")&&p(W,e,[E,l])&&e[g]==="#")continue;let f=fe(e,l);i+=x(e,s,a.index),i+=a[0],i+=f.replacement,s=f.end,r.lastIndex=f.end}return s===0?e:i+x(e,s)}function Ee(e){if(e.length>ie)return!0;let r=y(e,te,i=>`${i[1]} ${i[2]}`),t=y(r,Qt,i=>`${i[1]} ${i[2]}`),n=p(K,t,[]),s=ne(n);for(let i=0;i{let n=t[1],s=t[2],i=p(Yt,s,[":"]);if(i===-1)return`${n}${E}@`;let a=x(s,0,i);return`${n}${a}:${E}@`});return r=y(r,ue,t=>{let n=t[1],s=t[2],i=t[3];return me(n,s,i)?t[0]:`${n}${s}:${E}@`}),r=y(r,/([?#&;])([-a-z0-9_.%\\[\\]]+)=([^&#;\\s]*)/gi,t=>{let n=t[1],s=t[2],i=Re(s);return p(Wt,q,[v(i)])||ae(i)?`${n}${s}=${E}`:t[0]}),r=y(r,/(^|[^a-z0-9_-])((?:set-cookie|cookie)\\s*:\\s*)[^\\r\\n]*/gi,t=>`${t[1]}${t[2]}${E}`),r=y(r,/\\b(authorization\\s*[:=]\\s*)[^\\r\\n]*/gi,t=>`${t[1]}${E}`),r=y(r,/\\b(bearer|basic)(\\s+)(?:"[^"\\r\\n]*"|\'[^\'\\r\\n]*\'|[a-z0-9._~+/=-]+)/gi,t=>`${t[1]}${t[2]}${E}`),r=y(r,ee,E),r=Y(r,/(["\'])([_$a-z][a-z0-9_.$-]*)\\1(\\s*[:=]\\s*)/gi,2),r=Y(r,/(^|[^a-z0-9_.$-])([_$a-z][a-z0-9_.$-]*)(\\s*[:=]\\s*)/gi,2,1),r}var ye=2048;var lo=64*1024,he=256,xe="https://veryfront.com/docs/errors/",tt="...[truncated]",M="unknown-error";function et(e,r){if(e.length<=r)return e;let t=Math.max(0,r-tt.length);return`${_e(e,t)}${tt}`}function _e(e,r){let t=e.slice(0,r),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319&&(t=t.slice(0,-1)),t}function Se(e){let r="";for(let t=0;t=55296&&n<=56319){let s=e.charCodeAt(t+1);s>=56320&&s<=57343?(r+=e.slice(t,t+2),t++):r+="\\uFFFD";continue}r+=n>=56320&&n<=57343?"\\uFFFD":e.charAt(t)}return r}function I(e){return typeof e!="string"?E:et(P(e),ye)}function Ie(e){let r=typeof e=="string"?P(e):M,t=et(r||M,he),n=Se(t);return n==="."||n===".."?M:n}function b(e){let r=encodeURIComponent(Ie(e));return`${xe}${r}`}var ot=Reflect.apply,Oe=Object.freeze,Te=Object.getOwnPropertyDescriptors,rt=Number.isFinite,st=new WeakSet,Ae=WeakSet.prototype.add,Ce=WeakSet.prototype.has,Ne=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function o(e){let r={...e},t={...r,create(n){let s=n?.message,i=n?.detail,a=n?.cause,c=n?.instance,l=n?.context,u=n?.status??r.status;return new k(s||i||r.title,{slug:r.slug,category:r.category,status:u,title:r.title,suggestion:r.suggestion,exitCode:r.exitCode,detail:i,cause:a,instance:c,context:l})}};return Oe(t)}var k=class extends Error{constructor(t,n){super(t);m(this,"slug");m(this,"category");m(this,"status");m(this,"title");m(this,"suggestion");m(this,"exitCode");m(this,"detail");m(this,"cause");m(this,"instance");m(this,"context");ot(Ae,st,[this]),this.name="VeryfrontError",this.slug=n.slug,this.category=n.category,this.status=n.status,this.title=n.title,this.suggestion=n.suggestion,this.exitCode=n.exitCode,this.detail=n.detail,this.cause=n.cause,this.instance=n.instance,this.context=n.context}toRFC9457(){let t=nt(this);return t?{type:b(t.slug),title:I(t.title),status:t.status,detail:t.detail===void 0?void 0:I(t.detail),instance:t.instance===void 0?void 0:I(t.instance),category:t.category,suggestion:t.suggestion===void 0?void 0:I(t.suggestion),cause:typeof t.cause=="string"?I(t.cause):void 0}:{type:b("unknown-error"),title:"Unknown/unclassified error",status:500,category:"GENERAL"}}getDocsUrl(){let t=nt(this);return b(t?.slug??"unknown-error")}};function it(e){return typeof e=="object"&&e!==null&&ot(Ce,st,[e])===!0}function nt(e){return it(e)?be(e):null}function be(e){try{if(!it(e))return null;let r=Te(e),t=Ct=>{let L=r[Ct];return L&&"value"in L?L.value:void 0},n=t("slug"),s=t("category"),i=t("status"),a=t("title"),c=t("message"),l=t("suggestion"),u=t("exitCode"),g=t("detail"),f=t("cause"),T=t("instance"),At=t("context"),U=t("stack");return typeof n!="string"||!Ne.has(s)||typeof i!="number"||!rt(i)||typeof a!="string"||typeof c!="string"||l!==void 0&&typeof l!="string"||u!==void 0&&(typeof u!="number"||!rt(u))||g!==void 0&&typeof g!="string"||T!==void 0&&typeof T!="string"||U!==void 0&&typeof U!="string"?null:{slug:n,category:s,status:i,title:a,message:c,suggestion:l,exitCode:u,detail:g,cause:f,instance:T,context:At,stack:U}}catch{return null}}var De=o({slug:"config-not-found",category:"CONFIG",status:404,title:"Configuration file not found",suggestion:"Create veryfront.config.js, veryfront.config.ts, or veryfront.config.mjs in the project root"}),Ue=o({slug:"config-invalid",category:"CONFIG",status:400,title:"Invalid configuration format",suggestion:"Check the reported configuration path and validation details"}),Le=o({slug:"config-parse-error",category:"CONFIG",status:400,title:"Failed to parse configuration",suggestion:"Ensure your configuration file contains valid JavaScript or TypeScript"}),we=o({slug:"config-validation-error",category:"CONFIG",status:422,title:"Configuration validation failed",suggestion:"Check the configuration against the schema requirements"}),ve=o({slug:"config-type-error",category:"CONFIG",status:400,title:"Configuration type mismatch",suggestion:"Ensure configuration values match expected types"}),Pe=o({slug:"import-map-invalid",category:"CONFIG",status:400,title:"Invalid import map configuration",suggestion:"Check your import map syntax and paths"}),Me=o({slug:"cors-config-invalid",category:"CONFIG",status:400,title:"Invalid CORS configuration",suggestion:"Review CORS settings in your configuration"}),ke=o({slug:"config-validation-failed",category:"CONFIG",status:400,title:"Configuration validation failed",suggestion:"Check configuration values against requirements"}),$e=o({slug:"webhook-config-invalid",category:"CONFIG",status:400,title:"Invalid webhook configuration",suggestion:"Check webhook definition fields, target settings, and eventFilter conditions"}),Ve=o({slug:"schedule-config-invalid",category:"CONFIG",status:400,title:"Invalid schedule configuration",suggestion:"Check schedule definition fields, cron expression, target settings, and positive-integer limits"}),Ge=o({slug:"trigger-config-invalid",category:"CONFIG",status:400,title:"Invalid trigger configuration",suggestion:"Check trigger ID format (lowercase, alphanumeric, dots/slashes/hyphens) and ensure all input values are JSON-serializable"}),at={"config-not-found":De,"config-invalid":Ue,"config-parse-error":Le,"config-validation-error":we,"config-type-error":ve,"import-map-invalid":Pe,"cors-config-invalid":Me,"config-validation-failed":ke,"webhook-config-invalid":$e,"schedule-config-invalid":Ve,"trigger-config-invalid":Ge};var Fe=o({slug:"build-failed",category:"BUILD",status:500,title:"Build process failed",suggestion:"Check the build output for specific errors"}),He=o({slug:"bundle-error",category:"BUILD",status:500,title:"Bundle generation failed",suggestion:"Review bundler output for details"}),je=o({slug:"typescript-error",category:"BUILD",status:500,title:"TypeScript compilation error",suggestion:"Fix TypeScript errors shown in the output"}),ze=o({slug:"mdx-compile-error",category:"BUILD",status:500,title:"MDX compilation failed",suggestion:"Check your MDX file syntax"}),Ye=o({slug:"asset-optimization-error",category:"BUILD",status:500,title:"Asset optimization failed",suggestion:"Check asset file formats and paths"}),Be=o({slug:"ssg-generation-error",category:"BUILD",status:500,title:"Static site generation failed",suggestion:"Review SSG configuration and data fetching"}),We=o({slug:"sourcemap-error",category:"BUILD",status:500,title:"Source map generation failed",suggestion:"Check source map configuration"}),Ke=o({slug:"compilation-error",category:"BUILD",status:500,title:"Compilation failed",suggestion:"Review compiler output for specific errors"}),ct={"build-failed":Fe,"bundle-error":He,"typescript-error":je,"mdx-compile-error":ze,"asset-optimization-error":Ye,"ssg-generation-error":Be,"sourcemap-error":We,"compilation-error":Ke};var qe=o({slug:"hydration-mismatch",category:"RUNTIME",status:500,title:"Client/server hydration mismatch",suggestion:"Ensure server and client render the same content"}),Xe=o({slug:"render-error",category:"RUNTIME",status:500,title:"Component render failed",suggestion:"Check component for runtime errors"}),Je=o({slug:"component-error",category:"RUNTIME",status:500,title:"Component execution error",suggestion:"Review component logic and props"}),Ze=o({slug:"layout-not-found",category:"RUNTIME",status:404,title:"Layout component not found",suggestion:"Ensure layout file exists at the expected path"}),Qe=o({slug:"page-not-found",category:"RUNTIME",status:404,title:"Page component not found",suggestion:"Check that the page file exists in the routes directory"}),tr=o({slug:"api-error",category:"RUNTIME",status:500,title:"API route handler error",suggestion:"Review API route handler for errors"}),er=o({slug:"middleware-error",category:"RUNTIME",status:500,title:"Middleware execution error",suggestion:"Check middleware function for errors"}),rr=o({slug:"trigger-target-not-found",category:"RUNTIME",status:404,title:"Trigger target not found",suggestion:"Ensure the referenced task or workflow ID is registered in the project"}),nr=o({slug:"trigger-execution-failed",category:"RUNTIME",status:500,title:"Trigger target execution failed",suggestion:"Check the task or workflow for errors and review the trigger input"}),or=o({slug:"trigger-not-supported",category:"RUNTIME",status:501,title:"Trigger target type not supported in local runtime",suggestion:"Use a workflow or task target for local trigger runs; agent targets require the Cloud runtime"}),ut={"hydration-mismatch":qe,"render-error":Xe,"component-error":Je,"layout-not-found":Ze,"page-not-found":Qe,"api-error":tr,"middleware-error":er,"trigger-target-not-found":rr,"trigger-execution-failed":nr,"trigger-not-supported":or};var sr=o({slug:"route-conflict",category:"ROUTE",status:409,title:"Conflicting route definitions",suggestion:"Rename or reorganize conflicting route files"}),ir=o({slug:"invalid-route-file",category:"ROUTE",status:400,title:"Invalid route file structure",suggestion:"Ensure route file exports required functions"}),ar=o({slug:"route-handler-invalid",category:"ROUTE",status:400,title:"Invalid route handler export",suggestion:"Export a valid handler function from the route file"}),cr=o({slug:"dynamic-route-error",category:"ROUTE",status:500,title:"Dynamic route parsing failed",suggestion:"Check dynamic route segment syntax"}),ur=o({slug:"route-params-error",category:"ROUTE",status:400,title:"Route parameters invalid",suggestion:"Validate route parameter values"}),lr=o({slug:"api-route-error",category:"ROUTE",status:500,title:"API route definition error",suggestion:"Review API route configuration"}),lt={"route-conflict":sr,"invalid-route-file":ir,"route-handler-invalid":ar,"dynamic-route-error":cr,"route-params-error":ur,"api-route-error":lr};var gr=o({slug:"module-not-found",category:"MODULE",status:404,title:"Module could not be resolved",suggestion:"Check the import path and ensure the module is installed"}),dr=o({slug:"import-resolution-error",category:"MODULE",status:500,title:"Import path resolution failed",suggestion:"Verify import paths and module configuration"}),pr=o({slug:"circular-dependency",category:"MODULE",status:500,title:"Circular dependency detected",suggestion:"Refactor imports to break the circular dependency"}),fr=o({slug:"invalid-import",category:"MODULE",status:400,title:"Invalid import statement",suggestion:"Fix import syntax or path"}),Er=o({slug:"dependency-missing",category:"MODULE",status:404,title:"Required dependency not installed",suggestion:"Install the missing dependency with your package manager"}),mr=o({slug:"version-mismatch",category:"MODULE",status:409,title:"Dependency version mismatch",suggestion:"Update dependencies to compatible versions"}),Rr=o({slug:"lockfile-format-mismatch",category:"MODULE",status:409,title:"Lockfile format is not supported",suggestion:"Upgrade Veryfront or migrate the lockfile before modifying it"}),yr=o({slug:"lockfile-read-error",category:"MODULE",status:500,title:"Lockfile could not be read safely",suggestion:"Check file access or restore a valid lockfile before retrying"}),gt={"module-not-found":gr,"import-resolution-error":dr,"circular-dependency":pr,"invalid-import":fr,"dependency-missing":Er,"version-mismatch":mr,"lockfile-format-mismatch":Rr,"lockfile-read-error":yr};var hr=o({slug:"port-in-use",category:"SERVER",status:409,title:"Server port already in use",suggestion:"Use a different port or stop the process using this port"}),xr=o({slug:"server-start-error",category:"SERVER",status:500,title:"Server failed to start",suggestion:"Check server configuration and port availability"}),_r=o({slug:"cache-error",category:"SERVER",status:500,title:"Cache operation failed",suggestion:"Clear the cache and try again"}),Sr=o({slug:"file-watch-error",category:"SERVER",status:500,title:"File watcher error",suggestion:"Restart the development server"}),Ir=o({slug:"request-error",category:"SERVER",status:500,title:"HTTP request handling error",suggestion:"Check request handler and middleware"}),Or=o({slug:"service-overloaded",category:"SERVER",status:503,title:"Service overloaded",suggestion:"Reduce load or scale up resources"}),Tr=o({slug:"project-execution-unavailable",category:"SERVER",status:503,title:"Project execution unavailable",suggestion:"Route the project to a dedicated isolated runtime"}),Ar=o({slug:"semaphore-timeout",category:"SERVER",status:503,title:"Semaphore acquire timeout",suggestion:"Reduce concurrency or increase the semaphore acquire timeout"}),Cr=o({slug:"circuit-breaker-open",category:"SERVER",status:503,title:"Circuit breaker is open",suggestion:"Wait for the breaker reset timeout before retrying"}),Nr=o({slug:"cache-path-mismatch",category:"SERVER",status:500,title:"Cache path mismatch",suggestion:"Clear the cache directory and rebuild"}),br=o({slug:"network-error",category:"SERVER",status:502,title:"Network operation failed",suggestion:"Check network connectivity and retry"}),Dr=o({slug:"api-client-error",category:"SERVER",status:500,title:"API client request failed",suggestion:"Check API connectivity and authentication"}),Ur=o({slug:"token-storage-error",category:"SERVER",status:500,title:"Token storage operation failed",suggestion:"Check token storage backend and credentials"}),Lr=o({slug:"cache-invariant-violation",category:"SERVER",status:500,title:"Cache path invariant violated",suggestion:"Clear the cache and rebuild"}),wr=o({slug:"release-not-found",category:"SERVER",status:404,title:"No active release found",suggestion:"Deploy the project to create a release for this environment"}),vr=o({slug:"fallback-exhausted",category:"SERVER",status:500,title:"Primary and fallback operations both failed",suggestion:"Check service availability and connectivity"}),Pr=o({slug:"rag-store-corrupt",category:"SERVER",status:500,title:"RAG store file is corrupt",suggestion:"Repair or move the store file aside, then retry; it was not overwritten"}),Mr=o({slug:"rag-store-unavailable",category:"SERVER",status:500,title:"RAG store file is unavailable",suggestion:"Check storage availability, permissions, and concurrent operations, then retry"}),dt={"port-in-use":hr,"server-start-error":xr,"cache-error":_r,"file-watch-error":Sr,"request-error":Ir,"service-overloaded":Or,"project-execution-unavailable":Tr,"semaphore-timeout":Ar,"circuit-breaker-open":Cr,"cache-path-mismatch":Nr,"network-error":br,"api-client-error":Dr,"token-storage-error":Ur,"cache-invariant-violation":Lr,"release-not-found":wr,"fallback-exhausted":vr,"rag-store-corrupt":Pr,"rag-store-unavailable":Mr};var kr=o({slug:"client-boundary-violation",category:"BOUNDARY",status:400,title:"Client boundary rule violation",suggestion:"Add \'use client\' directive or move code to a client component"}),$r=o({slug:"server-only-in-client",category:"BOUNDARY",status:400,title:"Server-only code in client component",suggestion:"Move server-only code to a server component"}),Vr=o({slug:"client-only-in-server",category:"BOUNDARY",status:400,title:"Client-only code in server component",suggestion:"Move client-only code to a client component"}),Gr=o({slug:"invalid-use-client",category:"BOUNDARY",status:400,title:"Invalid \'use client\' directive",suggestion:"Place \'use client\' at the top of the file"}),Fr=o({slug:"invalid-use-server",category:"BOUNDARY",status:400,title:"Invalid \'use server\' directive",suggestion:"Place \'use server\' at the top of the file or function"}),Hr=o({slug:"rsc-payload-error",category:"BOUNDARY",status:500,title:"RSC payload serialization error",suggestion:"Ensure props are serializable (no functions, symbols, etc.)"}),jr=o({slug:"ssr-output-limit-exceeded",category:"BOUNDARY",status:500,title:"SSR output limit exceeded",suggestion:"Reduce the rendered HTML size or split the response into smaller pages"}),pt={"client-boundary-violation":kr,"server-only-in-client":$r,"client-only-in-server":Vr,"invalid-use-client":Gr,"invalid-use-server":Fr,"rsc-payload-error":Hr,"ssr-output-limit-exceeded":jr};var zr=o({slug:"hmr-error",category:"DEV",status:500,title:"Hot module replacement error",suggestion:"Restart the development server"}),Yr=o({slug:"dev-server-error",category:"DEV",status:500,title:"Development server error",suggestion:"Check the dev server logs and restart"}),Br=o({slug:"fast-refresh-error",category:"DEV",status:500,title:"Fast refresh failed",suggestion:"Save the file again or restart the dev server"}),Wr=o({slug:"error-overlay-error",category:"DEV",status:500,title:"Error overlay failed",suggestion:"Check browser console for details"}),Kr=o({slug:"source-map-error",category:"DEV",status:500,title:"Source map loading error",suggestion:"Rebuild or clear cache"}),ft={"hmr-error":zr,"dev-server-error":Yr,"fast-refresh-error":Br,"error-overlay-error":Wr,"source-map-error":Kr};var qr=o({slug:"deployment-error",category:"DEPLOY",status:500,title:"Deployment process failed",suggestion:"Check deployment logs for details"}),Xr=o({slug:"platform-error",category:"DEPLOY",status:500,title:"Platform-specific error",suggestion:"Check platform documentation and requirements"}),Jr=o({slug:"env-var-missing",category:"DEPLOY",status:500,title:"Required environment variable missing",suggestion:"Set the required environment variable"}),Zr=o({slug:"production-build-required",category:"DEPLOY",status:400,title:"Production build required",suggestion:"Run \'veryfront build\' before deploying"}),Qr=o({slug:"environment-not-found",category:"DEPLOY",status:404,title:"Deployment environment not found",suggestion:"Check environment names with: veryfront config"}),tn=o({slug:"release-missing-version",category:"DEPLOY",status:500,title:"Release has no version",suggestion:"Try again or check the build logs in Studio"}),en=o({slug:"release-build-timeout",category:"DEPLOY",status:408,title:"Release build timed out",suggestion:"Try again or check the build logs in Studio"}),rn=o({slug:"deployment-verification-timeout",category:"DEPLOY",status:408,title:"Deployment verification timed out",suggestion:"Try again or check the deployment status in Studio"}),nn=o({slug:"push-receipt-missing",category:"DEPLOY",status:400,title:"Push receipt not found",suggestion:"Run: veryfront push --branch main first"}),on=o({slug:"source-digest-mismatch",category:"DEPLOY",status:409,title:"Release source digest mismatch",suggestion:"Run veryfront push again to re-upload source files"}),sn=o({slug:"preview-hostname-too-long",category:"DEPLOY",status:400,title:"Preview hostname too long",suggestion:"Use a shorter project slug or branch name"}),an=o({slug:"branch-not-found",category:"DEPLOY",status:404,title:"Branch not found",suggestion:"List branches in Studio or push a new one with: veryfront push --branch "}),Et={"deployment-error":qr,"platform-error":Xr,"env-var-missing":Jr,"production-build-required":Zr,"environment-not-found":Qr,"release-missing-version":tn,"release-build-timeout":en,"deployment-verification-timeout":rn,"push-receipt-missing":nn,"source-digest-mismatch":on,"preview-hostname-too-long":sn,"branch-not-found":an};var cn=o({slug:"agent-error",category:"AGENT",status:500,title:"Agent operation error",suggestion:"Check agent configuration and logs"}),un=o({slug:"agent-not-found",category:"AGENT",status:404,title:"Agent not found",suggestion:"Verify the agent ID exists"}),ln=o({slug:"agent-timeout",category:"AGENT",status:408,title:"Agent operation timed out",suggestion:"Increase timeout or simplify the request"}),gn=o({slug:"agent-intent-error",category:"AGENT",status:400,title:"Agent intent parsing error",suggestion:"Rephrase the request more clearly"}),dn=o({slug:"orchestration-error",category:"AGENT",status:500,title:"Multi-agent orchestration error",suggestion:"Check agent coordination logic"}),pn=o({slug:"cost-limit-exceeded",category:"AGENT",status:429,title:"Cost limit exceeded",suggestion:"Wait for the budget period to reset or increase the limit"}),fn=o({slug:"tool-id-conflict",category:"AGENT",status:409,title:"Tool ID conflict",suggestion:"Use a unique tool ID or rename one of the conflicting tools"}),En=o({slug:"durable-run-event-persistence-failed",category:"AGENT",status:500,title:"Durable run event persistence failed",suggestion:"Correct invalid or oversized event data, or retry after durable event storage recovers"}),mt={"agent-error":cn,"agent-not-found":un,"agent-timeout":ln,"agent-intent-error":gn,"orchestration-error":dn,"cost-limit-exceeded":pn,"tool-id-conflict":fn,"durable-run-event-persistence-failed":En};var mn=o({slug:"unknown-error",category:"GENERAL",status:500,title:"Unknown/unclassified error",suggestion:"Check logs for more details"}),Rn=o({slug:"authentication-required",category:"GENERAL",status:401,title:"Authentication required",suggestion:"Set VERYFRONT_API_TOKEN or run \'veryfront login\'"}),yn=o({slug:"permission-denied",category:"GENERAL",status:403,title:"File/resource permission denied",suggestion:"Check file permissions and access rights"}),hn=o({slug:"file-not-found",category:"GENERAL",status:404,title:"File not found",suggestion:"Verify the file path exists"}),xn=o({slug:"resource-not-found",category:"GENERAL",status:404,title:"Requested resource not found",suggestion:"Verify the referenced resource ID or name exists"}),_n=o({slug:"invalid-argument",category:"GENERAL",status:400,title:"Invalid function argument",suggestion:"Check argument types and values",exitCode:2}),Sn=o({slug:"timeout-error",category:"GENERAL",status:408,title:"Operation timed out",suggestion:"Increase timeout or optimize the operation"}),In=o({slug:"initialization-error",category:"GENERAL",status:500,title:"Initialization failed",suggestion:"Check initialization requirements and dependencies"}),On=o({slug:"not-supported",category:"GENERAL",status:501,title:"Feature not supported",suggestion:"Check documentation for supported features"}),$=o({slug:"security-violation",category:"GENERAL",status:403,title:"Security violation detected",suggestion:"Check for path traversal or unauthorized access attempts"}),Tn=o({slug:"input-validation-failed",category:"GENERAL",status:400,title:"Input validation failed",suggestion:"Check request input against validation rules"}),An=o({slug:"project-source-empty",category:"GENERAL",status:400,title:"Project source is empty",suggestion:"Add project files or run \'veryfront init\'"}),Rt={"unknown-error":mn,"authentication-required":Rn,"permission-denied":yn,"file-not-found":hn,"resource-not-found":xn,"invalid-argument":_n,"timeout-error":Sn,"initialization-error":In,"not-supported":On,"security-violation":$,"input-validation-failed":Tn,"project-source-empty":An};var Qo=F(at,ct,ut,lt,gt,dt,pt,ft,Et,mt,Rt);var Cn=[{source:String.raw`]*>[\\s\\S]*?<\\/script>`,flags:"gi",name:"inline script"},{source:String.raw`javascript:`,flags:"gi",name:"javascript: URL"},{source:String.raw`\\bon\\w+\\s*=`,flags:"gi",name:"event handler attribute"},{source:String.raw`data:\\s*text\\/html`,flags:"gi",name:"data: HTML URL"}];function Nn(){return Cn.map(({source:e,flags:r,name:t})=>({pattern:new RegExp(e,r),name:t}))}function bn(){let e=globalThis;return e.__VERYFRONT_DEV__===!0||e.Deno?.env?.get?.("VERYFRONT_ENV")==="development"}function yt(e,r={}){let{allowInlineScripts:t=!1,strict:n=!1,warn:s=!0}=r;for(let{pattern:i,name:a}of Nn())if(!(t&&a==="inline script")&&(i.lastIndex=0,!!i.test(e)&&(s&&console.warn(`[Security] Suspicious ${a} detected in server HTML`),n||!bn())))throw $.create({detail:`Potentially unsafe HTML: ${a} detected`});return e}var O=class{constructor(r,t){m(this,"prefix",r);m(this,"level",t)}log(r,t,n,...s){this.level>r||t?.(n,...s)}debug(r,...t){this.log(0,console.debug,`[${this.prefix}] DEBUG: ${r}`,...t)}info(r,...t){this.log(1,console.log,`[${this.prefix}] ${r}`,...t)}warn(r,...t){this.log(2,console.warn,`[${this.prefix}] WARN: ${r}`,...t)}error(r,...t){this.log(3,console.error,`[${this.prefix}] ERROR: ${r}`,...t)}};function Dn(){if(typeof window>"u")return 2;let e=globalThis;return e.__VERYFRONT_DEV__||e.__RSC_DEV__?e.__VERYFRONT_DEBUG__||e.__RSC_DEBUG__?0:1:2}var D=Dn(),R=new O("RSC",D),fs=new O("PREFETCH",D),Es=new O("HYDRATE",D),ms=new O("VERYFRONT",D);var hs=Object.freeze({IPV4:"127.0.0.1",IPV6:"::1",HOSTNAME:"localhost"});var Un=5e3,Ln=1e4,Ss=16*1024*1024,wn=5e3;var vn=100;var Pn=Object.freeze([5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4]),Is=Object.freeze([1,5,10,25,50,100,250,500,1e3,2500,5e3,1e4]),Os=Object.freeze({server:Object.freeze({port:3e3,hostname:"0.0.0.0"}),timeouts:Object.freeze({default:Un,api:3e4,ssr:Ln,hmr:3e4,sandbox:wn}),cache:Object.freeze({jit:Object.freeze({maxSize:vn,tempDirPrefix:"vf-bundle-"})}),metrics:Object.freeze({ssrBoundaries:Pn})});var d="/_veryfront",V={RSC:`${d}/rsc/`,FS:`${d}/fs/`,MODULES:`${d}/modules/`,PAGES:`${d}/pages/`,DATA:`${d}/data/`,LIB:`${d}/lib/`,CHUNKS:`${d}/chunks/`,CLIENT:`${d}/client/`},xt={HMR_RUNTIME:`${d}/hmr-runtime.js`,HMR:`${d}/hmr.js`,ERROR_OVERLAY:`${d}/error-overlay.js`,DEV_LOADER:`${d}/dev-loader.js`,CLIENT_LOG:`${d}/log`,CLIENT_JS:`${d}/client.js`,ROUTER_JS:`${d}/router.js`,PREFETCH_JS:`${d}/prefetch.js`,MANIFEST_JSON:`${d}/manifest.json`,APP_JS:`${d}/app.js`,RSC_CLIENT:`${d}/rsc/client.js`,RSC_MANIFEST:`${d}/rsc/manifest`,RSC_STREAM:`${d}/rsc/stream`,RSC_PAYLOAD:`${d}/rsc/payload`,RSC_RENDER:`${d}/rsc/render`,RSC_PAGE:`${d}/rsc/page`,RSC_MODULE:`${d}/rsc/module`,RSC_DOM:`${d}/rsc/dom.js`,LIB_CHAT_REACT:`${d}/lib/chat/react.js`,LIB_CHAT_COMPONENTS:`${d}/lib/chat/components.js`,LIB_CHAT_PRIMITIVES:`${d}/lib/chat/primitives.js`};var Mn={ROOT:".veryfront",CACHE:".veryfront/cache",KV:".veryfront/kv",LOGS:".veryfront/logs",TMP:".veryfront/tmp"},As=Mn.CACHE;var Cs={HMR_RUNTIME:xt.HMR_RUNTIME,ERROR_OVERLAY:xt.ERROR_OVERLAY};var kn=V.RSC,$n=V.FS;var _t="rsc-root",G="x-veryfront-dependency-pins";var Ls=Array.prototype.at,ws=Array.prototype.filter,vs=Array.prototype.join,Ps=Array.prototype.map,Ms=Array.prototype.pop,ks=Array.prototype.push,$s=Array.prototype.sort;var Qs=Object.freeze({react:"","react-dom":"","react-dom/client":"","react-dom/server":"","react/jsx-runtime":"","react/jsx-dev-runtime":""});var Gn="veryfront-hydration-data";function St(e){try{let r=[...e.querySelectorAll(`[id="${Gn}"]`)];if(r.length!==1)return null;let t=e.body;if(!t)return null;let n=r[0];return t.firstElementChild!==n&&n.parentElement!==t||n.tagName?.toLowerCase()!=="script"||n.getAttribute("type")?.trim().toLowerCase()!=="application/json"?null:n}catch{return null}}function It(e,r){if(!r?.startsWith("on:"))return!1;try{let t=St(e);if(!t)return!1;let n=JSON.parse(t.textContent||"{}");return n.dependencyPinningCacheKey=r,t.textContent=JSON.stringify(n),!0}catch(t){return R.debug("hydration dependency snapshot seed failed",t),!1}}function Tt(e,r){let t=r==="root"?_t:`rsc-slot-${r}`,n=e.getElementById(t);if(n)return n;let s=e.createElement("div");return s.id=t,e.body.appendChild(s),s}function Fn(e,r){if(r.type!=="slot")return;let t=Tt(e,r.id);t.innerHTML=yt(String(r.html??""))}function Ot(e,r){let t=r.split(`\n`),n=t.pop()??"";for(let s of t){let i=s.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch(l){R.debug("[client-dom] malformed NDJSON line",{line:i,error:l instanceof Error?l.message:String(l)});continue}if(!a||typeof a!="object")continue;let c=a;if(c.type==="slot"){Fn(e,c);try{zn(e,c.id||"root")}catch(l){R.debug("[client-dom] hydration optional failed",l)}}}return n}function Hn(e){return new Promise((r,t)=>{let n=()=>t(new DOMException("aborted","AbortError"));if(e.aborted){n();return}e.addEventListener("abort",n,{once:!0})})}async function hi(e,r=document,t){let n="body"in e?e:null,s=n?.body??e;if(!s)return;n&&It(r,n.headers.get(G));let i=s.getReader(),a=new TextDecoder,c="",l=!1;try{for(;;){if(t?.aborted)throw new DOMException("aborted","AbortError");let u=i.read(),{done:g,value:f}=t?await Promise.race([u,Hn(t)]):await u;if(g){l=!0;break}c+=a.decode(f,{stream:!0}),c=Ot(r,c)}c&&Ot(r,`${c}\n`)}catch(u){throw u instanceof Error&&u.name==="AbortError"||R.debug("[client-dom] consumeNdjsonStream error",u),u}finally{try{await i.cancel()}catch(u){l||R.debug("[client-dom] reader.cancel failed",u)}try{i.releaseLock()}catch(u){R.debug("[client-dom] reader.releaseLock failed",u)}if(typeof s.cancel=="function")try{await s.cancel()}catch(u){R.debug("[client-dom] stream.cancel failed",u)}if(typeof n?.body?.cancel=="function")try{await n.body.cancel()}catch(u){R.debug("[client-dom] response.body.cancel failed",u)}}}function jn(e,r){let t=Tt(e,r),n=[],s=i=>{let a=i;a.dataset?.clientRef&&n.push(a);for(let c of i.children)s(c)};return s(t),n}function zn(e,r){let t=jn(e,r);for(let n of t){let s=n.dataset?.clientRef;s&&(n.dataset.hydrated="true",R.debug("[client-dom] marked for hydration",s))}}export{hi as consumeNdjsonStream,Tt as getContainer};\n'; + 'var Nt=Object.defineProperty;var bt=(e,r,t)=>r in e?Nt(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var m=(e,r,t)=>bt(e,typeof r!="symbol"?r+"":r,t);var Dt=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function Ut(e,...r){let t=Object.create(null),n=e.charAt(0).toUpperCase()+e.slice(1);for(let s of r)for(let[i,a]of Object.entries(s)){if(typeof a!="object"||a===null||!Object.hasOwn(a,"slug"))throw new Error(`${n} entry "${i}" must define a slug`);let c=a.slug;if(typeof c!="string")throw new Error(`${n} entry "${i}" must define a string slug`);if(c!==i)throw new Error(`${n} key "${i}" does not match entry slug "${c}"`);if(Object.hasOwn(t,i))throw new Error(`Duplicate ${e} slug "${i}"`);t[i]=a}return Object.freeze(t)}function F(...e){for(let r of e)for(let t of Object.values(r)){if(typeof t.slug!="string"||t.slug.length<3||t.slug.length>40||!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(t.slug))throw new TypeError(`Registered error slug must be 3-40 characters of lowercase kebab-case, got "${t.slug}"`);if(typeof t.category!="string"||!Dt.has(t.category))throw new TypeError(`Registered error has unknown category "${t.category}"`);if(!Number.isInteger(t.status)||t.status<400||t.status>=600)throw new RangeError(`Registered error status must be an integer from 400 through 599, got ${t.status}`);if(typeof t.title!="string"||t.title.trim().length===0)throw new TypeError("Registered error title must be a non-empty string");if(t.suggestion!==void 0&&(typeof t.suggestion!="string"||t.suggestion.trim().length===0))throw new TypeError("Registered error suggestion must be non-empty when provided")}return Ut("error registry",...e)}var C={reset:"\\x1B[0m",dim:"\\x1B[2m",gray:"\\x1B[90m",red:"\\x1B[31m",green:"\\x1B[32m",yellow:"\\x1B[33m",blue:"\\x1B[34m",magenta:"\\x1B[35m",cyan:"\\x1B[36m"},Kn={debug:C.gray,info:C.green,warn:C.yellow,error:C.red};var E="[REDACTED]",p=Reflect.apply,Lt=Array.prototype.pop,wt=Array.prototype.push;var Xn=Array.prototype,Jn=BigInt.prototype.toString,B=Map,vt=Map.prototype.delete,Pt=Map.prototype.get,Mt=Map.prototype.keys,kt=Map.prototype.set;var h=Object.getOwnPropertyDescriptor,$t=Object.getPrototypeOf,Zn=Object.hasOwn,Qn=Object.prototype,Vt=Set,Gt=decodeURIComponent,_=URL,to=Number.isFinite,eo=Number.isInteger,w=RegExp.prototype.exec,Ft=h(RegExp.prototype,"global").get,Ht=h(RegExp.prototype,"unicode").get,jt=String.prototype.charCodeAt,zt=String.prototype.includes,Yt=String.prototype.indexOf,H=String.prototype.slice,W=String.prototype.startsWith,K=String.prototype.toLowerCase,Bt=Set.prototype.add,ro=Set.prototype.delete,Wt=Set.prototype.has,Kt=$t(new B().keys()).next,qt=h(Map.prototype,"size").get,no=h(_.prototype,"host").get,oo=h(_.prototype,"origin").get,Xt=h(_.prototype,"password").get,so=h(_.prototype,"pathname").get,io=h(_.prototype,"protocol").get,Jt=h(_.prototype,"username").get,Zt=/[^a-z0-9]/g,Qt=/([a-z0-9])([A-Z])/g,te=/([A-Z])([A-Z][a-z])/g,ee=/\\b(?:sk-[A-Za-z0-9._-]{8,}|gh[po]_[A-Za-z0-9._-]{8,}|xox[baprs]-[A-Za-z0-9._-]{8,}|eyJ[A-Za-z0-9._-]{8,})\\b/g;function y(e,r,t){let n=p(Ft,r,[]),s=p(Ht,r,[]),i=0,a=!1,c="";r.lastIndex=0;try{for(;;){let l=p(w,r,[e]);if(l===null)break;let u=l[0],g=l.index;if(c+=x(e,i,g),c+=typeof t=="string"?t:t(l),i=g+u.length,a=!0,!n)break;u.length===0&&(r.lastIndex=re(e,g,s))}}finally{r.lastIndex=0}return a?c+x(e,i):e}function v(e){let r=p(K,e,[]);return y(r,Zt,"")}function S(e,r){return p(jt,e,[r])}function re(e,r,t){let n=r+1;if(!t||n>=e.length)return n;let s=S(e,r);if(s<55296||s>56319)return n;let i=S(e,n);return i>=56320&&i<=57343?r+2:n}function x(e,r,t){return t===void 0?p(H,e,[r]):p(H,e,[r,t])}function ne(e){let r=[],t=0;for(let n=0;n<=e.length;n++){let s=n===e.length?-1:S(e,n);s>=97&&s<=122||s>=48&&s<=57||(n>t&&(r[r.length]=x(e,t,n)),t=n+1)}return r}var N=["password","passwd","pwd","passphrase","secret","clientsecret","token","apikey","accesskey","privatekey","credential","authheader","authorization","cookie","bearer","jwt","connectionstring","signature","sessionid","sid","otp","mfa","pin","salt","xsrf","csrf"],oe=512,se=128,A=new B;var ie=256;function ae(e){let r=e.length<=se;if(r){let s=p(Pt,A,[e]);if(s!==void 0)return s}let t=v(e),n=t==="auth";for(let s=0;!n&&s=oe){let i=p(Mt,A,[]),a=p(Kt,i,[]).value;a!==void 0&&p(vt,A,[a])}p(kt,A,[e,n])}return n}var j=["access_token","accesstoken","refresh_token","api_key","apikey","code","token","secret","client_secret","password","passwd","pwd","state","sig","signature","auth","x-amz-credential","x-amz-signature","x-amz-security-token","x-goog-credential","x-goog-signature"],q=new Vt;for(let e=0;e=65&&r<=90||r>=97&&r<=122}function X(e){return de(e)||e==="_"||e==="$"}function pe(e){if(!e)return!1;let r=S(e,0);return X(e)||r>=48&&r<=57||e==="."||e==="-"}function J(e,r){let t=r,n=e[t]===\'"\'||e[t]==="\'"?e[t++]:"";if(!X(e[t]))return!1;for(t++;pe(e[t]);)t++;if(n){if(e[t]!==n)return!1;t++}for(;e[t]===" "||e[t]==="\t";)t++;return e[t]===":"||e[t]==="="}function Z(e){return e==="\\r"||e===`\n`||e==="}"||e==="]"||ge(e)}function Q(e,r){let t=r;for(;t=e.length||J(e,t)}function fe(e,r){let t=r,n=!0;if(p(W,e,[E,r])){let g=r+E.length;if(z(e,g))return{end:g,replacement:E};t=g,n=!1}let s=n&&(e[t]===\'"\'||e[t]==="\'"||e[t]==="`")?e[t]:"",i=!1,a=()=>s?`${s}${E}${i?s:""}`:E,c=[],l="",u=-1;for(let g=t;g0&&(f==="}"||f==="]")){if(c[c.length-1]!==f)return{end:e.length,replacement:a()};if(p(Lt,c,[]),g++,c.length===0&&z(e,g))return{end:g,replacement:a()};continue}if(c.length>0||!Z(f)){g++;continue}let T=g;if(g=Q(e,g),g>=e.length||J(e,g))return{end:T,replacement:a()}}return{end:e.length,replacement:a()}}function Y(e,r,t,n){let s=0,i="";for(let a=p(w,r,[e]);a;a=p(w,r,[e])){let c=a[t];if(!Ee(c))continue;let l=r.lastIndex,u=n===void 0?void 0:a[n],g=l+E.length;if((u==="?"||u==="&"||u===";")&&p(W,e,[E,l])&&e[g]==="#")continue;let f=fe(e,l);i+=x(e,s,a.index),i+=a[0],i+=f.replacement,s=f.end,r.lastIndex=f.end}return s===0?e:i+x(e,s)}function Ee(e){if(e.length>ie)return!0;let r=y(e,te,i=>`${i[1]} ${i[2]}`),t=y(r,Qt,i=>`${i[1]} ${i[2]}`),n=p(K,t,[]),s=ne(n);for(let i=0;i{let n=t[1],s=t[2],i=p(Yt,s,[":"]);if(i===-1)return`${n}${E}@`;let a=x(s,0,i);return`${n}${a}:${E}@`});return r=y(r,ue,t=>{let n=t[1],s=t[2],i=t[3];return me(n,s,i)?t[0]:`${n}${s}:${E}@`}),r=y(r,/([?#&;])([-a-z0-9_.%\\[\\]]+)=([^&#;\\s]*)/gi,t=>{let n=t[1],s=t[2],i=Re(s);return p(Wt,q,[v(i)])||ae(i)?`${n}${s}=${E}`:t[0]}),r=y(r,/(^|[^a-z0-9_-])((?:set-cookie|cookie)\\s*:\\s*)[^\\r\\n]*/gi,t=>`${t[1]}${t[2]}${E}`),r=y(r,/\\b(authorization\\s*[:=]\\s*)[^\\r\\n]*/gi,t=>`${t[1]}${E}`),r=y(r,/\\b(bearer|basic)(\\s+)(?:"[^"\\r\\n]*"|\'[^\'\\r\\n]*\'|[a-z0-9._~+/=-]+)/gi,t=>`${t[1]}${t[2]}${E}`),r=y(r,ee,E),r=Y(r,/(["\'])([_$a-z][a-z0-9_.$-]*)\\1(\\s*[:=]\\s*)/gi,2),r=Y(r,/(^|[^a-z0-9_.$-])([_$a-z][a-z0-9_.$-]*)(\\s*[:=]\\s*)/gi,2,1),r}var ye=2048;var go=64*1024,he=256,xe="https://veryfront.com/docs/errors/",tt="...[truncated]",M="unknown-error";function et(e,r){if(e.length<=r)return e;let t=Math.max(0,r-tt.length);return`${_e(e,t)}${tt}`}function _e(e,r){let t=e.slice(0,r),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319&&(t=t.slice(0,-1)),t}function Se(e){let r="";for(let t=0;t=55296&&n<=56319){let s=e.charCodeAt(t+1);s>=56320&&s<=57343?(r+=e.slice(t,t+2),t++):r+="\\uFFFD";continue}r+=n>=56320&&n<=57343?"\\uFFFD":e.charAt(t)}return r}function I(e){return typeof e!="string"?E:et(P(e),ye)}function Ie(e){let r=typeof e=="string"?P(e):M,t=et(r||M,he),n=Se(t);return n==="."||n===".."?M:n}function b(e){let r=encodeURIComponent(Ie(e));return`${xe}${r}`}var ot=Reflect.apply,Oe=Object.freeze,Te=Object.getOwnPropertyDescriptors,rt=Number.isFinite,st=new WeakSet,Ae=WeakSet.prototype.add,Ce=WeakSet.prototype.has,Ne=new Set(["CONFIG","BUILD","RUNTIME","ROUTE","MODULE","SERVER","BOUNDARY","DEV","DEPLOY","AGENT","GENERAL"]);function o(e){let r={...e},t={...r,create(n){let s=n?.message,i=n?.detail,a=n?.cause,c=n?.instance,l=n?.context,u=n?.status??r.status;return new k(s||i||r.title,{slug:r.slug,category:r.category,status:u,title:r.title,suggestion:r.suggestion,exitCode:r.exitCode,detail:i,cause:a,instance:c,context:l})}};return Oe(t)}var k=class extends Error{constructor(t,n){super(t);m(this,"slug");m(this,"category");m(this,"status");m(this,"title");m(this,"suggestion");m(this,"exitCode");m(this,"detail");m(this,"cause");m(this,"instance");m(this,"context");ot(Ae,st,[this]),this.name="VeryfrontError",this.slug=n.slug,this.category=n.category,this.status=n.status,this.title=n.title,this.suggestion=n.suggestion,this.exitCode=n.exitCode,this.detail=n.detail,this.cause=n.cause,this.instance=n.instance,this.context=n.context}toRFC9457(){let t=nt(this);return t?{type:b(t.slug),title:I(t.title),status:t.status,detail:t.detail===void 0?void 0:I(t.detail),instance:t.instance===void 0?void 0:I(t.instance),category:t.category,suggestion:t.suggestion===void 0?void 0:I(t.suggestion),cause:typeof t.cause=="string"?I(t.cause):void 0}:{type:b("unknown-error"),title:"Unknown/unclassified error",status:500,category:"GENERAL"}}getDocsUrl(){let t=nt(this);return b(t?.slug??"unknown-error")}};function it(e){return typeof e=="object"&&e!==null&&ot(Ce,st,[e])===!0}function nt(e){return it(e)?be(e):null}function be(e){try{if(!it(e))return null;let r=Te(e),t=Ct=>{let L=r[Ct];return L&&"value"in L?L.value:void 0},n=t("slug"),s=t("category"),i=t("status"),a=t("title"),c=t("message"),l=t("suggestion"),u=t("exitCode"),g=t("detail"),f=t("cause"),T=t("instance"),At=t("context"),U=t("stack");return typeof n!="string"||!Ne.has(s)||typeof i!="number"||!rt(i)||typeof a!="string"||typeof c!="string"||l!==void 0&&typeof l!="string"||u!==void 0&&(typeof u!="number"||!rt(u))||g!==void 0&&typeof g!="string"||T!==void 0&&typeof T!="string"||U!==void 0&&typeof U!="string"?null:{slug:n,category:s,status:i,title:a,message:c,suggestion:l,exitCode:u,detail:g,cause:f,instance:T,context:At,stack:U}}catch{return null}}var De=o({slug:"config-not-found",category:"CONFIG",status:404,title:"Configuration file not found",suggestion:"Create veryfront.config.js, veryfront.config.ts, or veryfront.config.mjs in the project root"}),Ue=o({slug:"config-invalid",category:"CONFIG",status:400,title:"Invalid configuration format",suggestion:"Check the reported configuration path and validation details"}),Le=o({slug:"config-parse-error",category:"CONFIG",status:400,title:"Failed to parse configuration",suggestion:"Ensure your configuration file contains valid JavaScript or TypeScript"}),we=o({slug:"config-validation-error",category:"CONFIG",status:422,title:"Configuration validation failed",suggestion:"Check the configuration against the schema requirements"}),ve=o({slug:"config-type-error",category:"CONFIG",status:400,title:"Configuration type mismatch",suggestion:"Ensure configuration values match expected types"}),Pe=o({slug:"import-map-invalid",category:"CONFIG",status:400,title:"Invalid import map configuration",suggestion:"Check your import map syntax and paths"}),Me=o({slug:"cors-config-invalid",category:"CONFIG",status:400,title:"Invalid CORS configuration",suggestion:"Review CORS settings in your configuration"}),ke=o({slug:"config-validation-failed",category:"CONFIG",status:400,title:"Configuration validation failed",suggestion:"Check configuration values against requirements"}),$e=o({slug:"webhook-config-invalid",category:"CONFIG",status:400,title:"Invalid webhook configuration",suggestion:"Check webhook definition fields, target settings, and eventFilter conditions"}),Ve=o({slug:"schedule-config-invalid",category:"CONFIG",status:400,title:"Invalid schedule configuration",suggestion:"Check schedule definition fields, cron expression, target settings, and positive-integer limits"}),Ge=o({slug:"trigger-config-invalid",category:"CONFIG",status:400,title:"Invalid trigger configuration",suggestion:"Check trigger ID format (lowercase, alphanumeric, dots/slashes/hyphens) and ensure all input values are JSON-serializable"}),at={"config-not-found":De,"config-invalid":Ue,"config-parse-error":Le,"config-validation-error":we,"config-type-error":ve,"import-map-invalid":Pe,"cors-config-invalid":Me,"config-validation-failed":ke,"webhook-config-invalid":$e,"schedule-config-invalid":Ve,"trigger-config-invalid":Ge};var Fe=o({slug:"build-failed",category:"BUILD",status:500,title:"Build process failed",suggestion:"Check the build output for specific errors"}),He=o({slug:"bundle-error",category:"BUILD",status:500,title:"Bundle generation failed",suggestion:"Review bundler output for details"}),je=o({slug:"typescript-error",category:"BUILD",status:500,title:"TypeScript compilation error",suggestion:"Fix TypeScript errors shown in the output"}),ze=o({slug:"mdx-compile-error",category:"BUILD",status:500,title:"MDX compilation failed",suggestion:"Check your MDX file syntax"}),Ye=o({slug:"asset-optimization-error",category:"BUILD",status:500,title:"Asset optimization failed",suggestion:"Check asset file formats and paths"}),Be=o({slug:"ssg-generation-error",category:"BUILD",status:500,title:"Static site generation failed",suggestion:"Review SSG configuration and data fetching"}),We=o({slug:"sourcemap-error",category:"BUILD",status:500,title:"Source map generation failed",suggestion:"Check source map configuration"}),Ke=o({slug:"compilation-error",category:"BUILD",status:500,title:"Compilation failed",suggestion:"Review compiler output for specific errors"}),ct={"build-failed":Fe,"bundle-error":He,"typescript-error":je,"mdx-compile-error":ze,"asset-optimization-error":Ye,"ssg-generation-error":Be,"sourcemap-error":We,"compilation-error":Ke};var qe=o({slug:"hydration-mismatch",category:"RUNTIME",status:500,title:"Client/server hydration mismatch",suggestion:"Ensure server and client render the same content"}),Xe=o({slug:"render-error",category:"RUNTIME",status:500,title:"Component render failed",suggestion:"Check component for runtime errors"}),Je=o({slug:"component-error",category:"RUNTIME",status:500,title:"Component execution error",suggestion:"Review component logic and props"}),Ze=o({slug:"layout-not-found",category:"RUNTIME",status:404,title:"Layout component not found",suggestion:"Ensure layout file exists at the expected path"}),Qe=o({slug:"page-not-found",category:"RUNTIME",status:404,title:"Page component not found",suggestion:"Check that the page file exists in the routes directory"}),tr=o({slug:"api-error",category:"RUNTIME",status:500,title:"API route handler error",suggestion:"Review API route handler for errors"}),er=o({slug:"middleware-error",category:"RUNTIME",status:500,title:"Middleware execution error",suggestion:"Check middleware function for errors"}),rr=o({slug:"trigger-target-not-found",category:"RUNTIME",status:404,title:"Trigger target not found",suggestion:"Ensure the referenced task or workflow ID is registered in the project"}),nr=o({slug:"trigger-execution-failed",category:"RUNTIME",status:500,title:"Trigger target execution failed",suggestion:"Check the task or workflow for errors and review the trigger input"}),or=o({slug:"trigger-not-supported",category:"RUNTIME",status:501,title:"Trigger target type not supported in local runtime",suggestion:"Use a workflow or task target for local trigger runs; agent targets require the Cloud runtime"}),ut={"hydration-mismatch":qe,"render-error":Xe,"component-error":Je,"layout-not-found":Ze,"page-not-found":Qe,"api-error":tr,"middleware-error":er,"trigger-target-not-found":rr,"trigger-execution-failed":nr,"trigger-not-supported":or};var sr=o({slug:"route-conflict",category:"ROUTE",status:409,title:"Conflicting route definitions",suggestion:"Rename or reorganize conflicting route files"}),ir=o({slug:"invalid-route-file",category:"ROUTE",status:400,title:"Invalid route file structure",suggestion:"Ensure route file exports required functions"}),ar=o({slug:"route-handler-invalid",category:"ROUTE",status:400,title:"Invalid route handler export",suggestion:"Export a valid handler function from the route file"}),cr=o({slug:"dynamic-route-error",category:"ROUTE",status:500,title:"Dynamic route parsing failed",suggestion:"Check dynamic route segment syntax"}),ur=o({slug:"route-params-error",category:"ROUTE",status:400,title:"Route parameters invalid",suggestion:"Validate route parameter values"}),lr=o({slug:"api-route-error",category:"ROUTE",status:500,title:"API route definition error",suggestion:"Review API route configuration"}),lt={"route-conflict":sr,"invalid-route-file":ir,"route-handler-invalid":ar,"dynamic-route-error":cr,"route-params-error":ur,"api-route-error":lr};var gr=o({slug:"module-not-found",category:"MODULE",status:404,title:"Module could not be resolved",suggestion:"Check the import path and ensure the module is installed"}),dr=o({slug:"import-resolution-error",category:"MODULE",status:500,title:"Import path resolution failed",suggestion:"Verify import paths and module configuration"}),pr=o({slug:"circular-dependency",category:"MODULE",status:500,title:"Circular dependency detected",suggestion:"Refactor imports to break the circular dependency"}),fr=o({slug:"invalid-import",category:"MODULE",status:400,title:"Invalid import statement",suggestion:"Fix import syntax or path"}),Er=o({slug:"dependency-missing",category:"MODULE",status:404,title:"Required dependency not installed",suggestion:"Install the missing dependency with your package manager"}),mr=o({slug:"version-mismatch",category:"MODULE",status:409,title:"Dependency version mismatch",suggestion:"Update dependencies to compatible versions"}),Rr=o({slug:"lockfile-format-mismatch",category:"MODULE",status:409,title:"Lockfile format is not supported",suggestion:"Upgrade Veryfront or migrate the lockfile before modifying it"}),yr=o({slug:"lockfile-read-error",category:"MODULE",status:500,title:"Lockfile could not be read safely",suggestion:"Check file access or restore a valid lockfile before retrying"}),gt={"module-not-found":gr,"import-resolution-error":dr,"circular-dependency":pr,"invalid-import":fr,"dependency-missing":Er,"version-mismatch":mr,"lockfile-format-mismatch":Rr,"lockfile-read-error":yr};var hr=o({slug:"port-in-use",category:"SERVER",status:409,title:"Server port already in use",suggestion:"Use a different port or stop the process using this port"}),xr=o({slug:"server-start-error",category:"SERVER",status:500,title:"Server failed to start",suggestion:"Check server configuration and port availability"}),_r=o({slug:"cache-error",category:"SERVER",status:500,title:"Cache operation failed",suggestion:"Clear the cache and try again"}),Sr=o({slug:"file-watch-error",category:"SERVER",status:500,title:"File watcher error",suggestion:"Restart the development server"}),Ir=o({slug:"request-error",category:"SERVER",status:500,title:"HTTP request handling error",suggestion:"Check request handler and middleware"}),Or=o({slug:"service-overloaded",category:"SERVER",status:503,title:"Service overloaded",suggestion:"Reduce load or scale up resources"}),Tr=o({slug:"project-execution-unavailable",category:"SERVER",status:503,title:"Project execution unavailable",suggestion:"Route the project to a dedicated isolated runtime"}),Ar=o({slug:"semaphore-timeout",category:"SERVER",status:503,title:"Semaphore acquire timeout",suggestion:"Reduce concurrency or increase the semaphore acquire timeout"}),Cr=o({slug:"circuit-breaker-open",category:"SERVER",status:503,title:"Circuit breaker is open",suggestion:"Wait for the breaker reset timeout before retrying"}),Nr=o({slug:"cache-path-mismatch",category:"SERVER",status:500,title:"Cache path mismatch",suggestion:"Clear the cache directory and rebuild"}),br=o({slug:"network-error",category:"SERVER",status:502,title:"Network operation failed",suggestion:"Check network connectivity and retry"}),Dr=o({slug:"api-client-error",category:"SERVER",status:500,title:"API client request failed",suggestion:"Check API connectivity and authentication"}),Ur=o({slug:"token-storage-error",category:"SERVER",status:500,title:"Token storage operation failed",suggestion:"Check token storage backend and credentials"}),Lr=o({slug:"cache-invariant-violation",category:"SERVER",status:500,title:"Cache path invariant violated",suggestion:"Clear the cache and rebuild"}),wr=o({slug:"release-not-found",category:"SERVER",status:404,title:"No active release found",suggestion:"Deploy the project to create a release for this environment"}),vr=o({slug:"fallback-exhausted",category:"SERVER",status:500,title:"Primary and fallback operations both failed",suggestion:"Check service availability and connectivity"}),Pr=o({slug:"rag-store-corrupt",category:"SERVER",status:500,title:"RAG store file is corrupt",suggestion:"Repair or move the store file aside, then retry; it was not overwritten"}),Mr=o({slug:"rag-store-unavailable",category:"SERVER",status:500,title:"RAG store file is unavailable",suggestion:"Check storage availability, permissions, and concurrent operations, then retry"}),dt={"port-in-use":hr,"server-start-error":xr,"cache-error":_r,"file-watch-error":Sr,"request-error":Ir,"service-overloaded":Or,"project-execution-unavailable":Tr,"semaphore-timeout":Ar,"circuit-breaker-open":Cr,"cache-path-mismatch":Nr,"network-error":br,"api-client-error":Dr,"token-storage-error":Ur,"cache-invariant-violation":Lr,"release-not-found":wr,"fallback-exhausted":vr,"rag-store-corrupt":Pr,"rag-store-unavailable":Mr};var kr=o({slug:"client-boundary-violation",category:"BOUNDARY",status:400,title:"Client boundary rule violation",suggestion:"Add \'use client\' directive or move code to a client component"}),$r=o({slug:"server-only-in-client",category:"BOUNDARY",status:400,title:"Server-only code in client component",suggestion:"Move server-only code to a server component"}),Vr=o({slug:"client-only-in-server",category:"BOUNDARY",status:400,title:"Client-only code in server component",suggestion:"Move client-only code to a client component"}),Gr=o({slug:"invalid-use-client",category:"BOUNDARY",status:400,title:"Invalid \'use client\' directive",suggestion:"Place \'use client\' at the top of the file"}),Fr=o({slug:"invalid-use-server",category:"BOUNDARY",status:400,title:"Invalid \'use server\' directive",suggestion:"Place \'use server\' at the top of the file or function"}),Hr=o({slug:"rsc-payload-error",category:"BOUNDARY",status:500,title:"RSC payload serialization error",suggestion:"Ensure props are serializable (no functions, symbols, etc.)"}),jr=o({slug:"ssr-output-limit-exceeded",category:"BOUNDARY",status:500,title:"SSR output limit exceeded",suggestion:"Reduce the rendered HTML size or split the response into smaller pages"}),pt={"client-boundary-violation":kr,"server-only-in-client":$r,"client-only-in-server":Vr,"invalid-use-client":Gr,"invalid-use-server":Fr,"rsc-payload-error":Hr,"ssr-output-limit-exceeded":jr};var zr=o({slug:"hmr-error",category:"DEV",status:500,title:"Hot module replacement error",suggestion:"Restart the development server"}),Yr=o({slug:"dev-server-error",category:"DEV",status:500,title:"Development server error",suggestion:"Check the dev server logs and restart"}),Br=o({slug:"fast-refresh-error",category:"DEV",status:500,title:"Fast refresh failed",suggestion:"Save the file again or restart the dev server"}),Wr=o({slug:"error-overlay-error",category:"DEV",status:500,title:"Error overlay failed",suggestion:"Check browser console for details"}),Kr=o({slug:"source-map-error",category:"DEV",status:500,title:"Source map loading error",suggestion:"Rebuild or clear cache"}),ft={"hmr-error":zr,"dev-server-error":Yr,"fast-refresh-error":Br,"error-overlay-error":Wr,"source-map-error":Kr};var qr=o({slug:"deployment-error",category:"DEPLOY",status:500,title:"Deployment process failed",suggestion:"Check deployment logs for details"}),Xr=o({slug:"platform-error",category:"DEPLOY",status:500,title:"Platform-specific error",suggestion:"Check platform documentation and requirements"}),Jr=o({slug:"env-var-missing",category:"DEPLOY",status:500,title:"Required environment variable missing",suggestion:"Set the required environment variable"}),Zr=o({slug:"production-build-required",category:"DEPLOY",status:400,title:"Production build required",suggestion:"Run \'veryfront build\' before deploying"}),Qr=o({slug:"environment-not-found",category:"DEPLOY",status:404,title:"Deployment environment not found",suggestion:"Check environment names with: veryfront config"}),tn=o({slug:"release-missing-version",category:"DEPLOY",status:500,title:"Release has no version",suggestion:"Try again or check the build logs in Studio"}),en=o({slug:"release-build-timeout",category:"DEPLOY",status:408,title:"Release build timed out",suggestion:"Try again or check the build logs in Studio"}),rn=o({slug:"deployment-verification-timeout",category:"DEPLOY",status:408,title:"Deployment verification timed out",suggestion:"Try again or check the deployment status in Studio"}),nn=o({slug:"push-receipt-missing",category:"DEPLOY",status:400,title:"Push receipt not found",suggestion:"Run: veryfront push --branch main first"}),on=o({slug:"source-digest-mismatch",category:"DEPLOY",status:409,title:"Release source digest mismatch",suggestion:"Run veryfront push again to re-upload source files"}),sn=o({slug:"preview-hostname-too-long",category:"DEPLOY",status:400,title:"Preview hostname too long",suggestion:"Use a shorter project slug or branch name"}),an=o({slug:"branch-not-found",category:"DEPLOY",status:404,title:"Branch not found",suggestion:"List branches in Studio or push a new one with: veryfront push --branch "}),Et={"deployment-error":qr,"platform-error":Xr,"env-var-missing":Jr,"production-build-required":Zr,"environment-not-found":Qr,"release-missing-version":tn,"release-build-timeout":en,"deployment-verification-timeout":rn,"push-receipt-missing":nn,"source-digest-mismatch":on,"preview-hostname-too-long":sn,"branch-not-found":an};var cn=o({slug:"agent-error",category:"AGENT",status:500,title:"Agent operation error",suggestion:"Check agent configuration and logs"}),un=o({slug:"agent-not-found",category:"AGENT",status:404,title:"Agent not found",suggestion:"Verify the agent ID exists"}),ln=o({slug:"agent-timeout",category:"AGENT",status:408,title:"Agent operation timed out",suggestion:"Increase timeout or simplify the request"}),gn=o({slug:"agent-intent-error",category:"AGENT",status:400,title:"Agent intent parsing error",suggestion:"Rephrase the request more clearly"}),dn=o({slug:"orchestration-error",category:"AGENT",status:500,title:"Multi-agent orchestration error",suggestion:"Check agent coordination logic"}),pn=o({slug:"cost-limit-exceeded",category:"AGENT",status:429,title:"Cost limit exceeded",suggestion:"Wait for the budget period to reset or increase the limit"}),fn=o({slug:"tool-id-conflict",category:"AGENT",status:409,title:"Tool ID conflict",suggestion:"Use a unique tool ID or rename one of the conflicting tools"}),En=o({slug:"durable-run-event-persistence-failed",category:"AGENT",status:500,title:"Durable run event persistence failed",suggestion:"Correct invalid or oversized event data, or retry after durable event storage recovers"}),mt={"agent-error":cn,"agent-not-found":un,"agent-timeout":ln,"agent-intent-error":gn,"orchestration-error":dn,"cost-limit-exceeded":pn,"tool-id-conflict":fn,"durable-run-event-persistence-failed":En};var mn=o({slug:"unknown-error",category:"GENERAL",status:500,title:"Unknown/unclassified error",suggestion:"Check logs for more details"}),Rn=o({slug:"authentication-required",category:"GENERAL",status:401,title:"Authentication required",suggestion:"Set VERYFRONT_API_TOKEN or run \'veryfront login\'"}),yn=o({slug:"permission-denied",category:"GENERAL",status:403,title:"File/resource permission denied",suggestion:"Check file permissions and access rights"}),hn=o({slug:"file-not-found",category:"GENERAL",status:404,title:"File not found",suggestion:"Verify the file path exists"}),xn=o({slug:"resource-not-found",category:"GENERAL",status:404,title:"Requested resource not found",suggestion:"Verify the referenced resource ID or name exists"}),_n=o({slug:"invalid-argument",category:"GENERAL",status:400,title:"Invalid function argument",suggestion:"Check argument types and values",exitCode:2}),Sn=o({slug:"timeout-error",category:"GENERAL",status:408,title:"Operation timed out",suggestion:"Increase timeout or optimize the operation"}),In=o({slug:"initialization-error",category:"GENERAL",status:500,title:"Initialization failed",suggestion:"Check initialization requirements and dependencies"}),On=o({slug:"not-supported",category:"GENERAL",status:501,title:"Feature not supported",suggestion:"Check documentation for supported features"}),$=o({slug:"security-violation",category:"GENERAL",status:403,title:"Security violation detected",suggestion:"Check for path traversal or unauthorized access attempts"}),Tn=o({slug:"input-validation-failed",category:"GENERAL",status:400,title:"Input validation failed",suggestion:"Check request input against validation rules"}),An=o({slug:"project-source-empty",category:"GENERAL",status:400,title:"Project source is empty",suggestion:"Add project files or run \'veryfront init\'"}),Cn=o({slug:"nested-cwd-scope",category:"GENERAL",status:500,title:"Working directory scope nested inside another",suggestion:"Do the inner work directly in the outer scope\'s callback instead of opening a second one"}),Rt={"unknown-error":mn,"authentication-required":Rn,"permission-denied":yn,"file-not-found":hn,"resource-not-found":xn,"invalid-argument":_n,"timeout-error":Sn,"initialization-error":In,"not-supported":On,"security-violation":$,"input-validation-failed":Tn,"project-source-empty":An,"nested-cwd-scope":Cn};var ts=F(at,ct,ut,lt,gt,dt,pt,ft,Et,mt,Rt);var Nn=[{source:String.raw`]*>[\\s\\S]*?<\\/script>`,flags:"gi",name:"inline script"},{source:String.raw`javascript:`,flags:"gi",name:"javascript: URL"},{source:String.raw`\\bon\\w+\\s*=`,flags:"gi",name:"event handler attribute"},{source:String.raw`data:\\s*text\\/html`,flags:"gi",name:"data: HTML URL"}];function bn(){return Nn.map(({source:e,flags:r,name:t})=>({pattern:new RegExp(e,r),name:t}))}function Dn(){let e=globalThis;return e.__VERYFRONT_DEV__===!0||e.Deno?.env?.get?.("VERYFRONT_ENV")==="development"}function yt(e,r={}){let{allowInlineScripts:t=!1,strict:n=!1,warn:s=!0}=r;for(let{pattern:i,name:a}of bn())if(!(t&&a==="inline script")&&(i.lastIndex=0,!!i.test(e)&&(s&&console.warn(`[Security] Suspicious ${a} detected in server HTML`),n||!Dn())))throw $.create({detail:`Potentially unsafe HTML: ${a} detected`});return e}var O=class{constructor(r,t){m(this,"prefix",r);m(this,"level",t)}log(r,t,n,...s){this.level>r||t?.(n,...s)}debug(r,...t){this.log(0,console.debug,`[${this.prefix}] DEBUG: ${r}`,...t)}info(r,...t){this.log(1,console.log,`[${this.prefix}] ${r}`,...t)}warn(r,...t){this.log(2,console.warn,`[${this.prefix}] WARN: ${r}`,...t)}error(r,...t){this.log(3,console.error,`[${this.prefix}] ERROR: ${r}`,...t)}};function Un(){if(typeof window>"u")return 2;let e=globalThis;return e.__VERYFRONT_DEV__||e.__RSC_DEV__?e.__VERYFRONT_DEBUG__||e.__RSC_DEBUG__?0:1:2}var D=Un(),R=new O("RSC",D),Es=new O("PREFETCH",D),ms=new O("HYDRATE",D),Rs=new O("VERYFRONT",D);var xs=Object.freeze({IPV4:"127.0.0.1",IPV6:"::1",HOSTNAME:"localhost"});var Ln=5e3,wn=1e4,Is=16*1024*1024,vn=5e3;var Pn=100;var Mn=Object.freeze([5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4]),Os=Object.freeze([1,5,10,25,50,100,250,500,1e3,2500,5e3,1e4]),Ts=Object.freeze({server:Object.freeze({port:3e3,hostname:"0.0.0.0"}),timeouts:Object.freeze({default:Ln,api:3e4,ssr:wn,hmr:3e4,sandbox:vn}),cache:Object.freeze({jit:Object.freeze({maxSize:Pn,tempDirPrefix:"vf-bundle-"})}),metrics:Object.freeze({ssrBoundaries:Mn})});var d="/_veryfront",V={RSC:`${d}/rsc/`,FS:`${d}/fs/`,MODULES:`${d}/modules/`,PAGES:`${d}/pages/`,DATA:`${d}/data/`,LIB:`${d}/lib/`,CHUNKS:`${d}/chunks/`,CLIENT:`${d}/client/`},xt={HMR_RUNTIME:`${d}/hmr-runtime.js`,HMR:`${d}/hmr.js`,ERROR_OVERLAY:`${d}/error-overlay.js`,DEV_LOADER:`${d}/dev-loader.js`,CLIENT_LOG:`${d}/log`,CLIENT_JS:`${d}/client.js`,ROUTER_JS:`${d}/router.js`,PREFETCH_JS:`${d}/prefetch.js`,MANIFEST_JSON:`${d}/manifest.json`,APP_JS:`${d}/app.js`,RSC_CLIENT:`${d}/rsc/client.js`,RSC_MANIFEST:`${d}/rsc/manifest`,RSC_STREAM:`${d}/rsc/stream`,RSC_PAYLOAD:`${d}/rsc/payload`,RSC_RENDER:`${d}/rsc/render`,RSC_PAGE:`${d}/rsc/page`,RSC_MODULE:`${d}/rsc/module`,RSC_DOM:`${d}/rsc/dom.js`,LIB_CHAT_REACT:`${d}/lib/chat/react.js`,LIB_CHAT_COMPONENTS:`${d}/lib/chat/components.js`,LIB_CHAT_PRIMITIVES:`${d}/lib/chat/primitives.js`};var kn={ROOT:".veryfront",CACHE:".veryfront/cache",KV:".veryfront/kv",LOGS:".veryfront/logs",TMP:".veryfront/tmp"},Cs=kn.CACHE;var Ns={HMR_RUNTIME:xt.HMR_RUNTIME,ERROR_OVERLAY:xt.ERROR_OVERLAY};var $n=V.RSC,Vn=V.FS;var _t="rsc-root",G="x-veryfront-dependency-pins";var ws=Array.prototype.at,vs=Array.prototype.filter,Ps=Array.prototype.join,Ms=Array.prototype.map,ks=Array.prototype.pop,$s=Array.prototype.push,Vs=Array.prototype.sort;var ti=Object.freeze({react:"","react-dom":"","react-dom/client":"","react-dom/server":"","react/jsx-runtime":"","react/jsx-dev-runtime":""});var Fn="veryfront-hydration-data";function St(e){try{let r=[...e.querySelectorAll(`[id="${Fn}"]`)];if(r.length!==1)return null;let t=e.body;if(!t)return null;let n=r[0];return t.firstElementChild!==n&&n.parentElement!==t||n.tagName?.toLowerCase()!=="script"||n.getAttribute("type")?.trim().toLowerCase()!=="application/json"?null:n}catch{return null}}function It(e,r){if(!r?.startsWith("on:"))return!1;try{let t=St(e);if(!t)return!1;let n=JSON.parse(t.textContent||"{}");return n.dependencyPinningCacheKey=r,t.textContent=JSON.stringify(n),!0}catch(t){return R.debug("hydration dependency snapshot seed failed",t),!1}}function Tt(e,r){let t=r==="root"?_t:`rsc-slot-${r}`,n=e.getElementById(t);if(n)return n;let s=e.createElement("div");return s.id=t,e.body.appendChild(s),s}function Hn(e,r){if(r.type!=="slot")return;let t=Tt(e,r.id);t.innerHTML=yt(String(r.html??""))}function Ot(e,r){let t=r.split(`\n`),n=t.pop()??"";for(let s of t){let i=s.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch(l){R.debug("[client-dom] malformed NDJSON line",{line:i,error:l instanceof Error?l.message:String(l)});continue}if(!a||typeof a!="object")continue;let c=a;if(c.type==="slot"){Hn(e,c);try{Yn(e,c.id||"root")}catch(l){R.debug("[client-dom] hydration optional failed",l)}}}return n}function jn(e){return new Promise((r,t)=>{let n=()=>t(new DOMException("aborted","AbortError"));if(e.aborted){n();return}e.addEventListener("abort",n,{once:!0})})}async function xi(e,r=document,t){let n="body"in e?e:null,s=n?.body??e;if(!s)return;n&&It(r,n.headers.get(G));let i=s.getReader(),a=new TextDecoder,c="",l=!1;try{for(;;){if(t?.aborted)throw new DOMException("aborted","AbortError");let u=i.read(),{done:g,value:f}=t?await Promise.race([u,jn(t)]):await u;if(g){l=!0;break}c+=a.decode(f,{stream:!0}),c=Ot(r,c)}c&&Ot(r,`${c}\n`)}catch(u){throw u instanceof Error&&u.name==="AbortError"||R.debug("[client-dom] consumeNdjsonStream error",u),u}finally{try{await i.cancel()}catch(u){l||R.debug("[client-dom] reader.cancel failed",u)}try{i.releaseLock()}catch(u){R.debug("[client-dom] reader.releaseLock failed",u)}if(typeof s.cancel=="function")try{await s.cancel()}catch(u){R.debug("[client-dom] stream.cancel failed",u)}if(typeof n?.body?.cancel=="function")try{await n.body.cancel()}catch(u){R.debug("[client-dom] response.body.cancel failed",u)}}}function zn(e,r){let t=Tt(e,r),n=[],s=i=>{let a=i;a.dataset?.clientRef&&n.push(a);for(let c of i.children)s(c)};return s(t),n}function Yn(e,r){let t=zn(e,r);for(let n of t){let s=n.dataset?.clientRef;s&&(n.dataset.hydrated="true",R.debug("[client-dom] marked for hydration",s))}}export{xi as consumeNdjsonStream,Tt as getContainer};\n'; From 2f1f0306163e0d01c7842983e644c7a74bbf1d4f Mon Sep 17 00:00:00 2001 From: Koji Wakayama Date: Sun, 9 Aug 2026 12:17:45 +0200 Subject: [PATCH 5/7] fix(testing): serialize withCwd across test files, not just within one The queue only ever ordered its own file. Under `deno test --parallel` each test file runs in its own isolate, sharing neither module state nor `globalThis` with its peers, while the working directory it mutates belongs to the process they all share. So every file held a private queue and raced every other one -- the helper could not serialize the failing test against the peers that actually race it, which is the whole reason it exists. The turn is now taken from the operating system, the only mutex those isolates can both see: a directory created with `Deno.mkdir`, which fails atomically when it already exists. It is keyed on the pid because the directory it guards is per-process; two concurrent `deno test` runs have no reason to wait for each other, and no run can inherit a lock from an earlier one. The in-isolate queue stays in front of it so callers within a file still take their turn in arrival order. Restoring no longer reads `Deno.cwd()`. That read was unsafe under exactly the concurrency this guards: the directory it reports may belong to a sibling, and if the sibling has since removed it the call throws `NotFound` outright. Callers return to a root derived from the module URL instead. That was the bug behind the migration reverted earlier -- it broke a webhook test that passed alone and failed in the suite. `restores the previous directory` was written on that same unsafe assumption, capturing `Deno.cwd()` before the call, so it now asserts what holds under a peer instead. The cross-file property needs two test files to be observable at all; inside one isolate the module queue is already sufficient and the bug is invisible. Hence the exclusion pair, which fails against the previous implementation. --- src/testing/cwd-exclusion-a.test.ts | 10 +++ src/testing/cwd-exclusion-b.test.ts | 9 +++ src/testing/cwd-exclusion-probe.ts | 61 +++++++++++++++++ src/testing/cwd.test.ts | 48 ++++++++++--- src/testing/cwd.ts | 101 ++++++++++++++++++++++++++-- 5 files changed, 214 insertions(+), 15 deletions(-) create mode 100644 src/testing/cwd-exclusion-a.test.ts create mode 100644 src/testing/cwd-exclusion-b.test.ts create mode 100644 src/testing/cwd-exclusion-probe.ts diff --git a/src/testing/cwd-exclusion-a.test.ts b/src/testing/cwd-exclusion-a.test.ts new file mode 100644 index 0000000000..495ed93cb3 --- /dev/null +++ b/src/testing/cwd-exclusion-a.test.ts @@ -0,0 +1,10 @@ +import { describe, it } from "#veryfront/testing/bdd.ts"; +import { assertExclusiveCwd } from "./cwd-exclusion-probe.ts"; + +// One half of a pair. See ./cwd-exclusion-probe.ts for why the property under +// test needs two files to be observable at all. +describe("testing/cwd cross-file exclusion (a)", () => { + it("never shares the working directory with another test file", async () => { + await assertExclusiveCwd("a"); + }); +}); diff --git a/src/testing/cwd-exclusion-b.test.ts b/src/testing/cwd-exclusion-b.test.ts new file mode 100644 index 0000000000..d381010e63 --- /dev/null +++ b/src/testing/cwd-exclusion-b.test.ts @@ -0,0 +1,9 @@ +import { describe, it } from "#veryfront/testing/bdd.ts"; +import { assertExclusiveCwd } from "./cwd-exclusion-probe.ts"; + +// The other half of the pair. See ./cwd-exclusion-probe.ts. +describe("testing/cwd cross-file exclusion (b)", () => { + it("never shares the working directory with another test file", async () => { + await assertExclusiveCwd("b"); + }); +}); diff --git a/src/testing/cwd-exclusion-probe.ts b/src/testing/cwd-exclusion-probe.ts new file mode 100644 index 0000000000..c32cfe096e --- /dev/null +++ b/src/testing/cwd-exclusion-probe.ts @@ -0,0 +1,61 @@ +/** + * Shared body for the cross-file working-directory exclusion test. + * + * `withCwd` has to serialize callers across test *files*, not merely within + * one. Under `deno test --parallel` every file runs in its own isolate, sharing + * neither module state nor `globalThis` with its peers, while the working + * directory it mutates belongs to the process they all share. A queue kept in + * module state therefore orders only its own callers and lets every other file + * race it -- which is the failure this helper exists to prevent, so it is worth + * a test that would actually notice its return. + * + * Noticing it takes two real test files. One file cannot: inside a single + * isolate the module queue is already sufficient, so the bug is invisible there + * by construction. + * + * Each participant repeatedly takes the directory and, while holding it, tries + * to create a marker exclusively. Failing to create it means someone else was + * inside at the same moment. + * + * @module testing/cwd-exclusion-probe + */ + +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { withCwd } from "./cwd.ts"; + +/** Scoped to the process, which is the scope of the directory being guarded. */ +const MARKER = join(tmpdir(), `veryfront-test-cwd-exclusion-${Deno.pid}`); + +/** Enough turns to interleave with a peer, few enough to stay cheap. */ +const ROUNDS = 5; + +/** Long enough that a peer running concurrently would overlap this hold. */ +const HOLD_MS = 5; + +/** + * Assert that no other test file holds the working directory while this one does. + * + * @param label participant name, so a failure names the side that saw the overlap + */ +export async function assertExclusiveCwd(label: string): Promise { + const dir = await Deno.makeTempDir({ prefix: `vf-cwd-exclusion-${label}-` }); + try { + for (let round = 0; round < ROUNDS; round++) { + await withCwd(dir, async () => { + try { + await Deno.writeTextFile(MARKER, label, { createNew: true }); + } catch (error) { + if (!(error instanceof Deno.errors.AlreadyExists)) throw error; + throw new Error( + `${label} entered the working directory while another test file still held it`, + ); + } + await new Promise((resolve) => setTimeout(resolve, HOLD_MS)); + await Deno.remove(MARKER); + }); + } + } finally { + await Deno.remove(dir, { recursive: true }); + } +} diff --git a/src/testing/cwd.test.ts b/src/testing/cwd.test.ts index eda5f671ad..2e79bc4ab4 100644 --- a/src/testing/cwd.test.ts +++ b/src/testing/cwd.test.ts @@ -1,14 +1,44 @@ import { describe, it } from "#veryfront/testing/bdd.ts"; -import { assert, assertEquals, assertRejects } from "#veryfront/testing/assert.ts"; +import { + assertEquals, + assertInstanceOf, + assertNotEquals, + assertRejects, +} from "#veryfront/testing/assert.ts"; +import { VeryfrontError } from "#veryfront/errors"; import { withCwd } from "./cwd.ts"; +/** + * The working directory, or `null` when it cannot be read. + * + * Outside a `withCwd` turn the directory belongs to whoever holds it, and a + * holder that has already removed its own temp directory makes `Deno.cwd()` + * throw `NotFound`. Unreadable is still an answer here: it cannot be this + * test's directory, because this test's directory still exists. + */ +function currentDirOrUnreadable(): string | null { + try { + return Deno.cwd(); + } catch { + return null; + } +} + describe("testing/cwd", () => { - it("restores the previous directory", async () => { - const before = Deno.cwd(); + it("enters the requested directory and does not park the process in it", async () => { const temp = await Deno.makeTempDir(); + const entered = await Deno.realPath(temp); try { - await withCwd(temp, () => assert(Deno.cwd() !== before)); - assertEquals(Deno.cwd(), before); + let inside = ""; + await withCwd(temp, () => { + inside = Deno.cwd(); + }); + + assertEquals(inside, entered, "the callback runs in the directory it asked for"); + // Deliberately not compared against a `Deno.cwd()` captured before the + // call: reading the directory outside a turn is the unsafe move this + // helper exists to remove, since a sibling test file may own it then. + assertNotEquals(currentDirOrUnreadable(), entered, "the turn is handed back"); } finally { await Deno.remove(temp, { recursive: true }); } @@ -69,11 +99,13 @@ describe("testing/cwd", () => { // named error. const temp = await Deno.makeTempDir(); try { - await assertRejects( + const error = await assertRejects( () => withCwd(temp, () => withCwd(temp, () => {})), - Error, - "cannot be nested", + VeryfrontError, ); + assertInstanceOf(error, VeryfrontError); + // The slug is the contract; the message is free to be reworded. + assertEquals(error.slug, "nested-cwd-scope"); // The queue still works afterwards. await withCwd(temp, () => assertEquals(typeof Deno.cwd(), "string")); } finally { diff --git a/src/testing/cwd.ts b/src/testing/cwd.ts index 407733ed18..0d5801e27c 100644 --- a/src/testing/cwd.ts +++ b/src/testing/cwd.ts @@ -12,10 +12,58 @@ * Every caller queues here instead, so at most one has the working directory at * a time and each is restored before the next begins. * + * ## Why the lock is on disk + * + * Under `deno test --parallel` each test *file* runs in its own isolate, and + * those isolates share neither module state nor `globalThis` -- but they do + * share one OS process, and therefore one working directory. A module-level + * queue is consequently per-file: it orders the callers inside a file and does + * nothing about the file next door, which is the race that actually bites. The + * only mutex those isolates can both see is one the operating system holds, so + * the cross-file turn is taken by creating a directory (`Deno.mkdir` fails with + * `AlreadyExists` atomically) and released by removing it. + * + * The lock is keyed on `Deno.pid` because the thing it protects is per-process: + * two concurrent `deno test` runs have independent working directories and have + * no reason to wait for each other. That also means a lock can never be left + * behind by an earlier run for this one to trip over. + * + * The in-isolate queue is kept in front of the disk lock so that callers within + * a file still take their turn in arrival order; polling alone would decide + * that arbitrarily. + * * @module testing/cwd */ import { AsyncLocalStorage } from "node:async_hooks"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { NESTED_CWD_SCOPE, TIMEOUT_ERROR } from "#veryfront/errors"; + +/** + * Where callers are returned to when they are done. + * + * Deliberately derived from this module's URL rather than read from + * `Deno.cwd()`: the whole premise here is that a sibling file may own the + * working directory at any moment, so the value `Deno.cwd()` reports is not + * reliably ours to restore. It can be a foreign temp directory, and if that + * directory has since been removed the call throws `NotFound` outright. + */ +const ANCHOR = new URL("../../", import.meta.url); + +/** Cross-isolate turn-holder. Present on disk exactly while someone holds it. */ +const LOCK_PATH = join(tmpdir(), `veryfront-test-cwd-${Deno.pid}.lock`); + +/** How long to wait between attempts at the lock. */ +const POLL_MS = 5; + +/** + * How long to wait for the lock before giving up. + * + * Generous, because a callback may bundle or transpile before it yields. It + * exists only so a lost release fails loudly instead of hanging the suite. + */ +const ACQUIRE_TIMEOUT_MS = 120_000; /** Tail of the queue. Each caller awaits the previous one before it chdirs. */ let queue: Promise = Promise.resolve(); @@ -32,11 +80,44 @@ let queue: Promise = Promise.resolve(); */ const insideCallback = new AsyncLocalStorage(); +/** Take the cross-isolate turn, waiting for whoever holds it to finish. */ +async function acquireLock(): Promise { + const deadline = Date.now() + ACQUIRE_TIMEOUT_MS; + for (;;) { + try { + await Deno.mkdir(LOCK_PATH); + return; + } catch (error) { + if (!(error instanceof Deno.errors.AlreadyExists)) throw error; + if (Date.now() >= deadline) { + throw TIMEOUT_ERROR.create({ + detail: + `Timed out waiting ${ACQUIRE_TIMEOUT_MS}ms for the test working-directory lock. ` + + `If no test run is active, remove ${LOCK_PATH} and retry.`, + context: { lockPath: LOCK_PATH, timeoutMs: ACQUIRE_TIMEOUT_MS }, + }); + } + // Jittered so that isolates released together do not collide again. + await new Promise((resolve) => setTimeout(resolve, POLL_MS + Math.random() * POLL_MS)); + } + } +} + +/** Hand the cross-isolate turn to whoever is polling for it next. */ +async function releaseLock(): Promise { + try { + await Deno.remove(LOCK_PATH); + } catch (error) { + if (!(error instanceof Deno.errors.NotFound)) throw error; + } +} + /** * Run `fn` with the process working directory set to `dir`. * - * Waits for any other caller to finish first, and restores the previous - * directory afterwards even if `fn` throws. + * Waits for any other caller to finish first -- in this file and in every other + * test file sharing the process -- and returns to the repository root + * afterwards even if `fn` throws. * * @param dir directory to enter * @param fn work to run inside it @@ -49,19 +130,25 @@ export function withCwd(dir: string, fn: () => Promise | T): Promise { // under the outer caller, which is the exact hazard this exists to prevent. if (insideCallback.getStore()) { return Promise.reject( - new Error( - "withCwd cannot be nested: the inner call would move the directory the outer call is using.", - ), + NESTED_CWD_SCOPE.create({ + detail: + "withCwd cannot be nested: the inner call would move the directory the outer call is using.", + context: { dir }, + }), ); } const run = queue.then(async () => { - const previous = Deno.cwd(); + await acquireLock(); try { Deno.chdir(dir); return await insideCallback.run(true, fn); } finally { - Deno.chdir(previous); + try { + Deno.chdir(ANCHOR); + } finally { + await releaseLock(); + } } }); From da7e306d7af229b673337237dca9bd5a3f8813a9 Mon Sep 17 00:00:00 2001 From: Koji Wakayama Date: Sun, 9 Aug 2026 12:17:53 +0200 Subject: [PATCH 6/7] test: move every process-directory mutation onto withCwd No test calls `Deno.chdir` directly any more, which is what the helper needs to be worth having: a queue that half the callers ignore serializes nothing. `webhook/handler.test.ts` had grown its own queue for this, which is why the hazard was already felt there. Its queue ordered only its own callers, so it is replaced rather than kept. The others held the directory from setup to a distant `finally`, spanning work that never needed it. Each now scopes it to the call that actually resolves a relative path, so the turn is held for a command rather than a test. The `afterEach` restores are gone too. They were the same hazard in a quieter form: reaching for the directory outside a turn, which takes it from whichever file holds it now. `src/platform/compat/process.test.ts` is included -- it moved the process to /tmp mid-suite. It tests `chdir` itself, so it takes the turn first and exercises the call inside it. --- cli/app/operations/project-creation.test.ts | 17 +++--- cli/commands/schedule/handler.test.ts | 57 +++++++++++---------- cli/commands/webhook/handler.test.ts | 30 ++--------- cli/router.test.ts | 17 +++--- src/platform/compat/process.test.ts | 32 ++++++++---- 5 files changed, 74 insertions(+), 79 deletions(-) diff --git a/cli/app/operations/project-creation.test.ts b/cli/app/operations/project-creation.test.ts index 43e67831eb..fe2a54f114 100644 --- a/cli/app/operations/project-creation.test.ts +++ b/cli/app/operations/project-creation.test.ts @@ -3,6 +3,7 @@ import "#veryfront/schemas/_test-setup.ts"; import { assertEquals } from "#veryfront/testing/assert.ts"; import { describe, it } from "#veryfront/testing/bdd.ts"; import { _resetEnvironmentConfig } from "#veryfront/config/environment-config.ts"; +import { withCwd } from "#veryfront/testing/cwd.ts"; import { join } from "veryfront/platform/path"; import { createProject } from "./project-creation.ts"; import { createInitialState } from "../state.ts"; @@ -21,7 +22,6 @@ function restoreEnv(name: string, value: string | undefined): void { describe("TUI project creation", () => { it("links the created project when the reservation omits the id", async () => { const originalFetch = globalThis.fetch; - const originalCwd = Deno.cwd(); const envKeys = ["VERYFRONT_API_URL", "VERYFRONT_API_BASE_URL", "XDG_CONFIG_HOME"]; const savedEnv = envKeys.map((key) => Deno.env.get(key)); const workDir = await Deno.makeTempDir(); @@ -35,7 +35,6 @@ describe("TUI project creation", () => { Deno.env.delete("VERYFRONT_API_BASE_URL"); Deno.env.set("XDG_CONFIG_HOME", configHome); _resetEnvironmentConfig(); - Deno.chdir(workDir); globalThis.fetch = ((input: string | URL | Request, init?: RequestInit) => { const request = input instanceof Request ? input : new Request(input, init); @@ -57,11 +56,14 @@ describe("TUI project creation", () => { throw new Error(`Unexpected request: ${request.method} ${url.pathname}`); }) as typeof fetch; - const state = await createProject( - { state: createInitialState(), render: () => {} }, - "My App", - "minimal", - ); + // Only the call itself needs the directory: it resolves the new project + // relative to the process cwd. Everything around it uses absolute paths. + const state = await withCwd(workDir, () => + createProject( + { state: createInitialState(), render: () => {} }, + "My App", + "minimal", + )); const link = JSON.parse( await Deno.readTextFile( @@ -81,7 +83,6 @@ describe("TUI project creation", () => { ); } finally { globalThis.fetch = originalFetch; - Deno.chdir(originalCwd); envKeys.forEach((key, index) => restoreEnv(key, savedEnv[index])); _resetEnvironmentConfig(); await Deno.remove(workDir, { recursive: true }); diff --git a/cli/commands/schedule/handler.test.ts b/cli/commands/schedule/handler.test.ts index 98b567a85f..6500f7137c 100644 --- a/cli/commands/schedule/handler.test.ts +++ b/cli/commands/schedule/handler.test.ts @@ -10,6 +10,7 @@ import { clearProjectAgentRuntimeRegistries } from "../../../src/agent/project/a import { _resetEnvironmentConfig } from "#veryfront/config/environment-config.ts"; import { stop as stopEsbuild } from "veryfront/extensions/bundler"; import { VeryfrontError } from "veryfront/errors"; +import { withCwd } from "#veryfront/testing/cwd.ts"; import type { CreateScheduleRunFromSourceResult, Run, VeryfrontRunsClient } from "veryfront/runs"; import { setJsonMode } from "../../shared/json-output.ts"; import type { ParsedArgs } from "../../shared/types.ts"; @@ -22,10 +23,6 @@ import { waitForRemoteScheduleRun, } from "./handler.ts"; -// Derived from the module URL rather than load-time Deno.cwd(): under -// `deno test --parallel` this module can be evaluated while a sibling test -// file is chdir'd into a soon-to-be-deleted temp directory. -const originalCwd = new URL("../../../", import.meta.url); const originalExit = Deno.exit; const originalFetch = globalThis.fetch; const originalConsoleLog = console.log; @@ -128,7 +125,8 @@ function restoreEnvironment(): void { describe("schedule command", () => { afterEach(() => { - Deno.chdir(originalCwd); + // No chdir here: withCwd already handed the directory back, and reaching + // for it outside a turn would yank it from whichever test file holds it now. // deno-lint-ignore no-explicit-any (Deno as any).exit = originalExit; globalThis.fetch = originalFetch; @@ -192,7 +190,6 @@ describe("schedule command", () => { Deno.env.delete("VERYFRONT_PROJECT_SLUG"); Deno.env.set("XDG_CONFIG_HOME", configHome); _resetEnvironmentConfig(); - Deno.chdir(projectDir); setJsonMode(true); console.log = (...args: unknown[]) => output.push(args.map(String).join(" ")); globalThis.fetch = (async ( @@ -215,16 +212,19 @@ describe("schedule command", () => { }; let exitCode: number | undefined; - try { - await handleScheduleCommand({ - _: ["schedule", "run", "process-job-submissions"], - remote: true, - json: true, - } as ParsedArgs); - } catch (error) { - if (!(error instanceof ExitSentinel)) throw error; - exitCode = error.code; - } + // Held only for the command, which resolves veryfront.json from the cwd. + await withCwd(projectDir, async () => { + try { + await handleScheduleCommand({ + _: ["schedule", "run", "process-job-submissions"], + remote: true, + json: true, + } as ParsedArgs); + } catch (error) { + if (!(error instanceof ExitSentinel)) throw error; + exitCode = error.code; + } + }); assertEquals(exitCode, 0); assertEquals(requests.map((request) => request.url), [ @@ -263,7 +263,6 @@ describe("schedule command", () => { }, }); } finally { - Deno.chdir(originalCwd); await stopEsbuild(); await Deno.remove(projectDir, { recursive: true }); await Deno.remove(configHome, { recursive: true }); @@ -319,7 +318,6 @@ describe("schedule command", () => { ].join("\n"), ); - Deno.chdir(projectDir); setJsonMode(true); console.log = (...args: unknown[]) => output.push(args.map(String).join(" ")); // deno-lint-ignore no-explicit-any @@ -328,22 +326,25 @@ describe("schedule command", () => { }; let exitCode: number | undefined; - try { - await handleScheduleCommand({ - _: ["schedule", "run", "timed-task"], - json: true, - } as ParsedArgs); - } catch (error) { - if (!(error instanceof ExitSentinel)) throw error; - exitCode = error.code; - } + // Held only for the command, which discovers schedules/ and tasks/ + // relative to the cwd. + await withCwd(projectDir, async () => { + try { + await handleScheduleCommand({ + _: ["schedule", "run", "timed-task"], + json: true, + } as ParsedArgs); + } catch (error) { + if (!(error instanceof ExitSentinel)) throw error; + exitCode = error.code; + } + }); assertEquals(exitCode, 0); assertEquals(JSON.parse(output.at(-1) ?? "{}").data.output, { signalPresent: true, }); } finally { - Deno.chdir(originalCwd); await stopEsbuild(); await Deno.remove(projectDir, { recursive: true }); } diff --git a/cli/commands/webhook/handler.test.ts b/cli/commands/webhook/handler.test.ts index dedfb526b4..8436d6ff8a 100644 --- a/cli/commands/webhook/handler.test.ts +++ b/cli/commands/webhook/handler.test.ts @@ -10,17 +10,13 @@ import { clearProjectAgentRuntimeRegistries } from "#veryfront/agent/project/age import { clearTranspileCache } from "#veryfront/discovery/transpiler.ts"; import { stop as stopEsbuild } from "veryfront/extensions/bundler"; import { VeryfrontError } from "veryfront/errors"; +import { withCwd } from "#veryfront/testing/cwd.ts"; import { setJsonMode } from "../../shared/json-output.ts"; import type { ParsedArgs } from "../../shared/types.ts"; import { handleWebhookCommand, toWebhookAgentOptions } from "./handler.ts"; -// Derived from the module URL rather than load-time Deno.cwd(): under -// `deno test --parallel` this module can be evaluated while a sibling test -// file is chdir'd into a soon-to-be-deleted temp directory. -const originalCwd = new URL("../../../", import.meta.url); const originalExit = Deno.exit; const originalConsoleLog = console.log; -let cwdCommandTail: Promise = Promise.resolve(); class ExitSentinel extends Error { constructor(readonly code: number) { @@ -50,34 +46,20 @@ async function runCommand(args: ParsedArgs): Promise<{ return { exitCode, output }; } -async function runCommandInProjectCwd( +function runCommandInProjectCwd( projectDir: string, args: ParsedArgs, ): Promise<{ exitCode: number | undefined; output: string[]; }> { - const previousTail = cwdCommandTail.catch(() => {}); - let release!: () => void; - cwdCommandTail = previousTail.then(() => - new Promise((resolve) => { - release = resolve; - }) - ); - await previousTail; - - try { - Deno.chdir(projectDir); - return await runCommand(args); - } finally { - Deno.chdir(originalCwd); - release(); - } + return withCwd(projectDir, () => runCommand(args)); } describe("webhook command", () => { afterEach(() => { - Deno.chdir(originalCwd); + // No chdir here: withCwd already handed the directory back, and reaching + // for it outside a turn would yank it from whichever test file holds it now. // deno-lint-ignore no-explicit-any (Deno as any).exit = originalExit; console.log = originalConsoleLog; @@ -142,7 +124,6 @@ describe("webhook command", () => { }, }); } finally { - Deno.chdir(originalCwd); await Deno.remove(projectDir, { recursive: true }); } }); @@ -224,7 +205,6 @@ describe("webhook command", () => { }, }); } finally { - Deno.chdir(originalCwd); await Deno.remove(projectDir, { recursive: true }); } }); diff --git a/cli/router.test.ts b/cli/router.test.ts index bb5448f8da..4a5e192dfc 100644 --- a/cli/router.test.ts +++ b/cli/router.test.ts @@ -2,6 +2,7 @@ import "#veryfront/schemas/_test-setup.ts"; import { _resetEnvironmentConfig } from "#veryfront/config/environment-config.ts"; import { assertEquals } from "#veryfront/testing/assert.ts"; import { describe, it } from "#veryfront/testing/bdd.ts"; +import { withCwd } from "#veryfront/testing/cwd.ts"; import { COMMANDS } from "./help/command-definitions.ts"; import { parseLoginMethod } from "./auth/utils.ts"; import { routeCommand } from "./router.ts"; @@ -552,7 +553,6 @@ describe("cli/router helpers", () => { }); it("reports missing credentials for schedule remote JSON runs as JSON command failure", async () => { - const originalCwd = Deno.cwd(); const projectDir = await Deno.makeTempDir({ prefix: "vf-schedule-json-auth-" }); const configHome = await Deno.makeTempDir({ prefix: "vf-schedule-json-auth-config-" }); const environmentNames = [ @@ -573,18 +573,20 @@ describe("cli/router helpers", () => { `${projectDir}/veryfront.json`, JSON.stringify({ projectSlug: "json-auth-project" }), ); - Deno.chdir(projectDir); Deno.env.delete("VERYFRONT_API_URL"); Deno.env.delete("VERYFRONT_API_TOKEN"); Deno.env.delete("VERYFRONT_PROJECT_SLUG"); Deno.env.set("XDG_CONFIG_HOME", configHome); _resetEnvironmentConfig(); - const code = await runAndCaptureExit({ - _: ["schedule", "run", "process-job-submissions"], - remote: true, - json: true, - } as ParsedArgs); + // Scoped to the call that resolves veryfront.json from the cwd, rather + // than held across the whole test. + const code = await withCwd(projectDir, () => + runAndCaptureExit({ + _: ["schedule", "run", "process-job-submissions"], + remote: true, + json: true, + } as ParsedArgs)); assertEquals(code, 1); assertEquals(consoleOutput.length, 1); const parsed = JSON.parse(consoleOutput[0] ?? "{}"); @@ -596,7 +598,6 @@ describe("cli/router helpers", () => { assertEquals(parsed.error.message, "Authentication required for this operation."); assertEquals(consoleErrorOutput, []); } finally { - Deno.chdir(originalCwd); for (const name of environmentNames) { const value = originalEnvironment[name]; if (value === undefined) Deno.env.delete(name); diff --git a/src/platform/compat/process.test.ts b/src/platform/compat/process.test.ts index 080c847a17..65385d9e82 100644 --- a/src/platform/compat/process.test.ts +++ b/src/platform/compat/process.test.ts @@ -7,6 +7,7 @@ import "#veryfront/schemas/_test-setup.ts"; import { assertEquals, assertExists } from "#veryfront/testing/assert.ts"; import { afterEach, describe, it } from "#veryfront/testing/bdd.ts"; +import { withCwd } from "#veryfront/testing/cwd.ts"; import { runWithProjectEnv } from "../../server/project-env/storage.ts"; import { chdir, @@ -356,19 +357,30 @@ describe("Process Compat", () => { }); describe("chdir", () => { - it("should change and restore directory", () => { - const original = cwd(); - + it("should change and restore directory", async () => { + // Takes the shared turn first. The directory belongs to the process, so + // moving it while another test file is resolving a relative path is the + // race `withCwd` exists to prevent -- and reading `cwd()` to restore from + // is only meaningful once this test owns it. + const base = await Deno.makeTempDir({ prefix: "vf-compat-chdir-" }); try { - chdir("/tmp"); - const newDir = cwd(); - // On macOS /tmp is a symlink to /private/tmp - assertEquals(newDir === "/tmp" || newDir === "/private/tmp", true); + await withCwd(base, () => { + const original = cwd(); + + try { + chdir("/tmp"); + const newDir = cwd(); + // On macOS /tmp is a symlink to /private/tmp + assertEquals(newDir === "/tmp" || newDir === "/private/tmp", true); + } finally { + chdir(original); + } + + assertEquals(cwd(), original); + }); } finally { - chdir(original); + await Deno.remove(base, { recursive: true }); } - - assertEquals(cwd(), original); }); }); From 48921b33a9a915546fe6f7d97adb26028dad2aaa Mon Sep 17 00:00:00 2001 From: Koji Wakayama Date: Sun, 9 Aug 2026 12:27:57 +0200 Subject: [PATCH 7/7] docs: regenerate the API reference for the new error slug `src/errors/index.ts` re-exports every registered error, so adding one makes `docs/api-reference/veryfront/errors.md` stale and fails `ci (lint)`. The line pins shift with it; regenerated rather than hand-edited. --- docs/api-reference/veryfront/errors.md | 32 ++++++++++++++------------ 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/docs/api-reference/veryfront/errors.md b/docs/api-reference/veryfront/errors.md index 985c4d750f..bb24b7e1db 100644 --- a/docs/api-reference/veryfront/errors.md +++ b/docs/api-reference/veryfront/errors.md @@ -107,6 +107,7 @@ throw INVALID_WIDGET.create({ detail: "The widget id is malformed." }); | `MIDDLEWARE_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/runtime.ts#L51) | | `MODULE_ERROR_CATALOG` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/catalog/module-errors.ts#L4) | | `MODULE_NOT_FOUND` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/module.ts#L3) | +| `NESTED_CWD_SCOPE` | A scope that owns the process working directory was opened inside another one. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L103) | | `NETWORK_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/server.ts#L83) | | `NOT_SUPPORTED` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L68) | | `ORCHESTRATION_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/agent.ts#L35) | @@ -253,21 +254,22 @@ import { #### Components -| Name | Description | Source | -| ------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `AUTHENTICATION_REQUIRED` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L11) | -| `FILE_NOT_FOUND` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L27) | -| `GENERAL_REGISTRY` | Registry fragment for GENERAL errors (slug → definition). | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L111) | -| `INITIALIZATION_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L60) | -| `INPUT_VALIDATION_FAILED` | HTTP request input validation failures (replaces ValidationError) | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L86) | -| `INVALID_ARGUMENT` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L43) | -| `NOT_SUPPORTED` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L68) | -| `PERMISSION_DENIED` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L19) | -| `PROJECT_SOURCE_EMPTY` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L94) | -| `RESOURCE_NOT_FOUND` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L35) | -| `SECURITY_VIOLATION` | Path traversal / secure-fs violations (replaces SecurityError) | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L77) | -| `TIMEOUT_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L52) | -| `UNKNOWN_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L3) | +| Name | Description | Source | +| ------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | +| `AUTHENTICATION_REQUIRED` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L11) | +| `FILE_NOT_FOUND` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L27) | +| `GENERAL_REGISTRY` | Registry fragment for GENERAL errors (slug → definition). | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L121) | +| `INITIALIZATION_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L60) | +| `INPUT_VALIDATION_FAILED` | HTTP request input validation failures (replaces ValidationError) | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L86) | +| `INVALID_ARGUMENT` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L43) | +| `NESTED_CWD_SCOPE` | A scope that owns the process working directory was opened inside another one. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L103) | +| `NOT_SUPPORTED` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L68) | +| `PERMISSION_DENIED` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L19) | +| `PROJECT_SOURCE_EMPTY` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L94) | +| `RESOURCE_NOT_FOUND` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L35) | +| `SECURITY_VIOLATION` | Path traversal / secure-fs violations (replaces SecurityError) | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L77) | +| `TIMEOUT_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L52) | +| `UNKNOWN_ERROR` | | [source](https://github.com/veryfront/veryfront-code/blob/main/src/errors/error-registry/general.ts#L3) | ### `veryfront/errors/module`