@http-forge/core 0.6.36-beta.1 → 0.6.36-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -239,8 +239,8 @@ ${s}
239
239
  `);let f="";p.once("data",h=>{if(f+=h.toString(),!f.includes("200")){d(new Error(`Proxy CONNECT failed: ${f.split(`\r
240
240
  `)[0]}`)),p.destroy();return}let g=cd.connect({...s,socket:p,servername:t});g.once("error",y=>d(y)),g.once("secureConnect",()=>d(null,g))})}),p.once("error",m=>d(m))},l}hostMatchesBypass(e,t){let n=t.toLowerCase().trim(),s=e.toLowerCase();return n==="*"?!0:n.startsWith("*.")?s===n.slice(2)||s.endsWith(`.${n.slice(2)}`):s===n}resolveTlsSettings(e,t){let n=t.tls||{};if(!!(n.caPath||n.certPath||n.keyPath||n.pfxPath||n.servername||n.passphrase))return n;let i=this.findCertificateMapping(e,t.certificates||[]);return i?{caPath:i.caPath,certPath:i.certPath,keyPath:i.keyPath,pfxPath:i.pfxPath,passphrase:i.passphrase,servername:i.servername}:n}findCertificateMapping(e,t){if(!Array.isArray(t)||t.length===0)return;let n=e.hostname,s=e.port?Number(e.port):443,i=t.find(o=>this.mappingMatchesHost(o,n,s,!0));return i||t.find(o=>this.mappingMatchesHost(o,n,s,!1))}mappingMatchesHost(e,t,n,s){if(!e||e.enabled===!1)return!1;let i=String(e.host||"").trim().toLowerCase();if(!i||e.port!=null&&Number(e.port)!==n)return!1;let o=t.toLowerCase();if(s)return i!=="*"&&!i.startsWith("*.")&&o===i;if(i==="*")return!0;if(i.startsWith("*.")){let a=i.slice(2);return o===a||o.endsWith(`.${a}`)}return o===i}readOptionalFile(e,t){if(!e)return;let n=uo.isAbsolute(e)?e:uo.resolve(this.basePath,e);try{return ad.readFileSync(n)}catch(s){throw new Error(`[NodeHttpClient] Failed to read ${t} file at ${n}: ${s?.message||"Unknown error"}`)}}parseCookies(e,t){return e?e.map(n=>{let s=n.split(";").map(u=>u.trim()),[i,...o]=s,[a,c]=i.split("="),l={name:a.trim(),value:c?.trim()||"",domain:t};for(let u of o){let[d,p]=u.split("=");switch(d.toLowerCase().trim()){case"domain":l.domain=p?.trim();break;case"path":l.path=p?.trim();break;case"expires":l.expires=p?.trim();break;case"httponly":l.httpOnly=!0;break;case"secure":l.secure=!0;break}}return l}):[]}}});var jc,hn,mo=E(()=>{"use strict";_c();jc={json:"application/json",xml:"application/xml",html:"text/html",text:"text/plain",javascript:"application/javascript",css:"text/css","x-www-form-urlencoded":"application/x-www-form-urlencoded","form-data":"multipart/form-data",graphql:"application/json"},hn=class{sanitizeHeaderValue(e){return Nc(e)}sanitizeHeaders(e){return co(e)}encodeBody(e){if(!e||e.type==="none")return null;let{type:t,content:n}=e;switch(t){case"x-www-form-urlencoded":return this.encodeUrlEncodedBody(n);case"form-data":return n;case"graphql":return this.encodeGraphQLBody(n);case"raw":return n;default:return n}}encodeUrlEncodedBody(e){if(Array.isArray(e)){let t=new URLSearchParams;for(let n of e)n.enabled!==!1&&n.key&&t.append(n.key,n.value||"");return t.toString()}return typeof e=="string"?e:String(e)}encodeGraphQLBody(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{return e}if(typeof e=="object"&&e!==null&&e.query){let t=e.variables;if(typeof t=="string")try{t=t.trim()?JSON.parse(t):void 0}catch{t=void 0}return JSON.stringify({query:e.query,...t!=null?{variables:t}:{},...e.operationName?{operationName:e.operationName}:{}})}return JSON.stringify(e)}setContentTypeHeader(e,t,n){if(Object.keys(e).some(o=>o.toLowerCase()==="content-type"))return;if(n){e["Content-Type"]=n;return}if(!t||t.type==="none")return;let i;switch(t.type){case"x-www-form-urlencoded":i=jc["x-www-form-urlencoded"];break;case"raw":i=t.format?jc[t.format]:"text/plain",i||(i="text/plain");break;case"graphql":i=jc.graphql;break;case"binary":i="application/octet-stream";break}i&&(e["Content-Type"]=i)}}});var yn,ho=E(()=>{"use strict";yn=class{parse(e,t){return t.toLowerCase().endsWith(".json")?this.parseJson(e):this.parseCsv(e)}parseJson(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[t]}catch{throw new Error("Failed to parse JSON data file: Invalid JSON format")}}parseCsv(e){let t=e.split(/\r?\n/).filter(i=>i.trim());if(t.length<2)return[{}];let n=this.parseCsvLine(t[0]),s=[];for(let i=1;i<t.length;i++){let o=this.parseCsvLine(t[i]),a={};n.forEach((c,l)=>{a[c]=o[l]||""}),s.push(a)}return s}parseCsvLine(e){let t=[],n="",s=!1;for(let i=0;i<e.length;i++){let o=e[i],a=e[i+1];o==='"'?s&&a==='"'?(n+='"',i++):s=!s:o===","&&!s?(t.push(n.trim()),n=""):n+=o}return t.push(n.trim()),t}}});var Lr,Oh,Hr,Lc=E(()=>{"use strict";Lr=T(require("crypto")),Oh=3e4,Hr=class{constructor(e,t,n,s,i="henry-huang.http-forge/oauth2/callback"){this.secretStore=e;this.browserService=t;this.envConfigService=n;this.httpService=s;this.callbackPath=i}secretStore;browserService;envConfigService;httpService;callbackPath;tokenCache=new Map;pendingAuthCallback=null;pendingImplicitCallback=null;async getToken(e,t){if(e.accessToken)return{accessToken:this.resolve(e.accessToken,t),tokenType:e.tokenPrefix||"Bearer",raw:{}};let n=this.buildCacheKeyString(e),s=this.tokenCache.get(n);if(s&&!this.isExpired(s))return s;if(s?.refreshToken)try{return await this.refreshToken(e,s.refreshToken,t)}catch{this.tokenCache.delete(n)}if(!s){let o=await this.secretStore.get(`oauth2_refresh_${n}`);if(o)try{return await this.refreshToken(e,o,t)}catch{await this.secretStore.delete(`oauth2_refresh_${n}`)}}let i;switch(e.grantType){case"client_credentials":i=await this.fetchToken(e,t,"client_credentials");break;case"password":i=await this.fetchToken(e,t,"password");break;case"authorization_code":i=await this.authorizationCodeFlow(e,t);break;case"implicit":i=await this.implicitFlow(e,t);break;default:throw new Error(`Unknown OAuth2 grant type: ${e.grantType}`)}return this.tokenCache.set(n,i),i.refreshToken&&await this.storeRefreshToken(n,i.refreshToken),i}async refreshToken(e,t,n){let s=this.resolve(e.tokenUrl||"",n);if(!s)throw new Error("OAuth2 tokenUrl is required for token refresh");let i=this.resolve(e.clientId||"",n),o=this.resolve(e.clientSecret||"",n),a=new URLSearchParams;a.append("grant_type","refresh_token"),a.append("refresh_token",t);let c={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,c,a,i,o,n);let l=await this.httpService.execute({method:"POST",url:s,headers:c,body:a.toString()}),u=this.parseTokenResponse(l.body,e);u.refreshToken||(u.refreshToken=t);let d=this.buildCacheKeyString(e);return this.tokenCache.set(d,u),u.refreshToken&&await this.storeRefreshToken(d,u.refreshToken),u}async authorizationCodeFlow(e,t){let n=this.resolve(e.authUrl||"",t),s=this.resolve(e.tokenUrl||"",t),i=this.resolve(e.clientId||"",t),o=this.resolve(e.clientSecret||"",t),a=e.scope?this.resolve(e.scope,t):void 0;if(!n)throw new Error("OAuth2 authUrl is required for authorization code flow");if(!s)throw new Error("OAuth2 tokenUrl is required for authorization code flow");if(!i)throw new Error("OAuth2 clientId is required for authorization code flow");let c=e.usePkce!==!1,l,u,d;if(c){l=this.generateCodeVerifier();let R=e.pkceMethod||"S256";u=R==="S256"?this.generateCodeChallengeS256(l):l,d=R}let p=e.state||Lr.randomBytes(16).toString("hex"),m=await this.getCallbackUri(),f=new URL(n);if(f.searchParams.set("response_type","code"),f.searchParams.set("client_id",i),f.searchParams.set("redirect_uri",m),a&&f.searchParams.set("scope",a),f.searchParams.set("state",p),u&&(f.searchParams.set("code_challenge",u),f.searchParams.set("code_challenge_method",d)),e.audience&&f.searchParams.set("audience",this.resolve(e.audience,t)),e.resource&&f.searchParams.set("resource",this.resolve(e.resource,t)),e.extraParams)for(let[R,A]of Object.entries(e.extraParams))f.searchParams.set(R,this.resolve(A,t));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let h=new Promise((R,A)=>{this.pendingAuthCallback={resolve:R,reject:A,state:p}});await this.browserService.openExternal(f.toString());let g;try{g=await Promise.race([h,new Promise((R,A)=>setTimeout(()=>{this.pendingAuthCallback=null,A(new Error("OAuth2 authorization timed out after 2 minutes"))},12e4))])}finally{this.pendingAuthCallback=null}if(g.state&&g.state!==p)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let y=new URLSearchParams;y.append("grant_type","authorization_code"),y.append("code",g.code),y.append("redirect_uri",m),l&&y.append("code_verifier",l);let v={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,v,y,i,o,t);let w=await this.httpService.execute({method:"POST",url:s,headers:v,body:y.toString()}),b=this.parseTokenResponse(w.body,e),C=this.buildCacheKeyString(e);return this.tokenCache.set(C,b),b.refreshToken&&await this.storeRefreshToken(C,b.refreshToken),b}async implicitFlow(e,t){let n=this.resolve(e.authUrl||"",t),s=this.resolve(e.clientId||"",t),i=e.scope?this.resolve(e.scope,t):void 0;if(!n)throw new Error("OAuth2 authUrl is required for implicit flow");if(!s)throw new Error("OAuth2 clientId is required for implicit flow");let o=e.state||Lr.randomBytes(16).toString("hex"),a=await this.getCallbackUri(),c=new URL(n);if(c.searchParams.set("response_type","token"),c.searchParams.set("client_id",s),c.searchParams.set("redirect_uri",a),i&&c.searchParams.set("scope",i),c.searchParams.set("state",o),e.audience&&c.searchParams.set("audience",this.resolve(e.audience,t)),e.resource&&c.searchParams.set("resource",this.resolve(e.resource,t)),e.extraParams)for(let[m,f]of Object.entries(e.extraParams))c.searchParams.set(m,this.resolve(f,t));this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow superseded by a new request")),this.pendingImplicitCallback=null);let l=new Promise((m,f)=>{this.pendingImplicitCallback={resolve:m,reject:f,state:o}});await this.browserService.openExternal(c.toString());let u;try{u=await Promise.race([l,new Promise((m,f)=>setTimeout(()=>{this.pendingImplicitCallback=null,f(new Error("OAuth2 implicit flow timed out after 2 minutes"))},12e4))])}finally{this.pendingImplicitCallback=null}if(u.state&&u.state!==o)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let d={accessToken:u.accessToken,tokenType:u.tokenType||e.tokenPrefix||"Bearer",expiresAt:u.expiresIn?Date.now()+u.expiresIn*1e3:void 0,raw:{access_token:u.accessToken,token_type:u.tokenType,expires_in:u.expiresIn}},p=this.buildCacheKeyString(e);return this.tokenCache.set(p,d),d}handleAuthorizationCallback(e,t,n){if(n){let s=new Error(`OAuth2 authorization error: ${n}`);this.pendingAuthCallback?.reject(s),this.pendingImplicitCallback?.reject(s),this.pendingAuthCallback=null,this.pendingImplicitCallback=null;return}if(e&&this.pendingAuthCallback){this.pendingAuthCallback.resolve({code:e,state:t}),this.pendingAuthCallback=null;return}!e&&!this.pendingAuthCallback&&this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow did not receive access_token")),this.pendingImplicitCallback=null)}handleImplicitCallback(e,t,n,s){this.pendingImplicitCallback&&(this.pendingImplicitCallback.resolve({accessToken:e,tokenType:t,expiresIn:n,state:s}),this.pendingImplicitCallback=null)}clearToken(e){let t=`${e.tokenUrl}|${e.clientId}|${e.scope||""}|${e.grantType}`;this.tokenCache.delete(t),this.secretStore.delete(`oauth2_refresh_${t}`)}clearAllTokens(){for(let e of this.tokenCache.keys())this.secretStore.delete(`oauth2_refresh_${e}`);this.tokenCache.clear()}async fetchToken(e,t,n){let s=this.resolve(e.tokenUrl||"",t);if(!s)throw new Error("OAuth2 tokenUrl is required");let i=this.resolve(e.clientId||"",t),o=this.resolve(e.clientSecret||"",t),a=e.scope?this.resolve(e.scope,t):void 0,c=new URLSearchParams;if(c.append("grant_type",n),a&&c.append("scope",a),n==="password"){let d=this.resolve(e.username||"",t),p=this.resolve(e.password||"",t);if(!d)throw new Error("OAuth2 password grant requires username");c.append("username",d),c.append("password",p)}if(e.audience&&c.append("audience",this.resolve(e.audience,t)),e.resource&&c.append("resource",this.resolve(e.resource,t)),e.extraParams)for(let[d,p]of Object.entries(e.extraParams))c.append(d,this.resolve(p,t));let l={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,l,c,i,o,t);let u=await this.httpService.execute({method:"POST",url:s,headers:l,body:c.toString()});return this.parseTokenResponse(u.body,e)}applyClientAuth(e,t,n,s,i,o){if(e.clientAuthentication==="header"){let a=Buffer.from(`${s}:${i}`).toString("base64");t.Authorization=`Basic ${a}`}else s&&n.set("client_id",s),i&&n.set("client_secret",i)}parseTokenResponse(e,t){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error("OAuth2 token response is not valid JSON")}if(!n||typeof n!="object")throw new Error("OAuth2 token response is not a valid JSON object");let s=n,i=t.tokenField||"access_token",o=s[i];if(!o)throw new Error(`OAuth2 token fetch failed: '${i}' not present in response`);let a=typeof s.expires_in=="number"?s.expires_in:void 0;return{accessToken:o,tokenType:s.token_type||t.tokenPrefix||"Bearer",expiresAt:a?Date.now()+a*1e3:void 0,refreshToken:s.refresh_token,scope:s.scope,raw:s}}isExpired(e){return e.expiresAt?Date.now()>=e.expiresAt-Oh:!1}buildCacheKeyString(e){return`${e.tokenUrl||""}|${e.clientId||""}|${e.scope||""}|${e.grantType}`}async getCallbackUri(){let e=`${this.browserService.uriScheme}://${this.callbackPath}`;return this.browserService.asExternalUri(e)}resolve(e,t){return this.envConfigService.resolveVariables(e,t)}generateCodeVerifier(){return Lr.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return Lr.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,t){try{await this.secretStore.store(`oauth2_refresh_${e}`,t)}catch{}}}});function Un(r,e={}){let t=[];Object.entries(e).forEach(([n,s])=>{t.push(`${n}=${s}`)}),t.length&&Bn.writeFileSync(r,t.join(`
241
241
  `),"utf-8")}function Ur(r,e,t){t&&(t.preRequest&&t.preRequest.trim()&&Bn.writeFileSync(Br.join(r,`${e}.pre.js`),t.preRequest,"utf-8"),t.postResponse&&t.postResponse.trim()&&Bn.writeFileSync(Br.join(r,`${e}.post.js`),t.postResponse,"utf-8"))}async function ld(r,e,t,n,s){await r.exportCollectionAsRestClientFolder(t,n),e.exportEnvironmentsToFolder(n,s)}function Xs(r,e,t){r.forEach(n=>{if(n.type==="folder"){let s=Br.join(e,ve(n.name));Bn.mkdirSync(s,{recursive:!0}),Ur(s,ve(n.name),n.scripts),Xs(n.items||[],s,t)}else if(n.type==="request"){let s=n,i=ve(s.name)+".http",o=Br.join(e,i),a=$h(s,t);Bn.writeFileSync(o,a,"utf-8"),Ur(e,ve(s.name),s.scripts)}})}function $h(r,e){let t=[];t.push(`### ${e.name} / ${r.name}`),t.push(`# collection env: ${ve(e.name)}.env`),t.push(`# request scripts: ${ve(r.name)}.pre.js and .post.js`);let n=Fh(r);return t.push(`${r.method} ${n}`),(r.headers||[]).filter(s=>s.enabled!==!1).forEach(s=>{t.push(`${s.key}: ${s.value}`)}),r.body&&r.body.content&&t.push("",r.body.content),t.join(`
242
- `)}function Fh(r){let e=r.url;if(r.query&&r.query.length){let t=r.query.filter(n=>n.enabled!==!1).map(n=>`${encodeURIComponent(n.key)}=${encodeURIComponent(n.value)}`).join("&");t&&(e+=(e.includes("?")?"&":"?")+t)}return e}var Bn,Br,yo=E(()=>{"use strict";Bn=T(require("fs")),Br=T(require("path"));We()});var Fe,Hc,Vn,Bc=E(()=>{"use strict";Fe=T(require("fs")),Hc=T(require("path"));We();ln();Vn=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e,this.ensureDirectory()}ensureDirectory(){Fe.existsSync(this.collectionsDir)||Fe.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Fe.existsSync(this.collectionsDir))return[];let e=Fe.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=Hc.join(this.collectionsDir,n),i=Fe.readFileSync(s,"utf-8"),o=JSON.parse(i);o.id&&o.name&&(this.cache.set(o.id,o),t.push(o))}catch(s){console.error(`[JsonCollectionLoader] Failed to load ${n}:`,s)}return t}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.getCollectionPath(e);if(Fe.existsSync(t))try{let n=Fe.readFileSync(t,"utf-8"),s=JSON.parse(n);return this.cache.set(e,s),s}catch(n){console.error(`[JsonCollectionLoader] Failed to load collection ${e}:`,n);return}}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");e.id||(e.id=re(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Fe.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!Fe.existsSync(t))return!1;try{return await Fe.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Fe.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return Hc.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||re(e),name:e,items:[]};return await this.save(n),n}async saveScripts(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=xe(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?xe(n.items,t)?.scripts:void 0}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);t.name!==void 0&&(n.name=t.name),t.description!==void 0&&(n.description=t.description),t.version!==void 0&&(n.version=t.version),t.variables!==void 0&&(n.variables=t.variables),t.auth!==void 0&&(n.auth=t.auth),await this.save(n)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=xe(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=xe(s.items,n);if(o&&o.type==="folder")o.items=o.items||[],o.items.push(t);else throw new Error(`Parent folder ${n} not found`)}else s.items.push(t);await this.save(s)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=Ht(n.items,t);return s&&await this.save(n),s}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=xe(s.items,t);if(!i)return!1;let{id:o,type:a,...c}=n;return Object.assign(i,c),await this.save(s),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=xe(s.items,t);if(!i)return!1;let o={...i};if(!Ht(s.items,t))return!1;if(n){let a=xe(s.items,n);if(a&&a.type==="folder")a.items=a.items||[],a.items.push(o);else return s.items.push(o),!1}else s.items.push(o);return await this.save(s),!0}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;try{let i;if(t){let c=xe(s.items,t);if(!c||!c.items)return!1;i=c.items}else i=s.items;let o=new Map(i.map(c=>[c.id,c])),a=[];for(let c of n){let l=o.get(c);l&&(a.push(l),o.delete(c))}for(let c of o.values())a.push(c);if(t){let c=xe(s.items,t);c&&(c.items=a)}else s.items=a;return await this.save(s),!0}catch(i){return console.error("[JsonCollectionLoader] Failed to reorder items:",i),!1}}}});var Vr,Uc=E(()=>{"use strict";Qi();Bc();Vr=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new Bt(n):new Vn(n)}static createForFormat(e,t){return e==="folder"?new Bt(t):new Vn(t)}}});function ud(r){if(typeof r!="string")return"text";let e=r.trim();try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null)return"json"}catch{}return/^<\?xml/.test(e)||/^<([a-zA-Z_][\w\-\.]*)[\s>]/.test(e)?/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":"xml":/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":/^(function\s*\(|\(\)\s*=>|const |let |var |export |import )/.test(e)?"javascript":"text"}function Nh(r){return{info:{name:r.name,_postman_id:r.id,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:r.items.map(e=>dd(e)),event:Vc(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function dd(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(dd):[],event:Vc(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(_h),url:Mh(e),body:Dh(e),auth:jh(e.auth),description:e.description},event:Vc(e.scripts),protocolProfileBehavior:Lh(e.settings)}}}function _h(r){return{key:r.key,value:r.value,disabled:r.enabled===!1,...r.description!==void 0?{description:r.description}:{},...r.type!==void 0?{type:r.type}:{},...r.required!==void 0?{required:r.required}:{},...r.format!==void 0?{format:r.format}:{},...r.enum!==void 0?{enum:r.enum}:{},...r.deprecated!==void 0?{deprecated:r.deprecated}:{},...r.pattern!==void 0?{pattern:r.pattern}:{},...r.minLength!==void 0?{minLength:r.minLength}:{},...r.maxLength!==void 0?{maxLength:r.maxLength}:{},...r.minimum!==void 0?{minimum:r.minimum}:{},...r.maximum!==void 0?{maximum:r.maximum}:{},...r.exclusiveMinimum!==void 0?{exclusiveMinimum:r.exclusiveMinimum}:{},...r.exclusiveMaximum!==void 0?{exclusiveMaximum:r.exclusiveMaximum}:{},...r.multipleOf!==void 0?{multipleOf:r.multipleOf}:{},...r.minItems!==void 0?{minItems:r.minItems}:{},...r.maxItems!==void 0?{maxItems:r.maxItems}:{},...r.uniqueItems!==void 0?{uniqueItems:r.uniqueItems}:{},...r.nullable!==void 0?{nullable:r.nullable}:{},...r.oneOf!==void 0?{oneOf:r.oneOf}:{}}}function Mh(r){let e=r.url,t=r.url.replace(/^[a-zA-Z]+:\/\//,""),n=[],s=t.match(/^([^\/\?]+)/);if(s){let l=s[1];/^{{.*}}$/.test(l)?n=[l]:n=l.split(".")}let i=[],o=t.match(/^[^\/\?]+(\/[^\?]*)?/);if(o&&o[1]!==void 0){let l=o[1].replace(/^\//,"");l.endsWith("/")?(i=l.slice(0,-1).split("/"),i.push("")):i=l.length>0?l.split("/"):[]}let a;if(Array.isArray(r.query)&&r.query.length>0)a=r.query.map(l=>{let u={key:l.key,value:l.value};return l.enabled===!1&&(u.disabled=!0),l.description!==void 0&&(u.description=l.description),l.type!==void 0&&(u.type=l.type),l.required!==void 0&&(u.required=l.required),l.format!==void 0&&(u.format=l.format),l.enum!==void 0&&(u.enum=l.enum),l.deprecated!==void 0&&(u.deprecated=l.deprecated),l.pattern!==void 0&&(u.pattern=l.pattern),l.minLength!==void 0&&(u.minLength=l.minLength),l.maxLength!==void 0&&(u.maxLength=l.maxLength),l.minimum!==void 0&&(u.minimum=l.minimum),l.maximum!==void 0&&(u.maximum=l.maximum),l.exclusiveMinimum!==void 0&&(u.exclusiveMinimum=l.exclusiveMinimum),l.exclusiveMaximum!==void 0&&(u.exclusiveMaximum=l.exclusiveMaximum),l.multipleOf!==void 0&&(u.multipleOf=l.multipleOf),l.minItems!==void 0&&(u.minItems=l.minItems),l.maxItems!==void 0&&(u.maxItems=l.maxItems),l.uniqueItems!==void 0&&(u.uniqueItems=l.uniqueItems),l.nullable!==void 0&&(u.nullable=l.nullable),l.oneOf!==void 0&&(u.oneOf=l.oneOf),u});else{let l=t.indexOf("?");l!==-1&&(a=t.substring(l+1).split("&").map(d=>{let[p,...m]=d.split("=");return{key:p,value:m.join("=")}}))}let c;return r.params&&typeof r.params=="object"&&(c=Object.entries(r.params).map(([l,u])=>({key:l,value:String(u)}))),{raw:e,host:n.length>0?n:void 0,path:i.length>0?i:void 0,query:a&&a.length>0?a:void 0,variable:c&&c.length>0?c:void 0}}function Dh(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=ud(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||ud(e.content);return{mode:"raw",raw:e.content,options:{raw:{language:i}}}}let t=e.type==="form-data"&&Array.isArray(e.content)?e.content:e.type==="formdata"&&Array.isArray(e.fields)?e.fields:null;if(t)return{mode:"formdata",formdata:t.map(i=>({key:i.key,value:i.value,type:i.type||"text",disabled:i.enabled===!1}))};let n=e.type==="x-www-form-urlencoded"&&Array.isArray(e.content)?e.content:e.type==="urlencoded"&&Array.isArray(e.fields)?e.fields:null;if(n)return{mode:"urlencoded",urlencoded:n.map(i=>({key:i.key,value:i.value,disabled:i.enabled===!1}))};if(e.type==="file"&&e.fileName)return{mode:"file",file:{src:e.fileName}};if(e.type==="binary")return{mode:"binary",file:{}};let s=e.type==="graphql"?e.content??(e.query?e:null):null;if(s){let i=s.query??"",o=s.variables;return{mode:"graphql",graphql:{query:i,variables:o?typeof o=="string"?o:JSON.stringify(o):void 0}}}if(e.content)return{mode:"raw",raw:e.content}}function jh(r){if(!(!r||!r.type||r.type==="none")){if(r.type==="bearer")return{type:"bearer",bearer:[{key:"token",value:r.bearerToken,type:"string"}]};if(r.type==="basic"&&r.basicAuth)return{type:"basic",basic:[{key:"username",value:r.basicAuth.username,type:"string"},{key:"password",value:r.basicAuth.password,type:"string"}]}}}function Lh(r){if(!r)return;let e={};return r.followRedirects===!1&&(e.followRedirects=!1),r.followOriginalMethod===!0&&(e.followOriginalHttpMethod=!0),r.followAuthHeader===!1&&(e.followAuthorizationHeader=!1),r.maxRedirects!==void 0&&(e.maxRedirects=r.maxRedirects),r.strictSSL===!1&&(e.disableUrlEncoding=!1),r.timeout!==void 0&&(e.requestTimeout=r.timeout),Object.keys(e).length>0?e:void 0}function Vc(r){if(!r)return[];let e=[];return r.preRequest&&e.push({listen:"prerequest",script:{type:"text/javascript",exec:[r.preRequest]}}),r.postResponse&&e.push({listen:"test",script:{type:"text/javascript",exec:[r.postResponse]}}),e}var le,vt,zr,zc=E(()=>{"use strict";We();yo();Uc();ln();le=T(require("fs")),vt=T(require("path"));zr=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=Vr.create(e),this.ensureCollectionsDir(),this.loadCollections(),this.setupFileWatcher()}configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){le.existsSync(this.collectionsDir)||le.mkdirSync(this.collectionsDir,{recursive:!0})}loadCollections(){this.collections.clear();let e=this.loader.loadAll();for(let t of e)this.collections.set(t.id,t)}setupFileWatcher(){if(!this.fileWatcherFactory)return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.collectionsDir,"**/*");let e=()=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null;let t=this.selfWritePending;this.selfWritePending=!1,t||this.loadCollections(),this.onCollectionsChanged?.()},300)};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}getAllCollections(){return Array.from(this.collections.values())}getCollection(e){return this.collections.get(e)}getCollectionById(e){for(let t of this.collections.values())if(t.id===e)return t}getCollectionByName(e){let t=e.toLowerCase();for(let n of this.collections.values())if(n.name.toLowerCase()===t)return n}async saveCollection(e){if(this.ensureCollectionsDir(),!e.name)throw new Error("Collection name is required");e.id||(e.id=re(e.name)),this.selfWritePending=!0,await this.loader.save(e),this.collections.set(e.id,e)}getCollectionVariables(e){let t=this.collections.get(e);return t?.variables?{...t.variables}:{}}getCollectionVariableLocals(e){return{...this.localCollectionValues.get(e)||{}}}setCollectionVariable(e,t,n){this.localCollectionValues.has(e)||this.localCollectionValues.set(e,{}),this.localCollectionValues.get(e)[t]=String(n)}deleteCollectionVariable(e,t){let n=this.localCollectionValues.get(e);n&&delete n[t]}clearCollectionVariables(e){this.localCollectionValues.set(e,{})}async deleteCollection(e){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let n=await this.loader.delete(e);return n&&this.collections.delete(e),n}findRequest(e,t){let n=this.collections.get(e);if(n)return this.findItemRecursive(n.items,t)}findRequestByPath(e,t){let n=this.collections.get(e);if(!n)return;let s=t.split("/").filter(i=>i.trim());return this.findItemByPath(n.items,s)}async updateRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,n);if(i){let o=this.findItemRecursive(s.items,t);if(o){let{id:a,type:c,...l}=n;Object.assign(o,l)}}return i}async addRequest(e,t,n){if(!this.collections.get(e))return!1;t.id||(t.id=re(t.name)),this.selfWritePending=!0;try{return await this.loader.saveItem(e,t,n),!0}catch(i){return console.error("[CollectionService] Failed to add request:",i),!1}}async deleteRequest(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&this.deleteItemRecursive(n.items,t),s}getAllRequests(e){let t=this.collections.get(e);if(!t)return[];let n=[];return this.collectRequestsRecursive(t.items,n),n}findItemRecursive(e,t){for(let n of e){if(n.id===t)return n;if(n.type==="folder"&&n.items){let s=this.findItemRecursive(n.items,t);if(s)return s}}}findItemByPath(e,t){if(t.length===0)return;let[n,...s]=t,i=e.find(o=>o.name===n);if(i){if(s.length===0)return i;if(i.type==="folder"&&i.items)return this.findItemByPath(i.items,s)}}deleteItemRecursive(e,t){for(let n=0;n<e.length;n++){let s=e[n];if(s.id===t)return e.splice(n,1),!0;if(s.type==="folder"&&s.items&&this.deleteItemRecursive(s.items,t))return!0}return!1}collectRequestsRecursive(e,t){for(let n of e)n.type==="request"?t.push(n):n.type==="folder"&&n.items&&this.collectRequestsRecursive(n.items,t)}async createCollection(e){let t={id:re(e),name:e,items:[]};return await this.saveCollection(t),t}async renameCollection(e,t){let n=this.collections.get(e);return n?(n.name=t,await this.saveCollection(n),!0):!1}async duplicateCollection(e,t){if(!this.collections.get(e))throw new Error(`Collection not found: ${e}`);this.selfWritePending=!0;let s=re(t),i=this.loader.getCollectionPath(e),o=vt.join(this.collectionsDir,s);if(!le.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=vt.join(o,"collection.json");if(le.existsSync(a)){let l=JSON.parse(le.readFileSync(a,"utf-8"));l.id=s,l.name=t,le.writeFileSync(a,JSON.stringify(l,null,2))}else le.writeFileSync(a,JSON.stringify({id:s,name:t},null,2));this.loadCollections();let c=this.collections.get(s);if(!c)throw new Error("Failed to load duplicated collection");return c}async createFolder(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:re(e.name),type:"folder",name:e.name,items:[]};await this.loader.saveItem(e.collectionId,n,e.parentId);let s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async deleteFolder(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&Ht(n.items,t),s}async renameFolder(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=xe(s.items,t);o&&(o.name=n)}return i}async duplicateFolder(e,t,n){if(!this.collections.get(e))throw new Error("Collection not found");let i=this.loader.getItemPath(e,t);if(!i||!le.existsSync(i))throw new Error(`Folder not found on disk: ${t}`);let o=vt.dirname(i),a=re(n),c=vt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=vt.join(c,"folder.json");if(le.existsSync(l)){let p=JSON.parse(le.readFileSync(l,"utf-8"));p.id=a,p.name=n,le.writeFileSync(l,JSON.stringify(p,null,2))}else le.writeFileSync(l,JSON.stringify({id:a,name:n,type:"folder"},null,2));this.loadCollections();let u=this.collections.get(e),d=u?xe(u.items,a):void 0;return d||{id:a,type:"folder",name:n,items:[]}}async createRequest(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:e.id||re(e.name),type:"request",name:e.name,method:e.method||"GET",url:e.url,params:e.params,query:e.query,headers:e.headers,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts,deprecated:e.deprecated,description:e.description,doc:e.doc,responseSchema:e.responseSchema,bodySchema:e.bodySchema,operationId:e.operationId,summary:e.summary,tags:e.tags,examples:e.examples,responses:e.responses,security:e.security};await this.loader.saveItem(e.collectionId,n,e.parentId);let s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async renameRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=xe(s.items,t);o&&(o.name=n)}return i}async moveItem(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.moveItem(e,t,n);return i&&this.loadCollections(),i}async reorderItems(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.reorderItems(e,t,n);return i&&this.loadCollections(),i}getRequestScript(e,t,n){let s=this.collections.get(e);if(!s)return;let i=xe(s.items,t);if(!i||i.type!=="request")return;let o=i;return n==="pre-request"?o.scripts?.preRequest:o.scripts?.postResponse}async setRequestScript(e,t,n,s){let i=this.collections.get(e);if(!i)return!1;let o=xe(i.items,t);if(!o||o.type!=="request")return!1;let a=o,l={...a.scripts??{},...n==="pre-request"?{preRequest:s}:{postResponse:s}};a.scripts=l,this.selfWritePending=!0;try{return await this.loader.saveScripts(e,t,l),!0}catch{return!1}}copyDirRecursive(e,t){le.existsSync(t)||le.mkdirSync(t,{recursive:!0});for(let n of le.readdirSync(e,{withFileTypes:!0})){let s=vt.join(e,n.name),i=vt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):le.copyFileSync(s,i)}}async importCollection(e){let t=le.readFileSync(e,"utf-8"),n;try{n=JSON.parse(t)}catch{throw new Error("Invalid JSON file")}if(n.info&&n.info._postman_id)return this.importPostmanCollection(n);let s={id:n.id||re(n.name||"Imported Collection"),name:n.name||"Imported Collection",description:n.description,items:n.items||[]};return await this.saveCollection(s),s}async importPostmanCollection(e){let t=p=>{if(!p)return;switch(p.type?.toLowerCase()){case"bearer":return{type:"bearer",bearerToken:p.bearer?.find(b=>b.key==="token")?.value||""};case"basic":let h=p.basic?.find(b=>b.key==="username"),g=p.basic?.find(b=>b.key==="password");return{type:"basic",basicAuth:{username:h?.value||"",password:g?.value||""}};case"apikey":let y=p.apikey?.find(b=>b.key==="key"),v=p.apikey?.find(b=>b.key==="value"),w=p.apikey?.find(b=>b.key==="in");return{type:"apikey",apikey:{key:y?.value||"",value:v?.value||"",in:w?.value||"header"}};case"noauth":return{type:"none"};default:return}},n=p=>{if(!Array.isArray(p)||p.length===0)return;let m={};for(let f of p){let h=f.script?.exec;if(!h)continue;let g=Array.isArray(h)?h.join(`
243
- `):h;f.listen==="prerequest"?m.preRequest=g:f.listen==="test"&&(m.postResponse=g)}return m.preRequest||m.postResponse?m:void 0},s=p=>{if(!p||typeof p!="object")return;let m={};return p.followRedirects===!1&&(m.followRedirects=!1),p.followOriginalHttpMethod===!0&&(m.followOriginalMethod=!0),p.followAuthorizationHeader===!1&&(m.followAuthHeader=!1),p.maxRedirects!==void 0&&(m.maxRedirects=p.maxRedirects),p.requestTimeout!==void 0&&(m.timeout=p.requestTimeout),Object.keys(m).length>0?m:void 0},i=p=>{if(!p||typeof p=="string")return;let m=p.query;if(!(!Array.isArray(m)||m.length===0))return m.map(f=>({key:f.key||"",value:f.value||"",enabled:f.disabled!==!0,...f.description!==void 0?{description:f.description}:{},...f.type!==void 0?{type:f.type}:{},...f.required!==void 0?{required:f.required}:{},...f.format!==void 0?{format:f.format}:{},...f.enum!==void 0?{enum:f.enum}:{},...f.deprecated!==void 0?{deprecated:f.deprecated}:{},...f.pattern!==void 0?{pattern:f.pattern}:{},...f.minLength!==void 0?{minLength:f.minLength}:{},...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.minimum!==void 0?{minimum:f.minimum}:{},...f.maximum!==void 0?{maximum:f.maximum}:{},...f.exclusiveMinimum!==void 0?{exclusiveMinimum:f.exclusiveMinimum}:{},...f.exclusiveMaximum!==void 0?{exclusiveMaximum:f.exclusiveMaximum}:{},...f.multipleOf!==void 0?{multipleOf:f.multipleOf}:{},...f.minItems!==void 0?{minItems:f.minItems}:{},...f.maxItems!==void 0?{maxItems:f.maxItems}:{},...f.uniqueItems!==void 0?{uniqueItems:f.uniqueItems}:{},...f.nullable!==void 0?{nullable:f.nullable}:{},...f.oneOf!==void 0?{oneOf:f.oneOf}:{}}))},o=p=>{if(typeof p=="string")return p;if(!p)return"";let m=new Set;if(Array.isArray(p.variable))for(let h of p.variable)h.key&&m.add(h.key);if(m.size===0&&p.raw)return p.raw;let f="";if(p.protocol&&(f+=p.protocol+"://"),p.host&&(f+=Array.isArray(p.host)?p.host.join("."):p.host),p.port&&(f+=":"+p.port),p.path){let g=(Array.isArray(p.path)?p.path:[p.path]).map(y=>{let v=y.startsWith(":")?y.substring(1):y;return m.has(v)?":"+v:(y.startsWith(":"),y)});f+="/"+g.join("/")}return!f&&p.raw?p.raw:f},a=p=>{if(!Array.isArray(p)||p.length===0)return;let m={responses:{}};for(let f of p){let h=String(f.code||200),g,y={};if(Array.isArray(f.header))for(let R of f.header)!R.key||R.disabled||(R.key.toLowerCase()==="content-type"?g=R.value?.split(";")[0]?.trim():y[R.key]={description:String(R.value??""),schema:{type:"string"}});let v=f.body;if(typeof f.body=="string"&&f.body)try{v=JSON.parse(f.body)}catch{}let w=f.originalRequest,b;if(w){let R=typeof w.url=="string"?w.url:w.url?.raw??"";b=`${w.method||""} ${R}`.trim()||void 0}let C=f.name?f.name.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()||`example_${h}`:`example_${h}`;if(m.responses[h]){let R=m.responses[h];R.examples=R.examples??{},R.examples[C]={summary:b,value:v}}else m.responses[h]={description:f.name,contentType:g,examples:{[C]:{summary:b,value:v}},...Object.keys(y).length>0?{headers:y}:{}}}return Object.keys(m.responses).length>0?m:void 0},c=p=>!(!p||typeof p!="object"||p.item===void 0&&p.request===void 0&&(p.listen!==void 0||p.script!==void 0)),l=p=>p.filter(c).map(m=>{if(m.item)return{id:re(m.name),type:"folder",name:m.name||"Folder",description:m.description,auth:t(m.auth),scripts:n(m.event),items:l(m.item)};{let f=m.request||{};return{id:re(m.name),type:"request",name:m.name||f.method||"Request",description:m.description||f.description,method:typeof f.method=="string"?f.method:"GET",url:o(f.url),query:i(f.url),headers:Array.isArray(f.header)?f.header.map(h=>({key:h.key||h.name||"",value:h.value||h.value||"",enabled:h.disabled!==!0,...h.description!==void 0?{description:h.description}:{},...h.type!==void 0?{type:h.type}:{},...h.required!==void 0?{required:h.required}:{},...h.format!==void 0?{format:h.format}:{},...h.enum!==void 0?{enum:h.enum}:{},...h.deprecated!==void 0?{deprecated:h.deprecated}:{},...h.pattern!==void 0?{pattern:h.pattern}:{},...h.minLength!==void 0?{minLength:h.minLength}:{},...h.maxLength!==void 0?{maxLength:h.maxLength}:{},...h.minimum!==void 0?{minimum:h.minimum}:{},...h.maximum!==void 0?{maximum:h.maximum}:{},...h.exclusiveMinimum!==void 0?{exclusiveMinimum:h.exclusiveMinimum}:{},...h.exclusiveMaximum!==void 0?{exclusiveMaximum:h.exclusiveMaximum}:{},...h.multipleOf!==void 0?{multipleOf:h.multipleOf}:{},...h.minItems!==void 0?{minItems:h.minItems}:{},...h.maxItems!==void 0?{maxItems:h.maxItems}:{},...h.uniqueItems!==void 0?{uniqueItems:h.uniqueItems}:{},...h.nullable!==void 0?{nullable:h.nullable}:{},...h.oneOf!==void 0?{oneOf:h.oneOf}:{}})):[],body:(()=>{let h=f.body;if(h){if(h.mode==="raw"&&h.raw){let g=h.options?.raw?.language;return{type:"raw",format:g==="xml"?"xml":g==="html"?"html":g==="javascript"?"javascript":g==="text"?"text":"json",content:h.raw}}if(h.mode==="urlencoded"&&Array.isArray(h.urlencoded))return{type:"x-www-form-urlencoded",content:h.urlencoded.map(g=>({key:g.key||"",value:g.value||"",enabled:g.disabled!==!0}))};if(h.mode==="formdata"&&Array.isArray(h.formdata))return{type:"form-data",content:h.formdata.map(g=>({key:g.key||"",value:g.value||"",type:g.type||"text",enabled:g.disabled!==!0}))};if(h.mode==="graphql"&&h.graphql){let g;if(h.graphql.variables)try{g=JSON.parse(h.graphql.variables)}catch{g=void 0}return{type:"graphql",content:{query:h.graphql.query||"",variables:g}}}if(h.mode==="binary")return{type:"binary",content:""}}})(),auth:t(f.auth),scripts:n(m.event),settings:s(m.protocolProfileBehavior),responseSchema:a(m.response)}}}),u=l(e.item||[]),d={id:re(e.info?.name||"Imported Postman Collection"),name:e.info?.name||"Imported Postman Collection",description:e.info?.description,auth:t(e.auth),scripts:n(e.event),variables:Array.isArray(e.variable)?Object.fromEntries(e.variable.filter(p=>p&&p.key).map(p=>[p.key,String(p.value??"")])):typeof e.variable=="object"&&e.variable!==null?Object.fromEntries(Object.entries(e.variable).map(([p,m])=>[p,String(m??"")])):void 0,items:u};return await this.saveCollection(d),d}async exportCollection(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=Nh(n),i=JSON.stringify(s,null,2);le.writeFileSync(t,i,"utf-8")}async exportCollectionAsRestClientFolder(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=vt.join(t,ve(n.name));le.mkdirSync(s,{recursive:!0});let i=n.variables||{};Un(vt.join(s,`${ve(n.name)}.env`),i),Ur(s,ve(n.name),n.scripts),Xs(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var de,vn,Vt,Jc=E(()=>{"use strict";de={version:"1.0",storage:{format:"folder",root:"./.http-forge/assets",history:"./.http-forge/.cache/histories",results:"./.http-forge/.cache/results"},request:{timeout:3e4,followRedirects:!0,maxRedirects:10,strictSSL:!0,tls:{},certificates:[]},scripts:{modulePaths:["./.http-forge/assets/src","./.http-forge/assets/lib"],scope:"shared",timeout:5e3},runner:{resultsRetentionDays:7,indexPageSize:1e3,recentErrorsLimit:20,report:{maxBodyChars:1e5,embedBodies:"failed"}},environments:{default:"dev"},restClientExport:{path:"collections-rest-client",mergeGlobals:!0},mcp:{port:3100,excludedCollections:[],excludedSuites:[],toolPrefix:"",maxRequestsPerCall:500,toolMode:"auto",drilldownThreshold:100,toolPageSize:200,cors:{allowedOrigins:["http://localhost","http://127.0.0.1"]}},proxy:null,secrets:{providers:{aws:{provider:"aws"},azure:{provider:"azure",vaultUrl:""},gcp:{provider:"gcp"},vault:{provider:"vault"},op:{provider:"1password"},doppler:{provider:"doppler"}}}},vn={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},Vt={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});var fe,ge,zt,vo=E(()=>{"use strict";fe=T(require("fs")),ge=T(require("path"));Jc();zt=class{constructor(e,t,n){this.workspacePath=e;this.fileWatcherFactory=t;this.notifications=n;this.configPath=this.resolveConfigPath(),this.config=this.loadConfig(),this.setupFileWatcher()}workspacePath;fileWatcherFactory;notifications;config;configPath;fileWatchers=[];resolveConfigPath(){let e=ge.join(this.workspacePath,vn.preferred);if(fe.existsSync(e))return e;let t=ge.join(this.workspacePath,vn.legacy);return fe.existsSync(t)?t:e}loadConfig(){if(this.configPath=this.resolveConfigPath(),!fe.existsSync(this.configPath))return{...de};try{let e=fe.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return this.mergeWithDefaults(t)}catch(e){return console.error("[ConfigService] Failed to load config:",e),this.notifications?.showWarning(`Failed to parse ${ge.relative(this.workspacePath,this.configPath)}. Using default configuration.`),{...de}}}mergeWithDefaults(e){return{version:e.version??de.version,storage:{...de.storage,...e.storage},request:{...de.request,...e.request},scripts:{...de.scripts,...e.scripts},runner:{...de.runner,...e.runner,report:{...de.runner.report,...e.runner?.report}},environments:{...de.environments,...e.environments},restClientExport:{...de.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:de.proxy,mcp:{...de.mcp,...e.mcp,cors:{...de.mcp.cors,...e.mcp?.cors}},secrets:{...de.secrets,...e.secrets,providers:{...de.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let t of[vn.preferred,vn.legacy]){let n=this.fileWatcherFactory.createFileWatcher(this.workspacePath,t);n.onDidChange(e),n.onDidCreate(e),n.onDidDelete(e),this.fileWatchers.push(n)}}getConfig(){return this.config}getStorageConfig(){return this.config.storage}getRequestConfig(){return this.config.request}getScriptsConfig(){return this.config.scripts}getRunnerConfig(){let e=this.config.runner,t=e.report??de.runner.report,n=["all","failed","none"];return{...e,report:{maxBodyChars:Math.max(1e3,Math.floor(t.maxBodyChars??de.runner.report.maxBodyChars)),embedBodies:n.includes(t.embedBodies)?t.embedBodies:de.runner.report.embedBodies}}}getEnvironmentsConfig(){return this.config.environments}getRestClientExportPath(){let e=this.config.restClientExport?.path||"collections-rest-client";return ge.isAbsolute(e)?e:this.resolvePath(e)}getRestClientMergeGlobals(){return this.config.restClientExport?.mergeGlobals??!0}getProxyConfig(){return this.config.proxy??null}getMcpConfig(){let e=this.config.mcp??de.mcp,t=["flat","drilldown","auto","execution-only"];return{...e,port:Math.min(65535,Math.max(1,Math.floor(e.port??3100))),toolMode:t.includes(e.toolMode)?e.toolMode:"auto",drilldownThreshold:Math.min(500,Math.max(10,e.drilldownThreshold??100)),toolPageSize:e.toolPageSize===0?0:Math.min(1e3,Math.max(10,e.toolPageSize??200)),maxRequestsPerCall:Math.min(1e4,Math.max(1,e.maxRequestsPerCall??500))}}resolvePath(e){let t=e.startsWith("./")?e.slice(2):e;return ge.join(this.workspacePath,...t.split("/"))}hasFolderCollectionsAtRoot(e){let t=ge.join(e,Vt.collections);if(!fe.existsSync(t))return!1;let n;try{n=fe.readdirSync(t,{withFileTypes:!0})}catch{return!1}return n.some(s=>{if(!s.isDirectory())return!1;let i=ge.join(t,s.name,"collection.json");return fe.existsSync(i)})}hasAnyEntries(e){if(!fe.existsSync(e))return!1;try{return fe.readdirSync(e).length>0}catch{return!1}}resolveStorageRootPath(){let e=this.resolvePath(this.config.storage.root);return this.configExists()||this.hasFolderCollectionsAtRoot(e)?e:[ge.join(this.workspacePath,"http-forge-assets")].find(s=>this.hasFolderCollectionsAtRoot(s))||e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return ge.join(this.getRootPath(),Vt.collections)}getEnvironmentsPath(){return ge.join(this.getRootPath(),Vt.environments)}getFlowsPath(){return ge.join(this.getRootPath(),Vt.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);if(this.configExists()||this.hasAnyEntries(e))return e;let t=ge.join(this.workspacePath,".http-forge-cache","histories");return this.hasAnyEntries(t)?t:e}getResultsPath(){let e=this.resolvePath(this.config.storage.results);if(this.configExists()||this.hasAnyEntries(e))return e;let t=ge.join(this.workspacePath,".http-forge-cache","results");return this.hasAnyEntries(t)?t:e}getSuitesPath(){return ge.join(this.getRootPath(),Vt.suites)}getModulePaths(){return this.config.scripts.modulePaths.map(e=>this.resolvePath(e))}getScriptScope(){return this.config.scripts.scope??"shared"}getScriptTimeout(){return this.config.scripts.timeout??5e3}getWorkspacePath(){return this.workspacePath}onConfigReloaded;reload(){this.configPath=this.resolveConfigPath(),this.config=this.loadConfig(),this.onConfigReloaded?.()}configExists(){return fe.existsSync(this.resolveConfigPath())}async createDefaultConfig(){await fe.promises.mkdir(ge.dirname(this.configPath),{recursive:!0});let e=JSON.stringify(de,null,2);await fe.promises.writeFile(this.configPath,e,"utf-8");let t=[this.getCollectionsPath(),this.getEnvironmentsPath(),this.getFlowsPath(),this.getSuitesPath()];for(let s of t)fe.existsSync(s)||await fe.promises.mkdir(s,{recursive:!0});let n=[this.getHistoryPath(),this.getResultsPath()];for(let s of n)fe.existsSync(s)||await fe.promises.mkdir(s,{recursive:!0});await this.createSampleEnvironments()}async createSampleEnvironments(){let e=this.getEnvironmentsPath(),t={id:"globals",name:"Global Variables",variables:{appName:"HTTP Forge"}};await fe.promises.writeFile(ge.join(e,"globals.json"),JSON.stringify(t,null,2),"utf-8");let n={id:"env_dev",name:"Development",variables:{baseUrl:"http://localhost:3000",apiVersion:"v1"}};await fe.promises.writeFile(ge.join(e,"dev.json"),JSON.stringify(n,null,2),"utf-8");let s={id:"default_headers",name:"Default Headers",headers:{"Content-Type":"application/json",Accept:"application/json"}};await fe.promises.writeFile(ge.join(e,"default-headers.json"),JSON.stringify(s,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var Hh,Jr,Gc=E(()=>{"use strict";Fn();Hh="httpForge.cookies",Jr=class{constructor(e,t=Hh){this.store=e;this.storeKey=t;this.loadCookies()}store;storeKey;cookies=new Map;loadCookies(){try{let e=this.store.get(this.storeKey);e&&(this.cookies=new Map(Object.entries(e)),this.cleanExpiredCookies())}catch(e){console.error("[CookieService] Failed to load cookies:",e)}}async saveCookies(){try{let e={};this.cookies.forEach((t,n)=>{e[n]=t}),await this.store.update(this.storeKey,e)}catch(e){console.error("[CookieService] Failed to save cookies:",e)}}getCookieKey(e,t,n){return ne.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}async set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e),await this.saveCookies()}async setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}await this.saveCookies()}has(e,t){return this.get(e,t)!==void 0}async delete(e,t,n){let s=this.getCookieKey(e,t,n),i=this.cookies.delete(s);return i&&await this.saveCookies(),i}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return ne.formatCookieHeader(t)}async clear(){this.cookies.clear(),await this.saveCookies()}async clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n);await this.saveCookies()}parseCookieHeaders(e,t){return ne.parseCookieHeaders(e,t)}isExpired(e){return ne.isExpired(e)}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t);e.length>0&&this.saveCookies()}domainMatches(e,t){return ne.domainMatches(e,t)}get count(){return this.cookies.size}}});var Gr,Wc=E(()=>{"use strict";Fn();Gr=class{constructor(e){this.cookieService=e;this.localCache=[...e.getAll()]}cookieService;localCache=[];pendingOperations=[];get(e,t){return t?this.localCache.find(n=>n.name===e&&(!n.domain||n.domain===t||t.endsWith(n.domain))):this.localCache.find(n=>n.name===e)}has(e,t){return this.get(e,t)!==void 0}set(e){let t=this.localCache.findIndex(n=>n.name===e.name&&(!e.domain||n.domain===e.domain));t>=0?this.localCache[t]=e:this.localCache.push(e),this.pendingOperations.push({type:"set",cookie:e})}delete(e,t,n){let s=this.localCache.findIndex(i=>i.name===e&&(!t||i.domain===t||i.domain&&t.endsWith(i.domain)));return s>=0&&this.localCache.splice(s,1),this.pendingOperations.push({type:"delete",name:e,domain:t,path:n}),!0}getAll(e){return e?this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)}):[...this.localCache]}getCookiesForDomain(e){return this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)})}async setCookiesFromResponse(e,t){let n=new URL(e).hostname,s=this.cookieService.parseCookieHeaders(t,n);s.length>0&&(s.forEach(i=>{let o=this.localCache.findIndex(a=>a.name===i.name&&a.domain===(i.domain||n));o>=0?this.localCache[o]=i:this.localCache.push(i)}),await this.cookieService.setFromResponse(s))}getCookieHeader(e){let t=new URL(e).hostname,n=new URL(e).pathname,s=this.localCache.filter(i=>!(ne.isExpired(i)||i.domain&&!ne.domainMatches(t,i.domain)||!i.domain||i.path&&!n.startsWith(i.path)));if(s.length!==0)return ne.formatCookieHeader(s)}clear(){this.localCache=[],this.pendingOperations.push({type:"clear"})}async flush(){for(let e of this.pendingOperations)switch(e.type){case"set":e.cookie&&await this.cookieService.set(e.cookie);break;case"delete":e.name&&await this.cookieService.delete(e.name,e.domain,e.path);break;case"clear":await this.cookieService.clear();break}this.pendingOperations=[]}}});function bo(r){try{let e=JSON.parse(typeof r=="string"?r:r.toString("utf-8"));if(!e)return null;let t=e.environment||e,n=t.name||e.name||"imported-environment",s=t.values||t.variables||e.values||e.variables||[],i={};if(Array.isArray(s))for(let a of s){if(!a)continue;let c=a.key??a.name,l=typeof a.enabled=="boolean"?a.enabled:!0;c&&l!==!1&&(i[c]=a.value??a.initial??"")}else if(typeof s=="object"&&s!==null)for(let[a,c]of Object.entries(s))i[a]=String(c??"");let o=t._postman_exported_at?"Imported from Postman export":t.description||"";return{name:n,variables:i,description:o}}catch{return null}}var Kc=E(()=>{"use strict"});var ke,Ze,ei,Wr,Qc=E(()=>{"use strict";ke=T(require("fs")),Ze=T(require("path"));We();Kc();yo();Yi();Or();ei={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},Wr=class{constructor(e,t,n,s,i,o=!0){this.workspaceFolder=e;this.workspaceStore=t;this.configService=n;this.fileWatcherFactory=s;this.secretStore=i;this.persistOverrides=o;let a=n.getEnvironmentsPath();this.environmentsPath=a,this.sharedConfigPath=Ze.join(a,"_global.json"),this.localConfigPath=Ze.join(a,"_global.local.json"),this.historiesPath=n.getHistoryPath(),this.selectedEnvironment=t?.get(ei.SELECTED_ENVIRONMENT,"dev")??"dev",this.localGlobalValues={},this.localEnvironmentValues=new Map,this.persistOverrides&&this.loadPersistedEnvironmentOverrides(),this.loadSecretVariables(this.selectedEnvironment).catch(()=>{}),this.setupFileWatcher(),this.configService.onConfigReloaded=()=>this.invalidateResolvedConfigCache()}workspaceFolder;workspaceStore;configService;fileWatcherFactory;secretStore;persistOverrides;environmentsPath;sharedConfigPath;localConfigPath;historiesPath;sharedConfig=null;localConfig=null;selectedEnvironment="dev";fileWatcher;resolvedConfigCache=new Map;localGlobalValues={};localEnvironmentValues=new Map;secretValuesCache=new Map;onEnvironmentsChanged;setupFileWatcher(){if(!this.fileWatcherFactory||!ke.existsSync(this.environmentsPath))return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.environmentsPath,"**/*.json");let e=()=>{this.reload(),this.onEnvironmentsChanged?.()};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}dispose(){this.fileWatcher?.dispose()}getWorkspaceFolder(){return this.workspaceFolder}getRootPath(){return this.configService.getRootPath()}loadConfigs(){if(!ke.existsSync(this.environmentsPath)){this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}},this.localConfig={credentials:{},variables:{}};return}this.loadFolderConfigs()}getSharedConfig(){return this.sharedConfig||this.loadConfigs(),this.sharedConfig}getLocalConfig(){return this.localConfig||this.loadConfigs(),this.localConfig}getEnvironmentNames(){let e=this.getSharedConfig();return e?.environments?Object.keys(e.environments):[]}getSelectedEnvironment(){return this.selectedEnvironment}async setSelectedEnvironment(e){if(this.selectedEnvironment=e,await this.workspaceStore?.update(ei.SELECTED_ENVIRONMENT,e),!this.localEnvironmentValues.has(e)){let t=this.getEnvOverridesStateKey(e),n=this.workspaceStore?.get(t,{});n&&Object.keys(n).length>0&&this.localEnvironmentValues.set(e,{...n})}await this.loadSecretVariables(e),this.resolvedConfigCache.delete(e)}getEnvOverridesStateKey(e){return`${ei.ENV_OVERRIDES_PREFIX}${e||this.selectedEnvironment}`}loadPersistedEnvironmentOverrides(){let e=this.getEnvOverridesStateKey(),t=this.workspaceStore?.get(e,{});t&&Object.keys(t).length>0&&this.localEnvironmentValues.set(this.selectedEnvironment,{...t})}persistEnvironmentOverrides(e){if(!this.persistOverrides)return;let t=this.getEnvOverridesStateKey(e),n=this.localEnvironmentValues.get(e)||{};this.workspaceStore?.update(t,n)}setEnvironmentVariable(e,t,n){let s=n??this.selectedEnvironment;this.localEnvironmentValues.has(s)||this.localEnvironmentValues.set(s,{}),this.localEnvironmentValues.get(s)[e]=String(t),this.persistEnvironmentOverrides(s)}deleteEnvironmentVariable(e,t){let n=t??this.selectedEnvironment,s=this.localEnvironmentValues.get(n);s&&(delete s[e],this.persistEnvironmentOverrides(n))}clearEnvironmentVariables(e){let t=e??this.selectedEnvironment;this.localEnvironmentValues.set(t,{}),this.persistEnvironmentOverrides(t)}async resetEnvironmentOverrides(e){let t=e||this.selectedEnvironment;this.localEnvironmentValues.delete(t),await this.workspaceStore?.update(this.getEnvOverridesStateKey(t),void 0)}getEnvironmentVariableLocal(e){return this.localEnvironmentValues.get(this.selectedEnvironment)?.[e]}getEnvironmentVariableLocals(){return{...this.localEnvironmentValues.get(this.selectedEnvironment)||{}}}setGlobalVariable(e,t){this.localGlobalValues[e]=String(t)}getGlobalVariable(e){return this.getSharedConfig()?.globalVariables?.[e]}getGlobalVariableLocal(e){return this.localGlobalValues[e]}getGlobalVariables(){return{...this.getSharedConfig()?.globalVariables||{},...this.getLocalConfig()?.variables||{},...this.localGlobalValues}}getGlobalVariableLocals(){return{...this.localGlobalValues}}deleteGlobalVariable(e){delete this.localGlobalValues[e]}clearGlobalVariables(){this.localGlobalValues={}}getResolvedEnvironment(e){let t=e||this.selectedEnvironment,n=this.getSharedConfig(),s=this.getLocalConfig();if(!n?.environments?.[t])return null;let i=n.environments[t],o=s?.credentials?.[t],a=s?.variables||{},c=o?.variables||{},l=o&&o.headers||{},u=Gi(n.defaultHeaders||{},l),d=this.localEnvironmentValues.get(t)||{},p=this.secretValuesCache.get(t)||{},m={...i.variables||{},...c,...d,...p};return{name:t,description:i.description,requiresConfirmation:i.requiresConfirmation,headers:u,variables:m}}async getSecretVariable(e,t){return this.secretStore?.get(`${e}:${t}`)}async setSecretVariable(e,t,n){await this.secretStore?.store(`${e}:${t}`,n),this.secretValuesCache.has(e)||this.secretValuesCache.set(e,{}),this.secretValuesCache.get(e)[t]=n}async deleteSecretVariable(e,t){await this.secretStore?.delete(`${e}:${t}`),this.secretValuesCache.get(e)&&delete this.secretValuesCache.get(e)[t]}async loadSecretVariables(e){if(!this.secretStore)return;let t=e||this.selectedEnvironment,n=this.getSharedConfig()?.environments?.[t]?.secretVariables??[];if(n.length===0)return;let s={};await Promise.all(n.map(async i=>{let o=await this.secretStore.get(`${t}:${i}`);o!==void 0&&(s[i]=o)})),this.secretValuesCache.set(t,s)}resolveVariables(e,t){return this.createResolver(t).resolveString(e,!0)}exportEnvironmentsToFolder(e,t=!0){let n=this.getEnvironmentNames(),s=this.getSharedConfig(),i=s?.globalVariables?{...s.globalVariables}:{};if(!t&&Object.keys(i).length){let o=Ze.join(e,"globals.env");Un(o,i)}n.forEach(o=>{let a=s?.environments?.[o];if(!a)return;let c={...a.variables||{}};t&&(c={...i,...c});let l=Ze.join(e,`${ve(o)}.env`);Un(l,c)})}resolveVariablesWithExtra(e,t,n){return this.createResolver(n,t).resolveString(e,!0)}resolveVariablesInObject(e,t){return this.createResolver(t).resolveObject(e,!0)}resolveVariablesInObjectWithExtra(e,t,n){return this.createResolver(n,t).resolveObject(e,!0)}getHistoriesPath(){return this.historiesPath}getSharedConfigPath(){return this.sharedConfigPath}getLocalConfigPath(){return this.localConfigPath}getEnvironmentConfigPath(e){return Ze.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return ke.existsSync(this.localConfigPath)}saveSharedConfig(e){this.saveFolderSharedConfig(e),this.sharedConfig=e}saveLocalConfig(e){let t={variables:e.variables||{}};this.saveJsonFile(this.localConfigPath,t);for(let[n,s]of Object.entries(e.credentials||{})){let i=this.getEnvLocalConfigPath(n),o={variables:s.variables||{}};this.saveJsonFile(i,o)}this.localConfig=e}importPostmanEnvironmentFile(e){try{let t=ke.readFileSync(e,"utf-8"),n=bo(t);if(!n)throw new Error("Failed to parse Postman environment file");this.sharedConfig||this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}});let s=n.name||`imported-${Date.now()}`;return this.sharedConfig.environments=this.sharedConfig.environments||{},this.sharedConfig.environments[s]=this.sharedConfig.environments[s]||{},this.sharedConfig.environments[s].variables=n.variables,n.description&&(this.sharedConfig.environments[s].description=n.description),this.saveSharedConfig(this.sharedConfig),n}catch(t){throw console.error("[EnvironmentConfigService] importPostmanEnvironmentFile failed:",t),t}}saveEnvLocalConfig(e,t){let n=this.getEnvLocalConfigPath(e),s={variables:t};this.saveJsonFile(n,s),this.localConfig||(this.localConfig={credentials:{},variables:{}}),this.localConfig.credentials||(this.localConfig.credentials={}),this.localConfig.credentials[e]={variables:t}}getEnvLocalPath(e){return this.getEnvLocalConfigPath(e)}getEnvLocalConfigPath(e){return Ze.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=Ar(this.environmentsPath);this.sharedConfig={environments:e.environments,globalVariables:e.globalVariables,defaultHeaders:e.defaultHeaders},this.localConfig={credentials:e.localCredentials,variables:e.localVariables}}createResolver(e,t){let s=this.getResolvedEnvironment(e)?.variables||{},i=this.getGlobalVariables(),o=this.getGlobalVariableLocals();return new pn({globals:i,collectionVariables:{},environmentVariables:s,variables:{...o,...t||{}}})}saveFolderSharedConfig(e){ke.existsSync(this.environmentsPath)||ke.mkdirSync(this.environmentsPath,{recursive:!0});let t={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/global-environment.schema.json",variables:e.globalVariables||{},defaultHeaders:e.defaultHeaders||{}};this.saveJsonFile(this.sharedConfigPath,t);let n=ke.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!js(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=Ze.basename(i,".json");if(!s.has(o))try{ke.unlinkSync(Ze.join(this.environmentsPath,i))}catch{}}for(let[i,o]of Object.entries(e.environments||{})){let a={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/environment.schema.json",name:i,description:o.description,requiresConfirmation:o.requiresConfirmation,variables:o.variables||{}};this.saveJsonFile(Ze.join(this.environmentsPath,`${i}.json`),a)}}reload(){this.sharedConfig=null,this.localConfig=null,this.loadConfigs(),this.invalidateResolvedConfigCache()}invalidateResolvedConfigCache(){this.resolvedConfigCache.clear()}getFileOnlyVariables(e){this.loadConfigs();let t=this.sharedConfig,n=this.localConfig,s=t?.environments?.[e];return{...t?.globalVariables||{},...n?.variables||{},...s?.variables||{},...n?.credentials?.[e]?.variables||{}}}resolveConfigValues(e,t){if(e==null)return e;if(typeof e=="string"){let n=new pn({globals:{},collectionVariables:{},environmentVariables:t,variables:{}});if(/^\s*\{\{.*\}\}\s*$/.test(e)){let s=n.resolveString(e);if(s==="true")return!0;if(s==="false")return!1;let i=Number(s);return s!==""&&!isNaN(i)?i:s}return n.resolveString(e)}if(Array.isArray(e))return e.map(n=>this.resolveConfigValues(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveConfigValues(i,t);return n}return e}getResolvedConfig(e){let t=e??this.selectedEnvironment;if(!this.resolvedConfigCache.has(t)){let n=this.configService.getConfig(),s=this.getFileOnlyVariables(t),i=this.resolveConfigValues(n,s);this.resolvedConfigCache.set(t,i)}return this.resolvedConfigCache.get(t)}getAllEnvironments(){return this.loadConfigs(),this.sharedConfig?Object.entries(this.sharedConfig.environments).map(([e,t])=>({id:e,name:e,active:e===this.selectedEnvironment,variables:t.variables||{}})):[]}async setActiveEnvironment(e){await this.setSelectedEnvironment(e)}async createEnvironment(e){if(this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{}}),this.sharedConfig.environments[e])throw new Error(`Environment "${e}" already exists`);this.sharedConfig.environments[e]={description:`Created ${new Date().toISOString()}`,variables:{}},this.saveSharedConfig(this.sharedConfig)}async deleteEnvironment(e){if(this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentExists(e),delete this.sharedConfig.environments[e],this.selectedEnvironment===e){let t=Object.keys(this.sharedConfig.environments);this.selectedEnvironment=t.length>0?t[0]:"dev",await this.workspaceStore?.update(ei.SELECTED_ENVIRONMENT,this.selectedEnvironment)}this.saveSharedConfig(this.sharedConfig)}async duplicateEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),this.validateEnvironmentNameNotTaken(t);let n=this.sharedConfig.environments[e];this.sharedConfig.environments[t]=JSON.parse(JSON.stringify(n)),this.sharedConfig.environments[t].description=`Copied from ${e}`,this.saveSharedConfig(this.sharedConfig)}async renameEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),t!==e&&(this.validateEnvironmentNameNotTaken(t),this.sharedConfig.environments[t]=this.sharedConfig.environments[e],delete this.sharedConfig.environments[e],this.selectedEnvironment===e&&(this.selectedEnvironment=t,await this.workspaceStore?.update(ei.SELECTED_ENVIRONMENT,t)),this.saveSharedConfig(this.sharedConfig))}validateEnvironmentName(e){if(!e||e.trim().length===0)throw new Error("Environment name cannot be empty");if(e.length>128)throw new Error("Environment name cannot exceed 128 characters");if(!/^[a-zA-Z0-9_\-\.]+$/.test(e))throw new Error("Environment name can only contain letters, numbers, hyphens, underscores, and dots")}validateEnvironmentExists(e){if(!this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" not found`)}validateEnvironmentNameNotTaken(e){if(this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" already exists`)}validateConfigLoaded(){if(!this.sharedConfig)throw new Error("No environment configuration loaded")}async updateEnvironmentVariables(e,t){if(this.loadConfigs(),!this.sharedConfig)throw new Error("No configuration loaded");let n=this.sharedConfig.environments[e];if(!n)throw new Error(`Environment "${e}" not found`);n.variables=t,this.saveSharedConfig(this.sharedConfig)}saveJsonFile(e,t){try{let n=Ze.dirname(e);ke.existsSync(n)||ke.mkdirSync(n,{recursive:!0}),ke.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var _t,ti=E(()=>{"use strict";Qs();_t=class r{constructor(e,t,n,s,i,o,a,c,l,u,d,p,m){this.httpService=e;this.scriptExecutor=t;this.envConfigService=n;this.requestPreparer=s;this.environment=i;this.cookieJar=o;this.collectionScripts=a;this.folderScriptsChain=c;this.onConsoleOutput=l;this.collectionName=u;this.collectionAuth=d;this.iteration=p;this.iterationCount=m}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;async execute(e,t,n){let s=Date.now();return this.executeWithSession(e,t,n,s)}async executeWithSession(e,t,n,s){let i=this.collectPreRequestScripts(e),o=this.collectPostResponseScripts(e),a=this.envConfigService.getResolvedEnvironment(this.environment);if(!a)throw new Error(`Environment "${this.environment}" not found or not configured`);let c=this.envConfigService.getGlobalVariables(),l={request:e,variables:{...t},environmentVariables:a.variables||{},globals:{...c},environmentName:this.environment,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:this.collectionName,iteration:this.iteration,iterationCount:this.iterationCount},onEnvironmentChange:async(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setEnvironmentVariable(m,f,this.environment):p==="unset"&&m?this.envConfigService.deleteEnvironmentVariable(m,this.environment):p==="clear"&&this.envConfigService.clearEnvironmentVariables(this.environment)},onGlobalsChange:(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setGlobalVariable(m,f):p==="unset"&&m?this.envConfigService.deleteGlobalVariable(m):p==="clear"&&this.envConfigService.clearGlobalVariables()}},u=this.scriptExecutor.createRequestSession(l),d=null;try{let p={...t},m={...e},f;if((!m.auth||m.auth.type==="inherit")&&(m.auth=this.collectionAuth&&this.collectionAuth.type!=="inherit"?this.collectionAuth:void 0),i.length>0){let O=await u.executePreRequest(i);if(O.consoleOutput&&O.consoleOutput.length>0&&this.onConsoleOutput?.(O.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),O.nextRequest!==void 0&&(f=O.nextRequest),O.skipRequest){let L={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:L,params:{},query:{}},response:{status:0,statusText:"Skipped",headers:{},body:null,time:0,cookies:[]},duration:Date.now()-s,timestamp:Date.now(),passed:!0,assertions:[],modifiedVariables:p,nextRequest:f}}O.success&&(O.modifiedRequest&&(O.modifiedRequest.url&&(m.url=O.modifiedRequest.url),O.modifiedRequest.headers&&(m.headers=O.modifiedRequest.headers),O.modifiedRequest.params&&(m.params=O.modifiedRequest.params),O.modifiedRequest.query&&(m.query=O.modifiedRequest.query),O.modifiedRequest.body!==void 0&&(m.body=O.modifiedRequest.body)),(O.localVariables??O.modifiedVariables)&&(p=O.localVariables??O.modifiedVariables))}d=await this.requestPreparer.prepareRequest(m,this.environment,a,p);let{url:h,headers:g,body:y,method:v}=d,w={};for(let O in g)Object.prototype.hasOwnProperty.call(g,O)&&(w[O.toUpperCase()]=g[O]);if(!w.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let L=this.cookieJar.getCookieHeader(h);L&&(w.COOKIE=L)}let b={method:v,url:h,headers:w,body:y.content,signal:n,settings:m.settings?{...m.settings}:void 0},C=await this.httpService.execute(b);this.cookieJar&&C.headers&&await this.cookieJar.setCookiesFromResponse(h,C.headers);let R=Date.now()-s,A=[],N={},M;if(o.length>0){let O=0;if(C.body)if(typeof C.body=="string")O=Buffer.byteLength(C.body,"utf8");else if(Buffer.isBuffer(C.body))O=C.body.length;else try{O=Buffer.byteLength(JSON.stringify(C.body),"utf8")}catch{O=0}let L=oo(C.headers,C.cookies,d.url),Q={executedRequest:d,status:C.status,statusText:C.statusText,headers:io(C.headers||{}),body:C.body,cookies:L,responseTime:C.time,responseSize:O},Y=await u.executePostResponse(o,Q);A=Y.testResults,N=Y.modifiedEnvironmentVariables||{},M=Y.visualizerData,(Y.localVariables??Y.modifiedVariables)&&(p=Y.localVariables??Y.modifiedVariables),Y.nextRequest!==void 0&&(f=Y.nextRequest),Y.consoleOutput&&Y.consoleOutput.length>0&&this.onConsoleOutput?.(Y.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let j=A.length===0||A.every(O=>O.passed),U=A.length>0?j:C.status>=200&&C.status<=302;return{requestId:e.id,name:e.name,executedRequest:{...d,headers:w},response:{status:C.status,statusText:C.statusText,headers:C.headers||{},body:C.body,time:C.time||R,cookies:C.cookies||[]},duration:R,timestamp:Date.now(),passed:U,assertions:A,modifiedVariables:p,modifiedEnvironmentVariables:N,nextRequest:f,visualizerData:M}}catch(p){return this.handleError(e,d,p,s)}finally{u.dispose?.()}}collectPreRequestScripts(e){let t=[];if(this.collectionScripts?.preRequest&&t.push(this.collectionScripts.preRequest),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain))for(let n of this.folderScriptsChain)n?.preRequest&&t.push(n.preRequest);else this.folderScriptsChain.preRequest&&t.push(this.folderScriptsChain.preRequest);return e.scripts?.preRequest&&t.push(e.scripts.preRequest),t}collectPostResponseScripts(e){let t=[];if(e.scripts?.postResponse&&t.push(e.scripts.postResponse),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain)){let n=[...this.folderScriptsChain].reverse();for(let s of n)s?.postResponse&&t.push(s.postResponse)}else this.folderScriptsChain.postResponse&&t.push(this.folderScriptsChain.postResponse);return this.collectionScripts?.postResponse&&t.push(this.collectionScripts.postResponse),t}handleError(e,t,n,s){let i=Date.now()-s,o=t?.method||e.method,a=t?.url||e.url;this.onConsoleOutput?.([`${n.message||n}`],{requestName:e.name||"",phase:"error"});let c=String(n.name==="AbortError"?"Request was aborted":n.message||n),l=n?.stack?String(n.stack):"",u=this.errorBodyFormat,d,p;u==="html"||u==="both"?(d=r.formatErrorAsHtml(c,l),p={"content-type":"text/html; charset=utf-8"}):(d=c,p={});let m={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:a||"",method:o||"GET",headers:t?.headers||{},body:t?.body||m,params:t?.params||{},query:t?.query||{}},response:{status:0,statusText:n.name==="AbortError"?"Aborted":n.code||n.message||"Request Error",headers:p,cookies:[],body:d,time:0},duration:i,timestamp:Date.now(),passed:!1,assertions:[],error:c}}get errorBodyFormat(){return"text"}static formatErrorAsHtml(e,t){let n=s=>s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");return`<!doctype html>
242
+ `)}function Fh(r){let e=r.url;if(r.query&&r.query.length){let t=r.query.filter(n=>n.enabled!==!1).map(n=>`${encodeURIComponent(n.key)}=${encodeURIComponent(n.value)}`).join("&");t&&(e+=(e.includes("?")?"&":"?")+t)}return e}var Bn,Br,yo=E(()=>{"use strict";Bn=T(require("fs")),Br=T(require("path"));We()});var Fe,Hc,Vn,Bc=E(()=>{"use strict";Fe=T(require("fs")),Hc=T(require("path"));We();ln();Vn=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e,this.ensureDirectory()}ensureDirectory(){Fe.existsSync(this.collectionsDir)||Fe.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Fe.existsSync(this.collectionsDir))return[];let e=Fe.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=Hc.join(this.collectionsDir,n),i=Fe.readFileSync(s,"utf-8"),o=JSON.parse(i);o.id&&o.name&&(this.cache.set(o.id,o),t.push(o))}catch(s){console.error(`[JsonCollectionLoader] Failed to load ${n}:`,s)}return t}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.getCollectionPath(e);if(Fe.existsSync(t))try{let n=Fe.readFileSync(t,"utf-8"),s=JSON.parse(n);return this.cache.set(e,s),s}catch(n){console.error(`[JsonCollectionLoader] Failed to load collection ${e}:`,n);return}}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");e.id||(e.id=re(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Fe.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!Fe.existsSync(t))return!1;try{return await Fe.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Fe.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return Hc.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||re(e),name:e,items:[]};return await this.save(n),n}async saveScripts(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=xe(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?xe(n.items,t)?.scripts:void 0}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);t.name!==void 0&&(n.name=t.name),t.description!==void 0&&(n.description=t.description),t.version!==void 0&&(n.version=t.version),t.variables!==void 0&&(n.variables=t.variables),t.auth!==void 0&&(n.auth=t.auth),await this.save(n)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=xe(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=xe(s.items,n);if(o&&o.type==="folder")o.items=o.items||[],o.items.push(t);else throw new Error(`Parent folder ${n} not found`)}else s.items.push(t);await this.save(s)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=Ht(n.items,t);return s&&await this.save(n),s}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=xe(s.items,t);if(!i)return!1;let{id:o,type:a,...c}=n;return Object.assign(i,c),await this.save(s),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=xe(s.items,t);if(!i)return!1;let o={...i};if(!Ht(s.items,t))return!1;if(n){let a=xe(s.items,n);if(a&&a.type==="folder")a.items=a.items||[],a.items.push(o);else return s.items.push(o),!1}else s.items.push(o);return await this.save(s),!0}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;try{let i;if(t){let c=xe(s.items,t);if(!c||!c.items)return!1;i=c.items}else i=s.items;let o=new Map(i.map(c=>[c.id,c])),a=[];for(let c of n){let l=o.get(c);l&&(a.push(l),o.delete(c))}for(let c of o.values())a.push(c);if(t){let c=xe(s.items,t);c&&(c.items=a)}else s.items=a;return await this.save(s),!0}catch(i){return console.error("[JsonCollectionLoader] Failed to reorder items:",i),!1}}}});var Vr,Uc=E(()=>{"use strict";Qi();Bc();Vr=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new Bt(n):new Vn(n)}static createForFormat(e,t){return e==="folder"?new Bt(t):new Vn(t)}}});function ud(r){if(typeof r!="string")return"text";let e=r.trim();try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null)return"json"}catch{}return/^<\?xml/.test(e)||/^<([a-zA-Z_][\w\-\.]*)[\s>]/.test(e)?/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":"xml":/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":/^(function\s*\(|\(\)\s*=>|const |let |var |export |import )/.test(e)?"javascript":"text"}function Nh(r){return{info:{name:r.name,_postman_id:r.id,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:r.items.map(e=>dd(e)),event:Vc(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function dd(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(dd):[],event:Vc(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(_h),url:Mh(e),body:Dh(e),auth:jh(e.auth),description:e.description},event:Vc(e.scripts),protocolProfileBehavior:Lh(e.settings)}}}function _h(r){return{key:r.key,value:r.value,disabled:r.enabled===!1,...r.description!==void 0?{description:r.description}:{},...r.type!==void 0?{type:r.type}:{},...r.required!==void 0?{required:r.required}:{},...r.format!==void 0?{format:r.format}:{},...r.enum!==void 0?{enum:r.enum}:{},...r.deprecated!==void 0?{deprecated:r.deprecated}:{},...r.pattern!==void 0?{pattern:r.pattern}:{},...r.minLength!==void 0?{minLength:r.minLength}:{},...r.maxLength!==void 0?{maxLength:r.maxLength}:{},...r.minimum!==void 0?{minimum:r.minimum}:{},...r.maximum!==void 0?{maximum:r.maximum}:{},...r.exclusiveMinimum!==void 0?{exclusiveMinimum:r.exclusiveMinimum}:{},...r.exclusiveMaximum!==void 0?{exclusiveMaximum:r.exclusiveMaximum}:{},...r.multipleOf!==void 0?{multipleOf:r.multipleOf}:{},...r.minItems!==void 0?{minItems:r.minItems}:{},...r.maxItems!==void 0?{maxItems:r.maxItems}:{},...r.uniqueItems!==void 0?{uniqueItems:r.uniqueItems}:{},...r.nullable!==void 0?{nullable:r.nullable}:{},...r.oneOf!==void 0?{oneOf:r.oneOf}:{}}}function Mh(r){let e=r.url,t=r.url.replace(/^[a-zA-Z]+:\/\//,""),n=[],s=t.match(/^([^\/\?]+)/);if(s){let l=s[1];/^{{.*}}$/.test(l)?n=[l]:n=l.split(".")}let i=[],o=t.match(/^[^\/\?]+(\/[^\?]*)?/);if(o&&o[1]!==void 0){let l=o[1].replace(/^\//,"");l.endsWith("/")?(i=l.slice(0,-1).split("/"),i.push("")):i=l.length>0?l.split("/"):[]}let a;if(Array.isArray(r.query)&&r.query.length>0)a=r.query.map(l=>{let u={key:l.key,value:l.value};return l.enabled===!1&&(u.disabled=!0),l.description!==void 0&&(u.description=l.description),l.type!==void 0&&(u.type=l.type),l.required!==void 0&&(u.required=l.required),l.format!==void 0&&(u.format=l.format),l.enum!==void 0&&(u.enum=l.enum),l.deprecated!==void 0&&(u.deprecated=l.deprecated),l.pattern!==void 0&&(u.pattern=l.pattern),l.minLength!==void 0&&(u.minLength=l.minLength),l.maxLength!==void 0&&(u.maxLength=l.maxLength),l.minimum!==void 0&&(u.minimum=l.minimum),l.maximum!==void 0&&(u.maximum=l.maximum),l.exclusiveMinimum!==void 0&&(u.exclusiveMinimum=l.exclusiveMinimum),l.exclusiveMaximum!==void 0&&(u.exclusiveMaximum=l.exclusiveMaximum),l.multipleOf!==void 0&&(u.multipleOf=l.multipleOf),l.minItems!==void 0&&(u.minItems=l.minItems),l.maxItems!==void 0&&(u.maxItems=l.maxItems),l.uniqueItems!==void 0&&(u.uniqueItems=l.uniqueItems),l.nullable!==void 0&&(u.nullable=l.nullable),l.oneOf!==void 0&&(u.oneOf=l.oneOf),u});else{let l=t.indexOf("?");l!==-1&&(a=t.substring(l+1).split("&").map(d=>{let[p,...m]=d.split("=");return{key:p,value:m.join("=")}}))}let c;return r.params&&typeof r.params=="object"&&(c=Object.entries(r.params).map(([l,u])=>({key:l,value:String(u)}))),{raw:e,host:n.length>0?n:void 0,path:i.length>0?i:void 0,query:a&&a.length>0?a:void 0,variable:c&&c.length>0?c:void 0}}function Dh(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=ud(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||ud(e.content);return{mode:"raw",raw:e.content,options:{raw:{language:i}}}}let t=e.type==="form-data"&&Array.isArray(e.content)?e.content:e.type==="formdata"&&Array.isArray(e.fields)?e.fields:null;if(t)return{mode:"formdata",formdata:t.map(i=>({key:i.key,value:i.value,type:i.type||"text",disabled:i.enabled===!1}))};let n=e.type==="x-www-form-urlencoded"&&Array.isArray(e.content)?e.content:e.type==="urlencoded"&&Array.isArray(e.fields)?e.fields:null;if(n)return{mode:"urlencoded",urlencoded:n.map(i=>({key:i.key,value:i.value,disabled:i.enabled===!1}))};if(e.type==="file"&&e.fileName)return{mode:"file",file:{src:e.fileName}};if(e.type==="binary")return{mode:"binary",file:{}};let s=e.type==="graphql"?e.content??(e.query?e:null):null;if(s){let i=s.query??"",o=s.variables;return{mode:"graphql",graphql:{query:i,variables:o?typeof o=="string"?o:JSON.stringify(o):void 0}}}if(e.content)return{mode:"raw",raw:e.content}}function jh(r){if(!(!r||!r.type||r.type==="none")){if(r.type==="bearer")return{type:"bearer",bearer:[{key:"token",value:r.bearerToken,type:"string"}]};if(r.type==="basic"&&r.basicAuth)return{type:"basic",basic:[{key:"username",value:r.basicAuth.username,type:"string"},{key:"password",value:r.basicAuth.password,type:"string"}]}}}function Lh(r){if(!r)return;let e={};return r.followRedirects===!1&&(e.followRedirects=!1),r.followOriginalMethod===!0&&(e.followOriginalHttpMethod=!0),r.followAuthHeader===!1&&(e.followAuthorizationHeader=!1),r.maxRedirects!==void 0&&(e.maxRedirects=r.maxRedirects),r.strictSSL===!1&&(e.disableUrlEncoding=!1),r.timeout!==void 0&&(e.requestTimeout=r.timeout),Object.keys(e).length>0?e:void 0}function Vc(r){if(!r)return[];let e=[];return r.preRequest&&e.push({listen:"prerequest",script:{type:"text/javascript",exec:[r.preRequest]}}),r.postResponse&&e.push({listen:"test",script:{type:"text/javascript",exec:[r.postResponse]}}),e}var ue,vt,zr,zc=E(()=>{"use strict";We();yo();Uc();ln();ue=T(require("fs")),vt=T(require("path"));zr=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=Vr.create(e),this.ensureCollectionsDir(),this.loadCollections(),this.setupFileWatcher()}configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){ue.existsSync(this.collectionsDir)||ue.mkdirSync(this.collectionsDir,{recursive:!0})}loadCollections(){this.collections.clear();let e=this.loader.loadAll();for(let t of e)this.collections.set(t.id,t)}setupFileWatcher(){if(!this.fileWatcherFactory)return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.collectionsDir,"**/*");let e=()=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null;let t=this.selfWritePending;this.selfWritePending=!1,t||this.loadCollections(),this.onCollectionsChanged?.()},300)};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}getAllCollections(){return Array.from(this.collections.values())}getCollection(e){return this.collections.get(e)}getCollectionById(e){for(let t of this.collections.values())if(t.id===e)return t}getCollectionByName(e){let t=e.toLowerCase();for(let n of this.collections.values())if(n.name.toLowerCase()===t)return n}async saveCollection(e){if(this.ensureCollectionsDir(),!e.name)throw new Error("Collection name is required");e.id||(e.id=re(e.name)),this.selfWritePending=!0,await this.loader.save(e),this.collections.set(e.id,e)}getCollectionVariables(e){let t=this.collections.get(e);return t?.variables?{...t.variables}:{}}getCollectionVariableLocals(e){return{...this.localCollectionValues.get(e)||{}}}setCollectionVariable(e,t,n){this.localCollectionValues.has(e)||this.localCollectionValues.set(e,{}),this.localCollectionValues.get(e)[t]=String(n)}deleteCollectionVariable(e,t){let n=this.localCollectionValues.get(e);n&&delete n[t]}clearCollectionVariables(e){this.localCollectionValues.set(e,{})}async deleteCollection(e){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let n=await this.loader.delete(e);return n&&this.collections.delete(e),n}findRequest(e,t){let n=this.collections.get(e);if(n)return this.findItemRecursive(n.items,t)}findRequestByPath(e,t){let n=this.collections.get(e);if(!n)return;let s=t.split("/").filter(i=>i.trim());return this.findItemByPath(n.items,s)}async updateRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,n);if(i){let o=this.findItemRecursive(s.items,t);if(o){let{id:a,type:c,...l}=n;Object.assign(o,l)}}return i}async addRequest(e,t,n){if(!this.collections.get(e))return!1;t.id||(t.id=re(t.name)),this.selfWritePending=!0;try{return await this.loader.saveItem(e,t,n),!0}catch(i){return console.error("[CollectionService] Failed to add request:",i),!1}}async deleteRequest(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&this.deleteItemRecursive(n.items,t),s}getAllRequests(e){let t=this.collections.get(e);if(!t)return[];let n=[];return this.collectRequestsRecursive(t.items,n),n}findItemRecursive(e,t){for(let n of e){if(n.id===t)return n;if(n.type==="folder"&&n.items){let s=this.findItemRecursive(n.items,t);if(s)return s}}}findItemByPath(e,t){if(t.length===0)return;let[n,...s]=t,i=e.find(o=>o.name===n);if(i){if(s.length===0)return i;if(i.type==="folder"&&i.items)return this.findItemByPath(i.items,s)}}deleteItemRecursive(e,t){for(let n=0;n<e.length;n++){let s=e[n];if(s.id===t)return e.splice(n,1),!0;if(s.type==="folder"&&s.items&&this.deleteItemRecursive(s.items,t))return!0}return!1}collectRequestsRecursive(e,t){for(let n of e)n.type==="request"?t.push(n):n.type==="folder"&&n.items&&this.collectRequestsRecursive(n.items,t)}async createCollection(e){let t={id:re(e),name:e,items:[]};return await this.saveCollection(t),t}async renameCollection(e,t){let n=this.collections.get(e);return n?(n.name=t,await this.saveCollection(n),!0):!1}async duplicateCollection(e,t){if(!this.collections.get(e))throw new Error(`Collection not found: ${e}`);this.selfWritePending=!0;let s=re(t),i=this.loader.getCollectionPath(e),o=vt.join(this.collectionsDir,s);if(!ue.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=vt.join(o,"collection.json");if(ue.existsSync(a)){let l=JSON.parse(ue.readFileSync(a,"utf-8"));l.id=s,l.name=t,ue.writeFileSync(a,JSON.stringify(l,null,2))}else ue.writeFileSync(a,JSON.stringify({id:s,name:t},null,2));this.loadCollections();let c=this.collections.get(s);if(!c)throw new Error("Failed to load duplicated collection");return c}async createFolder(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:re(e.name),type:"folder",name:e.name,items:[]};await this.loader.saveItem(e.collectionId,n,e.parentId);let s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async deleteFolder(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&Ht(n.items,t),s}async renameFolder(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=xe(s.items,t);o&&(o.name=n)}return i}async duplicateFolder(e,t,n){if(!this.collections.get(e))throw new Error("Collection not found");let i=this.loader.getItemPath(e,t);if(!i||!ue.existsSync(i))throw new Error(`Folder not found on disk: ${t}`);let o=vt.dirname(i),a=re(n),c=vt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=vt.join(c,"folder.json");if(ue.existsSync(l)){let p=JSON.parse(ue.readFileSync(l,"utf-8"));p.id=a,p.name=n,ue.writeFileSync(l,JSON.stringify(p,null,2))}else ue.writeFileSync(l,JSON.stringify({id:a,name:n,type:"folder"},null,2));this.loadCollections();let u=this.collections.get(e),d=u?xe(u.items,a):void 0;return d||{id:a,type:"folder",name:n,items:[]}}async createRequest(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:e.id||re(e.name),type:"request",name:e.name,method:e.method||"GET",url:e.url,params:e.params,query:e.query,headers:e.headers,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts,deprecated:e.deprecated,description:e.description,doc:e.doc,responseSchema:e.responseSchema,bodySchema:e.bodySchema,operationId:e.operationId,summary:e.summary,tags:e.tags,examples:e.examples,responses:e.responses,security:e.security};await this.loader.saveItem(e.collectionId,n,e.parentId);let s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async renameRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=xe(s.items,t);o&&(o.name=n)}return i}async moveItem(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.moveItem(e,t,n);return i&&this.loadCollections(),i}async reorderItems(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.reorderItems(e,t,n);return i&&this.loadCollections(),i}getRequestScript(e,t,n){let s=this.collections.get(e);if(!s)return;let i=xe(s.items,t);if(!i||i.type!=="request")return;let o=i;return n==="pre-request"?o.scripts?.preRequest:o.scripts?.postResponse}async setRequestScript(e,t,n,s){let i=this.collections.get(e);if(!i)return!1;let o=xe(i.items,t);if(!o||o.type!=="request")return!1;let a=o,l={...a.scripts??{},...n==="pre-request"?{preRequest:s}:{postResponse:s}};a.scripts=l,this.selfWritePending=!0;try{return await this.loader.saveScripts(e,t,l),!0}catch{return!1}}copyDirRecursive(e,t){ue.existsSync(t)||ue.mkdirSync(t,{recursive:!0});for(let n of ue.readdirSync(e,{withFileTypes:!0})){let s=vt.join(e,n.name),i=vt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):ue.copyFileSync(s,i)}}async importCollection(e){let t=ue.readFileSync(e,"utf-8"),n;try{n=JSON.parse(t)}catch{throw new Error("Invalid JSON file")}if(n.info&&n.info._postman_id)return this.importPostmanCollection(n);let s={id:n.id||re(n.name||"Imported Collection"),name:n.name||"Imported Collection",description:n.description,items:n.items||[]};return await this.saveCollection(s),s}async importPostmanCollection(e){let t=p=>{if(!p)return;switch(p.type?.toLowerCase()){case"bearer":return{type:"bearer",bearerToken:p.bearer?.find(b=>b.key==="token")?.value||""};case"basic":let h=p.basic?.find(b=>b.key==="username"),g=p.basic?.find(b=>b.key==="password");return{type:"basic",basicAuth:{username:h?.value||"",password:g?.value||""}};case"apikey":let y=p.apikey?.find(b=>b.key==="key"),v=p.apikey?.find(b=>b.key==="value"),w=p.apikey?.find(b=>b.key==="in");return{type:"apikey",apikey:{key:y?.value||"",value:v?.value||"",in:w?.value||"header"}};case"noauth":return{type:"none"};default:return}},n=p=>{if(!Array.isArray(p)||p.length===0)return;let m={};for(let f of p){let h=f.script?.exec;if(!h)continue;let g=Array.isArray(h)?h.join(`
243
+ `):h;f.listen==="prerequest"?m.preRequest=g:f.listen==="test"&&(m.postResponse=g)}return m.preRequest||m.postResponse?m:void 0},s=p=>{if(!p||typeof p!="object")return;let m={};return p.followRedirects===!1&&(m.followRedirects=!1),p.followOriginalHttpMethod===!0&&(m.followOriginalMethod=!0),p.followAuthorizationHeader===!1&&(m.followAuthHeader=!1),p.maxRedirects!==void 0&&(m.maxRedirects=p.maxRedirects),p.requestTimeout!==void 0&&(m.timeout=p.requestTimeout),Object.keys(m).length>0?m:void 0},i=p=>{if(!p||typeof p=="string")return;let m=p.query;if(!(!Array.isArray(m)||m.length===0))return m.map(f=>({key:f.key||"",value:f.value||"",enabled:f.disabled!==!0,...f.description!==void 0?{description:f.description}:{},...f.type!==void 0?{type:f.type}:{},...f.required!==void 0?{required:f.required}:{},...f.format!==void 0?{format:f.format}:{},...f.enum!==void 0?{enum:f.enum}:{},...f.deprecated!==void 0?{deprecated:f.deprecated}:{},...f.pattern!==void 0?{pattern:f.pattern}:{},...f.minLength!==void 0?{minLength:f.minLength}:{},...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.minimum!==void 0?{minimum:f.minimum}:{},...f.maximum!==void 0?{maximum:f.maximum}:{},...f.exclusiveMinimum!==void 0?{exclusiveMinimum:f.exclusiveMinimum}:{},...f.exclusiveMaximum!==void 0?{exclusiveMaximum:f.exclusiveMaximum}:{},...f.multipleOf!==void 0?{multipleOf:f.multipleOf}:{},...f.minItems!==void 0?{minItems:f.minItems}:{},...f.maxItems!==void 0?{maxItems:f.maxItems}:{},...f.uniqueItems!==void 0?{uniqueItems:f.uniqueItems}:{},...f.nullable!==void 0?{nullable:f.nullable}:{},...f.oneOf!==void 0?{oneOf:f.oneOf}:{}}))},o=p=>{if(typeof p=="string")return p;if(!p)return"";let m=new Set;if(Array.isArray(p.variable))for(let h of p.variable)h.key&&m.add(h.key);if(m.size===0&&p.raw)return p.raw;let f="";if(p.protocol&&(f+=p.protocol+"://"),p.host&&(f+=Array.isArray(p.host)?p.host.join("."):p.host),p.port&&(f+=":"+p.port),p.path){let g=(Array.isArray(p.path)?p.path:[p.path]).map(y=>{let v=y.startsWith(":")?y.substring(1):y;return m.has(v)?":"+v:(y.startsWith(":"),y)});f+="/"+g.join("/")}return!f&&p.raw?p.raw:f},a=p=>{if(!Array.isArray(p)||p.length===0)return;let m={responses:{}};for(let f of p){let h=String(f.code||200),g,y={};if(Array.isArray(f.header))for(let R of f.header)!R.key||R.disabled||(R.key.toLowerCase()==="content-type"?g=R.value?.split(";")[0]?.trim():y[R.key]={description:String(R.value??""),schema:{type:"string"}});let v=f.body;if(typeof f.body=="string"&&f.body)try{v=JSON.parse(f.body)}catch{}let w=f.originalRequest,b;if(w){let R=typeof w.url=="string"?w.url:w.url?.raw??"";b=`${w.method||""} ${R}`.trim()||void 0}let C=f.name?f.name.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()||`example_${h}`:`example_${h}`;if(m.responses[h]){let R=m.responses[h];R.examples=R.examples??{},R.examples[C]={summary:b,value:v}}else m.responses[h]={description:f.name,contentType:g,examples:{[C]:{summary:b,value:v}},...Object.keys(y).length>0?{headers:y}:{}}}return Object.keys(m.responses).length>0?m:void 0},c=p=>!(!p||typeof p!="object"||p.item===void 0&&p.request===void 0&&(p.listen!==void 0||p.script!==void 0)),l=p=>p.filter(c).map(m=>{if(m.item)return{id:re(m.name),type:"folder",name:m.name||"Folder",description:m.description,auth:t(m.auth),scripts:n(m.event),items:l(m.item)};{let f=m.request||{};return{id:re(m.name),type:"request",name:m.name||f.method||"Request",description:m.description||f.description,method:typeof f.method=="string"?f.method:"GET",url:o(f.url),query:i(f.url),headers:Array.isArray(f.header)?f.header.map(h=>({key:h.key||h.name||"",value:h.value||h.value||"",enabled:h.disabled!==!0,...h.description!==void 0?{description:h.description}:{},...h.type!==void 0?{type:h.type}:{},...h.required!==void 0?{required:h.required}:{},...h.format!==void 0?{format:h.format}:{},...h.enum!==void 0?{enum:h.enum}:{},...h.deprecated!==void 0?{deprecated:h.deprecated}:{},...h.pattern!==void 0?{pattern:h.pattern}:{},...h.minLength!==void 0?{minLength:h.minLength}:{},...h.maxLength!==void 0?{maxLength:h.maxLength}:{},...h.minimum!==void 0?{minimum:h.minimum}:{},...h.maximum!==void 0?{maximum:h.maximum}:{},...h.exclusiveMinimum!==void 0?{exclusiveMinimum:h.exclusiveMinimum}:{},...h.exclusiveMaximum!==void 0?{exclusiveMaximum:h.exclusiveMaximum}:{},...h.multipleOf!==void 0?{multipleOf:h.multipleOf}:{},...h.minItems!==void 0?{minItems:h.minItems}:{},...h.maxItems!==void 0?{maxItems:h.maxItems}:{},...h.uniqueItems!==void 0?{uniqueItems:h.uniqueItems}:{},...h.nullable!==void 0?{nullable:h.nullable}:{},...h.oneOf!==void 0?{oneOf:h.oneOf}:{}})):[],body:(()=>{let h=f.body;if(h){if(h.mode==="raw"&&h.raw){let g=h.options?.raw?.language;return{type:"raw",format:g==="xml"?"xml":g==="html"?"html":g==="javascript"?"javascript":g==="text"?"text":"json",content:h.raw}}if(h.mode==="urlencoded"&&Array.isArray(h.urlencoded))return{type:"x-www-form-urlencoded",content:h.urlencoded.map(g=>({key:g.key||"",value:g.value||"",enabled:g.disabled!==!0}))};if(h.mode==="formdata"&&Array.isArray(h.formdata))return{type:"form-data",content:h.formdata.map(g=>({key:g.key||"",value:g.value||"",type:g.type||"text",enabled:g.disabled!==!0}))};if(h.mode==="graphql"&&h.graphql){let g;if(h.graphql.variables)try{g=JSON.parse(h.graphql.variables)}catch{g=void 0}return{type:"graphql",content:{query:h.graphql.query||"",variables:g}}}if(h.mode==="binary")return{type:"binary",content:""}}})(),auth:t(f.auth),scripts:n(m.event),settings:s(m.protocolProfileBehavior),responseSchema:a(m.response)}}}),u=l(e.item||[]),d={id:re(e.info?.name||"Imported Postman Collection"),name:e.info?.name||"Imported Postman Collection",description:e.info?.description,auth:t(e.auth),scripts:n(e.event),variables:Array.isArray(e.variable)?Object.fromEntries(e.variable.filter(p=>p&&p.key).map(p=>[p.key,String(p.value??"")])):typeof e.variable=="object"&&e.variable!==null?Object.fromEntries(Object.entries(e.variable).map(([p,m])=>[p,String(m??"")])):void 0,items:u};return await this.saveCollection(d),d}async exportCollection(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=Nh(n),i=JSON.stringify(s,null,2);ue.writeFileSync(t,i,"utf-8")}async exportCollectionAsRestClientFolder(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=vt.join(t,ve(n.name));ue.mkdirSync(s,{recursive:!0});let i=n.variables||{};Un(vt.join(s,`${ve(n.name)}.env`),i),Ur(s,ve(n.name),n.scripts),Xs(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var ce,vn,Vt,Jc=E(()=>{"use strict";ce={version:"1.0",storage:{format:"folder",root:"./.http-forge/assets",history:"./.http-forge/.cache/histories",results:"./.http-forge/.cache/results"},request:{timeout:3e4,followRedirects:!0,maxRedirects:10,strictSSL:!0,tls:{},certificates:[]},scripts:{modulePaths:["./.http-forge/assets/src","./.http-forge/assets/lib"],scope:"shared",timeout:5e3},runner:{resultsRetentionDays:7,indexPageSize:1e3,recentErrorsLimit:20,report:{maxBodyChars:1e5,embedBodies:"failed"}},environments:{default:"dev"},restClientExport:{path:"collections-rest-client",mergeGlobals:!0},discovery:{customSeedLoaderModulePath:void 0,frameworks:["auto"],contextProperties:["locals"],skipComponentAnalysis:!1},mcp:{port:3100,excludedCollections:[],excludedSuites:[],toolPrefix:"",maxRequestsPerCall:500,toolMode:"auto",drilldownThreshold:100,toolPageSize:200,cors:{allowedOrigins:["http://localhost","http://127.0.0.1"]}},proxy:null,secrets:{providers:{aws:{provider:"aws"},azure:{provider:"azure",vaultUrl:""},gcp:{provider:"gcp"},vault:{provider:"vault"},op:{provider:"1password"},doppler:{provider:"doppler"}}}},vn={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},Vt={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});var fe,ge,zt,vo=E(()=>{"use strict";fe=T(require("fs")),ge=T(require("path"));Jc();zt=class{constructor(e,t,n){this.workspacePath=e;this.fileWatcherFactory=t;this.notifications=n;this.configPath=this.resolveConfigPath(),this.config=this.loadConfig(),this.setupFileWatcher()}workspacePath;fileWatcherFactory;notifications;config;configPath;fileWatchers=[];resolveConfigPath(){let e=ge.join(this.workspacePath,vn.preferred);if(fe.existsSync(e))return e;let t=ge.join(this.workspacePath,vn.legacy);return fe.existsSync(t)?t:e}loadConfig(){if(this.configPath=this.resolveConfigPath(),!fe.existsSync(this.configPath))return{...ce};try{let e=fe.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return this.mergeWithDefaults(t)}catch(e){return console.error("[ConfigService] Failed to load config:",e),this.notifications?.showWarning(`Failed to parse ${ge.relative(this.workspacePath,this.configPath)}. Using default configuration.`),{...ce}}}mergeWithDefaults(e){return{version:e.version??ce.version,storage:{...ce.storage,...e.storage},request:{...ce.request,...e.request},scripts:{...ce.scripts,...e.scripts},runner:{...ce.runner,...e.runner,report:{...ce.runner.report,...e.runner?.report}},environments:{...ce.environments,...e.environments},restClientExport:{...ce.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:ce.proxy,discovery:{...ce.discovery,...e.discovery},mcp:{...ce.mcp,...e.mcp,cors:{...ce.mcp.cors,...e.mcp?.cors}},secrets:{...ce.secrets,...e.secrets,providers:{...ce.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let t of[vn.preferred,vn.legacy]){let n=this.fileWatcherFactory.createFileWatcher(this.workspacePath,t);n.onDidChange(e),n.onDidCreate(e),n.onDidDelete(e),this.fileWatchers.push(n)}}getConfig(){return this.config}getStorageConfig(){return this.config.storage}getRequestConfig(){return this.config.request}getScriptsConfig(){return this.config.scripts}getRunnerConfig(){let e=this.config.runner,t=e.report??ce.runner.report,n=["all","failed","none"];return{...e,report:{maxBodyChars:Math.max(1e3,Math.floor(t.maxBodyChars??ce.runner.report.maxBodyChars)),embedBodies:n.includes(t.embedBodies)?t.embedBodies:ce.runner.report.embedBodies}}}getEnvironmentsConfig(){return this.config.environments}getRestClientExportPath(){let e=this.config.restClientExport?.path||"collections-rest-client";return ge.isAbsolute(e)?e:this.resolvePath(e)}getRestClientMergeGlobals(){return this.config.restClientExport?.mergeGlobals??!0}getProxyConfig(){return this.config.proxy??null}getDiscoveryConfig(){let e=this.config.discovery??ce.discovery;return{customSeedLoaderModulePath:e.customSeedLoaderModulePath,frameworks:e.frameworks??ce.discovery.frameworks,contextProperties:e.contextProperties??ce.discovery.contextProperties,skipComponentAnalysis:e.skipComponentAnalysis??ce.discovery.skipComponentAnalysis}}getMcpConfig(){let e=this.config.mcp??ce.mcp,t=["flat","drilldown","auto","execution-only"];return{...e,port:Math.min(65535,Math.max(1,Math.floor(e.port??3100))),toolMode:t.includes(e.toolMode)?e.toolMode:"auto",drilldownThreshold:Math.min(500,Math.max(10,e.drilldownThreshold??100)),toolPageSize:e.toolPageSize===0?0:Math.min(1e3,Math.max(10,e.toolPageSize??200)),maxRequestsPerCall:Math.min(1e4,Math.max(1,e.maxRequestsPerCall??500))}}resolvePath(e){let t=e.startsWith("./")?e.slice(2):e;return ge.join(this.workspacePath,...t.split("/"))}hasFolderCollectionsAtRoot(e){let t=ge.join(e,Vt.collections);if(!fe.existsSync(t))return!1;let n;try{n=fe.readdirSync(t,{withFileTypes:!0})}catch{return!1}return n.some(s=>{if(!s.isDirectory())return!1;let i=ge.join(t,s.name,"collection.json");return fe.existsSync(i)})}hasAnyEntries(e){if(!fe.existsSync(e))return!1;try{return fe.readdirSync(e).length>0}catch{return!1}}resolveStorageRootPath(){let e=this.resolvePath(this.config.storage.root);return this.configExists()||this.hasFolderCollectionsAtRoot(e)?e:[ge.join(this.workspacePath,"http-forge-assets")].find(s=>this.hasFolderCollectionsAtRoot(s))||e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return ge.join(this.getRootPath(),Vt.collections)}getEnvironmentsPath(){return ge.join(this.getRootPath(),Vt.environments)}getFlowsPath(){return ge.join(this.getRootPath(),Vt.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);if(this.configExists()||this.hasAnyEntries(e))return e;let t=ge.join(this.workspacePath,".http-forge-cache","histories");return this.hasAnyEntries(t)?t:e}getResultsPath(){let e=this.resolvePath(this.config.storage.results);if(this.configExists()||this.hasAnyEntries(e))return e;let t=ge.join(this.workspacePath,".http-forge-cache","results");return this.hasAnyEntries(t)?t:e}getSuitesPath(){return ge.join(this.getRootPath(),Vt.suites)}getModulePaths(){return this.config.scripts.modulePaths.map(e=>this.resolvePath(e))}getScriptScope(){return this.config.scripts.scope??"shared"}getScriptTimeout(){return this.config.scripts.timeout??5e3}getWorkspacePath(){return this.workspacePath}onConfigReloaded;reload(){this.configPath=this.resolveConfigPath(),this.config=this.loadConfig(),this.onConfigReloaded?.()}configExists(){return fe.existsSync(this.resolveConfigPath())}async createDefaultConfig(){await fe.promises.mkdir(ge.dirname(this.configPath),{recursive:!0});let e=JSON.stringify(ce,null,2);await fe.promises.writeFile(this.configPath,e,"utf-8");let t=[this.getCollectionsPath(),this.getEnvironmentsPath(),this.getFlowsPath(),this.getSuitesPath()];for(let s of t)fe.existsSync(s)||await fe.promises.mkdir(s,{recursive:!0});let n=[this.getHistoryPath(),this.getResultsPath()];for(let s of n)fe.existsSync(s)||await fe.promises.mkdir(s,{recursive:!0});await this.createSampleEnvironments()}async createSampleEnvironments(){let e=this.getEnvironmentsPath(),t={id:"globals",name:"Global Variables",variables:{appName:"HTTP Forge"}};await fe.promises.writeFile(ge.join(e,"globals.json"),JSON.stringify(t,null,2),"utf-8");let n={id:"env_dev",name:"Development",variables:{baseUrl:"http://localhost:3000",apiVersion:"v1"}};await fe.promises.writeFile(ge.join(e,"dev.json"),JSON.stringify(n,null,2),"utf-8");let s={id:"default_headers",name:"Default Headers",headers:{"Content-Type":"application/json",Accept:"application/json"}};await fe.promises.writeFile(ge.join(e,"default-headers.json"),JSON.stringify(s,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var Hh,Jr,Gc=E(()=>{"use strict";Fn();Hh="httpForge.cookies",Jr=class{constructor(e,t=Hh){this.store=e;this.storeKey=t;this.loadCookies()}store;storeKey;cookies=new Map;loadCookies(){try{let e=this.store.get(this.storeKey);e&&(this.cookies=new Map(Object.entries(e)),this.cleanExpiredCookies())}catch(e){console.error("[CookieService] Failed to load cookies:",e)}}async saveCookies(){try{let e={};this.cookies.forEach((t,n)=>{e[n]=t}),await this.store.update(this.storeKey,e)}catch(e){console.error("[CookieService] Failed to save cookies:",e)}}getCookieKey(e,t,n){return ne.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}async set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e),await this.saveCookies()}async setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}await this.saveCookies()}has(e,t){return this.get(e,t)!==void 0}async delete(e,t,n){let s=this.getCookieKey(e,t,n),i=this.cookies.delete(s);return i&&await this.saveCookies(),i}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return ne.formatCookieHeader(t)}async clear(){this.cookies.clear(),await this.saveCookies()}async clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n);await this.saveCookies()}parseCookieHeaders(e,t){return ne.parseCookieHeaders(e,t)}isExpired(e){return ne.isExpired(e)}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t);e.length>0&&this.saveCookies()}domainMatches(e,t){return ne.domainMatches(e,t)}get count(){return this.cookies.size}}});var Gr,Wc=E(()=>{"use strict";Fn();Gr=class{constructor(e){this.cookieService=e;this.localCache=[...e.getAll()]}cookieService;localCache=[];pendingOperations=[];get(e,t){return t?this.localCache.find(n=>n.name===e&&(!n.domain||n.domain===t||t.endsWith(n.domain))):this.localCache.find(n=>n.name===e)}has(e,t){return this.get(e,t)!==void 0}set(e){let t=this.localCache.findIndex(n=>n.name===e.name&&(!e.domain||n.domain===e.domain));t>=0?this.localCache[t]=e:this.localCache.push(e),this.pendingOperations.push({type:"set",cookie:e})}delete(e,t,n){let s=this.localCache.findIndex(i=>i.name===e&&(!t||i.domain===t||i.domain&&t.endsWith(i.domain)));return s>=0&&this.localCache.splice(s,1),this.pendingOperations.push({type:"delete",name:e,domain:t,path:n}),!0}getAll(e){return e?this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)}):[...this.localCache]}getCookiesForDomain(e){return this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)})}async setCookiesFromResponse(e,t){let n=new URL(e).hostname,s=this.cookieService.parseCookieHeaders(t,n);s.length>0&&(s.forEach(i=>{let o=this.localCache.findIndex(a=>a.name===i.name&&a.domain===(i.domain||n));o>=0?this.localCache[o]=i:this.localCache.push(i)}),await this.cookieService.setFromResponse(s))}getCookieHeader(e){let t=new URL(e).hostname,n=new URL(e).pathname,s=this.localCache.filter(i=>!(ne.isExpired(i)||i.domain&&!ne.domainMatches(t,i.domain)||!i.domain||i.path&&!n.startsWith(i.path)));if(s.length!==0)return ne.formatCookieHeader(s)}clear(){this.localCache=[],this.pendingOperations.push({type:"clear"})}async flush(){for(let e of this.pendingOperations)switch(e.type){case"set":e.cookie&&await this.cookieService.set(e.cookie);break;case"delete":e.name&&await this.cookieService.delete(e.name,e.domain,e.path);break;case"clear":await this.cookieService.clear();break}this.pendingOperations=[]}}});function bo(r){try{let e=JSON.parse(typeof r=="string"?r:r.toString("utf-8"));if(!e)return null;let t=e.environment||e,n=t.name||e.name||"imported-environment",s=t.values||t.variables||e.values||e.variables||[],i={};if(Array.isArray(s))for(let a of s){if(!a)continue;let c=a.key??a.name,l=typeof a.enabled=="boolean"?a.enabled:!0;c&&l!==!1&&(i[c]=a.value??a.initial??"")}else if(typeof s=="object"&&s!==null)for(let[a,c]of Object.entries(s))i[a]=String(c??"");let o=t._postman_exported_at?"Imported from Postman export":t.description||"";return{name:n,variables:i,description:o}}catch{return null}}var Kc=E(()=>{"use strict"});var ke,Ze,ei,Wr,Qc=E(()=>{"use strict";ke=T(require("fs")),Ze=T(require("path"));We();Kc();yo();Yi();Or();ei={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},Wr=class{constructor(e,t,n,s,i,o=!0){this.workspaceFolder=e;this.workspaceStore=t;this.configService=n;this.fileWatcherFactory=s;this.secretStore=i;this.persistOverrides=o;let a=n.getEnvironmentsPath();this.environmentsPath=a,this.sharedConfigPath=Ze.join(a,"_global.json"),this.localConfigPath=Ze.join(a,"_global.local.json"),this.historiesPath=n.getHistoryPath(),this.selectedEnvironment=t?.get(ei.SELECTED_ENVIRONMENT,"dev")??"dev",this.localGlobalValues={},this.localEnvironmentValues=new Map,this.persistOverrides&&this.loadPersistedEnvironmentOverrides(),this.loadSecretVariables(this.selectedEnvironment).catch(()=>{}),this.setupFileWatcher(),this.configService.onConfigReloaded=()=>this.invalidateResolvedConfigCache()}workspaceFolder;workspaceStore;configService;fileWatcherFactory;secretStore;persistOverrides;environmentsPath;sharedConfigPath;localConfigPath;historiesPath;sharedConfig=null;localConfig=null;selectedEnvironment="dev";fileWatcher;resolvedConfigCache=new Map;localGlobalValues={};localEnvironmentValues=new Map;secretValuesCache=new Map;onEnvironmentsChanged;setupFileWatcher(){if(!this.fileWatcherFactory||!ke.existsSync(this.environmentsPath))return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.environmentsPath,"**/*.json");let e=()=>{this.reload(),this.onEnvironmentsChanged?.()};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}dispose(){this.fileWatcher?.dispose()}getWorkspaceFolder(){return this.workspaceFolder}getRootPath(){return this.configService.getRootPath()}loadConfigs(){if(!ke.existsSync(this.environmentsPath)){this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}},this.localConfig={credentials:{},variables:{}};return}this.loadFolderConfigs()}getSharedConfig(){return this.sharedConfig||this.loadConfigs(),this.sharedConfig}getLocalConfig(){return this.localConfig||this.loadConfigs(),this.localConfig}getEnvironmentNames(){let e=this.getSharedConfig();return e?.environments?Object.keys(e.environments):[]}getSelectedEnvironment(){return this.selectedEnvironment}async setSelectedEnvironment(e){if(this.selectedEnvironment=e,await this.workspaceStore?.update(ei.SELECTED_ENVIRONMENT,e),!this.localEnvironmentValues.has(e)){let t=this.getEnvOverridesStateKey(e),n=this.workspaceStore?.get(t,{});n&&Object.keys(n).length>0&&this.localEnvironmentValues.set(e,{...n})}await this.loadSecretVariables(e),this.resolvedConfigCache.delete(e)}getEnvOverridesStateKey(e){return`${ei.ENV_OVERRIDES_PREFIX}${e||this.selectedEnvironment}`}loadPersistedEnvironmentOverrides(){let e=this.getEnvOverridesStateKey(),t=this.workspaceStore?.get(e,{});t&&Object.keys(t).length>0&&this.localEnvironmentValues.set(this.selectedEnvironment,{...t})}persistEnvironmentOverrides(e){if(!this.persistOverrides)return;let t=this.getEnvOverridesStateKey(e),n=this.localEnvironmentValues.get(e)||{};this.workspaceStore?.update(t,n)}setEnvironmentVariable(e,t,n){let s=n??this.selectedEnvironment;this.localEnvironmentValues.has(s)||this.localEnvironmentValues.set(s,{}),this.localEnvironmentValues.get(s)[e]=String(t),this.persistEnvironmentOverrides(s)}deleteEnvironmentVariable(e,t){let n=t??this.selectedEnvironment,s=this.localEnvironmentValues.get(n);s&&(delete s[e],this.persistEnvironmentOverrides(n))}clearEnvironmentVariables(e){let t=e??this.selectedEnvironment;this.localEnvironmentValues.set(t,{}),this.persistEnvironmentOverrides(t)}async resetEnvironmentOverrides(e){let t=e||this.selectedEnvironment;this.localEnvironmentValues.delete(t),await this.workspaceStore?.update(this.getEnvOverridesStateKey(t),void 0)}getEnvironmentVariableLocal(e){return this.localEnvironmentValues.get(this.selectedEnvironment)?.[e]}getEnvironmentVariableLocals(){return{...this.localEnvironmentValues.get(this.selectedEnvironment)||{}}}setGlobalVariable(e,t){this.localGlobalValues[e]=String(t)}getGlobalVariable(e){return this.getSharedConfig()?.globalVariables?.[e]}getGlobalVariableLocal(e){return this.localGlobalValues[e]}getGlobalVariables(){return{...this.getSharedConfig()?.globalVariables||{},...this.getLocalConfig()?.variables||{},...this.localGlobalValues}}getGlobalVariableLocals(){return{...this.localGlobalValues}}deleteGlobalVariable(e){delete this.localGlobalValues[e]}clearGlobalVariables(){this.localGlobalValues={}}getResolvedEnvironment(e){let t=e||this.selectedEnvironment,n=this.getSharedConfig(),s=this.getLocalConfig();if(!n?.environments?.[t])return null;let i=n.environments[t],o=s?.credentials?.[t],a=s?.variables||{},c=o?.variables||{},l=o&&o.headers||{},u=Gi(n.defaultHeaders||{},l),d=this.localEnvironmentValues.get(t)||{},p=this.secretValuesCache.get(t)||{},m={...i.variables||{},...c,...d,...p};return{name:t,description:i.description,requiresConfirmation:i.requiresConfirmation,headers:u,variables:m}}async getSecretVariable(e,t){return this.secretStore?.get(`${e}:${t}`)}async setSecretVariable(e,t,n){await this.secretStore?.store(`${e}:${t}`,n),this.secretValuesCache.has(e)||this.secretValuesCache.set(e,{}),this.secretValuesCache.get(e)[t]=n}async deleteSecretVariable(e,t){await this.secretStore?.delete(`${e}:${t}`),this.secretValuesCache.get(e)&&delete this.secretValuesCache.get(e)[t]}async loadSecretVariables(e){if(!this.secretStore)return;let t=e||this.selectedEnvironment,n=this.getSharedConfig()?.environments?.[t]?.secretVariables??[];if(n.length===0)return;let s={};await Promise.all(n.map(async i=>{let o=await this.secretStore.get(`${t}:${i}`);o!==void 0&&(s[i]=o)})),this.secretValuesCache.set(t,s)}resolveVariables(e,t){return this.createResolver(t).resolveString(e,!0)}exportEnvironmentsToFolder(e,t=!0){let n=this.getEnvironmentNames(),s=this.getSharedConfig(),i=s?.globalVariables?{...s.globalVariables}:{};if(!t&&Object.keys(i).length){let o=Ze.join(e,"globals.env");Un(o,i)}n.forEach(o=>{let a=s?.environments?.[o];if(!a)return;let c={...a.variables||{}};t&&(c={...i,...c});let l=Ze.join(e,`${ve(o)}.env`);Un(l,c)})}resolveVariablesWithExtra(e,t,n){return this.createResolver(n,t).resolveString(e,!0)}resolveVariablesInObject(e,t){return this.createResolver(t).resolveObject(e,!0)}resolveVariablesInObjectWithExtra(e,t,n){return this.createResolver(n,t).resolveObject(e,!0)}getHistoriesPath(){return this.historiesPath}getSharedConfigPath(){return this.sharedConfigPath}getLocalConfigPath(){return this.localConfigPath}getEnvironmentConfigPath(e){return Ze.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return ke.existsSync(this.localConfigPath)}saveSharedConfig(e){this.saveFolderSharedConfig(e),this.sharedConfig=e}saveLocalConfig(e){let t={variables:e.variables||{}};this.saveJsonFile(this.localConfigPath,t);for(let[n,s]of Object.entries(e.credentials||{})){let i=this.getEnvLocalConfigPath(n),o={variables:s.variables||{}};this.saveJsonFile(i,o)}this.localConfig=e}importPostmanEnvironmentFile(e){try{let t=ke.readFileSync(e,"utf-8"),n=bo(t);if(!n)throw new Error("Failed to parse Postman environment file");this.sharedConfig||this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}});let s=n.name||`imported-${Date.now()}`;return this.sharedConfig.environments=this.sharedConfig.environments||{},this.sharedConfig.environments[s]=this.sharedConfig.environments[s]||{},this.sharedConfig.environments[s].variables=n.variables,n.description&&(this.sharedConfig.environments[s].description=n.description),this.saveSharedConfig(this.sharedConfig),n}catch(t){throw console.error("[EnvironmentConfigService] importPostmanEnvironmentFile failed:",t),t}}saveEnvLocalConfig(e,t){let n=this.getEnvLocalConfigPath(e),s={variables:t};this.saveJsonFile(n,s),this.localConfig||(this.localConfig={credentials:{},variables:{}}),this.localConfig.credentials||(this.localConfig.credentials={}),this.localConfig.credentials[e]={variables:t}}getEnvLocalPath(e){return this.getEnvLocalConfigPath(e)}getEnvLocalConfigPath(e){return Ze.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=Ar(this.environmentsPath);this.sharedConfig={environments:e.environments,globalVariables:e.globalVariables,defaultHeaders:e.defaultHeaders},this.localConfig={credentials:e.localCredentials,variables:e.localVariables}}createResolver(e,t){let s=this.getResolvedEnvironment(e)?.variables||{},i=this.getGlobalVariables(),o=this.getGlobalVariableLocals();return new pn({globals:i,collectionVariables:{},environmentVariables:s,variables:{...o,...t||{}}})}saveFolderSharedConfig(e){ke.existsSync(this.environmentsPath)||ke.mkdirSync(this.environmentsPath,{recursive:!0});let t={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/global-environment.schema.json",variables:e.globalVariables||{},defaultHeaders:e.defaultHeaders||{}};this.saveJsonFile(this.sharedConfigPath,t);let n=ke.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!js(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=Ze.basename(i,".json");if(!s.has(o))try{ke.unlinkSync(Ze.join(this.environmentsPath,i))}catch{}}for(let[i,o]of Object.entries(e.environments||{})){let a={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/environment.schema.json",name:i,description:o.description,requiresConfirmation:o.requiresConfirmation,variables:o.variables||{}};this.saveJsonFile(Ze.join(this.environmentsPath,`${i}.json`),a)}}reload(){this.sharedConfig=null,this.localConfig=null,this.loadConfigs(),this.invalidateResolvedConfigCache()}invalidateResolvedConfigCache(){this.resolvedConfigCache.clear()}getFileOnlyVariables(e){this.loadConfigs();let t=this.sharedConfig,n=this.localConfig,s=t?.environments?.[e];return{...t?.globalVariables||{},...n?.variables||{},...s?.variables||{},...n?.credentials?.[e]?.variables||{}}}resolveConfigValues(e,t){if(e==null)return e;if(typeof e=="string"){let n=new pn({globals:{},collectionVariables:{},environmentVariables:t,variables:{}});if(/^\s*\{\{.*\}\}\s*$/.test(e)){let s=n.resolveString(e);if(s==="true")return!0;if(s==="false")return!1;let i=Number(s);return s!==""&&!isNaN(i)?i:s}return n.resolveString(e)}if(Array.isArray(e))return e.map(n=>this.resolveConfigValues(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveConfigValues(i,t);return n}return e}getResolvedConfig(e){let t=e??this.selectedEnvironment;if(!this.resolvedConfigCache.has(t)){let n=this.configService.getConfig(),s=this.getFileOnlyVariables(t),i=this.resolveConfigValues(n,s);this.resolvedConfigCache.set(t,i)}return this.resolvedConfigCache.get(t)}getAllEnvironments(){return this.loadConfigs(),this.sharedConfig?Object.entries(this.sharedConfig.environments).map(([e,t])=>({id:e,name:e,active:e===this.selectedEnvironment,variables:t.variables||{}})):[]}async setActiveEnvironment(e){await this.setSelectedEnvironment(e)}async createEnvironment(e){if(this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{}}),this.sharedConfig.environments[e])throw new Error(`Environment "${e}" already exists`);this.sharedConfig.environments[e]={description:`Created ${new Date().toISOString()}`,variables:{}},this.saveSharedConfig(this.sharedConfig)}async deleteEnvironment(e){if(this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentExists(e),delete this.sharedConfig.environments[e],this.selectedEnvironment===e){let t=Object.keys(this.sharedConfig.environments);this.selectedEnvironment=t.length>0?t[0]:"dev",await this.workspaceStore?.update(ei.SELECTED_ENVIRONMENT,this.selectedEnvironment)}this.saveSharedConfig(this.sharedConfig)}async duplicateEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),this.validateEnvironmentNameNotTaken(t);let n=this.sharedConfig.environments[e];this.sharedConfig.environments[t]=JSON.parse(JSON.stringify(n)),this.sharedConfig.environments[t].description=`Copied from ${e}`,this.saveSharedConfig(this.sharedConfig)}async renameEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),t!==e&&(this.validateEnvironmentNameNotTaken(t),this.sharedConfig.environments[t]=this.sharedConfig.environments[e],delete this.sharedConfig.environments[e],this.selectedEnvironment===e&&(this.selectedEnvironment=t,await this.workspaceStore?.update(ei.SELECTED_ENVIRONMENT,t)),this.saveSharedConfig(this.sharedConfig))}validateEnvironmentName(e){if(!e||e.trim().length===0)throw new Error("Environment name cannot be empty");if(e.length>128)throw new Error("Environment name cannot exceed 128 characters");if(!/^[a-zA-Z0-9_\-\.]+$/.test(e))throw new Error("Environment name can only contain letters, numbers, hyphens, underscores, and dots")}validateEnvironmentExists(e){if(!this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" not found`)}validateEnvironmentNameNotTaken(e){if(this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" already exists`)}validateConfigLoaded(){if(!this.sharedConfig)throw new Error("No environment configuration loaded")}async updateEnvironmentVariables(e,t){if(this.loadConfigs(),!this.sharedConfig)throw new Error("No configuration loaded");let n=this.sharedConfig.environments[e];if(!n)throw new Error(`Environment "${e}" not found`);n.variables=t,this.saveSharedConfig(this.sharedConfig)}saveJsonFile(e,t){try{let n=Ze.dirname(e);ke.existsSync(n)||ke.mkdirSync(n,{recursive:!0}),ke.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var _t,ti=E(()=>{"use strict";Qs();_t=class r{constructor(e,t,n,s,i,o,a,c,l,u,d,p,m){this.httpService=e;this.scriptExecutor=t;this.envConfigService=n;this.requestPreparer=s;this.environment=i;this.cookieJar=o;this.collectionScripts=a;this.folderScriptsChain=c;this.onConsoleOutput=l;this.collectionName=u;this.collectionAuth=d;this.iteration=p;this.iterationCount=m}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;async execute(e,t,n){let s=Date.now();return this.executeWithSession(e,t,n,s)}async executeWithSession(e,t,n,s){let i=this.collectPreRequestScripts(e),o=this.collectPostResponseScripts(e),a=this.envConfigService.getResolvedEnvironment(this.environment);if(!a)throw new Error(`Environment "${this.environment}" not found or not configured`);let c=this.envConfigService.getGlobalVariables(),l={request:e,variables:{...t},environmentVariables:a.variables||{},globals:{...c},environmentName:this.environment,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:this.collectionName,iteration:this.iteration,iterationCount:this.iterationCount},onEnvironmentChange:async(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setEnvironmentVariable(m,f,this.environment):p==="unset"&&m?this.envConfigService.deleteEnvironmentVariable(m,this.environment):p==="clear"&&this.envConfigService.clearEnvironmentVariables(this.environment)},onGlobalsChange:(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setGlobalVariable(m,f):p==="unset"&&m?this.envConfigService.deleteGlobalVariable(m):p==="clear"&&this.envConfigService.clearGlobalVariables()}},u=this.scriptExecutor.createRequestSession(l),d=null;try{let p={...t},m={...e},f;if((!m.auth||m.auth.type==="inherit")&&(m.auth=this.collectionAuth&&this.collectionAuth.type!=="inherit"?this.collectionAuth:void 0),i.length>0){let O=await u.executePreRequest(i);if(O.consoleOutput&&O.consoleOutput.length>0&&this.onConsoleOutput?.(O.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),O.nextRequest!==void 0&&(f=O.nextRequest),O.skipRequest){let L={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:L,params:{},query:{}},response:{status:0,statusText:"Skipped",headers:{},body:null,time:0,cookies:[]},duration:Date.now()-s,timestamp:Date.now(),passed:!0,assertions:[],modifiedVariables:p,nextRequest:f}}O.success&&(O.modifiedRequest&&(O.modifiedRequest.url&&(m.url=O.modifiedRequest.url),O.modifiedRequest.headers&&(m.headers=O.modifiedRequest.headers),O.modifiedRequest.params&&(m.params=O.modifiedRequest.params),O.modifiedRequest.query&&(m.query=O.modifiedRequest.query),O.modifiedRequest.body!==void 0&&(m.body=O.modifiedRequest.body)),(O.localVariables??O.modifiedVariables)&&(p=O.localVariables??O.modifiedVariables))}d=await this.requestPreparer.prepareRequest(m,this.environment,a,p);let{url:h,headers:g,body:y,method:v}=d,w={};for(let O in g)Object.prototype.hasOwnProperty.call(g,O)&&(w[O.toUpperCase()]=g[O]);if(!w.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let L=this.cookieJar.getCookieHeader(h);L&&(w.COOKIE=L)}let b={method:v,url:h,headers:w,body:y.content,signal:n,settings:m.settings?{...m.settings}:void 0},C=await this.httpService.execute(b);this.cookieJar&&C.headers&&await this.cookieJar.setCookiesFromResponse(h,C.headers);let R=Date.now()-s,A=[],N={},M;if(o.length>0){let O=0;if(C.body)if(typeof C.body=="string")O=Buffer.byteLength(C.body,"utf8");else if(Buffer.isBuffer(C.body))O=C.body.length;else try{O=Buffer.byteLength(JSON.stringify(C.body),"utf8")}catch{O=0}let L=oo(C.headers,C.cookies,d.url),Q={executedRequest:d,status:C.status,statusText:C.statusText,headers:io(C.headers||{}),body:C.body,cookies:L,responseTime:C.time,responseSize:O},Y=await u.executePostResponse(o,Q);A=Y.testResults,N=Y.modifiedEnvironmentVariables||{},M=Y.visualizerData,(Y.localVariables??Y.modifiedVariables)&&(p=Y.localVariables??Y.modifiedVariables),Y.nextRequest!==void 0&&(f=Y.nextRequest),Y.consoleOutput&&Y.consoleOutput.length>0&&this.onConsoleOutput?.(Y.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let j=A.length===0||A.every(O=>O.passed),U=A.length>0?j:C.status>=200&&C.status<=302;return{requestId:e.id,name:e.name,executedRequest:{...d,headers:w},response:{status:C.status,statusText:C.statusText,headers:C.headers||{},body:C.body,time:C.time||R,cookies:C.cookies||[]},duration:R,timestamp:Date.now(),passed:U,assertions:A,modifiedVariables:p,modifiedEnvironmentVariables:N,nextRequest:f,visualizerData:M}}catch(p){return this.handleError(e,d,p,s)}finally{u.dispose?.()}}collectPreRequestScripts(e){let t=[];if(this.collectionScripts?.preRequest&&t.push(this.collectionScripts.preRequest),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain))for(let n of this.folderScriptsChain)n?.preRequest&&t.push(n.preRequest);else this.folderScriptsChain.preRequest&&t.push(this.folderScriptsChain.preRequest);return e.scripts?.preRequest&&t.push(e.scripts.preRequest),t}collectPostResponseScripts(e){let t=[];if(e.scripts?.postResponse&&t.push(e.scripts.postResponse),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain)){let n=[...this.folderScriptsChain].reverse();for(let s of n)s?.postResponse&&t.push(s.postResponse)}else this.folderScriptsChain.postResponse&&t.push(this.folderScriptsChain.postResponse);return this.collectionScripts?.postResponse&&t.push(this.collectionScripts.postResponse),t}handleError(e,t,n,s){let i=Date.now()-s,o=t?.method||e.method,a=t?.url||e.url;this.onConsoleOutput?.([`${n.message||n}`],{requestName:e.name||"",phase:"error"});let c=String(n.name==="AbortError"?"Request was aborted":n.message||n),l=n?.stack?String(n.stack):"",u=this.errorBodyFormat,d,p;u==="html"||u==="both"?(d=r.formatErrorAsHtml(c,l),p={"content-type":"text/html; charset=utf-8"}):(d=c,p={});let m={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:a||"",method:o||"GET",headers:t?.headers||{},body:t?.body||m,params:t?.params||{},query:t?.query||{}},response:{status:0,statusText:n.name==="AbortError"?"Aborted":n.code||n.message||"Request Error",headers:p,cookies:[],body:d,time:0},duration:i,timestamp:Date.now(),passed:!1,assertions:[],error:c}}get errorBodyFormat(){return"text"}static formatErrorAsHtml(e,t){let n=s=>s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");return`<!doctype html>
244
244
  <html>
245
245
  <body style="font-family:system-ui,Segoe UI,Roboto,-apple-system,Helvetica,Arial,sans-serif;padding:12px;color:#c7254e;">
246
246
  <h2 style="margin-top:0;color:#a94442">Request Error</h2>
@@ -465,13 +465,13 @@ Return ONLY a valid JSON object (no markdown fences):
465
465
 
466
466
  `)||void 0,requests:l,total:c.length,offset:o,hasMore:o+a<c.length,nextOffset:o+a,expectedCallAfterThis:"create_request"}}}},{toolNames:[S.healAssertions],handle({args:r,services:e,collections:t,runStore:n}){let s=z(r.collection,t),i=Ue(r.request,s),o=e.collection.getRequestScript(s.id,i.id,"post-response")??"",a,c=typeof r.runId=="string"?r.runId.trim():void 0;if(c)try{let u=n.require(c).allResults.find(d=>typeof d.name=="string"&&d.name.toLowerCase()===i.name.toLowerCase());u&&(a={status:u.status,responseBody:u.responseBody,responseHeaders:u.responseHeaders,failedTests:u.failedTests})}catch{}return{task:{action:"heal_assertions",instructions:[`Request: ${i.method} ${i.url??""}`,"The current test script may have stale or incorrect assertions (e.g. wrong status code, missing/renamed fields).","Compare task.currentScript against task.lastResponse (if available).","Rewrite the complete post-response script so all assertions match the observed response while keeping valid checks.",'Call set_request_script (phase: "post-response") with the updated script immediately.',"Do NOT ask for confirmation."],collection:s.name,request:i.name,method:i.method,url:i.url??"",businessContext:[Xe(i,op(s,i)).snapshot().body,et(e.workspaceFolder).snapshot().body].filter(Boolean).join(`
467
467
 
468
- `)||void 0,currentScript:o,lastResponse:a??null,note:a?"Last response data available \u2014 use it to align assertions with actual behavior.":"No run data available \u2014 run the request first with run_request, then call heal_assertions again with the runId.",expectedCallAfterThis:"set_request_script"}}}},{toolNames:[S.generateIterationData],handle({args:r,collections:e}){let t=z(r.collection,e),n=Ue(r.request,t),s=typeof r.iterations=="number"?Math.min(50,Math.max(1,r.iterations)):5,i=n.body?.type==="raw"&&typeof n.body.content=="string"?n.body.content:void 0,o=(n.headers??[]).filter(u=>u.enabled!==!1).map(u=>({key:u.key,value:u.value})),a=(n.query??[]).filter(u=>u.enabled!==!1).map(u=>({key:u.key,value:u.value})),c=/\{\{([^}]+)\}\}/g,l=new Set;for(let u of[n.url??"",i??"",...o.map(d=>d.value),...a.map(d=>d.value)]){let d;for(c.lastIndex=0;(d=c.exec(u))!==null;)l.add(d[1])}return{task:{action:"generate_iteration_data",instructions:[`Generate ${s} test data rows for: ${n.method} ${n.url??""}`,`The request uses these {{variable}} placeholders: ${[...l].join(", ")||"(none detected)"}`,"Each row must be a JSON object whose keys match the placeholder names.","Cover a mix of: (1) valid happy-path data, (2) boundary values, (3) invalid inputs that should fail, (4) edge cases.",'Return the rows as a JSON array in a code block labeled "iterationData".',"This data can be used with: http-forge run-request --collection ... --variables '[...]' or passed to run_request via the variables argument."],collection:t.name,request:n.name,method:n.method,url:n.url??"",businessContext:Xe(n,op(t,n)).snapshot().body||void 0,body:i??null,headers:o,queryParams:a,placeholders:[...l],iterations:s}}}}]});function lp(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.name===e||e.endsWith("/"+n.name))return{id:n.id};let s=lp(n.items??[],e);if(s)return s}}var up,dp=E(()=>{"use strict";Ne();_e();_e();up=[{toolNames:[S.createCollection],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw I('"name" is required');let n=await e.collection.createCollection(t);return{id:n.id,name:n.name,created:!0,hint:"Collection is empty. Call create_folder to add folders, or create_request to add requests directly."}}},{toolNames:[S.renameCollection],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw I('"newName" is required');return await e.collection.renameCollection(n.id,s),{id:n.id,oldName:n.name,newName:s,renamed:!0}}},{toolNames:[S.deleteCollection],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw I('"confirm" must be true to delete a collection');let n=z(r.collection,t);return await e.collection.deleteCollection(n.id),{deleted:!0,collection:n.name}}},{toolNames:[S.duplicateCollection],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw I('"newName" is required');let i=await e.collection.duplicateCollection(n.id,s);return{id:i.id,name:i.name,duplicatedFrom:n.name}}},{toolNames:[S.createFolder],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw I('"name" is required');let i;if(typeof r.parentFolder=="string"&&r.parentFolder.trim()){let a=r.parentFolder.toLowerCase(),c=Re(n);if(K(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let d=Re(n).find(p=>p.folderPath===r.parentFolder||p.folderPath.toLowerCase()===a);if(d){let p=n.items;i=lp(p,d.folderPath)?.id}}}let o=await e.collection.createFolder({collectionId:n.id,name:s,parentId:i});return{id:o.id,name:o.name,created:!0,collection:n.name}}},{toolNames:[S.deleteFolder],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw I('"confirm" must be true to delete a folder');let n=z(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw I('"folder" is required');let s=r.folder.toLowerCase(),i=Re(n).find(c=>c.folderPath===r.folder||c.folderPath.toLowerCase()===s);if(!i)throw I(`folder "${r.folder}" not found in collection "${n.name}"`);let o=Ol(n.items,i.folderId);if(!o)throw I(`folder "${r.folder}" could not be resolved`);let a=i.requestCount;return await e.collection.deleteFolder(n.id,o.id),{deleted:!0,folder:i.folderPath,requestsRemoved:a}}}]});var Nl=E(()=>{"use strict"});var pp=E(()=>{"use strict"});var Rt,cs,Eg,qg,Ag,rr,Yo=E(()=>{"use strict";Rt=T(require("fs")),cs=T(require("path")),Eg=["package.json","src/main.ts","src/main.js","src/app.ts","src/app.js","pom.xml","build.gradle","build.gradle.kts","settings.gradle","requirements.txt","pyproject.toml","poetry.lock","Pipfile","app/main.py","main.py"],qg={express:["express","router.","app.use(","app.get(","express.Router"],nestjs:["@nestjs/common","@Controller(","@Get(","@Post("],fastify:["fastify","fastify.route(","fastify.get(","register("],lambda:["exports.handler","event.pathParameters","APIGatewayProxyEvent","aws-lambda"],spring:["@RestController","@Controller","@GetMapping","@PostMapping","@RequestMapping"],fastapi:["from fastapi","import fastapi","@app.get(","@router.get("],unknown:[]},Ag={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},rr=class{buildFingerprint(e){let t=[],n=cs.join(e,"package.json"),s;for(let i of Eg){let o=cs.join(e,i);Rt.existsSync(o)&&t.push(o)}if(Rt.existsSync(n))try{let i=JSON.parse(Rt.readFileSync(n,"utf-8"));s={dependencies:i.dependencies,devDependencies:i.devDependencies,scripts:i.scripts}}catch{}return{projectRoot:e,packageJsonPath:Rt.existsSync(n)?n:void 0,packageJson:s,evidenceFiles:t}}detectFrameworks(e){let t=[];return(this.hasDependency(e,"express")||this.hasSourceHint(e,"express"))&&t.push("express"),(this.hasDependency(e,"@nestjs/common")||this.hasSourceHint(e,"nestjs"))&&t.push("nestjs"),(this.hasDependency(e,"fastify")||this.hasSourceHint(e,"fastify"))&&t.push("fastify"),(this.hasBuildFile(e,"pom.xml")||this.hasBuildFile(e,"build.gradle")||this.hasBuildFile(e,"build.gradle.kts")||this.hasBuildFile(e,"settings.gradle")||this.hasSourceHint(e,"spring"))&&t.push("spring"),(this.hasBuildFile(e,"requirements.txt")||this.hasBuildFile(e,"pyproject.toml")||this.hasBuildFile(e,"poetry.lock")||this.hasBuildFile(e,"Pipfile")||this.hasSourceHint(e,"fastapi"))&&t.push("fastapi"),t.includes("express")||t.includes("fastify")||(this.hasDependency(e,"@types/aws-lambda")||this.hasDependency(e,"aws-lambda")||this.hasDependency(e,"serverless")||this.hasSourceHint(e,"lambda"))&&t.push("lambda"),t.length>0?t:["unknown"]}hasDependency(e,t){let n=e.packageJson?.dependencies??{},s=e.packageJson?.devDependencies??{};return!!(n[t]||s[t])}hasBuildFile(e,t){return Rt.existsSync(cs.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=qg[t],i=Ag[t],o=0,a=120;for(let c of n){let l=cs.join(e.projectRoot,c);if(!Rt.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let d=u.shift(),p;try{p=Rt.readdirSync(d,{withFileTypes:!0})}catch{continue}for(let m of p){let f=cs.join(d,m.name);if(m.isDirectory()){u.push(f);continue}if(!m.isFile()||!i.some(g=>f.endsWith(g)))continue;o+=1;let h="";try{h=Rt.readFileSync(f,"utf-8")}catch{continue}if(s.some(g=>h.includes(g)))return!0}}}return!1}}});function nt(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=fp.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=mp.join(n,i.name);if(i.isDirectory()){Pg.has(i.name)||t.push(o);continue}i.isFile()&&(kg.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var fp,mp,Pg,kg,Rn=E(()=>{"use strict";fp=T(require("fs")),mp=T(require("path")),Pg=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),kg=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});function Ri(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=Xo.isAbsolute(t)?t:Xo.join(r,t);if(!hp.existsSync(n))return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader module not found: ${n}`}]};try{let s=require(n),i=s.loadSeedManifestEndpoints??s.default;if(typeof i!="function")return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:"Custom seed loader module must export a function named loadSeedManifestEndpoints or a default function."}]};let o=i(r,e);return Array.isArray(o)?{endpoints:o,warnings:[]}:{endpoints:o?.endpoints??[],warnings:o?.warnings??[]}}catch(s){return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader failed at ${n}: ${s instanceof Error?s.message:String(s)}`}]}}}var hp,Xo,ea=E(()=>{"use strict";hp=T(require("fs")),Xo=T(require("path"))});function _l(r,e){let t=r.projectName?.trim();if(t)return t;let n=gp(r.source.filePath),s=Ig(n);if(s)return s;let i;for(let a of e){let c=gp(a);(n===c||n.startsWith(`${c}/`))&&(!i||c.length>i.length)&&(i=c)}if(!i)return;let o=i.split("/").filter(Boolean);return o[o.length-1]||void 0}function Ig(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function gp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Ml=E(()=>{"use strict"});function Yt(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function Xt(r,e,t){let n=[],s=/:([a-zA-Z_]\w*)/g,i=/\{([a-zA-Z_]\w*)\}/g,o;for(;(o=s.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});for(;(o=i.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});return n}function Ci(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,d=new Map,p=Gg(o),m=zg(r,e,p),f=Zg(r,e,p);if(i?.requestAliases)for(let R of i.requestAliases)m.add(R);if(i?.responseAliases)for(let R of i.responseAliases)f.add(R);let h=Rp(e),g=Tg(e,t),y=Jg(r,t,h,g,m,f),v=(R,A)=>{let N=l.find(M=>M.statusCode===R);return N||(N={statusCode:R},l.push(N)),A&&(N.body={type:A,schema:N.body?.schema}),N};x.isFunctionLike(r)&&Ug(r,e,d,m,f,p);let w=(R,A)=>{let N=h.get(R);if(N){let Q=`${t}:${R}`;if(s.visitedSymbols.has(Q))return;s.visitedSymbols.add(Q);let Y=y.get(Q),Je=A?sa(A,N,m,f):void 0,an=wp(Y,Je),kt=Ci(N,e,t,n,s,an,o);jl({parameters:a,requestBody:u,cookies:c,responses:l},kt),!u&&kt.requestBody&&(u=kt.requestBody);return}let M=g.get(R);if(!M||s.visitedSymbols.has(M.symbolKey))return;s.visitedSymbols.add(M.symbolKey);let j=y.get(M.symbolKey),U=A?sa(A,M.node,m,f):void 0,O=wp(j,U),L=Ci(M.node,M.sourceFile,M.filePath,n,s,O,o);jl({parameters:a,requestBody:u,cookies:c,responses:l},L),!u&&L.requestBody&&(u=L.requestBody)},b=["POST","PUT","PATCH"].includes(n),C=R=>{x.isVariableDeclaration(R)&&Bg(R,e,d,m,f,p),x.isIdentifier(R)&&(x.isCallExpression(R.parent)&&R.parent.expression===R||w(R.text));let A=ls(R,e,"query",d,m,f,p);if(A){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:A.path,location:"query",type:na(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let N=ls(R,e,"params",d,m,f,p);if(N){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:N.path,location:"path",required:!0,type:na(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}if(Hg(R,e,m)&&!u){let O=e.getLineAndCharacterOfPosition(R.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}}let M=ls(R,e,"body",d,m,f,p);if(M){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:M.path,location:"body",type:na(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let j=ls(R,e,"headers",d,m,f,p);if(j){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:j.path,location:"header",type:"string",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let U=ls(R,e,"cookies",d,m,f,p);if(U){let O=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:U.path,type:"request",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}for(let O of p){let L=ls(R,e,O,d,m,f,p);if(!L)continue;let Q=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:L.path,location:O,type:na(R,e),detectionLocation:{filePath:t,line:Q.line+1,column:Q.character+1,accessMode:"read"}})}if(x.isCallExpression(R)){let O=Wg(R,e,f);O&&v(O.statusCode,O.bodyType)}if(x.isCallExpression(R)){let O=Kg(R,f);if(O){let L=v(O.statusCode);if(!L.headers?.some(Q=>Q.name===O.headerName)){let Q=e.getLineAndCharacterOfPosition(R.getStart(e));L.headers=L.headers??[],L.headers.push({name:O.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:Q.line+1,column:Q.character+1,accessMode:"write"}})}}}if(x.isCallExpression(R)&&x.isPropertyAccessExpression(R.expression)&&Yg(R.expression.expression,f)&&R.expression.name.text==="cookie"&&R.arguments[0]&&x.isStringLiteral(R.arguments[0])){let O=R.arguments[0].text;if(O&&!c.some(L=>L.name===O&&L.type==="response")){let L=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:O,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:L.line+1,column:L.character+1,accessMode:"write"}})}}x.isCallExpression(R)&&x.isIdentifier(R.expression)&&w(R.expression.text,R),x.forEachChild(R,C)};return r&&C(r),{parameters:a,requestBody:b?u||{type:"json",required:!0}:void 0,cookies:c,responses:l.length>0?l:[{statusCode:200}]}}function us(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=Ci(o,e,t,n,void 0,void 0,s);jl(i,a)}return i.parameters=en(i.parameters),i.cookies=Lg(i.cookies),!i.requestBody&&["POST","PUT","PATCH"].includes(n)&&(i.requestBody={type:"json",required:!0}),i.responses.length===0&&(i.responses=[{statusCode:200}]),i}function Rp(r){let e=new Map,t=n=>{x.isFunctionDeclaration(n)&&n.name&&e.set(n.name.text,n),x.isVariableDeclaration(n)&&x.isIdentifier(n.name)&&n.initializer&&(x.isArrowFunction(n.initializer)||x.isFunctionExpression(n.initializer))&&e.set(n.name.text,n.initializer),x.forEachChild(n,t)};return t(r),e}function Tg(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=$g(e,s);if(!o)return;let a=Og(o);if(!a)return;let c=Fg(a,o);for(let l of i){let u=c.get(l.importedName);u&&t.set(l.localName,{node:u,sourceFile:a,filePath:o,symbolKey:`${o}:${l.importedName}`})}};for(let s of r.statements){if(x.isImportDeclaration(s)&&s.importClause&&x.isStringLiteral(s.moduleSpecifier)){let i=s.moduleSpecifier.text,o=[];s.importClause.name&&o.push({localName:s.importClause.name.text,importedName:"default"});let a=s.importClause.namedBindings;if(a&&x.isNamedImports(a))for(let c of a.elements)o.push({localName:c.name.text,importedName:c.propertyName?c.propertyName.text:c.name.text});n(i,o);continue}if(x.isVariableStatement(s))for(let i of s.declarationList.declarations){if(!i.initializer||!x.isCallExpression(i.initializer)||!x.isIdentifier(i.initializer.expression)||i.initializer.expression.text!=="require")continue;let o=i.initializer.arguments[0];if(!o||!x.isStringLiteral(o))continue;let a=o.text,c=[];if(x.isIdentifier(i.name))c.push({localName:i.name.text,importedName:"default"});else if(x.isObjectBindingPattern(i.name))for(let l of i.name.elements){if(!x.isIdentifier(l.name))continue;let u=l.propertyName&&(x.isIdentifier(l.propertyName)||x.isStringLiteral(l.propertyName))?l.propertyName.text:l.name.text;c.push({localName:l.name.text,importedName:u})}n(a,c)}}return t}function Og(r){let e="";try{e=ia.readFileSync(r,"utf-8")}catch{return}return x.createSourceFile(r,e,x.ScriptTarget.Latest,!0,r.endsWith(".ts")?x.ScriptKind.TS:x.ScriptKind.JS)}function $g(r,e){let t=ir.resolve(ir.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,ir.join(t,"index.ts"),ir.join(t,"index.js")];for(let s of n)try{if(ia.statSync(s).isFile())return s}catch{continue}}function Fg(r,e){let t=new Map,n=Rp(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(x.isFunctionDeclaration(i)&&i.name&&yp(i)){s(i.name.text,i),vp(i)&&s("default",i);continue}if(x.isVariableStatement(i)&&yp(i)){for(let c of i.declarationList.declarations)!x.isIdentifier(c.name)||!c.initializer||(x.isArrowFunction(c.initializer)||x.isFunctionExpression(c.initializer))&&(s(c.name.text,c.initializer),vp(i)&&s("default",c.initializer));continue}if(x.isExportAssignment(i)){let c=i.expression;if(x.isIdentifier(c)){let l=n.get(c.text);l&&s("default",l)}else(x.isFunctionExpression(c)||x.isArrowFunction(c))&&s("default",c);continue}if(!x.isExpressionStatement(i)||!x.isBinaryExpression(i.expression))continue;let o=i.expression.left,a=i.expression.right;if(x.isPropertyAccessExpression(o)&&o.expression.getText(r)==="module.exports"){let c=o.name.text,l=Dl(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=Dl(a,n);c&&s("default",c);continue}if(x.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=Dl(a,n);c&&s(o.name.text,c)}}return t}function Dl(r,e){if(x.isFunctionExpression(r)||x.isArrowFunction(r))return r;if(x.isIdentifier(r))return e.get(r.text)}function yp(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.ExportKeyword):!1}function vp(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.DefaultKeyword):!1}function jl(r,e){r.parameters.push(...e.parameters),r.cookies.push(...e.cookies),!r.requestBody&&e.requestBody&&(r.requestBody=e.requestBody);for(let t of e.responses){let n=r.responses.find(o=>o.statusCode===t.statusCode);if(!n){r.responses.push({statusCode:t.statusCode,headers:t.headers?[...t.headers]:void 0,body:t.body});continue}let s=n.headers??[],i=t.headers??[];n.headers=en([...s,...i])}}function en(r){let e=new Map;for(let i of r){let o=`${i.location}:${i.name}`,a=e.get(o);if(!a){e.set(o,{...i,evidenceLocations:bp([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=bp(a.evidenceLocations??[],i),!a.detectionLocation&&i.detectionLocation&&(a.detectionLocation=i.detectionLocation),!a.type&&i.type){a.type=i.type;continue}if(!i.type||!a.type||a.type===i.type)continue;let c=new Set(a.conflictingTypes??[]);c.add(a.type),c.add(i.type),a.conflictingTypes=Array.from(c),a.location==="body"&&(a.type==="object"||i.type==="object")&&(a.type="object")}let t=Array.from(e.values()).map(i=>Ng(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=ta(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=ta(o)}}for(let i of s.values()){let o=ta(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=ta(o)}}return t}function bp(r,e){let t=[...r??[]];e.detectionLocation&&t.push(e.detectionLocation),e.evidenceLocations&&t.push(...e.evidenceLocations);let n=new Set,s=[];for(let i of t){let o=`${i.filePath}:${i.line}:${i.column??0}:${i.symbolName??""}:${i.accessMode??""}`;n.has(o)||(n.add(o),s.push(i))}return s}function Ng(r){let e=Dg([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=_g(e),n=e.filter(s=>!jg(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function _g(r){return[...r].sort(Mg)[0]}function Mg(r,e){let t=Sp(r),n=Sp(e);if(t!==n)return n-t;if(r.line!==e.line)return r.line-e.line;let s=r.column??0,i=e.column??0;return s!==i?s-i:r.filePath.localeCompare(e.filePath)}function Sp(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function Dg(r){let e=[],t=new Set;for(let n of r){let s=`${n.filePath}:${n.line}:${n.column??0}:${n.symbolName??""}:${n.accessMode??""}`;t.has(s)||(t.add(s),e.push(n))}return e}function jg(r,e){return r.filePath===e.filePath&&r.line===e.line&&(r.column??0)===(e.column??0)&&(r.symbolName??"")===(e.symbolName??"")&&(r.accessMode??"")===(e.accessMode??"")}function Lg(r){let e=new Set,t=[];for(let n of r){let s=`${n.type??"unknown"}:${n.name}`;e.has(s)||(e.add(s),t.push(n))}return t}function Hg(r,e,t){return x.isPropertyAccessExpression(r)&&x.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function ls(r,e,t,n,s,i,o){return Hl(r,e,t,n,!1,s,i,o)}function Hl(r,e,t,n,s,i,o,a){let c=[],l=r;for(;l&&(x.isPropertyAccessExpression(l)||x.isElementAccessExpression(l)||x.isPropertyAccessChain(l)||x.isElementAccessChain(l));){if(x.isPropertyAccessExpression(l)||x.isPropertyAccessChain(l)){c.unshift(l.name.text),l=l.expression;continue}if(x.isElementAccessExpression(l)||x.isElementAccessChain(l)){let h=l.argumentExpression;if(h&&(x.isStringLiteral(h)||x.isNumericLiteral(h))){let g=h.text;x.isNumericLiteral(h)||/^\d+$/.test(g)?c.unshift("[]"):c.unshift(g)}else return;l=l.expression}}let u=c.indexOf(t),p=a?.has(t)??!1?l&&x.isIdentifier(l)&&((o?.has(l.text)??!1)||(i?.has(l.text)??!1)):l&&x.isIdentifier(l)&&i?.has(l.text)===!0;if(u!==-1&&p){let h=c.slice(u+1);return h.length===0?s?{path:""}:void 0:{path:ra(h)}}if(!l||!x.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=ra(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function Bg(r,e,t,n,s,i){let o=r.initializer;if(!o)return;x.isIdentifier(o)&&n.has(o.text)&&x.isIdentifier(r.name)&&n.add(r.name.text),x.isIdentifier(o)&&s.has(o.text)&&x.isIdentifier(r.name)&&s.add(r.name.text);let a=["body","query","params","headers","cookies",...i],c,l="";for(let u of a){let d=Hl(o,e,u,t,!0,n,s,i);if(d){c=u,l=d.path;break}}if(c){if(x.isIdentifier(r.name)){t.set(r.name.text,{target:c,path:l});return}(x.isObjectBindingPattern(r.name)||x.isArrayBindingPattern(r.name))&&Ei(r.name,c,l,t)}}function Ug(r,e,t,n,s,i){let o=["body","query","params","headers","cookies",...i];for(let a of r.parameters){if((x.isObjectBindingPattern(a.name)||x.isArrayBindingPattern(a.name))&&!a.initializer){Vg(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let d of o){let p=Hl(c,e,d,t,!0,n,s,i);if(p){l=d,u=p.path;break}}if(l){if(x.isIdentifier(a.name)){t.set(a.name.text,{target:l,path:u});continue}(x.isObjectBindingPattern(a.name)||x.isArrayBindingPattern(a.name))&&Ei(a.name,l,u,t)}}}function Vg(r,e,t){if(!x.isObjectBindingPattern(r))return;let n=new Set(["body","query","params","headers","cookies",...t]);for(let s of r.elements){let i=Ll(s);if(!i||!n.has(i))continue;let o=i;if(x.isIdentifier(s.name)){e.set(s.name.text,{target:o,path:""});continue}(x.isObjectBindingPattern(s.name)||x.isArrayBindingPattern(s.name))&&Ei(s.name,o,"",e)}}function zg(r,e,t){let n=new Set,s=new Set(["query","params","body","headers","cookies",...t]),i=o=>{if(x.isPropertyAccessExpression(o)||x.isPropertyAccessChain(o)){let a=o.name.text;if(s.has(a)){let c=sr(o.expression);c&&n.add(c)}}if(x.isElementAccessExpression(o)||x.isElementAccessChain(o)){let a=o.argumentExpression;if(a&&x.isStringLiteral(a)&&s.has(a.text)){let c=sr(o.expression);c&&n.add(c)}}x.isVariableDeclaration(o)&&o.initializer&&x.isIdentifier(o.name)&&x.isIdentifier(o.initializer)&&n.has(o.initializer.text)&&n.add(o.name.text),x.forEachChild(o,i)};return i(r),n}function Ei(r,e,t,n){if(x.isObjectBindingPattern(r)){for(let s of r.elements){let i=Ll(s);if(!i)continue;let o=xp(t,i);if(x.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(x.isObjectBindingPattern(s.name)||x.isArrayBindingPattern(s.name))&&Ei(s.name,e,o,n)}return}for(let s of r.elements){if(!x.isBindingElement(s))continue;let i=Ll(s)??"[]",o=xp(t,/^\d+$/.test(i)?"[]":i);if(x.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(x.isObjectBindingPattern(s.name)||x.isArrayBindingPattern(s.name))&&Ei(s.name,e,o,n)}}function Ll(r){let e=r.propertyName;if(!e)return x.isIdentifier(r.name)?r.name.text:void 0;if(x.isIdentifier(e)||x.isStringLiteral(e)||x.isNumericLiteral(e))return e.text}function xp(r,e){return ra(r?`${r}.${e}`.split("."):[e])}function ra(r){if(r.length===0)return"";let e="";for(let t of r)if(t){if(t==="[]"){e.endsWith("[]")||(e+="[]");continue}e+=e?`.${t}`:t}return e}function ta(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function Jg(r,e,t,n,s,i){let o=new Map,a=(l,u)=>{let d=o.get(l);if(!d){o.set(l,{requestAliases:u.requestAliases?new Set(u.requestAliases):void 0,responseAliases:u.responseAliases?new Set(u.responseAliases):void 0});return}if(u.requestAliases)if(!d.requestAliases)d.requestAliases=new Set(u.requestAliases);else for(let p of u.requestAliases)d.requestAliases.add(p);if(u.responseAliases)if(!d.responseAliases)d.responseAliases=new Set(u.responseAliases);else for(let p of u.responseAliases)d.responseAliases.add(p)},c=l=>{if(x.isCallExpression(l)&&x.isIdentifier(l.expression)){let u=l.expression.text,d=t.get(u);if(d){let m=sa(l,d,s,i);m&&a(`${e}:${u}`,m)}let p=n.get(u);if(p){let m=sa(l,p.node,s,i);m&&a(p.symbolKey,m)}}x.forEachChild(l,c)};return c(r),o}function wp(r,e){if(!r&&!e)return;let t=new Set([...r?.requestAliases??[],...e?.requestAliases??[]]),n=new Set([...r?.responseAliases??[],...e?.responseAliases??[]]);return{requestAliases:t.size>0?t:void 0,responseAliases:n.size>0?n:void 0}}function Gg(r){let e=new Set,t=new Set(["query","params","body","headers","cookies"]);for(let n of r){let s=n.trim();!s||t.has(s)||e.add(s)}return e.size===0&&e.add("locals"),e}function sa(r,e,t,n){let s=new Set,i=new Set,o=Math.min(r.arguments.length,e.parameters.length);for(let a=0;a<o;a+=1){let c=e.parameters[a];if(!x.isIdentifier(c.name))continue;let l=r.arguments[a],u=sr(l);u&&(t.has(u)&&s.add(c.name.text),n.has(u)&&i.add(c.name.text))}if(!(s.size===0&&i.size===0))return{requestAliases:s.size>0?s:void 0,responseAliases:i.size>0?i:void 0}}function na(r,e){if(!r||!r.parent)return"string";if(x.isCallExpression(r.parent)&&x.isIdentifier(r.parent.expression)){let t=r.parent.expression.text;if(t==="parseInt"||t==="parseFloat")return"number"}if(x.isBinaryExpression(r.parent)&&(r.parent.operatorToken.kind===x.SyntaxKind.EqualsEqualsToken||r.parent.operatorToken.kind===x.SyntaxKind.EqualsEqualsEqualsToken)){let t=r.parent.left===r?r.parent.right:r.parent.left;if(x.isNumericLiteral(t))return"number"}return"string"}function Wg(r,e,t){let n=r.expression;if(!x.isPropertyAccessExpression(n))return;let s=n.name.text;if(s!=="json"&&s!=="send")return;let i=Cp(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":Qg(r.arguments[0])}}function Kg(r,e){let t=r.expression;if(!x.isPropertyAccessExpression(t))return;let n=t.name.text;if(n!=="header"&&n!=="set")return;let s=r.arguments[0];if(!s||!x.isStringLiteral(s))return;let i=Cp(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function Cp(r,e){if(!x.isPropertyAccessExpression(r.expression))return;let t=200,n=r.expression.expression;for(;;){if(x.isIdentifier(n)&&e.has(n.text))return{receiver:n.text,statusCode:t};if(!x.isCallExpression(n)||!x.isPropertyAccessExpression(n.expression))return;let s=n.expression.name.text;if(s==="status"||s==="code"){let i=n.arguments[0];i&&x.isNumericLiteral(i)&&(t=Number(i.text))}n=n.expression.expression}}function Qg(r){return r&&(x.isObjectLiteralExpression(r)||x.isArrayLiteralExpression(r))?"json":"text"}function Zg(r,e,t){let n=new Set,s=new Set(["status","code","json","send","header","set","cookie"]),i=new Set(t),o=a=>{if(x.isPropertyAccessExpression(a)||x.isPropertyAccessChain(a)){let c=a.name.text;if(i.has(c)){let l=sr(a.expression);l&&n.add(l)}}if(x.isElementAccessExpression(a)||x.isElementAccessChain(a)){let c=a.argumentExpression;if(c&&x.isStringLiteral(c)&&i.has(c.text)){let l=sr(a.expression);l&&n.add(l)}}if(x.isCallExpression(a)&&x.isPropertyAccessExpression(a.expression)){let c=a.expression.name.text;if(s.has(c)){let l=sr(a.expression.expression);l&&n.add(l)}}x.isVariableDeclaration(a)&&a.initializer&&x.isIdentifier(a.name)&&x.isIdentifier(a.initializer)&&n.has(a.initializer.text)&&n.add(a.name.text),x.forEachChild(a,o)};return o(r),n}function Yg(r,e){let t=sr(r);return t?e.has(t):!1}function sr(r){let e=r;for(;;){if(x.isIdentifier(e))return e.text;if(x.isPropertyAccessExpression(e)||x.isPropertyAccessChain(e)){e=e.expression;continue}if(x.isElementAccessExpression(e)||x.isElementAccessChain(e)){e=e.expression;continue}if(x.isCallExpression(e)&&x.isPropertyAccessExpression(e.expression)){e=e.expression.expression;continue}return}}var ia,ir,x,oa=E(()=>{"use strict";ia=T(require("fs")),ir=T(require("path")),x=T(require("typescript"))});function ds(r,e,t){let n={},s=o=>{if(ce.isVariableDeclaration(o)&&ce.isIdentifier(o.name)&&o.initializer){let a=Cn(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}ce.forEachChild(o,s)};s(r);let i={...ey(e),...t};return{variables:n,env:i}}function Ct(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=Cn(r,e,t);if(n!==void 0)return{pathExpression:n,resolvedPath:n,confidence:"high"};if(ce.isStringLiteral(r)||ce.isNoSubstitutionTemplateLiteral(r)){let s=r.text||"/";return{pathExpression:s,resolvedPath:s,confidence:"high"}}if(ce.isTemplateExpression(r)){let s=Xg(r,e,t);if(s.resolvedPath)return s;let i=r.head.text;return{pathExpression:r.getText(e),resolvedPath:i||void 0,confidence:i?"medium":"low"}}return ce.isIdentifier(r)?{pathExpression:r.getText(e),confidence:"low"}:{pathExpression:r.getText(e),confidence:"low"}}function tn(r,e){let t=Ep(r??""),n=Ep(e??""),s=qp(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function Ep(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function qp(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function Cn(r,e,t){if(ce.isStringLiteral(r)||ce.isNoSubstitutionTemplateLiteral(r))return r.text;if(ce.isParenthesizedExpression(r))return Cn(r.expression,e,t);if(ce.isIdentifier(r))return t?.variables?.[r.text];if(ce.isBinaryExpression(r)&&r.operatorToken.kind===ce.SyntaxKind.PlusToken){let n=Cn(r.left,e,t),s=Cn(r.right,e,t);if(n!==void 0&&s!==void 0)return`${n}${s}`}if(ce.isBinaryExpression(r)&&(r.operatorToken.kind===ce.SyntaxKind.BarBarToken||r.operatorToken.kind===ce.SyntaxKind.QuestionQuestionToken))return Cn(r.left,e,t)??Cn(r.right,e,t);if(ce.isPropertyAccessExpression(r)){let n=r.getText(e);if(n.startsWith("process.env.")){let s=n.substring(12);return t?.env?.[s]}}}function Xg(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=Cn(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?qp(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function ey(r){if(!r)return{};let e=[".env",".env.local",".env.development",".env.production"],t={};for(let n of e){let s=`${r}/${n}`;try{let i=require("fs").readFileSync(s,"utf-8");for(let o of i.split(/\r?\n/)){let a=o.trim();if(!a||a.startsWith("#"))continue;let c=a.indexOf("=");if(c<=0)continue;let l=a.slice(0,c).trim(),u=a.slice(c+1).trim().replace(/^['"]|['"]$/g,"");t[l]=u}}catch{continue}}return t}var ce,aa=E(()=>{"use strict";ce=T(require("typescript"))});function Ap(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function ty(r,e){if(r.length<=2)return[];let t=[];for(let n of r.slice(1,-1))t.push({name:n.getText(e)});return t}function ny(r){let e=new Map;for(let s of r){let i=e.get(s.parent)??[];i.push(s),e.set(s.parent,i)}let t=new Map;t.set("app",[{pathExpression:"",resolvedPath:"",confidence:"high",middlewareNodes:[]}]);let n=["app"];for(;n.length>0;){let s=n.shift(),i=t.get(s)??[],o=e.get(s)??[];for(let a of o){let c=t.get(a.child)??[],l=!1;for(let u of i){let d=tn(u.pathExpression,a.prefix.pathExpression),p=Yt(u.confidence,a.prefix.confidence),m={pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&a.prefix.resolvedPath?d.resolvedPath:void 0,confidence:p,middlewareNodes:[...u.middlewareNodes,...a.middlewareNodes]};c.some(f=>f.pathExpression===m.pathExpression&&f.resolvedPath===m.resolvedPath)||(c.push(m),l=!0)}l&&(t.set(a.child,c),n.push(a.child))}}return t}function ry(r){return ie.isStringLiteral(r)||ie.isNoSubstitutionTemplateLiteral(r)||ie.isTemplateExpression(r)}function sy(r){if(ie.isStringLiteral(r)||ie.isNoSubstitutionTemplateLiteral(r))return r.text}function iy(r,e,t,n){let s=new Set(Xt(n).map(a=>a.name));if(s.size===0)return[];let i=oy(r,e),o=[];for(let a of i){let c=t.get(a)??[];for(let l of c)s.has(l.paramName)&&o.push(l.node)}return o}function oy(r,e){let t=new Map;for(let o of e){let a=t.get(o.child)??[];a.push(o.parent),t.set(o.child,a)}let n=[],s=new Set,i=o=>{if(!s.has(o)){s.add(o);for(let a of t.get(o)??[])i(a);n.push(o)}};return i(r),n}var ie,ps,Pp=E(()=>{"use strict";ie=T(require("typescript"));aa();oa();ps=class{async analyzeFile(e,t,n,s){let i=ie.createSourceFile(e,t,ie.ScriptTarget.Latest,!0,e.endsWith(".ts")?ie.ScriptKind.TS:ie.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,d=ds(i,n.projectRoot,s.envOverrides),p=g=>{if(ie.isVariableDeclaration(g)&&ie.isIdentifier(g.name)&&g.initializer){let y=g.initializer.getText(i);(/express\.Router\s*\(/.test(y)||/Router\s*\(/.test(y)||/express\(\)/.test(y))&&o.add(g.name.text)}ie.forEachChild(g,p)};p(i);let m=g=>{if(ie.isCallExpression(g)&&ie.isPropertyAccessExpression(g.expression)){let y=g.expression.expression.getText(i),v=g.expression.name.text;if(v==="use"&&g.arguments.length>=1&&o.has(y)){let b=g.arguments[g.arguments.length-1];if(g.arguments.length>=2&&ie.isIdentifier(b)&&o.has(b.text)&&ie.isIdentifier(b)){let R=Ct(g.arguments[0],i,d);a.push({parent:y,child:b.text,prefix:R,middlewareNodes:g.arguments.slice(1,-1)})}else{let R=ry(g.arguments[0])?g.arguments.slice(1):g.arguments.slice(0),A=l.get(y)??[];A.push(...R),l.set(y,A)}}if(v==="param"&&g.arguments.length>=2&&o.has(y)){let b=sy(g.arguments[0]),C=g.arguments[1];if(b&&C&&ie.isExpression(C)){let R=u.get(y)??[];R.push({paramName:b,node:C}),u.set(y,R)}}let w=Ap(v);if(w&&o.has(y)&&g.arguments.length>=1){let b=Ct(g.arguments[0],i,d),C=ty(g.arguments,i),R=g.arguments[g.arguments.length-1],A=i.getLineAndCharacterOfPosition(R.getStart(i));c.push({owner:y,method:w,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:C,middlewareNodes:g.arguments.slice(1,-1),handlerNode:R,source:{filePath:e,line:A.line+1,column:A.character+1,symbolName:R.getText(i)}})}if(v==="route"&&g.arguments[0]){let b=Ct(g.arguments[0],i,d),C=g.parent;if(ie.isCallExpression(C)&&ie.isPropertyAccessExpression(C.expression)){let R=Ap(C.expression.name.text);if(R){let A=C.arguments[0]??g.arguments[0],N=i.getLineAndCharacterOfPosition(A.getStart(i));c.push({owner:y,method:R,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:[],middlewareNodes:[],handlerNode:A,source:{filePath:e,line:N.line+1,column:N.character+1,symbolName:A.getText(i)}})}}}}ie.forEachChild(g,m)};m(i);let f=[],h=ny(a);for(let g of c){let y=h.get(g.owner)??[],v=y.length>0?y:[{pathExpression:"",confidence:"high",middlewareNodes:[]}];for(let w of v){let b=tn(w.pathExpression,g.pathExpression),C=Yt(w.confidence,g.confidence),R=!!b.resolvedPath,A=Xt(b.pathExpression),N=l.get(g.owner)??[],M=iy(g.owner,a,u,b.pathExpression),j=[...w.middlewareNodes,...N,...M,...g.middlewareNodes,g.handlerNode],U=us(j,i,e,g.method,s.contextProperties);U.parameters.unshift(...A),U.parameters=en(U.parameters),f.push({id:"",method:g.method,framework:"express",pathExpression:b.pathExpression,resolvedPath:C==="high"&&R?b.resolvedPath:void 0,confidence:C,source:g.source,middleware:g.middleware,params:U.parameters.length>0?U.parameters:void 0,requestBody:U.requestBody,cookies:U.cookies.length>0?U.cookies:void 0,responses:U.responses})}}return f}}});function ay(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=cy(a,e,i),l=c?n.map(u=>{let d=tn(u.pathExpression,c.pathExpression);return{pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?d.resolvedPath:void 0,confidence:Yt(u.confidence,c.confidence)}}):n;if(F.isArrowFunction(o)||F.isFunctionExpression(o)){let u=new Set(t),d=o.parameters[0];d&&F.isIdentifier(d.name)&&u.add(d.name.text),o.body&&F.forEachChild(o.body,p=>s(p,u,l))}}function cy(r,e,t){if(!r||!F.isObjectLiteralExpression(r))return;let n=Ae(r,"prefix");if(!n)return;let s=Ct(n,e,t);return{pathExpression:s.pathExpression,resolvedPath:s.resolvedPath,confidence:s.confidence}}function ly(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function Ae(r,e){for(let t of r.properties){if(!F.isPropertyAssignment(t))continue;if((F.isIdentifier(t.name)||F.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function uy(r,e){return r?F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:F.isArrayLiteralExpression(r)?r.elements.map(t=>F.isStringLiteral(t)||F.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function kp(r,e){return r?F.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function Ip(r){return r?F.isArrayLiteralExpression(r)?r.elements.filter(e=>F.isExpression(e)):[r]:[]}function dy(r){if(r&&(F.isArrowFunction(r)||F.isFunctionExpression(r))&&r.parameters[0]&&F.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function py(r,e){if(!r||!F.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function fy(r,e,t){let n=[],s=new Set,i=r;for(;i&&!s.has(i);)s.add(i),n.unshift(i),i=t.get(i);let o=[];for(let a of n){let c=e.get(a)??[];o.push(...c)}return o}function my(r,e){return e?{parameters:en([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function Tp(r,e,t){if(!r||!F.isObjectLiteralExpression(r))return;let n=[],s=Ae(r,"params");s&&n.push(...qi(s,"path",""));let i=Ae(r,"querystring")??Ae(r,"query");i&&n.push(...qi(i,"query",""));let o=Ae(r,"headers");o&&n.push(...qi(o,"header",""));let a=Ae(r,"body");a&&n.push(...qi(a,"body",""));let c=a?Op(a,e):void 0,l=a?{type:"json",required:["POST","PUT","PATCH"].includes(t),schema:c??{type:"object"}}:void 0;return{parameters:n,requestBody:l,cookies:[],responses:[]}}function Op(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if(F.isNumericLiteral(r))return{type:"number"};if(!F.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!F.isPropertyAssignment(n))continue;let s=n.name,i=F.isIdentifier(s)||F.isStringLiteral(s)||F.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=$p(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function $p(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return r.text;if(F.isNumericLiteral(r))return Number(r.text);if(r.kind===F.SyntaxKind.TrueKeyword||r.kind===F.SyntaxKind.FalseKeyword)return r.kind===F.SyntaxKind.TrueKeyword;if(r.kind===F.SyntaxKind.NullKeyword)return null;if(F.isArrayLiteralExpression(r)){let t=r.elements.map(n=>$p(n,e));return t.every(n=>n!==void 0)?t:void 0}if(F.isObjectLiteralExpression(r))return Op(r,e)}function qi(r,e,t){if(!F.isObjectLiteralExpression(r))return[];let n=Ae(r,"properties");if(!n||!F.isObjectLiteralExpression(n))return[];let s=Ae(r,"required"),i=new Set;if(s&&F.isArrayLiteralExpression(s))for(let a of s.elements)(F.isStringLiteral(a)||F.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!F.isPropertyAssignment(a))continue;let c=F.isIdentifier(a.name)||F.isStringLiteral(a.name)||F.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=hy(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...qi(a.initializer,e,l))}return o}function hy(r){if(!F.isObjectLiteralExpression(r))return;let e=Ae(r,"type");if(e&&(F.isStringLiteral(e)||F.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=Ae(r,"properties");if(t&&F.isObjectLiteralExpression(t))return"object"}var F,fs,Fp=E(()=>{"use strict";F=T(require("typescript"));aa();oa();fs=class{async analyzeFile(e,t,n,s){let i=F.createSourceFile(e,t,F.ScriptTarget.Latest,!0,e.endsWith(".ts")?F.ScriptKind.TS:F.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,d=ds(i,n.projectRoot,s.envOverrides),p=(f,h,g)=>{if(F.isVariableDeclaration(f)&&F.isIdentifier(f.name)&&f.initializer){let y=f.initializer.getText(i);(y.includes("fastify(")||y.includes("Fastify("))&&h.add(f.name.text)}if(F.isCallExpression(f)&&F.isPropertyAccessExpression(f.expression)){let y=f.expression.expression.getText(i),v=f.expression.name.text;if(v==="register"){let b=dy(f.arguments[0]);b&&u.set(b,y),ay(f,i,h,g,p,d)}if(v==="addHook"&&h.has(y)&&f.arguments.length>=2&&py(f.arguments[0],i)){let b=l.get(y)??[];b.push(f.arguments[1]),l.set(y,b)}let w=ly(v);if(w&&h.has(y)&&f.arguments[0]){let b=Ct(f.arguments[0],i,d),C=f.arguments.length>=2&&F.isObjectLiteralExpression(f.arguments[1])?f.arguments[1]:void 0,R=C&&f.arguments[2]?f.arguments[2]:f.arguments[f.arguments.length-1],A=i.getLineAndCharacterOfPosition(R.getStart(i)),N=C?Ae(C,"preHandler"):void 0,M=kp(N,i),j=Ip(N),U=C?Tp(Ae(C,"schema"),i,w):void 0;for(let O of g){let L=tn(O.pathExpression,b.pathExpression),Q=Yt(O.confidence,b.confidence),Y=!!L.resolvedPath;c.push({owner:y,method:w,pathExpression:L.pathExpression,resolvedPath:Q==="high"&&Y?L.resolvedPath:void 0,confidence:Q,handlerNode:R,middlewareNodes:j,schemaMetadata:U,source:{filePath:e,line:A.line+1,column:A.character+1,symbolName:R.getText(i)},middleware:M})}}if(v==="route"&&h.has(y)&&f.arguments[0]&&F.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],C=Ae(b,"method"),R=Ae(b,"url")??Ae(b,"path"),A=Ae(b,"handler"),N=Ae(b,"preHandler"),M=Ae(b,"schema"),j=Ct(R,i,d),U=uy(C,i),O=kp(N,i);for(let L of U){let Q=A?i.getLineAndCharacterOfPosition(A.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let Y of g){let Je=tn(Y.pathExpression,j.pathExpression),an=Yt(Y.confidence,j.confidence),kt=!!Je.resolvedPath;c.push({owner:y,method:L,pathExpression:Je.pathExpression,resolvedPath:an==="high"&&kt?Je.resolvedPath:void 0,confidence:an,handlerNode:A??b,middlewareNodes:Ip(N),schemaMetadata:Tp(M,i,L),source:{filePath:e,line:Q.line+1,column:Q.character+1,symbolName:A?.getText(i)},middleware:O})}}}}F.forEachChild(f,y=>p(y,h,g))};p(i,o,a);let m=[];for(let f of c){let h=Xt(f.pathExpression),y=[...fy(f.owner,l,u),...f.middlewareNodes,f.handlerNode],v=us(y,i,e,f.method,s.contextProperties);v.parameters.unshift(...h),v.parameters=en(v.parameters);let w=my(v,f.schemaMetadata);m.push({id:"",method:f.method,framework:"fastify",pathExpression:f.pathExpression,resolvedPath:f.resolvedPath,confidence:f.confidence,source:f.source,middleware:f.middleware,params:w.parameters.length>0?w.parameters:void 0,requestBody:w.requestBody,cookies:w.cookies.length>0?w.cookies:void 0,responses:w.responses})}return m}}});function gy(r,e){D.forEachChild(r,t=>yy(t,r,e))}function yy(r,e,t){if(D.isExpressionStatement(r)&&D.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===D.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(D.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&ca(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Bl(s,e);t.push({exportName:o,handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:o}});return}if(i==="module"&&o==="exports"&&ca(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Bl(s,e);t.push({exportName:"handler",handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:"handler"}});return}}}if(D.isVariableStatement(r)&&Np(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!D.isIdentifier(n.name)||!n.initializer)&&ca(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=Bl(n.initializer,e);t.push({exportName:s,handlerNode:o,middlewareNodes:a,location:{filePath:e.fileName,line:i.line+1,column:i.character+1,symbolName:s}})}return}if(D.isFunctionDeclaration(r)&&Np(r)&&r.name&&vy(r)){let n=r.name.text,s=e.getLineAndCharacterOfPosition(r.getStart(e));t.push({exportName:n,handlerNode:r,middlewareNodes:[],location:{filePath:e.fileName,line:s.line+1,column:s.character+1,symbolName:n}})}}function ca(r,e){if(D.isArrowFunction(r)||D.isFunctionExpression(r))return by(r);if(D.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(D.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return ca(r.expression.expression,e)}return D.isIdentifier(r)?/handler/i.test(r.text):!1}function vy(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function by(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Np(r){return(D.getCombinedModifierFlags(r)&D.ModifierFlags.Export)!==0}function Bl(r,e){let t=[],n=r;for(;D.isCallExpression(n)&&D.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return D.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function Sy(r,e,t){return r.map(n=>{let s=xy(n,e),i=e.getLineAndCharacterOfPosition(n.getStart(e));return{name:s,location:{filePath:t,line:i.line+1,column:i.character+1,symbolName:s}}})}function xy(r,e){return D.isIdentifier(r)?r.text:D.isCallExpression(r)&&D.isIdentifier(r.expression)?r.expression.text:D.isCallExpression(r)&&D.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function Ry(r,e,t){let n=Cy(r);if(!n)return[];let s=new Map,i=o=>{if(D.isPropertyAccessExpression(o)||D.isElementAccessExpression(o)){let a=Ai(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=wy[c];if(l==="body"){let u="body::body";if(!s.has(u)){let d=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(u,{name:"body",location:"body",detectionLocation:{filePath:t,line:d.line+1,column:d.character+1}})}}else if(l&&a.length>=3){let u=a[2],d=`${l}::${u}`;if(!s.has(d)){let p=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(d,{name:u,location:l,detectionLocation:{filePath:t,line:p.line+1,column:p.character+1}})}}}}if(D.isCallExpression(o)&&D.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Ai(a,e);if(c.length===2&&c[0]===n&&c[1]==="body"){let l="body::body";if(!s.has(l)){let u=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(l,{name:"body",location:"body",type:"json",detectionLocation:{filePath:t,line:u.line+1,column:u.character+1}})}}}D.forEachChild(o,i)};return i(r),Array.from(s.values())}function Cy(r){if(D.isArrowFunction(r)||D.isFunctionExpression(r)||D.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&D.isIdentifier(e.name))return e.name.text}return D.isIdentifier(r),"event"}function Ai(r,e){return D.isIdentifier(r)?[r.text]:D.isPropertyAccessExpression(r)?[...Ai(r.expression,e),r.name.text]:r.kind===D.SyntaxKind.PropertyAccessExpression||D.isNonNullExpression(r)?Ai(r.expression,e):D.isElementAccessExpression(r)&&D.isStringLiteral(r.argumentExpression)?[...Ai(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var D,ms,wy,Ul=E(()=>{"use strict";D=T(require("typescript")),ms=class{async analyzeFile(e,t,n,s){let i=D.createSourceFile(e,t,D.ScriptTarget.Latest,!0,e.endsWith(".ts")?D.ScriptKind.TS:D.ScriptKind.JS),o=[];return gy(i,o),o.length===0?[]:o.map(a=>{let c=Ry(a.handlerNode,i,e),l=Sy(a.middlewareNodes,i,e);return{id:"",method:"ANY",framework:"lambda",pathExpression:"<unknown-lambda>",resolvedPath:void 0,confidence:"low",source:a.location,middleware:l,params:c.length>0?c:void 0}})}};wy={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var hs=E(()=>{"use strict";oa();Pp();Fp();Ul()});function _p(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Ey(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"express",filePath:t.source.filePath,message:`Express route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"express",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var la,or,Vl=E(()=>{"use strict";la=T(require("fs"));hs();Rn();or=class{id="provider.express";framework="express";analyzer=new ps;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(_p(t)===_p(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.express?{supported:!0,confidence:.95,reasons:["express dependency detected"]}:{supported:!1,confidence:0,reasons:["express dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=la.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=la.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Ey(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["express"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function Mp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function qy(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"fastify",filePath:t.source.filePath,message:`Fastify route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"fastify",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var ua,ar,zl=E(()=>{"use strict";ua=T(require("fs"));hs();Rn();ar=class{id="provider.fastify";framework="fastify";analyzer=new fs;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Mp(t)===Mp(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.fastify?{supported:!0,confidence:.95,reasons:["fastify dependency detected"]}:{supported:!1,confidence:0,reasons:["fastify dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=ua.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=ua.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=qy(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["fastify"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function Dp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Jl(r,e){let t=r.expression;if(pe.isCallExpression(t))return pe.isIdentifier(t.expression)?t.expression.text:t.expression.getText(e);if(pe.isIdentifier(t))return t.text}function jp(r){let e=r.expression;if(pe.isCallExpression(e))return e.arguments[0]}function Ay(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function Lp(r){return pe.canHaveDecorators(r)?pe.getDecorators(r)??[]:[]}function Hp(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=Jl(s,e);if(!i||!t.has(i))continue;let o=s.expression;if(!pe.isCallExpression(o)){n.push({name:i});continue}for(let a of o.arguments)n.push({name:`${i}:${a.getText(e)}`})}return n}function Py(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var da,pe,cr,Gl=E(()=>{"use strict";da=T(require("fs")),pe=T(require("typescript"));aa();Rn();cr=class{id="provider.nestjs";framework="nestjs";fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Dp(t)===Dp(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}["@nestjs/common"]?{supported:!0,confidence:.98,reasons:["@nestjs/common dependency detected"]}:{supported:!1,confidence:0,reasons:["@nestjs/common dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=da.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(g=>structuredClone(g))),s.push(...l.warnings.map(g=>({...g})));continue}let u="";try{u=da.readFileSync(a,"utf-8")}catch{continue}let d=[],p=[],m=pe.createSourceFile(a,u,pe.ScriptTarget.Latest,!0,a.endsWith(".ts")?pe.ScriptKind.TS:pe.ScriptKind.JS),f=ds(m,t.projectRoot,e.envOverrides),h=g=>{if(pe.isClassDeclaration(g)){let y=Lp(g),v=y.find(w=>Jl(w,m)==="Controller");if(v){let w=Ct(jp(v),m,f),b=Hp(y,m);for(let C of g.members){if(!pe.isMethodDeclaration(C))continue;let R=Lp(C),A=R.map(N=>({decorator:N,name:Jl(N,m)})).filter(N=>!!N.name);for(let N of A){let M=Ay(N.name);if(!M)continue;let j=Ct(jp(N.decorator),m,f),U=tn(w.pathExpression,j.pathExpression),O=Hp(R,m),L=C.name?.getText(m),Q=C.name??C,Y=m.getLineAndCharacterOfPosition(Q.getStart(m)),Je=Py(w.confidence,j.confidence);p.push({id:"",method:M,framework:"nestjs",pathExpression:U.pathExpression,resolvedPath:Je==="high"?U.resolvedPath:void 0,confidence:Je,source:{filePath:a,line:Y.line+1,column:Y.character+1,symbolName:L},middleware:[...b,...O]}),Je!=="high"&&d.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${L??"unknown handler"} in ${a}`})}}}}pe.forEachChild(g,h)};h(m),i.push(...p),s.push(...d),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:p.map(g=>structuredClone(g)),warnings:d.map(g=>({...g}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["nestjs"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function ky(r,e,t){let n=[],s=r.functions;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o,c=a.handler;if(!c||typeof c!="string")continue;let{filePath:l,exportName:u}=Vp(c,e),d=zp(l,e);d||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for function '${i}': ${c}`});let p=a.events;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let f=m.http;if(!f||typeof f!="object")continue;let h=f.path,g=f.method;if(!h||!g)continue;let y=Jp(h),v=[];if(f.authorizer){let w=typeof f.authorizer=="string"?f.authorizer:"authorizer";v.push({name:w})}n.push({id:"",method:g.toUpperCase(),framework:"lambda",pathExpression:y,resolvedPath:y,confidence:"high",source:{filePath:d??l,line:1,column:1,symbolName:u},middleware:v})}}return n}function Bp(r,e,t){let n=[],s=r.Resources;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o;if(a.Type!=="AWS::Serverless::Function")continue;let c=a.Properties;if(!c)continue;let l=c.Handler;if(!l||typeof l!="string")continue;let{filePath:u,exportName:d}=Vp(l,e),p=zp(u,e);p||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for SAM resource '${i}': ${l}`});let m=c.Events;if(!(!m||typeof m!="object"))for(let[,f]of Object.entries(m)){if(!f||typeof f!="object")continue;let h=f;if(h.Type!=="Api"&&h.Type!=="HttpApi")continue;let g=h.Properties;if(!g)continue;let y=g.Path,v=g.Method;if(!y||!v)continue;let w=Jp(y),b=g.Auth,C=[];b?.Authorizer&&C.push({name:String(b.Authorizer)}),n.push({id:"",method:v.toUpperCase(),framework:"lambda",pathExpression:w,resolvedPath:w,confidence:"high",source:{filePath:p??u,line:1,column:1,symbolName:d},middleware:C})}}return n}function Vp(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function zp(r,e){let t=[pt.join(e,`${r}.ts`),pt.join(e,`${r}.js`),pt.join(e,r,"index.ts"),pt.join(e,r,"index.js")];for(let n of t)if(Me.existsSync(n))return n}function Jp(r){return r.startsWith("/")?r:`/${r}`}function Kl(r){let e=r.split(`
469
- `);return Pi(e,0,-1).value}function Pi(r,e,t){let n={},s=[],i=!1,o=e;for(;o<r.length;){let a=r[o],c=a.trimEnd();if(c.trim()===""||c.trimStart().startsWith("#")){o++;continue}let l=Iy(a);if(l<=t)break;let u=c.trimStart();if(u.startsWith("- ")){i=!0;let f=u.slice(2).trim();if(f===""||f.endsWith(":"))if(f.endsWith(":")){let h=f.slice(0,-1).trim(),g=Pi(r,o+1,l),y={};y[h]=g.value,s.push(y),o=g.nextLine}else{let h=Pi(r,o+1,l);s.push(h.value),o=h.nextLine}else if(f.includes(": ")||f.endsWith(":")){let h={},g=f.indexOf(":"),y=f.slice(0,g).trim(),v=f.slice(g+1).trim();if(v===""){let w=Pi(r,o+1,l);h[y]=w.value,s.push(h),o=w.nextLine}else h[y]=Wl(v),s.push(h),o++}else s.push(Wl(f)),o++;continue}let d=u.indexOf(":");if(d===-1){o++;continue}let p=u.slice(0,d).trim(),m=u.slice(d+1).trim();if(m===""||m.startsWith("#")){let f=Pi(r,o+1,l);n[p]=f.value,o=f.nextLine}else n[p]=Wl(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function Iy(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function Wl(r){let e=r.indexOf(" #"),t=e!==-1?r.slice(0,e).trim():r.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t==="true"?!0:t==="false"?!1:t==="null"||t==="~"?null:/^-?\d+(\.\d+)?$/.test(t)?Number(t):t}function Ty(r){return Kl(r)}function Up(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Me,pt,lr,Ql=E(()=>{"use strict";Me=T(require("fs")),pt=T(require("path"));Ul();Rn();lr=class{id="provider.lambda";framework="lambda";analyzer=new ms;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Up(t)===Up(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){let t={...e.packageJson?.dependencies,...e.packageJson?.devDependencies};if(t.express||t.fastify)return{supported:!1,confidence:0,reasons:["express or fastify detected \u2014 deferring to existing provider"]};let n=!!(t["@types/aws-lambda"]||t["aws-lambda"]||t.serverless),s=Me.existsSync(pt.join(e.projectRoot,"serverless.yml"))||Me.existsSync(pt.join(e.projectRoot,"serverless.yaml"))||Me.existsSync(pt.join(e.projectRoot,"template.yaml"))||Me.existsSync(pt.join(e.projectRoot,"template.json"));return n?{supported:!0,confidence:.95,reasons:["lambda-related dependency detected"]}:s?{supported:!0,confidence:.75,reasons:["serverless/SAM config file detected"]}:{supported:!1,confidence:0,reasons:["no lambda indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.projectRoot;for(let a of["serverless.yml","serverless.yaml"]){let c=pt.join(o,a);if(Me.existsSync(c)){try{let l=Me.readFileSync(c,"utf-8"),u=Ty(l),d=ky(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse Serverless Framework config: ${c}`})}break}}if(i.length===0){let a=pt.join(o,"template.yaml"),c=pt.join(o,"template.json");if(Me.existsSync(c))try{let l=Me.readFileSync(c,"utf-8"),u=JSON.parse(l),d=Bp(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse SAM template: ${c}`})}else if(Me.existsSync(a))try{let l=Me.readFileSync(a,"utf-8"),u=Kl(l),d=Bp(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:a,message:`Failed to parse SAM template: ${a}`})}}if(i.length===0){let a=t.sourceFiles??nt(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=Me.statSync(c)}catch{continue}let u=this.fileCache.get(c);if(u&&u.mtimeMs===l.mtimeMs&&u.size===l.size){i.push(...u.endpoints.map(f=>structuredClone(f))),s.push(...u.warnings.map(f=>({...f})));continue}let d="";try{d=Me.readFileSync(c,"utf-8")}catch{continue}let p=await this.analyzer.analyzeFile(c,d,t,e),m=p.map(f=>({code:"seed-endpoint-unmatched",framework:"lambda",filePath:f.source.filePath,message:`Lambda handler '${f.source.symbolName}' found without a config-file route definition. Path is unknown.`}));i.push(...p),s.push(...m),this.fileCache.set(c,{mtimeMs:l.mtimeMs,size:l.size,endpoints:p.map(f=>structuredClone(f)),warnings:m.map(f=>({...f}))})}}return{endpoints:i,warnings:s,stats:{frameworksDetected:["lambda"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function $y(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=pa.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=Wp.join(s,o.name);o.isDirectory()?Oy.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function ki(r){return $y(r,/\.java$/)}function Ii(r){return pa.promises.readFile(r,"utf-8")}function Zl(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function Yl(r){return r.replace(/\\/g,"/").split("/").pop()||""}function Kp(r,e){let t=Gp.get(e);if(t&&Date.now()-t.ts<Fy)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=ki(r).filter(i=>n.test(Yl(i)));return Gp.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var pa,Wp,Oy,Gp,Fy,fa=E(()=>{"use strict";pa=T(require("fs")),Wp=T(require("path")),Oy=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);Gp=new Map,Fy=3e4});function Ny(r){if(r.includes("/"))return r;if(nn[r])return nn[r];let e=`MediaType.${r}`;if(nn[e])return nn[e];for(let[s,i]of Object.entries(nn))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(nn[i])return nn[i];let o=`MediaType.${s}_VALUE`;if(nn[o])return nn[o]}let n=r.toUpperCase();return n.includes("JSON")?"application/json":n.includes("XML")&&!n.includes("HTML")?"application/xml":n.includes("FORM_URLENCODED")?"application/x-www-form-urlencoded":n.includes("MULTIPART")?"multipart/form-data":n.includes("TEXT_PLAIN")||n.includes("PLAIN_TEXT")?"text/plain":n.includes("OCTET_STREAM")?"application/octet-stream":r}function Ti(r){return r.map(Ny)}function rn(r){if(!r)return r;let e=/^([A-Za-z0-9_]+)<(.+)>$/.exec(r);if(!e)return r;let t=e[1],n=e[2];return _y.has(t)?rn(n.trim()):r}function gs(r){return/MultipartFile/.test(r)}var nn,_y,ma=E(()=>{"use strict";nn={"MediaType.ALL_VALUE":"*/*","MediaType.APPLICATION_ATOM_XML_VALUE":"application/atom+xml","MediaType.APPLICATION_CBOR_VALUE":"application/cbor","MediaType.APPLICATION_FORM_URLENCODED_VALUE":"application/x-www-form-urlencoded","MediaType.APPLICATION_GRAPHQL_VALUE":"application/graphql","MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE":"application/graphql-response+json","MediaType.APPLICATION_JSON_VALUE":"application/json","MediaType.APPLICATION_JSON_UTF8_VALUE":"application/json;charset=UTF-8","MediaType.APPLICATION_NDJSON_VALUE":"application/x-ndjson","MediaType.APPLICATION_OCTET_STREAM_VALUE":"application/octet-stream","MediaType.APPLICATION_PDF_VALUE":"application/pdf","MediaType.APPLICATION_PROBLEM_JSON_VALUE":"application/problem+json","MediaType.APPLICATION_PROBLEM_XML_VALUE":"application/problem+xml","MediaType.APPLICATION_PROTOBUF_VALUE":"application/x-protobuf","MediaType.APPLICATION_RSS_XML_VALUE":"application/rss+xml","MediaType.APPLICATION_STREAM_JSON_VALUE":"application/stream+json","MediaType.APPLICATION_XHTML_XML_VALUE":"application/xhtml+xml","MediaType.APPLICATION_XML_VALUE":"application/xml","MediaType.APPLICATION_YAML_VALUE":"application/yaml","MediaType.IMAGE_GIF_VALUE":"image/gif","MediaType.IMAGE_JPEG_VALUE":"image/jpeg","MediaType.IMAGE_PNG_VALUE":"image/png","MediaType.MULTIPART_FORM_DATA_VALUE":"multipart/form-data","MediaType.MULTIPART_MIXED_VALUE":"multipart/mixed","MediaType.MULTIPART_RELATED_VALUE":"multipart/related","MediaType.TEXT_EVENT_STREAM_VALUE":"text/event-stream","MediaType.TEXT_HTML_VALUE":"text/html","MediaType.TEXT_MARKDOWN_VALUE":"text/markdown","MediaType.TEXT_PLAIN_VALUE":"text/plain","MediaType.TEXT_XML_VALUE":"text/xml"};_y=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var ur,Qp=E(()=>{"use strict";fa();ma();ur=class{constructor(e){this.projectRoot=e}projectRoot;cache=new Map;clearCache(){this.cache.clear()}async generate(e){if(!e)return;let t=this.primitiveSchema(e);if(t)return t;let n=e,s=[],i=/^([^<]+)<(.+)>$/.exec(e);i&&(n=i[1].trim(),s=this.splitGenericArgs(i[2]));let o=n.split("."),a=o.pop(),c=o.length?o.join("."):void 0;if(this.cache.has(e))return this.cache.get(e);let l={type:"object",properties:{},required:[]};this.cache.set(e,l);let u=await Kp(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await Ii(f),g=m.exec(h);if(g&&g[1]===c){u=[f];break}}}if(u.length===0){if(s.length>0){let m=await this.generate(s[0]);if(m&&m.properties&&Object.keys(m.properties).length>0)return Object.assign(l,m),l}return{type:"object"}}let d=await Ii(u[0]),p=this.buildTypeParamMap(d,a,s);return await this.parseClassToSchema(d,a,l,p),l.required&&l.required.length===0&&delete l.required,l}async generateResponseSchema(e){if(!e||e==="void")return;let t=rn(e);if(t==="void")return;let n=/(List|Set|Collection)<([^>]+)>/.exec(t);if(n){let s=n[2].trim();return{type:"array",items:await this.generate(s)||{type:"object"}}}if(t.endsWith("[]")){let s=t.replace(/\[\]$/,"");return{type:"array",items:await this.generate(s)||{type:"object"}}}return this.generate(t)}async parseClassToSchema(e,t,n,s){let i=this.extractFieldsRegex(e,t);for(let o of i){s&&s.size>0&&(o.javaType=this.resolveTypeParams(o.javaType,s));let a=await this.fieldToSchema(o),c=o.jsonPropertyName||o.name;n.properties[c]=a,o.required&&n.required.push(c)}}buildTypeParamMap(e,t,n){let s=new Map;if(n.length===0)return s;let i=new RegExp(`class\\s+${t}\\s*<([^{]+?)>\\s*(?:extends|implements|\\{)`).exec(e);return i&&this.splitGenericArgs(i[1]).map(a=>a.trim().split(/\s+/)[0]).forEach((a,c)=>{c<n.length&&s.set(a,n[c])}),s}splitGenericArgs(e){let t=[],n=0,s="";for(let i of e)i==="<"?(n++,s+=i):i===">"?(n--,s+=i):i===","&&n===0?(t.push(s.trim()),s=""):s+=i;return s.trim()&&t.push(s.trim()),t}resolveTypeParams(e,t){let n=e;for(let[s,i]of t)n=n.replace(new RegExp(`\\b${s}\\b`,"g"),i);return n}extractFieldsRegex(e,t){let n=[],s=e.split(/\r?\n/),i=!1,o=0,a=e.search(new RegExp(`class\\s+${t}\\b`)),c=a>=0?e.substring(Math.max(0,a-500),a):"",l=/@(?:lombok\.)?(?:Data|Getter|Value)\b/.test(c),u=/public\s+\S+\s+(?:get|is)[A-Z]\w*\s*\(/.test(e),d=[];for(let p of s){let m=p.trim();if(!i){new RegExp(`class\\s+${t}\\b`).test(m)&&(i=!0,o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length);continue}let f=o;if(o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length,o<=0)break;if(f>1)continue;if(/^@(\w+)/.exec(m)&&!/(?:private|public|protected)\s/.test(m)&&!m.includes(";")){d.push(m);continue}if(/^public\s+\S+\s+(get|is|set)[A-Z]\w*\s*\(/.test(m)){d=[];continue}let g=/(?:(private|public|protected)\s+)?([A-Za-z0-9_<>,\s\[\]?]+?)\s+([A-Za-z0-9_]+)\s*(?:=.*)?;/.exec(m);if(g){let y=g[2].replace(/\b(final)\b/g,"").trim().replace(/@\w+\s*/g,"").trim(),v=g[3],w=g[1]||"";if(y&&v&&!/^(class|interface|enum|return|if|for|while|void)\b/.test(y)){let b=/\bstatic\b/.test(m),C=/\btransient\b/.test(m),R=[...d,m],A=R.join(" ");!b&&!C&&!/@JsonIgnore\b/.test(A)&&(w==="public"||l||u||/@JsonProperty\b/.test(A))&&n.push(this.parseFieldAnnotations(v,y,R))}}d=[]}return n}parseFieldAnnotations(e,t,n){let s=n.join(" "),i={name:e,javaType:t},o=/\bvalue\s*=\s*"([^"]*)"/.exec(s.match(/@JsonProperty\([^)]*\)/)?.[0]||"")||/@JsonProperty\(\s*"([^"]*)"/.exec(s);o&&o[1]&&(i.jsonPropertyName=o[1]),i.description=this.extractAttr(s,"Schema","description"),i.example=this.extractAttr(s,"Schema","example");let a=this.extractAttr(s,"Schema","type");a&&(i.schemaTypeOverride=a);let c=this.extractAttr(s,"Schema","format");c&&(i.format=c),this.extractAttr(s,"Schema","nullable")==="true"&&(i.nullable=!0),this.extractAttr(s,"Schema","readOnly")==="true"&&(i.readOnly=!0),this.extractAttr(s,"Schema","writeOnly")==="true"&&(i.writeOnly=!0),this.extractAttr(s,"Schema","deprecated")==="true"&&(i.deprecated=!0);let m=this.extractAttr(s,"Schema","title");m&&(i.title=m);let f=this.extractAttr(s,"Schema","defaultValue");f&&(i.defaultValue=f);let h=/allowableValues\s*=\s*\{([^}]*)\}/.exec(s);h&&(i.enumValues=h[1].split(",").map(O=>O.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean));let g=this.extractAttr(s,"Schema","minimum");g&&(i.minimum=Number(g));let y=this.extractAttr(s,"Schema","maximum");y&&(i.maximum=Number(y));let v=this.extractAttr(s,"Schema","minLength");v&&(i.minLength=Number(v));let w=this.extractAttr(s,"Schema","maxLength");w&&(i.maxLength=Number(w));let b=this.extractAttr(s,"Schema","pattern");b&&(i.pattern=b),i.description||(i.description=this.extractAttr(s,"ApiModelProperty","value")),i.example||(i.example=this.extractAttr(s,"ApiModelProperty","example")),(/@NotNull\b/.test(s)||/@NotBlank\b/.test(s)||/@NotEmpty\b/.test(s))&&(i.required=!0);let C=this.extractAttr(s,"Size","min");C&&!i.minLength&&(i.minLength=Number(C));let R=this.extractAttr(s,"Size","max");R&&!i.maxLength&&(i.maxLength=Number(R));let A=this.extractAttr(s,"Min","value")||this.extractSingleArg(s,"Min");A&&i.minimum===void 0&&(i.minimum=Number(A));let N=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");N&&i.maximum===void 0&&(i.maximum=Number(N));let M=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");M&&i.minimum===void 0&&(i.minimum=Number(M));let j=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");j&&i.maximum===void 0&&(i.maximum=Number(j)),/@Email\b/.test(s)&&(i.format=i.format||"email");let U=this.extractAttr(s,"Pattern","regexp");return U&&!i.pattern&&(i.pattern=U),/@PositiveOrZero\b/.test(s)&&i.minimum===void 0&&(i.minimum=0),/@Positive\b/.test(s)&&i.minimum===void 0&&(i.minimum=1),/@NegativeOrZero\b/.test(s)&&i.maximum===void 0&&(i.maximum=0),/@Negative\b/.test(s)&&i.maximum===void 0&&(i.maximum=-1),(/@Past\b/.test(s)||/@PastOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),(/@Future\b/.test(s)||/@FutureOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),i}async fieldToSchema(e){let t={};if(e.schemaTypeOverride?t.type=e.schemaTypeOverride:Object.assign(t,this.javaTypeToJsonSchema(e.javaType)),e.description&&(t.description=e.description),e.title&&(t.title=e.title),e.format&&(t.format=e.format),e.example!==void 0&&(t.example=this.coerceValue(e.example)),e.defaultValue!==void 0&&(t.default=this.coerceValue(e.defaultValue)),e.nullable&&(t.nullable=!0),e.readOnly&&(t.readOnly=!0),e.writeOnly&&(t.writeOnly=!0),e.deprecated&&(t.deprecated=!0),e.enumValues&&(t.enum=e.enumValues),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern),t.type==="object"&&!t.properties){let n=await this.generate(e.javaType);n&&n.properties&&(t.properties=n.properties,n.required&&(t.required=n.required))}if(t.type==="array"&&!t.items){let n=/(List|Set|Collection)<([^>]+)>/.exec(e.javaType);if(n){let s=n[2].trim(),i=this.primitiveSchema(s)||await this.generate(s);t.items=i||{type:"object"}}}return t}javaTypeToJsonSchema(e){if(/^(String|CharSequence|char|Character)$/.test(e))return{type:"string"};if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return{type:"integer",format:"int32"};if(/^(long|Long|BigInteger)$/.test(e))return{type:"integer",format:"int64"};if(/^(float|Float)$/.test(e))return{type:"number",format:"float"};if(/^(double|Double|BigDecimal)$/.test(e))return{type:"number",format:"double"};if(/^(boolean|Boolean)$/.test(e))return{type:"boolean"};if(/^(LocalDate)$/.test(e))return{type:"string",format:"date"};if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return{type:"string",format:"date-time"};if(/^(LocalTime|OffsetTime)$/.test(e))return{type:"string",format:"time"};if(/^UUID$/.test(e))return{type:"string",format:"uuid"};if(/^(URI|URL)$/.test(e))return{type:"string",format:"uri"};if(/^(byte\[\]|Byte\[\])$/.test(e))return{type:"string",format:"binary"};if(/^Map\b/.test(e))return{type:"object",additionalProperties:!0};if(/(List|Set|Collection)</.test(e))return{type:"array"};if(e.endsWith("[]")){let t=e.replace(/\[\]$/,"");return{type:"array",items:this.primitiveSchema(t)||{type:"object"}}}return{type:"object"}}primitiveSchema(e){let t=this.javaTypeToJsonSchema(e);if(t.type!=="object"||/^Map\b/.test(e))return t}static javaTypeToParamType(e){return/^(int|Integer|long|Long|short|Short|byte|Byte|BigInteger)$/.test(e)?"integer":/^(float|Float|double|Double|BigDecimal)$/.test(e)?"number":/^(boolean|Boolean)$/.test(e)?"boolean":/(List|Set|Collection)</.test(e)||e.endsWith("[]")?"array":"string"}static javaTypeToFormat(e){if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return"int32";if(/^(long|Long|BigInteger)$/.test(e))return"int64";if(/^(float|Float)$/.test(e))return"float";if(/^(double|Double|BigDecimal)$/.test(e))return"double";if(/^(LocalDate)$/.test(e))return"date";if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return"date-time";if(/^(LocalTime|OffsetTime)$/.test(e))return"time";if(/^UUID$/.test(e))return"uuid";if(/^(URI|URL)$/.test(e))return"uri"}extractAttr(e,t,n){let i=new RegExp(`@${t}\\b[^)]*\\b${n}\\s*=\\s*"([^"]*)"`,"s").exec(e);return i?i[1]:void 0}extractSingleArg(e,t){let s=new RegExp(`@${t}\\(\\s*([^")]+?)\\s*\\)`).exec(e);if(s&&!/=/.test(s[1]))return s[1].trim()}coerceValue(e){return/^-?\d+$/.test(e)?parseInt(e,10):/^-?\d+\.\d+$/.test(e)?parseFloat(e):e==="true"?!0:e==="false"?!1:e}}});function Xl(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var Zp,ha,Yp=E(()=>{"use strict";Zp=require("java-parser");ma();ha=class extends Zp.BaseJavaCstVisitorWithDefaults{controllers=[];contextStack=[];constructor(){super(),this.validateVisitor()}annotation(e){if(this.contextStack.length===0)return;let t=e.typeName[0].children.Identifier[0].image,n=new Map;if(e.elementValuePairList){let i=e.elementValuePairList[0].children.elementValuePair;for(let o of i){let a=o.children.Identifier[0].image,c=this.extractElementValue(o.children.elementValue[0]);c!==void 0&&n.set(a,c)}}else if(e.elementValue){let i=this.extractElementValue(e.elementValue[0]);i!==void 0&&n.set("value",i)}this.contextStack[this.contextStack.length-1].annotations.push({name:t,attributes:n}),this.visitNestedAnnotations(e)}visitNestedAnnotations(e){let t=[];if(e.elementValue&&t.push(e.elementValue[0]),e.elementValuePairList){let n=e.elementValuePairList[0].children.elementValuePair||[];for(let s of n)s.children.elementValue&&t.push(s.children.elementValue[0])}for(let n of t){if(n.children?.annotation)for(let i of n.children.annotation)this.annotation(i.children);let s=n.children?.elementValueArrayInitializer?.[0];if(s){let i=s.children?.elementValueList?.[0]?.children?.elementValue||[];for(let o of i)if(o.children?.annotation)for(let a of o.children.annotation)this.annotation(a.children)}}}typeIdentifier(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}classDeclaration(e){let t={type:"class",name:"",line:0,annotations:[],endpoints:[]};this.contextStack.push(t);for(let i of e.classModifier||[])this.visit(i);let n=t.annotations.find(i=>i.name==="RequestMapping");if(n){let i=n.attributes.get("value")||n.attributes.get("path");i&&typeof i=="string"&&(t.basePath=i.replace(/^['\"]|['\"]$/g,""))}for(let i of e.normalClassDeclaration||[])this.visit(i);if(this.contextStack.pop(),t.annotations.some(i=>i.name==="RestController"||i.name==="Controller")){let i={name:t.name,basePath:t.basePath||"",file:"",line:t.line,endpoints:t.endpoints};this.controllers.push(i)}}methodDeclarator(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}methodDeclaration(e){if(this.contextStack.length===0||this.contextStack[this.contextStack.length-1].type!=="class")return;let t=this.contextStack[this.contextStack.length-1],n={type:"method",name:"",line:0,annotations:[]};this.contextStack.push(n);for(let i of e.methodHeader||[])this.visit(i);for(let i of e.methodModifier||[])this.visit(i);this.contextStack.pop();let s=n.annotations.filter(i=>/Mapping$/.test(i.name));if(s.length!==0)for(let i of s){let o=this.buildEndpoint(i,n,e,t);o&&t.endpoints.push(o)}}collectTokens(e){if(!e)return[];if(e.image!==void 0)return[e];let t=[];if(e.children)for(let n of Object.keys(e.children))for(let s of e.children[n])t.push(...this.collectTokens(s));return t.sort((n,s)=>n.startOffset-s.startOffset),t}extractElementValue(e){if(!e)return;let t=e.children;if(t){if(t.annotation){let n=this.collectTokens(t.annotation[0]);if(n.length>0)return n.map(s=>s.image).join("")}if(t.elementValueArrayInitializer){let s=t.elementValueArrayInitializer[0].children?.elementValueList?.[0]?.children?.elementValue;return s?s.map(o=>{let a=this.extractElementValue(o);return Array.isArray(a)?a.join(","):a}).filter(o=>typeof o=="string"&&o.length>0):[]}if(t.conditionalExpression){let n=this.collectTokens(t.conditionalExpression[0]);return n.length===0?void 0:n.map(s=>s.image).join("")}}}buildEndpoint(e,t,n,s){let i=e.name.replace("Mapping","").toUpperCase();i==="REQUEST"&&(i="");let o="",a=[],c=[];for(let[m,f]of e.attributes.entries())if(m==="value"||m==="path")typeof f=="string"&&(o=f.replace(/^['\"]|['\"]$/g,""));else if(m==="consumes")Array.isArray(f)?a=Ti(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Ti([f.replace(/^['\"]|['\"]$/g,"")]));else if(m==="produces")Array.isArray(f)?c=f.map(h=>h.replace(/^['\"]|['\"]$/g,"")):typeof f=="string"&&(c=[f.replace(/^['\"]|['\"]$/g,"")]);else if(m==="method"&&e.name==="RequestMapping"&&typeof f=="string"){let h=f.match(/RequestMethod\.([A-Z]+)/);h&&(i=h[1])}!i&&e.name==="RequestMapping"&&(i="GET");let l=o;s.basePath&&(l&&!l.startsWith("/")?l=s.basePath+"/"+l:l=s.basePath+l),l&&!l.startsWith("/")&&(l="/"+l);let u=this.extractParameters(n),d=this.extractReturnType(n),p=this.extractOpenApiAnnotations(t.annotations,s.annotations);return{method:i,path:l,file:"",line:t.line,pathParams:Xl(l),consumes:a,produces:c.length>0?c:void 0,headers:u.headers,queryParams:u.queryParams,hasBody:u.hasBody,bodyType:u.bodyType,formParts:u.formParts.length>0?u.formParts:void 0,modelAttributeType:u.modelAttributeType,returnType:d||void 0,summary:p.summary,description:p.description,operationId:p.operationId,tags:p.tags.length>0?p.tags:void 0,deprecated:p.deprecated||void 0,responses:p.responses.length>0?p.responses:void 0,parameterMeta:u.parameterMeta.length>0?u.parameterMeta:void 0,security:p.security.length>0?p.security:void 0}}extractOpenApiAnnotations(e,t){let n,s,i,o=[],a=!1,c=[],l=[];for(let u of t)if(u.name==="Tag"){let d=this.getAnnotationAttrString(u,"name");d&&o.push(d)}for(let u of e)switch(u.name){case"Operation":{n=this.getAnnotationAttrString(u,"summary")||n,s=this.getAnnotationAttrString(u,"description")||s,i=this.getAnnotationAttrString(u,"operationId")||i;let d=u.attributes.get("deprecated");typeof d=="string"&&d==="true"&&(a=!0);let p=u.attributes.get("tags");if(Array.isArray(p))p.forEach(m=>{let f=m.replace(/^['"]|['"]$/g,"");f&&o.push(f)});else if(typeof p=="string"){let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)}break}case"ApiOperation":{n=this.getAnnotationAttrString(u,"value")||n,s=this.getAnnotationAttrString(u,"notes")||s;let d=u.attributes.get("tags");Array.isArray(d)&&d.forEach(p=>{let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)});break}case"Tag":{let d=this.getAnnotationAttrString(u,"name");d&&o.push(d);break}case"Deprecated":{a=!0;break}case"ApiResponse":{let d=this.parseApiResponse(u);d&&c.push(d);break}case"ApiResponses":break;case"SecurityRequirement":{let d=this.getAnnotationAttrString(u,"name");d&&l.push(d);break}}return{summary:n,description:s,operationId:i,tags:[...new Set(o)],deprecated:a,responses:c,security:l}}parseApiResponse(e){let t=this.getAnnotationAttrString(e,"responseCode")||this.getAnnotationAttrString(e,"code")||"200",n=this.getAnnotationAttrString(e,"description"),s=this.getAnnotationAttrRaw(e,"content"),i=s?this.extractAttrFromRaw(s,"mediaType"):void 0,o=s?this.extractImplementationType(s):this.extractImplementationType(this.getAnnotationAttrRaw(e,"schema")),a=s?this.extractExampleObjects(s):void 0,c=this.getAnnotationAttrRaw(e,"headers"),l=c?this.extractHeaderObjects(c):void 0;return{statusCode:t,description:n,...i&&{contentType:i},...o&&{schemaType:o},...a&&Object.keys(a).length>0&&{examples:a},...l&&Object.keys(l).length>0&&{headers:l}}}getAnnotationAttrRaw(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n;if(Array.isArray(n))return n.join(",")}extractAttrFromRaw(e,t){let n=new RegExp(`${t}\\s*=\\s*(["'])(.*?)\\1`);return e.match(n)?.[2]}extractImplementationType(e){if(!e)return;let t=e.match(/implementation\s*=\s*([A-Za-z0-9_$.<>?]+)\.class/);if(!t?.[1])return;let n=t[1];return n=n.split(".").pop()||n,rn(n)}extractExampleObjects(e){let t={},n=e.match(/@ExampleObject\(([^)]*)\)/g)||[],s=1;for(let i of n){let a=(i.match(/name\s*=\s*"((?:\\.|[^"\\])*)"/)?.[1]||this.extractAttrFromRaw(i,"name")||`example${s++}`).replace(/\\"/g,'"').replace(/\\\\/g,"\\"),c=i.match(/value\s*=\s*"((?:\\.|[^"\\])*)"/),l=c?.[1]?c[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):this.extractAttrFromRaw(i,"value");if(!l)continue;let u=this.parseExampleValue(l);t[a]=u}return Object.keys(t).length>0?t:void 0}extractHeaderObjects(e){let t={},n=e.match(/@Header\(([^)]*)\)/g)||[];for(let s of n){let i=this.extractAttrFromRaw(s,"name")||this.extractAttrFromRaw(s,"value");if(!i)continue;let o={},a=this.extractAttrFromRaw(s,"description");a&&(o.description=a);let c=this.extractAttrFromRaw(s,"format");c&&(o.format=c);let l=s.match(/required\s*=\s*(true|false)/)?.[1];l&&(o.required=l==="true");let u=s.match(/deprecated\s*=\s*(true|false)/)?.[1];u&&(o.deprecated=u==="true");let d=this.extractAttrFromRaw(s,"type")||this.extractImplementationType(s);d&&(o.schemaType=d),t[i]=o}return Object.keys(t).length>0?t:void 0}parseExampleValue(e){let t=e.trim();if(!t)return"";if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return t}return t}getAnnotationAttrString(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n.replace(/^['"]|['"]$/g,"")||void 0}extractReturnType(e){let t=e.methodHeader?.[0]?.children?.result?.[0];if(!t)return"";if(t.children?.Void)return"void";let n=t.children?.unannType?.[0];if(!n)return"";let s=this.extractUnannTypeName(n);return rn(s)}extractParameters(e){let t=[],n=[],s=[],i=[],o=!1,a,c,l=e.methodHeader?.[0]?.children?.methodDeclarator?.[0]?.children?.formalParameterList?.[0]?.children?.formalParameter;if(!l)return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i};for(let u of l){let d=u.children?.variableParaRegularParameter?.[0]?.children;if(!d)continue;let p=d.variableDeclaratorId?.[0]?.children?.Identifier?.[0]?.image||"",m=d.variableModifier||[],f=this.collectAnnotationsFromModifiers(m),h=d.unannType?.[0],g=h?this.extractUnannTypeName(h):"",y=f.find(b=>b.name==="Parameter"),v;for(let b of f)if(b.name==="RequestHeader"){let C=this.getAnnotationStringValue(b)||p;t.push(C),v=this.buildParameterMeta(C,"header",g,y,f);let R=b.attributes.get("required");v&&typeof R=="string"&&(R==="true"||R==="false")&&(v.required=R==="true")}else if(b.name==="RequestParam")if(gs(g)){o=!0;let C=this.getAnnotationStringValue(b)||p;s.push({name:C,type:g,isFile:!0})}else{let C=this.getAnnotationStringValue(b)||p;n.push(C);let R=b.attributes.get("required");v=this.buildParameterMeta(C,"query",g,y,f),v&&typeof R=="string"&&(R==="true"||R==="false")&&(v.required=R==="true")}else if(b.name==="RequestBody")o=!0,g&&(a=rn(g));else if(b.name==="RequestPart"){o=!0;let C=this.getAnnotationStringValue(b)||p,R=gs(g);s.push({name:C,type:g,isFile:R})}else b.name==="ModelAttribute"&&(o=!0,g&&(c=g));let w=f.find(b=>b.name==="PathVariable");if(w){let b=this.getAnnotationStringValue(w)||p;v=this.buildParameterMeta(b,"path",g,y,f)}v&&i.push(v)}return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i}}buildParameterMeta(e,t,n,s,i){let o={name:e,in:t};if(s){let a=this.getAnnotationAttrString(s,"description");a&&(o.description=a);let c=this.getAnnotationAttrString(s,"example");c&&(o.example=c);let l=s.attributes.get("required");typeof l=="string"&&(l==="true"||l==="false")&&(o.required=l==="true");let u=s.attributes.get("deprecated");typeof u=="string"&&u==="true"&&(o.deprecated=!0)}return n&&(o.schemaType=n),i&&this.extractConstraintAnnotations(o,i),o}extractConstraintAnnotations(e,t){for(let n of t)switch(n.name){case"Schema":{let s=this.getAnnotationAttrString(n,"pattern");s&&!e.pattern&&(e.pattern=s);let i=this.getAnnotationAttrString(n,"format");i&&!e.format&&(e.format=i);let o=this.getAnnotationAttrString(n,"minimum");o&&e.minimum===void 0&&(e.minimum=Number(o));let a=this.getAnnotationAttrString(n,"maximum");a&&e.maximum===void 0&&(e.maximum=Number(a));let c=this.getAnnotationAttrString(n,"minLength");c&&e.minLength===void 0&&(e.minLength=Number(c));let l=this.getAnnotationAttrString(n,"maxLength");l&&e.maxLength===void 0&&(e.maxLength=Number(l));let u=n.attributes.get("allowableValues");Array.isArray(u)&&!e.enum&&(e.enum=u.map(d=>d.replace(/^['"]|['"]$/g,"")).filter(Boolean));break}case"Pattern":{let s=this.getAnnotationAttrString(n,"regexp");s&&!e.pattern&&(e.pattern=s);break}case"Size":{let s=this.getAnnotationAttrString(n,"min");s&&e.minLength===void 0&&(e.minLength=Number(s));let i=this.getAnnotationAttrString(n,"max");i&&e.maxLength===void 0&&(e.maxLength=Number(i));break}case"Min":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.minimum===void 0&&(e.minimum=Number(s));break}case"Max":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.maximum===void 0&&(e.maximum=Number(s));break}case"DecimalMin":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=Number(s)):e.minimum===void 0&&(e.minimum=Number(s)));break}case"DecimalMax":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=Number(s)):e.maximum===void 0&&(e.maximum=Number(s)));break}case"Email":{e.format||(e.format="email");break}case"Positive":{e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=0);break}case"PositiveOrZero":{e.minimum===void 0&&(e.minimum=0);break}case"Negative":{e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=0);break}case"NegativeOrZero":{e.maximum===void 0&&(e.maximum=0);break}case"NotNull":case"NotBlank":case"NotEmpty":{e.required===void 0&&(e.required=!0);break}}}getAnnotationStringValue(e){let t=e.attributes.get("value");return typeof t=="string"?t.replace(/^['"]|['"]$/g,""):""}extractUnannTypeName(e){return this.collectTokens(e).map(n=>n.image).join("")}collectAnnotationsFromModifiers(e){let t=[];for(let n of e){let s=n.children?.annotation;if(!s)continue;let i=s[0].children,o=i.typeName[0].children.Identifier[0].image,a=new Map;if(i.elementValuePairList){let c=i.elementValuePairList[0].children.elementValuePair;for(let l of c){let u=l.children.Identifier[0].image,d=this.extractElementValue(l.children.elementValue[0]);d!==void 0&&a.set(u,d)}}else if(i.elementValue){let c=this.extractElementValue(i.elementValue[0]);c!==void 0&&a.set("value",c)}t.push({name:o,attributes:a})}return t}extractTypeName(e){if(!e)return"";if(e.primitiveType)return e.primitiveType[0].children?.literal?.[0]?.image||"";if(e.classOrInterfaceType){let t=e.classOrInterfaceType[0],n="",s=t.Identifier||[];for(let o=0;o<s.length;o++)o>0&&(n+="."),n+=s[o].image;let i=t.typeArguments?.[0]?.typeArgument;return i&&(n+="<",n+=i.map(o=>o.typeType?this.extractTypeName(o.typeType[0]):"?").join(","),n+=">"),n}if(e.typeType&&e.dims){let t=this.extractTypeName(e.typeType[0]),n=e.dims.length;return t+"[]".repeat(n)}return""}}});var ef={};Tt(ef,{EndpointParser:()=>eu});var Xp,eu,tf=E(()=>{"use strict";Xp=require("java-parser");fa();ma();Yp();eu=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>Zl(n.trim()));for(let n of[...this.fileCache.keys()]){let s=Zl(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=ki(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(Yl(a))&&!s.has(a)){if(s.add(a),this.fileCache.has(a)){n.push(...this.fileCache.get(a));continue}i.push(a)}let o=30;for(let a=0;a<i.length;a+=o){let c=i.slice(a,a+o),l=await Promise.all(c.map(u=>this.parseFile(u).then(d=>({filePath:u,ctrls:d})).catch(()=>({filePath:u,ctrls:[]}))));for(let{filePath:u,ctrls:d}of l)this.fileCache.set(u,d),n.push(...d)}for(let a of this.fileCache.keys())s.has(a)||this.fileCache.delete(a);return n}removeFile(e){this.fileCache.delete(e)}static CONTROLLER_HINT_RE=/@(?:RestController|Controller)\b|@(?:Request|Get|Post|Put|Delete|Patch)Mapping\b/;looksLikeController(e){return r.CONTROLLER_HINT_RE.test(e)}async parseFile(e){let t=await Ii(e);if(!this.looksLikeController(t))return[];let n=this.parseWithAst(t);if(n){for(let s of n){s.file=e;for(let i of s.endpoints)i.file=e}return n}return this.parseWithRegex(t,e)}async findEndpoints(e){return(await this.parseControllers(e)).flatMap(n=>n.endpoints)}parseWithAst(e){try{let t=(0,Xp.parse)(e),n=new ha;if(n.visit(t),n.controllers.length>0){for(let s of n.controllers){let i=new Set;s.endpoints=s.endpoints.filter(o=>{let a=`${o.method}:${o.path}:${o.line}`;return i.has(a)?!1:(i.add(a),!0)})}return n.controllers}return null}catch{return null}}parseWithRegex(e,t){let n=[],s=e.split(/\r?\n/),i=[],o=new Map,a=null,c=0,l=!1;for(let u=0;u<s.length;u++){let d=s[u],p=d.trim(),m=/^@(\w+)\s*(?:\(([^)]*)\))?/.exec(p);if(m&&!/\b(class|interface|enum)\b/.test(p)&&(i.push(m[1]),m[2]!==void 0&&o.set(m[1],m[2]),!/(private|public|protected|static|final|void|class)\b/.test(p)))continue;let f=/\bclass\s+(\w+)/.exec(p);if(f){if(a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i.some(v=>v==="RestController"||v==="Controller")){let v="",w=o.get("RequestMapping");w!==void 0&&(v=this.extractPathFromArgs(w)),a={name:f[1],basePath:v,file:t,line:u+1,endpoints:[]}}l=!0,c=0,c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,i=[],o=new Map;continue}if(l&&(c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,c<=0)){l=!1,a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i=[],o=new Map;continue}if(!a){m||(i=[],o=new Map);continue}let h=i.find(y=>/Mapping$/.test(y)),g=/^@(GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping)\s*(?:\(([^)]*)\))?/.exec(p);if(h||g){let y=u,v=this.collectMethodSignature(s,y),w=[];g&&w.push({name:g[1],args:g[2]||""});for(let b of i)/Mapping$/.test(b)&&(!g||b!==g[1])&&w.push({name:b,args:o.get(b)||""});for(let b of w){let C=b.name.replace("Mapping","").toUpperCase();C==="REQUEST"&&(C="");let R="",A=[],N=b.args;if(N){R=this.extractPathFromArgs(N);let U=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(N);if(U){let O=U[1],L=[...O.matchAll(/["']([^"']+)["']/g)].map(Y=>Y[1]),Q=[...O.matchAll(/MediaType\.([A-Z_]+)/g)].map(Y=>`MediaType.${Y[1]}`);A=Ti([...L,...Q])}if(b.name==="RequestMapping"){let O=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(N);O&&(C=O[1])}}!C&&b.name==="RequestMapping"&&(C="GET");let M=R;a.basePath&&(M&&!M.startsWith("/")?M=a.basePath+"/"+M:M=a.basePath+M),M&&!M.startsWith("/")&&(M="/"+M);let j=this.extractParameterMetadataFromSig(v);a.endpoints.push({method:C,path:M,file:t,line:u+1,pathParams:Xl(M),consumes:A,bodyType:j.bodyType,headers:j.headers,queryParams:j.queryParams,hasBody:j.hasBody,formParts:j.formParts.length>0?j.formParts:void 0,modelAttributeType:j.modelAttributeType})}i=[],o=new Map;continue}m||(i=[],o=new Map)}return a&&(this.deduplicateEndpoints(a),n.push(a)),n}extractPathFromArgs(e){let t=/(?:value|path)\s*=\s*["']([^"']+)["']/.exec(e);if(t)return t[1];let n=/^\s*["']([^"']+)["']/.exec(e);return n?n[1]:""}collectMethodSignature(e,t){let n="";for(let s=t;s<e.length&&(n+=e[s]+" ",!e[s].includes("{"));s++);return n}extractParameterMetadataFromSig(e){let t=[],n=[],s=[],i=!1,o,a,c=/@RequestHeader\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+(?:[A-Za-z0-9_<>\[\]]+)\s+(\w+)/g,l;for(;(l=c.exec(e))!==null;)t.push(l[1]||l[2]);let u=/@RequestParam\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=u.exec(e))!==null;){let g=l[2];if(gs(g)){i=!0;let y=l[1]||l[3];s.push({name:y,type:g,isFile:!0})}else n.push(l[1]||l[3])}let p=/@RequestBody\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);p?(i=!0,o=rn(p[1])):/@RequestBody/.test(e)&&(i=!0);let m=/@RequestPart\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=m.exec(e))!==null;){i=!0;let g=l[1]||l[3],y=l[2],v=gs(y);s.push({name:g,type:y,isFile:v})}let h=/@ModelAttribute\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);return h?(i=!0,a=h[1]):/@ModelAttribute/.test(e)&&(i=!0),{headers:t,queryParams:n,hasBody:i,bodyType:o,formParts:s,modelAttributeType:a}}deduplicateEndpoints(e){let t=new Set;e.endpoints=e.endpoints.filter(n=>{let s=`${n.method}:${n.path}:${n.line}`;return t.has(s)?!1:(t.add(s),!0)})}}});function jy(r){let e=[];for(let t of r.parameterMeta??[]){let n=[];t.required&&n.push("required"),t.pattern&&n.push(`pattern=${t.pattern}`),t.format&&n.push(`format=${t.format}`),t.enum&&t.enum.length>0&&n.push(`enum=[${t.enum.join(", ")}]`),t.minimum!==void 0&&n.push(`min=${t.minimum}`),t.maximum!==void 0&&n.push(`max=${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(`exclusiveMin=${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(`exclusiveMax=${t.exclusiveMaximum}`),t.minLength!==void 0&&n.push(`minLength=${t.minLength}`),t.maxLength!==void 0&&n.push(`maxLength=${t.maxLength}`),n.length>0&&e.push(`${t.in==="header"?"header":t.in} ${t.name}: ${n.join(", ")}`)}return e.length>0?e:void 0}var ga,nf,My,Dy,dr,tu=E(()=>{"use strict";ga=T(require("fs")),nf=T(require("path"));fa();Qp();My=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],Dy=/@(?:RestController|Controller)\b/,dr=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of My)if(ga.existsSync(nf.join(e.projectRoot,s)))return{supported:!0,confidence:.95,reasons:[`${s} detected`]};let t=e.sourceFiles??ki(e.projectRoot),n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=ga.readFileSync(s,"utf-8");if(Dy.test(i))return{supported:!0,confidence:.8,reasons:["Spring controller annotation found"]}}catch{continue}}return{supported:!1,confidence:0,reasons:["no Spring indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=t.projectRoot,o=await this.loadParser(),a=new o.EndpointParser,c=[];try{c=await a.parseControllers(i)}catch(d){let p=d instanceof Error?d.message:String(d);s.push({code:"provider-failed",framework:"spring",message:`Spring discovery failed for ${i}: ${p}`})}let l=new ur(i),u=[];for(let d of c)for(let p of d.endpoints)u.push(await this.endpointToDiscoveredApi(p,l));return{endpoints:u,warnings:s,stats:{frameworksDetected:["spring"],providersRun:[this.id],endpointCount:u.length,unresolvedEndpointCount:u.filter(d=>!d.resolvedPath).length,scanDurationMs:Date.now()-n}}}clearCache(){this.parserModule=void 0}async loadParser(){return this.parserModule||(this.parserModule=await Promise.resolve().then(()=>(tf(),ef))),this.parserModule}async endpointToDiscoveredApi(e,t){let n=await this.buildParams(e,t),s=await this.buildRequestBody(e,t),i=await this.buildResponses(e,t),o=e.security&&e.security.length>0?{required:!0,type:"oauth2",annotation:e.security.join(", ")}:void 0,a=e.line>0?e.line:1;return{id:"",framework:"spring",method:e.method||"GET",pathExpression:e.path||"/",resolvedPath:e.path||"/",confidence:"high",source:{filePath:e.file,line:a,symbolName:`${e.method||"GET"} ${e.path||"/"}`},params:n.length>0?n:void 0,requestBody:s,responses:i,validation:jy(e),auth:o,tags:e.tags,deprecated:e.deprecated,description:e.summary||e.description}}async buildParams(e,t){let n=[],s=(e.consumes??[]).join(" "),i=s.includes("x-www-form-urlencoded"),o=s.includes("multipart");for(let a of e.headers??[])n.push(this.paramFromMeta(a,"header",e.parameterMeta,!0));for(let a of e.queryParams??[]){let c=i||o?"form":"query",l=e.parameterMeta?.find(u=>u.name===a&&u.in==="query");n.push(this.paramFromMeta(a,c,e.parameterMeta,l?.required))}for(let a of e.formParts??[])n.push({name:a.name,location:"form",type:a.isFile?"file":"string",required:!0});return n}paramFromMeta(e,t,n,s){let i=n?.find(a=>a.name===e&&(a.in===t||t==="form"&&a.in==="query")),o={name:e,location:t};return i&&(o.description=i.description,o.required=i.required??s,o.example=i.example,i.schemaType&&(o.type=ur.javaTypeToParamType(i.schemaType)),o.schema=this.constraintsToSchema(i)),o.required=t==="path"?!0:o.required,o.type=o.type??"string",o}constraintsToSchema(e){let t={};if(e.schemaType){t.type=ur.javaTypeToParamType(e.schemaType);let n=ur.javaTypeToFormat(e.schemaType);n&&(t.format=n)}return e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.enum&&e.enum.length>0&&(t.enum=e.enum),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),Object.keys(t).length>0?t:void 0}async buildRequestBody(e,t){let n=e.consumes??[];if(e.formParts&&e.formParts.length>0)return{type:"multipart",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(e.modelAttributeType)return{type:"form",required:!0,schema:await this.maybeSchema(t,e.modelAttributeType)};if(n.some(a=>a.includes("x-www-form-urlencoded"))&&(e.queryParams?.length??0)>0)return{type:"form",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(!e.hasBody)return;let s=e.bodyType??e.modelAttributeType;if(!s)return{type:"json",required:!0};let i=n.some(a=>a.includes("x-www-form-urlencoded"))?"form":n.some(a=>a.includes("multipart"))?"multipart":"json",o=await this.maybeSchema(t,s);return{type:i,required:!0,schema:o}}async buildResponses(e,t){let n=[];for(let s of e.responses??[]){let i={statusCode:parseInt(s.statusCode,10)||200},o=s.schemaType?await this.maybeSchema(t,s.schemaType):void 0;i.body={type:s.contentType??"json"},o&&(i.body.schema=o),n.push(i)}if(n.length===0){let s=e.returnType;if(s&&s!=="void"){let i=await t.generateResponseSchema(s);n.push({statusCode:200,body:{type:"json",schema:i??{type:"object"}}})}else n.push({statusCode:200})}return n}async maybeSchema(e,t){return await e.generate(t)??{type:"object"}}}});function nu(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=va.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=cf.join(n,i.name);if(i.isDirectory()){Ly.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function lf(r){let e=nu(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let d="";try{d=va.readFileSync(u,"utf-8")}catch{continue}let p=By(d,u,t);n.set(u,p);for(let m of p.routers)s.has(m.name)||s.set(m.name,m)}let o=new Map;for(let u of s.values())o.set(u.name,[u.constructorPrefix]);let a=new Map,c=new Set;for(let u of n.values())for(let d of u.includes){let p=sf(u.imports,d.routerName);if(!s.has(p)){i.push(`include_router references unknown router '${d.routerName}' at ${d.line}`);continue}let m=s.get(p);if(d.prefix){c.add(p);let f=o.get(p),h=`${d.prefix.replace(/\/+$/,"")}/${m.constructorPrefix.replace(/^\/+/,"")}`;f.includes(h)||f.push(h)}d.tags&&d.tags.length>0&&a.set(p,[...a.get(p)??[],...d.tags])}let l=[];for(let[u,d]of n.entries())for(let p of d.routes)for(let m of p.decorators){let f=sf(d.imports,m.object),h=d.appNames.has(m.object)||d.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let y=Gy(m.method,m.args);if(y.length===0)continue;let v=Wy(m.args),w=m.unresolved||v.startsWith("f"),b=g?o.get(f)??[g.constructorPrefix]:[""];for(let C of b){if(g&&c.has(f)&&C===g.constructorPrefix)continue;let R=g?tv(C,v):v,A=nv(p.signature,ev(R)),N=g?a.get(f):void 0,j=uf(m.args)??N;l.push({methods:y,path:R,file:u,line:m.line,functionName:p.functionName,statusCode:Ky(m.args),responseModel:Qy(m.args)??zy(p.signature),tags:j,deprecated:Zy(m.args),summary:Yy(m.args),params:A.params,security:Xy(m.args,p.signature),pathUnresolved:w})}}return{endpoints:l,models:t,warnings:i}}function sf(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function sn(r,e){let t=r.trim();if(!t||t==="None")return;let n=/^(?:Optional|Union)\[([^\]]*)\](?:\s*\|\s*None)?$/.exec(t)||/^(.+?)(?:\s*\|\s*None)+$/.exec(t);if(n)return sn(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return sn(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:sn(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:sn(o[2],e)??{}};let a={int:{type:"integer"},float:{type:"number"},Decimal:{type:"number"},bool:{type:"boolean"},str:{type:"string"},datetime:{type:"string",format:"date-time"},date:{type:"string",format:"date"},time:{type:"string",format:"time"},UUID:{type:"string",format:"uuid"},bytes:{type:"string",format:"binary"},UploadFile:{type:"string",format:"binary"}};if(t in a)return{...a[t]};let c=e.get(t);if(c){let l={},u=[];for(let p of c.fields){let m=sn(p.type,e)??{type:"string"};l[p.name]=p.description?{...m,description:p.description}:m,p.required&&u.push(p.name)}let d={type:"object",properties:l};return u.length>0&&(d.required=u),d}return{type:"object"}}function By(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=iv(r).split(/\r?\n/),o=[],a=0;for(;a<i.length;){let c=i[a],l=a+1,u=c.trim();if(a+=1,u==="")continue;let d=/^from\s+[\w.]+(?:\s+import\s+(.+))?$/.exec(u)||/^import\s+([\w.,\s]+)$/.exec(u);if(d){let y=d[1]??"";for(let v of y.split(",")){let w=v.trim();if(!w)continue;let b=/^([\w.]+)\s+as\s+(\w+)$/.exec(w);if(b)n.imports.push({alias:b[2],target:b[1].split(".").pop()});else if(/^[\w.]+$/.test(w)){let C=w.split(".").pop();n.imports.push({alias:C,target:C})}}o=[];continue}if(u.startsWith("@")){let{joined:y,nextIndex:v}=ya(i,a-1),w=Jy(y,l);w&&o.push(w),a=v+1;continue}let p=/^(?:async\s+)?def\s+(\w+)\s*\(/.exec(u);if(p){let{joined:y,nextIndex:v}=ya(i,a-1),w=y.slice(y.indexOf("(")),b=Vy(i,a-1,w);o.length>0&&n.routes.push({decorators:o,functionName:p[1],signature:b,line:l}),o=[],a=v+1;continue}let m=/^class\s+(\w+)\s*\(\s*(\w+)\s*\)\s*:/.exec(u);if(m&&(m[2]==="BaseModel"||m[2].endsWith("BaseModel"))){let{nextIndex:y,fields:v}=Uy(i,a);t.set(m[1],{name:m[1],fields:v}),a=y,o=[];continue}let f=/^(\w+)\s*=\s*(?:fastapi\.)?FastAPI\(/.exec(u);if(f){n.appNames.add(f[1]),o=[];continue}let h=/^(\w+)\s*=\s*(?:fastapi\.)?APIRouter\((.*)$/.exec(u);if(h){let{joined:y}=ya(i,a-1),v=y.slice(y.indexOf("("));n.routers.push({name:h[1],constructorPrefix:af(v)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:y}=ya(i,a-1),v=y.slice(y.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:af(v),tags:uf(v),line:l}),o=[];continue}o=[]}return n}function Uy(r,e){let t=[],n=e,s=(r[e-1]||"").match(/^(\s*)/)[1].length;for(;n<r.length;){let i=r[n];if(i.trim()===""){n+=1;continue}if(i.match(/^(\s*)/)[1].length<=s)break;let a=i.trim();if(a.startsWith("#")){n+=1;continue}let c=/^([A-Za-z_]\w*)\s*:\s*(.+?)\s*(?:=\s*(.*))?$/.exec(a);if(c&&!a.startsWith("def ")&&!a.startsWith("class ")){let l=c[2].replace(/,\s*$/,""),u=(c[3]??"").trim(),d=/^Optional\[/.test(l)||/None\s*\|/.test(l)||u==="None"||u.startsWith("None")||u!==""&&!u.startsWith("Field("),p,m=/Field\(([^)]*)\)/.exec(a);if(m){let f=/description\s*=\s*["']([^"']+)["']/.exec(m[1]);f&&(p=f[1])}t.push({name:c[1],type:l,required:!d,description:p})}n+=1}return{nextIndex:n,fields:t}}function ya(r,e){let t=0,n=r[e]??"",s=e,i=null,o=a=>{for(let c of a){if(i){c===i&&(i=null);continue}c==='"'||c==="'"?i=c:c==="("||c==="["||c==="{"?t+=1:(c===")"||c==="]"||c==="}")&&(t-=1)}};for(o(n);t>0&&s+1<r.length;){s+=1;let a=r[s];o(a),n+=`
468
+ `)||void 0,currentScript:o,lastResponse:a??null,note:a?"Last response data available \u2014 use it to align assertions with actual behavior.":"No run data available \u2014 run the request first with run_request, then call heal_assertions again with the runId.",expectedCallAfterThis:"set_request_script"}}}},{toolNames:[S.generateIterationData],handle({args:r,collections:e}){let t=z(r.collection,e),n=Ue(r.request,t),s=typeof r.iterations=="number"?Math.min(50,Math.max(1,r.iterations)):5,i=n.body?.type==="raw"&&typeof n.body.content=="string"?n.body.content:void 0,o=(n.headers??[]).filter(u=>u.enabled!==!1).map(u=>({key:u.key,value:u.value})),a=(n.query??[]).filter(u=>u.enabled!==!1).map(u=>({key:u.key,value:u.value})),c=/\{\{([^}]+)\}\}/g,l=new Set;for(let u of[n.url??"",i??"",...o.map(d=>d.value),...a.map(d=>d.value)]){let d;for(c.lastIndex=0;(d=c.exec(u))!==null;)l.add(d[1])}return{task:{action:"generate_iteration_data",instructions:[`Generate ${s} test data rows for: ${n.method} ${n.url??""}`,`The request uses these {{variable}} placeholders: ${[...l].join(", ")||"(none detected)"}`,"Each row must be a JSON object whose keys match the placeholder names.","Cover a mix of: (1) valid happy-path data, (2) boundary values, (3) invalid inputs that should fail, (4) edge cases.",'Return the rows as a JSON array in a code block labeled "iterationData".',"This data can be used with: http-forge run-request --collection ... --variables '[...]' or passed to run_request via the variables argument."],collection:t.name,request:n.name,method:n.method,url:n.url??"",businessContext:Xe(n,op(t,n)).snapshot().body||void 0,body:i??null,headers:o,queryParams:a,placeholders:[...l],iterations:s}}}}]});function lp(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.name===e||e.endsWith("/"+n.name))return{id:n.id};let s=lp(n.items??[],e);if(s)return s}}var up,dp=E(()=>{"use strict";Ne();_e();_e();up=[{toolNames:[S.createCollection],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw I('"name" is required');let n=await e.collection.createCollection(t);return{id:n.id,name:n.name,created:!0,hint:"Collection is empty. Call create_folder to add folders, or create_request to add requests directly."}}},{toolNames:[S.renameCollection],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw I('"newName" is required');return await e.collection.renameCollection(n.id,s),{id:n.id,oldName:n.name,newName:s,renamed:!0}}},{toolNames:[S.deleteCollection],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw I('"confirm" must be true to delete a collection');let n=z(r.collection,t);return await e.collection.deleteCollection(n.id),{deleted:!0,collection:n.name}}},{toolNames:[S.duplicateCollection],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw I('"newName" is required');let i=await e.collection.duplicateCollection(n.id,s);return{id:i.id,name:i.name,duplicatedFrom:n.name}}},{toolNames:[S.createFolder],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw I('"name" is required');let i;if(typeof r.parentFolder=="string"&&r.parentFolder.trim()){let a=r.parentFolder.toLowerCase(),c=Re(n);if(K(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let d=Re(n).find(p=>p.folderPath===r.parentFolder||p.folderPath.toLowerCase()===a);if(d){let p=n.items;i=lp(p,d.folderPath)?.id}}}let o=await e.collection.createFolder({collectionId:n.id,name:s,parentId:i});return{id:o.id,name:o.name,created:!0,collection:n.name}}},{toolNames:[S.deleteFolder],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw I('"confirm" must be true to delete a folder');let n=z(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw I('"folder" is required');let s=r.folder.toLowerCase(),i=Re(n).find(c=>c.folderPath===r.folder||c.folderPath.toLowerCase()===s);if(!i)throw I(`folder "${r.folder}" not found in collection "${n.name}"`);let o=Ol(n.items,i.folderId);if(!o)throw I(`folder "${r.folder}" could not be resolved`);let a=i.requestCount;return await e.collection.deleteFolder(n.id,o.id),{deleted:!0,folder:i.folderPath,requestsRemoved:a}}}]});var Nl=E(()=>{"use strict"});var pp=E(()=>{"use strict"});var Rt,cs,Eg,qg,Ag,rr,Yo=E(()=>{"use strict";Rt=T(require("fs")),cs=T(require("path")),Eg=["package.json","src/main.ts","src/main.js","src/app.ts","src/app.js","pom.xml","build.gradle","build.gradle.kts","settings.gradle","requirements.txt","pyproject.toml","poetry.lock","Pipfile","app/main.py","main.py"],qg={express:["express","router.","app.use(","app.get(","express.Router"],nestjs:["@nestjs/common","@Controller(","@Get(","@Post("],fastify:["fastify","fastify.route(","fastify.get(","register("],lambda:["exports.handler","event.pathParameters","APIGatewayProxyEvent","aws-lambda"],spring:["@RestController","@Controller","@GetMapping","@PostMapping","@RequestMapping"],fastapi:["from fastapi","import fastapi","@app.get(","@router.get("],unknown:[]},Ag={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},rr=class{buildFingerprint(e){let t=[],n=cs.join(e,"package.json"),s;for(let i of Eg){let o=cs.join(e,i);Rt.existsSync(o)&&t.push(o)}if(Rt.existsSync(n))try{let i=JSON.parse(Rt.readFileSync(n,"utf-8"));s={dependencies:i.dependencies,devDependencies:i.devDependencies,scripts:i.scripts}}catch{}return{projectRoot:e,packageJsonPath:Rt.existsSync(n)?n:void 0,packageJson:s,evidenceFiles:t}}detectFrameworks(e){let t=[];return(this.hasDependency(e,"express")||this.hasSourceHint(e,"express"))&&t.push("express"),(this.hasDependency(e,"@nestjs/common")||this.hasSourceHint(e,"nestjs"))&&t.push("nestjs"),(this.hasDependency(e,"fastify")||this.hasSourceHint(e,"fastify"))&&t.push("fastify"),(this.hasBuildFile(e,"pom.xml")||this.hasBuildFile(e,"build.gradle")||this.hasBuildFile(e,"build.gradle.kts")||this.hasBuildFile(e,"settings.gradle")||this.hasSourceHint(e,"spring"))&&t.push("spring"),(this.hasBuildFile(e,"requirements.txt")||this.hasBuildFile(e,"pyproject.toml")||this.hasBuildFile(e,"poetry.lock")||this.hasBuildFile(e,"Pipfile")||this.hasSourceHint(e,"fastapi"))&&t.push("fastapi"),t.includes("express")||t.includes("fastify")||(this.hasDependency(e,"@types/aws-lambda")||this.hasDependency(e,"aws-lambda")||this.hasDependency(e,"serverless")||this.hasSourceHint(e,"lambda"))&&t.push("lambda"),t.length>0?t:["unknown"]}hasDependency(e,t){let n=e.packageJson?.dependencies??{},s=e.packageJson?.devDependencies??{};return!!(n[t]||s[t])}hasBuildFile(e,t){return Rt.existsSync(cs.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=qg[t],i=Ag[t],o=0,a=120;for(let c of n){let l=cs.join(e.projectRoot,c);if(!Rt.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let d=u.shift(),p;try{p=Rt.readdirSync(d,{withFileTypes:!0})}catch{continue}for(let m of p){let f=cs.join(d,m.name);if(m.isDirectory()){u.push(f);continue}if(!m.isFile()||!i.some(g=>f.endsWith(g)))continue;o+=1;let h="";try{h=Rt.readFileSync(f,"utf-8")}catch{continue}if(s.some(g=>h.includes(g)))return!0}}}return!1}}});function nt(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=fp.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=mp.join(n,i.name);if(i.isDirectory()){Pg.has(i.name)||t.push(o);continue}i.isFile()&&(kg.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var fp,mp,Pg,kg,Rn=E(()=>{"use strict";fp=T(require("fs")),mp=T(require("path")),Pg=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),kg=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});function Ri(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=Xo.isAbsolute(t)?t:Xo.join(r,t);if(!hp.existsSync(n))return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader module not found: ${n}`}]};try{let s=require(n),i=s.loadSeedManifestEndpoints??s.default;if(typeof i!="function")return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:"Custom seed loader module must export a function named loadSeedManifestEndpoints or a default function."}]};let o=i(r,e);return Array.isArray(o)?{endpoints:o,warnings:[]}:{endpoints:o?.endpoints??[],warnings:o?.warnings??[]}}catch(s){return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader failed at ${n}: ${s instanceof Error?s.message:String(s)}`}]}}}var hp,Xo,ea=E(()=>{"use strict";hp=T(require("fs")),Xo=T(require("path"))});function _l(r,e){let t=r.projectName?.trim();if(t)return t;let n=gp(r.source.filePath),s=Ig(n);if(s)return s;let i;for(let a of e){let c=gp(a);(n===c||n.startsWith(`${c}/`))&&(!i||c.length>i.length)&&(i=c)}if(!i)return;let o=i.split("/").filter(Boolean);return o[o.length-1]||void 0}function Ig(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function gp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Ml=E(()=>{"use strict"});function Yt(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function Xt(r,e,t){let n=[],s=/:([a-zA-Z_]\w*)/g,i=/\{([a-zA-Z_]\w*)\}/g,o;for(;(o=s.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});for(;(o=i.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});return n}function Ci(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,d=new Map,p=Gg(o),m=zg(r,e,p),f=Zg(r,e,p);if(i?.requestAliases)for(let R of i.requestAliases)m.add(R);if(i?.responseAliases)for(let R of i.responseAliases)f.add(R);let h=Rp(e),g=Tg(e,t),y=Jg(r,t,h,g,m,f),v=(R,A)=>{let N=l.find(M=>M.statusCode===R);return N||(N={statusCode:R},l.push(N)),A&&(N.body={type:A,schema:N.body?.schema}),N};x.isFunctionLike(r)&&Ug(r,e,d,m,f,p);let w=(R,A)=>{let N=h.get(R);if(N){let Q=`${t}:${R}`;if(s.visitedSymbols.has(Q))return;s.visitedSymbols.add(Q);let Y=y.get(Q),Je=A?sa(A,N,m,f):void 0,an=wp(Y,Je),kt=Ci(N,e,t,n,s,an,o);jl({parameters:a,requestBody:u,cookies:c,responses:l},kt),!u&&kt.requestBody&&(u=kt.requestBody);return}let M=g.get(R);if(!M||s.visitedSymbols.has(M.symbolKey))return;s.visitedSymbols.add(M.symbolKey);let j=y.get(M.symbolKey),U=A?sa(A,M.node,m,f):void 0,O=wp(j,U),L=Ci(M.node,M.sourceFile,M.filePath,n,s,O,o);jl({parameters:a,requestBody:u,cookies:c,responses:l},L),!u&&L.requestBody&&(u=L.requestBody)},b=["POST","PUT","PATCH"].includes(n),C=R=>{x.isVariableDeclaration(R)&&Bg(R,e,d,m,f,p),x.isIdentifier(R)&&(x.isCallExpression(R.parent)&&R.parent.expression===R||w(R.text));let A=ls(R,e,"query",d,m,f,p);if(A){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:A.path,location:"query",type:na(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let N=ls(R,e,"params",d,m,f,p);if(N){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:N.path,location:"path",required:!0,type:na(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}if(Hg(R,e,m)&&!u){let O=e.getLineAndCharacterOfPosition(R.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}}let M=ls(R,e,"body",d,m,f,p);if(M){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:M.path,location:"body",type:na(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let j=ls(R,e,"headers",d,m,f,p);if(j){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:j.path,location:"header",type:"string",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let U=ls(R,e,"cookies",d,m,f,p);if(U){let O=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:U.path,type:"request",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}for(let O of p){let L=ls(R,e,O,d,m,f,p);if(!L)continue;let Q=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:L.path,location:O,type:na(R,e),detectionLocation:{filePath:t,line:Q.line+1,column:Q.character+1,accessMode:"read"}})}if(x.isCallExpression(R)){let O=Wg(R,e,f);O&&v(O.statusCode,O.bodyType)}if(x.isCallExpression(R)){let O=Kg(R,f);if(O){let L=v(O.statusCode);if(!L.headers?.some(Q=>Q.name===O.headerName)){let Q=e.getLineAndCharacterOfPosition(R.getStart(e));L.headers=L.headers??[],L.headers.push({name:O.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:Q.line+1,column:Q.character+1,accessMode:"write"}})}}}if(x.isCallExpression(R)&&x.isPropertyAccessExpression(R.expression)&&Yg(R.expression.expression,f)&&R.expression.name.text==="cookie"&&R.arguments[0]&&x.isStringLiteral(R.arguments[0])){let O=R.arguments[0].text;if(O&&!c.some(L=>L.name===O&&L.type==="response")){let L=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:O,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:L.line+1,column:L.character+1,accessMode:"write"}})}}x.isCallExpression(R)&&x.isIdentifier(R.expression)&&w(R.expression.text,R),x.forEachChild(R,C)};return r&&C(r),{parameters:a,requestBody:b?u||{type:"json",required:!0}:void 0,cookies:c,responses:l.length>0?l:[{statusCode:200}]}}function us(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=Ci(o,e,t,n,void 0,void 0,s);jl(i,a)}return i.parameters=en(i.parameters),i.cookies=Lg(i.cookies),!i.requestBody&&["POST","PUT","PATCH"].includes(n)&&(i.requestBody={type:"json",required:!0}),i.responses.length===0&&(i.responses=[{statusCode:200}]),i}function Rp(r){let e=new Map,t=n=>{x.isFunctionDeclaration(n)&&n.name&&e.set(n.name.text,n),x.isVariableDeclaration(n)&&x.isIdentifier(n.name)&&n.initializer&&(x.isArrowFunction(n.initializer)||x.isFunctionExpression(n.initializer))&&e.set(n.name.text,n.initializer),x.forEachChild(n,t)};return t(r),e}function Tg(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=$g(e,s);if(!o)return;let a=Og(o);if(!a)return;let c=Fg(a,o);for(let l of i){let u=c.get(l.importedName);u&&t.set(l.localName,{node:u,sourceFile:a,filePath:o,symbolKey:`${o}:${l.importedName}`})}};for(let s of r.statements){if(x.isImportDeclaration(s)&&s.importClause&&x.isStringLiteral(s.moduleSpecifier)){let i=s.moduleSpecifier.text,o=[];s.importClause.name&&o.push({localName:s.importClause.name.text,importedName:"default"});let a=s.importClause.namedBindings;if(a&&x.isNamedImports(a))for(let c of a.elements)o.push({localName:c.name.text,importedName:c.propertyName?c.propertyName.text:c.name.text});n(i,o);continue}if(x.isVariableStatement(s))for(let i of s.declarationList.declarations){if(!i.initializer||!x.isCallExpression(i.initializer)||!x.isIdentifier(i.initializer.expression)||i.initializer.expression.text!=="require")continue;let o=i.initializer.arguments[0];if(!o||!x.isStringLiteral(o))continue;let a=o.text,c=[];if(x.isIdentifier(i.name))c.push({localName:i.name.text,importedName:"default"});else if(x.isObjectBindingPattern(i.name))for(let l of i.name.elements){if(!x.isIdentifier(l.name))continue;let u=l.propertyName&&(x.isIdentifier(l.propertyName)||x.isStringLiteral(l.propertyName))?l.propertyName.text:l.name.text;c.push({localName:l.name.text,importedName:u})}n(a,c)}}return t}function Og(r){let e="";try{e=ia.readFileSync(r,"utf-8")}catch{return}return x.createSourceFile(r,e,x.ScriptTarget.Latest,!0,r.endsWith(".ts")?x.ScriptKind.TS:x.ScriptKind.JS)}function $g(r,e){let t=ir.resolve(ir.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,ir.join(t,"index.ts"),ir.join(t,"index.js")];for(let s of n)try{if(ia.statSync(s).isFile())return s}catch{continue}}function Fg(r,e){let t=new Map,n=Rp(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(x.isFunctionDeclaration(i)&&i.name&&yp(i)){s(i.name.text,i),vp(i)&&s("default",i);continue}if(x.isVariableStatement(i)&&yp(i)){for(let c of i.declarationList.declarations)!x.isIdentifier(c.name)||!c.initializer||(x.isArrowFunction(c.initializer)||x.isFunctionExpression(c.initializer))&&(s(c.name.text,c.initializer),vp(i)&&s("default",c.initializer));continue}if(x.isExportAssignment(i)){let c=i.expression;if(x.isIdentifier(c)){let l=n.get(c.text);l&&s("default",l)}else(x.isFunctionExpression(c)||x.isArrowFunction(c))&&s("default",c);continue}if(!x.isExpressionStatement(i)||!x.isBinaryExpression(i.expression))continue;let o=i.expression.left,a=i.expression.right;if(x.isPropertyAccessExpression(o)&&o.expression.getText(r)==="module.exports"){let c=o.name.text,l=Dl(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=Dl(a,n);c&&s("default",c);continue}if(x.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=Dl(a,n);c&&s(o.name.text,c)}}return t}function Dl(r,e){if(x.isFunctionExpression(r)||x.isArrowFunction(r))return r;if(x.isIdentifier(r))return e.get(r.text)}function yp(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.ExportKeyword):!1}function vp(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.DefaultKeyword):!1}function jl(r,e){r.parameters.push(...e.parameters),r.cookies.push(...e.cookies),!r.requestBody&&e.requestBody&&(r.requestBody=e.requestBody);for(let t of e.responses){let n=r.responses.find(o=>o.statusCode===t.statusCode);if(!n){r.responses.push({statusCode:t.statusCode,headers:t.headers?[...t.headers]:void 0,body:t.body});continue}let s=n.headers??[],i=t.headers??[];n.headers=en([...s,...i])}}function en(r){let e=new Map;for(let i of r){let o=`${i.location}:${i.name}`,a=e.get(o);if(!a){e.set(o,{...i,evidenceLocations:bp([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=bp(a.evidenceLocations??[],i),!a.detectionLocation&&i.detectionLocation&&(a.detectionLocation=i.detectionLocation),!a.type&&i.type){a.type=i.type;continue}if(!i.type||!a.type||a.type===i.type)continue;let c=new Set(a.conflictingTypes??[]);c.add(a.type),c.add(i.type),a.conflictingTypes=Array.from(c),a.location==="body"&&(a.type==="object"||i.type==="object")&&(a.type="object")}let t=Array.from(e.values()).map(i=>Ng(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=ta(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=ta(o)}}for(let i of s.values()){let o=ta(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=ta(o)}}return t}function bp(r,e){let t=[...r??[]];e.detectionLocation&&t.push(e.detectionLocation),e.evidenceLocations&&t.push(...e.evidenceLocations);let n=new Set,s=[];for(let i of t){let o=`${i.filePath}:${i.line}:${i.column??0}:${i.symbolName??""}:${i.accessMode??""}`;n.has(o)||(n.add(o),s.push(i))}return s}function Ng(r){let e=Dg([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=_g(e),n=e.filter(s=>!jg(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function _g(r){return[...r].sort(Mg)[0]}function Mg(r,e){let t=Sp(r),n=Sp(e);if(t!==n)return n-t;if(r.line!==e.line)return r.line-e.line;let s=r.column??0,i=e.column??0;return s!==i?s-i:r.filePath.localeCompare(e.filePath)}function Sp(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function Dg(r){let e=[],t=new Set;for(let n of r){let s=`${n.filePath}:${n.line}:${n.column??0}:${n.symbolName??""}:${n.accessMode??""}`;t.has(s)||(t.add(s),e.push(n))}return e}function jg(r,e){return r.filePath===e.filePath&&r.line===e.line&&(r.column??0)===(e.column??0)&&(r.symbolName??"")===(e.symbolName??"")&&(r.accessMode??"")===(e.accessMode??"")}function Lg(r){let e=new Set,t=[];for(let n of r){let s=`${n.type??"unknown"}:${n.name}`;e.has(s)||(e.add(s),t.push(n))}return t}function Hg(r,e,t){return x.isPropertyAccessExpression(r)&&x.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function ls(r,e,t,n,s,i,o){return Hl(r,e,t,n,!1,s,i,o)}function Hl(r,e,t,n,s,i,o,a){let c=[],l=r;for(;l&&(x.isPropertyAccessExpression(l)||x.isElementAccessExpression(l)||x.isPropertyAccessChain(l)||x.isElementAccessChain(l));){if(x.isPropertyAccessExpression(l)||x.isPropertyAccessChain(l)){c.unshift(l.name.text),l=l.expression;continue}if(x.isElementAccessExpression(l)||x.isElementAccessChain(l)){let h=l.argumentExpression;if(h&&(x.isStringLiteral(h)||x.isNumericLiteral(h))){let g=h.text;x.isNumericLiteral(h)||/^\d+$/.test(g)?c.unshift("[]"):c.unshift(g)}else return;l=l.expression}}let u=c.indexOf(t),p=a?.has(t)??!1?l&&x.isIdentifier(l)&&((o?.has(l.text)??!1)||(i?.has(l.text)??!1)):l&&x.isIdentifier(l)&&i?.has(l.text)===!0;if(u!==-1&&p){let h=c.slice(u+1);return h.length===0?s?{path:""}:void 0:{path:ra(h)}}if(!l||!x.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=ra(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function Bg(r,e,t,n,s,i){let o=r.initializer;if(!o)return;x.isIdentifier(o)&&n.has(o.text)&&x.isIdentifier(r.name)&&n.add(r.name.text),x.isIdentifier(o)&&s.has(o.text)&&x.isIdentifier(r.name)&&s.add(r.name.text);let a=["body","query","params","headers","cookies",...i],c,l="";for(let u of a){let d=Hl(o,e,u,t,!0,n,s,i);if(d){c=u,l=d.path;break}}if(c){if(x.isIdentifier(r.name)){t.set(r.name.text,{target:c,path:l});return}(x.isObjectBindingPattern(r.name)||x.isArrayBindingPattern(r.name))&&Ei(r.name,c,l,t)}}function Ug(r,e,t,n,s,i){let o=["body","query","params","headers","cookies",...i];for(let a of r.parameters){if((x.isObjectBindingPattern(a.name)||x.isArrayBindingPattern(a.name))&&!a.initializer){Vg(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let d of o){let p=Hl(c,e,d,t,!0,n,s,i);if(p){l=d,u=p.path;break}}if(l){if(x.isIdentifier(a.name)){t.set(a.name.text,{target:l,path:u});continue}(x.isObjectBindingPattern(a.name)||x.isArrayBindingPattern(a.name))&&Ei(a.name,l,u,t)}}}function Vg(r,e,t){if(!x.isObjectBindingPattern(r))return;let n=new Set(["body","query","params","headers","cookies",...t]);for(let s of r.elements){let i=Ll(s);if(!i||!n.has(i))continue;let o=i;if(x.isIdentifier(s.name)){e.set(s.name.text,{target:o,path:""});continue}(x.isObjectBindingPattern(s.name)||x.isArrayBindingPattern(s.name))&&Ei(s.name,o,"",e)}}function zg(r,e,t){let n=new Set,s=new Set(["query","params","body","headers","cookies",...t]),i=o=>{if(x.isPropertyAccessExpression(o)||x.isPropertyAccessChain(o)){let a=o.name.text;if(s.has(a)){let c=sr(o.expression);c&&n.add(c)}}if(x.isElementAccessExpression(o)||x.isElementAccessChain(o)){let a=o.argumentExpression;if(a&&x.isStringLiteral(a)&&s.has(a.text)){let c=sr(o.expression);c&&n.add(c)}}x.isVariableDeclaration(o)&&o.initializer&&x.isIdentifier(o.name)&&x.isIdentifier(o.initializer)&&n.has(o.initializer.text)&&n.add(o.name.text),x.forEachChild(o,i)};return i(r),n}function Ei(r,e,t,n){if(x.isObjectBindingPattern(r)){for(let s of r.elements){let i=Ll(s);if(!i)continue;let o=xp(t,i);if(x.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(x.isObjectBindingPattern(s.name)||x.isArrayBindingPattern(s.name))&&Ei(s.name,e,o,n)}return}for(let s of r.elements){if(!x.isBindingElement(s))continue;let i=Ll(s)??"[]",o=xp(t,/^\d+$/.test(i)?"[]":i);if(x.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(x.isObjectBindingPattern(s.name)||x.isArrayBindingPattern(s.name))&&Ei(s.name,e,o,n)}}function Ll(r){let e=r.propertyName;if(!e)return x.isIdentifier(r.name)?r.name.text:void 0;if(x.isIdentifier(e)||x.isStringLiteral(e)||x.isNumericLiteral(e))return e.text}function xp(r,e){return ra(r?`${r}.${e}`.split("."):[e])}function ra(r){if(r.length===0)return"";let e="";for(let t of r)if(t){if(t==="[]"){e.endsWith("[]")||(e+="[]");continue}e+=e?`.${t}`:t}return e}function ta(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function Jg(r,e,t,n,s,i){let o=new Map,a=(l,u)=>{let d=o.get(l);if(!d){o.set(l,{requestAliases:u.requestAliases?new Set(u.requestAliases):void 0,responseAliases:u.responseAliases?new Set(u.responseAliases):void 0});return}if(u.requestAliases)if(!d.requestAliases)d.requestAliases=new Set(u.requestAliases);else for(let p of u.requestAliases)d.requestAliases.add(p);if(u.responseAliases)if(!d.responseAliases)d.responseAliases=new Set(u.responseAliases);else for(let p of u.responseAliases)d.responseAliases.add(p)},c=l=>{if(x.isCallExpression(l)&&x.isIdentifier(l.expression)){let u=l.expression.text,d=t.get(u);if(d){let m=sa(l,d,s,i);m&&a(`${e}:${u}`,m)}let p=n.get(u);if(p){let m=sa(l,p.node,s,i);m&&a(p.symbolKey,m)}}x.forEachChild(l,c)};return c(r),o}function wp(r,e){if(!r&&!e)return;let t=new Set([...r?.requestAliases??[],...e?.requestAliases??[]]),n=new Set([...r?.responseAliases??[],...e?.responseAliases??[]]);return{requestAliases:t.size>0?t:void 0,responseAliases:n.size>0?n:void 0}}function Gg(r){let e=new Set,t=new Set(["query","params","body","headers","cookies"]);for(let n of r){let s=n.trim();!s||t.has(s)||e.add(s)}return e.size===0&&e.add("locals"),e}function sa(r,e,t,n){let s=new Set,i=new Set,o=Math.min(r.arguments.length,e.parameters.length);for(let a=0;a<o;a+=1){let c=e.parameters[a];if(!x.isIdentifier(c.name))continue;let l=r.arguments[a],u=sr(l);u&&(t.has(u)&&s.add(c.name.text),n.has(u)&&i.add(c.name.text))}if(!(s.size===0&&i.size===0))return{requestAliases:s.size>0?s:void 0,responseAliases:i.size>0?i:void 0}}function na(r,e){if(!r||!r.parent)return"string";if(x.isCallExpression(r.parent)&&x.isIdentifier(r.parent.expression)){let t=r.parent.expression.text;if(t==="parseInt"||t==="parseFloat")return"number"}if(x.isBinaryExpression(r.parent)&&(r.parent.operatorToken.kind===x.SyntaxKind.EqualsEqualsToken||r.parent.operatorToken.kind===x.SyntaxKind.EqualsEqualsEqualsToken)){let t=r.parent.left===r?r.parent.right:r.parent.left;if(x.isNumericLiteral(t))return"number"}return"string"}function Wg(r,e,t){let n=r.expression;if(!x.isPropertyAccessExpression(n))return;let s=n.name.text;if(s!=="json"&&s!=="send")return;let i=Cp(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":Qg(r.arguments[0])}}function Kg(r,e){let t=r.expression;if(!x.isPropertyAccessExpression(t))return;let n=t.name.text;if(n!=="header"&&n!=="set")return;let s=r.arguments[0];if(!s||!x.isStringLiteral(s))return;let i=Cp(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function Cp(r,e){if(!x.isPropertyAccessExpression(r.expression))return;let t=200,n=r.expression.expression;for(;;){if(x.isIdentifier(n)&&e.has(n.text))return{receiver:n.text,statusCode:t};if(!x.isCallExpression(n)||!x.isPropertyAccessExpression(n.expression))return;let s=n.expression.name.text;if(s==="status"||s==="code"){let i=n.arguments[0];i&&x.isNumericLiteral(i)&&(t=Number(i.text))}n=n.expression.expression}}function Qg(r){return r&&(x.isObjectLiteralExpression(r)||x.isArrayLiteralExpression(r))?"json":"text"}function Zg(r,e,t){let n=new Set,s=new Set(["status","code","json","send","header","set","cookie"]),i=new Set(t),o=a=>{if(x.isPropertyAccessExpression(a)||x.isPropertyAccessChain(a)){let c=a.name.text;if(i.has(c)){let l=sr(a.expression);l&&n.add(l)}}if(x.isElementAccessExpression(a)||x.isElementAccessChain(a)){let c=a.argumentExpression;if(c&&x.isStringLiteral(c)&&i.has(c.text)){let l=sr(a.expression);l&&n.add(l)}}if(x.isCallExpression(a)&&x.isPropertyAccessExpression(a.expression)){let c=a.expression.name.text;if(s.has(c)){let l=sr(a.expression.expression);l&&n.add(l)}}x.isVariableDeclaration(a)&&a.initializer&&x.isIdentifier(a.name)&&x.isIdentifier(a.initializer)&&n.has(a.initializer.text)&&n.add(a.name.text),x.forEachChild(a,o)};return o(r),n}function Yg(r,e){let t=sr(r);return t?e.has(t):!1}function sr(r){let e=r;for(;;){if(x.isIdentifier(e))return e.text;if(x.isPropertyAccessExpression(e)||x.isPropertyAccessChain(e)){e=e.expression;continue}if(x.isElementAccessExpression(e)||x.isElementAccessChain(e)){e=e.expression;continue}if(x.isCallExpression(e)&&x.isPropertyAccessExpression(e.expression)){e=e.expression.expression;continue}return}}var ia,ir,x,oa=E(()=>{"use strict";ia=T(require("fs")),ir=T(require("path")),x=T(require("typescript"))});function ds(r,e,t){let n={},s=o=>{if(le.isVariableDeclaration(o)&&le.isIdentifier(o.name)&&o.initializer){let a=Cn(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}le.forEachChild(o,s)};s(r);let i={...ey(e),...t};return{variables:n,env:i}}function Ct(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=Cn(r,e,t);if(n!==void 0)return{pathExpression:n,resolvedPath:n,confidence:"high"};if(le.isStringLiteral(r)||le.isNoSubstitutionTemplateLiteral(r)){let s=r.text||"/";return{pathExpression:s,resolvedPath:s,confidence:"high"}}if(le.isTemplateExpression(r)){let s=Xg(r,e,t);if(s.resolvedPath)return s;let i=r.head.text;return{pathExpression:r.getText(e),resolvedPath:i||void 0,confidence:i?"medium":"low"}}return le.isIdentifier(r)?{pathExpression:r.getText(e),confidence:"low"}:{pathExpression:r.getText(e),confidence:"low"}}function tn(r,e){let t=Ep(r??""),n=Ep(e??""),s=qp(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function Ep(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function qp(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function Cn(r,e,t){if(le.isStringLiteral(r)||le.isNoSubstitutionTemplateLiteral(r))return r.text;if(le.isParenthesizedExpression(r))return Cn(r.expression,e,t);if(le.isIdentifier(r))return t?.variables?.[r.text];if(le.isBinaryExpression(r)&&r.operatorToken.kind===le.SyntaxKind.PlusToken){let n=Cn(r.left,e,t),s=Cn(r.right,e,t);if(n!==void 0&&s!==void 0)return`${n}${s}`}if(le.isBinaryExpression(r)&&(r.operatorToken.kind===le.SyntaxKind.BarBarToken||r.operatorToken.kind===le.SyntaxKind.QuestionQuestionToken))return Cn(r.left,e,t)??Cn(r.right,e,t);if(le.isPropertyAccessExpression(r)){let n=r.getText(e);if(n.startsWith("process.env.")){let s=n.substring(12);return t?.env?.[s]}}}function Xg(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=Cn(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?qp(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function ey(r){if(!r)return{};let e=[".env",".env.local",".env.development",".env.production"],t={};for(let n of e){let s=`${r}/${n}`;try{let i=require("fs").readFileSync(s,"utf-8");for(let o of i.split(/\r?\n/)){let a=o.trim();if(!a||a.startsWith("#"))continue;let c=a.indexOf("=");if(c<=0)continue;let l=a.slice(0,c).trim(),u=a.slice(c+1).trim().replace(/^['"]|['"]$/g,"");t[l]=u}}catch{continue}}return t}var le,aa=E(()=>{"use strict";le=T(require("typescript"))});function Ap(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function ty(r,e){if(r.length<=2)return[];let t=[];for(let n of r.slice(1,-1))t.push({name:n.getText(e)});return t}function ny(r){let e=new Map;for(let s of r){let i=e.get(s.parent)??[];i.push(s),e.set(s.parent,i)}let t=new Map;t.set("app",[{pathExpression:"",resolvedPath:"",confidence:"high",middlewareNodes:[]}]);let n=["app"];for(;n.length>0;){let s=n.shift(),i=t.get(s)??[],o=e.get(s)??[];for(let a of o){let c=t.get(a.child)??[],l=!1;for(let u of i){let d=tn(u.pathExpression,a.prefix.pathExpression),p=Yt(u.confidence,a.prefix.confidence),m={pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&a.prefix.resolvedPath?d.resolvedPath:void 0,confidence:p,middlewareNodes:[...u.middlewareNodes,...a.middlewareNodes]};c.some(f=>f.pathExpression===m.pathExpression&&f.resolvedPath===m.resolvedPath)||(c.push(m),l=!0)}l&&(t.set(a.child,c),n.push(a.child))}}return t}function ry(r){return ie.isStringLiteral(r)||ie.isNoSubstitutionTemplateLiteral(r)||ie.isTemplateExpression(r)}function sy(r){if(ie.isStringLiteral(r)||ie.isNoSubstitutionTemplateLiteral(r))return r.text}function iy(r,e,t,n){let s=new Set(Xt(n).map(a=>a.name));if(s.size===0)return[];let i=oy(r,e),o=[];for(let a of i){let c=t.get(a)??[];for(let l of c)s.has(l.paramName)&&o.push(l.node)}return o}function oy(r,e){let t=new Map;for(let o of e){let a=t.get(o.child)??[];a.push(o.parent),t.set(o.child,a)}let n=[],s=new Set,i=o=>{if(!s.has(o)){s.add(o);for(let a of t.get(o)??[])i(a);n.push(o)}};return i(r),n}var ie,ps,Pp=E(()=>{"use strict";ie=T(require("typescript"));aa();oa();ps=class{async analyzeFile(e,t,n,s){let i=ie.createSourceFile(e,t,ie.ScriptTarget.Latest,!0,e.endsWith(".ts")?ie.ScriptKind.TS:ie.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,d=ds(i,n.projectRoot,s.envOverrides),p=g=>{if(ie.isVariableDeclaration(g)&&ie.isIdentifier(g.name)&&g.initializer){let y=g.initializer.getText(i);(/express\.Router\s*\(/.test(y)||/Router\s*\(/.test(y)||/express\(\)/.test(y))&&o.add(g.name.text)}ie.forEachChild(g,p)};p(i);let m=g=>{if(ie.isCallExpression(g)&&ie.isPropertyAccessExpression(g.expression)){let y=g.expression.expression.getText(i),v=g.expression.name.text;if(v==="use"&&g.arguments.length>=1&&o.has(y)){let b=g.arguments[g.arguments.length-1];if(g.arguments.length>=2&&ie.isIdentifier(b)&&o.has(b.text)&&ie.isIdentifier(b)){let R=Ct(g.arguments[0],i,d);a.push({parent:y,child:b.text,prefix:R,middlewareNodes:g.arguments.slice(1,-1)})}else{let R=ry(g.arguments[0])?g.arguments.slice(1):g.arguments.slice(0),A=l.get(y)??[];A.push(...R),l.set(y,A)}}if(v==="param"&&g.arguments.length>=2&&o.has(y)){let b=sy(g.arguments[0]),C=g.arguments[1];if(b&&C&&ie.isExpression(C)){let R=u.get(y)??[];R.push({paramName:b,node:C}),u.set(y,R)}}let w=Ap(v);if(w&&o.has(y)&&g.arguments.length>=1){let b=Ct(g.arguments[0],i,d),C=ty(g.arguments,i),R=g.arguments[g.arguments.length-1],A=i.getLineAndCharacterOfPosition(R.getStart(i));c.push({owner:y,method:w,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:C,middlewareNodes:g.arguments.slice(1,-1),handlerNode:R,source:{filePath:e,line:A.line+1,column:A.character+1,symbolName:R.getText(i)}})}if(v==="route"&&g.arguments[0]){let b=Ct(g.arguments[0],i,d),C=g.parent;if(ie.isCallExpression(C)&&ie.isPropertyAccessExpression(C.expression)){let R=Ap(C.expression.name.text);if(R){let A=C.arguments[0]??g.arguments[0],N=i.getLineAndCharacterOfPosition(A.getStart(i));c.push({owner:y,method:R,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:[],middlewareNodes:[],handlerNode:A,source:{filePath:e,line:N.line+1,column:N.character+1,symbolName:A.getText(i)}})}}}}ie.forEachChild(g,m)};m(i);let f=[],h=ny(a);for(let g of c){let y=h.get(g.owner)??[],v=y.length>0?y:[{pathExpression:"",confidence:"high",middlewareNodes:[]}];for(let w of v){let b=tn(w.pathExpression,g.pathExpression),C=Yt(w.confidence,g.confidence),R=!!b.resolvedPath,A=Xt(b.pathExpression),N=l.get(g.owner)??[],M=iy(g.owner,a,u,b.pathExpression),j=[...w.middlewareNodes,...N,...M,...g.middlewareNodes,g.handlerNode],U=us(j,i,e,g.method,s.contextProperties);U.parameters.unshift(...A),U.parameters=en(U.parameters),f.push({id:"",method:g.method,framework:"express",pathExpression:b.pathExpression,resolvedPath:C==="high"&&R?b.resolvedPath:void 0,confidence:C,source:g.source,middleware:g.middleware,params:U.parameters.length>0?U.parameters:void 0,requestBody:U.requestBody,cookies:U.cookies.length>0?U.cookies:void 0,responses:U.responses})}}return f}}});function ay(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=cy(a,e,i),l=c?n.map(u=>{let d=tn(u.pathExpression,c.pathExpression);return{pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?d.resolvedPath:void 0,confidence:Yt(u.confidence,c.confidence)}}):n;if(F.isArrowFunction(o)||F.isFunctionExpression(o)){let u=new Set(t),d=o.parameters[0];d&&F.isIdentifier(d.name)&&u.add(d.name.text),o.body&&F.forEachChild(o.body,p=>s(p,u,l))}}function cy(r,e,t){if(!r||!F.isObjectLiteralExpression(r))return;let n=Ae(r,"prefix");if(!n)return;let s=Ct(n,e,t);return{pathExpression:s.pathExpression,resolvedPath:s.resolvedPath,confidence:s.confidence}}function ly(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function Ae(r,e){for(let t of r.properties){if(!F.isPropertyAssignment(t))continue;if((F.isIdentifier(t.name)||F.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function uy(r,e){return r?F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:F.isArrayLiteralExpression(r)?r.elements.map(t=>F.isStringLiteral(t)||F.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function kp(r,e){return r?F.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function Ip(r){return r?F.isArrayLiteralExpression(r)?r.elements.filter(e=>F.isExpression(e)):[r]:[]}function dy(r){if(r&&(F.isArrowFunction(r)||F.isFunctionExpression(r))&&r.parameters[0]&&F.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function py(r,e){if(!r||!F.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function fy(r,e,t){let n=[],s=new Set,i=r;for(;i&&!s.has(i);)s.add(i),n.unshift(i),i=t.get(i);let o=[];for(let a of n){let c=e.get(a)??[];o.push(...c)}return o}function my(r,e){return e?{parameters:en([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function Tp(r,e,t){if(!r||!F.isObjectLiteralExpression(r))return;let n=[],s=Ae(r,"params");s&&n.push(...qi(s,"path",""));let i=Ae(r,"querystring")??Ae(r,"query");i&&n.push(...qi(i,"query",""));let o=Ae(r,"headers");o&&n.push(...qi(o,"header",""));let a=Ae(r,"body");a&&n.push(...qi(a,"body",""));let c=a?Op(a,e):void 0,l=a?{type:"json",required:["POST","PUT","PATCH"].includes(t),schema:c??{type:"object"}}:void 0;return{parameters:n,requestBody:l,cookies:[],responses:[]}}function Op(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if(F.isNumericLiteral(r))return{type:"number"};if(!F.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!F.isPropertyAssignment(n))continue;let s=n.name,i=F.isIdentifier(s)||F.isStringLiteral(s)||F.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=$p(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function $p(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return r.text;if(F.isNumericLiteral(r))return Number(r.text);if(r.kind===F.SyntaxKind.TrueKeyword||r.kind===F.SyntaxKind.FalseKeyword)return r.kind===F.SyntaxKind.TrueKeyword;if(r.kind===F.SyntaxKind.NullKeyword)return null;if(F.isArrayLiteralExpression(r)){let t=r.elements.map(n=>$p(n,e));return t.every(n=>n!==void 0)?t:void 0}if(F.isObjectLiteralExpression(r))return Op(r,e)}function qi(r,e,t){if(!F.isObjectLiteralExpression(r))return[];let n=Ae(r,"properties");if(!n||!F.isObjectLiteralExpression(n))return[];let s=Ae(r,"required"),i=new Set;if(s&&F.isArrayLiteralExpression(s))for(let a of s.elements)(F.isStringLiteral(a)||F.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!F.isPropertyAssignment(a))continue;let c=F.isIdentifier(a.name)||F.isStringLiteral(a.name)||F.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=hy(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...qi(a.initializer,e,l))}return o}function hy(r){if(!F.isObjectLiteralExpression(r))return;let e=Ae(r,"type");if(e&&(F.isStringLiteral(e)||F.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=Ae(r,"properties");if(t&&F.isObjectLiteralExpression(t))return"object"}var F,fs,Fp=E(()=>{"use strict";F=T(require("typescript"));aa();oa();fs=class{async analyzeFile(e,t,n,s){let i=F.createSourceFile(e,t,F.ScriptTarget.Latest,!0,e.endsWith(".ts")?F.ScriptKind.TS:F.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,d=ds(i,n.projectRoot,s.envOverrides),p=(f,h,g)=>{if(F.isVariableDeclaration(f)&&F.isIdentifier(f.name)&&f.initializer){let y=f.initializer.getText(i);(y.includes("fastify(")||y.includes("Fastify("))&&h.add(f.name.text)}if(F.isCallExpression(f)&&F.isPropertyAccessExpression(f.expression)){let y=f.expression.expression.getText(i),v=f.expression.name.text;if(v==="register"){let b=dy(f.arguments[0]);b&&u.set(b,y),ay(f,i,h,g,p,d)}if(v==="addHook"&&h.has(y)&&f.arguments.length>=2&&py(f.arguments[0],i)){let b=l.get(y)??[];b.push(f.arguments[1]),l.set(y,b)}let w=ly(v);if(w&&h.has(y)&&f.arguments[0]){let b=Ct(f.arguments[0],i,d),C=f.arguments.length>=2&&F.isObjectLiteralExpression(f.arguments[1])?f.arguments[1]:void 0,R=C&&f.arguments[2]?f.arguments[2]:f.arguments[f.arguments.length-1],A=i.getLineAndCharacterOfPosition(R.getStart(i)),N=C?Ae(C,"preHandler"):void 0,M=kp(N,i),j=Ip(N),U=C?Tp(Ae(C,"schema"),i,w):void 0;for(let O of g){let L=tn(O.pathExpression,b.pathExpression),Q=Yt(O.confidence,b.confidence),Y=!!L.resolvedPath;c.push({owner:y,method:w,pathExpression:L.pathExpression,resolvedPath:Q==="high"&&Y?L.resolvedPath:void 0,confidence:Q,handlerNode:R,middlewareNodes:j,schemaMetadata:U,source:{filePath:e,line:A.line+1,column:A.character+1,symbolName:R.getText(i)},middleware:M})}}if(v==="route"&&h.has(y)&&f.arguments[0]&&F.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],C=Ae(b,"method"),R=Ae(b,"url")??Ae(b,"path"),A=Ae(b,"handler"),N=Ae(b,"preHandler"),M=Ae(b,"schema"),j=Ct(R,i,d),U=uy(C,i),O=kp(N,i);for(let L of U){let Q=A?i.getLineAndCharacterOfPosition(A.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let Y of g){let Je=tn(Y.pathExpression,j.pathExpression),an=Yt(Y.confidence,j.confidence),kt=!!Je.resolvedPath;c.push({owner:y,method:L,pathExpression:Je.pathExpression,resolvedPath:an==="high"&&kt?Je.resolvedPath:void 0,confidence:an,handlerNode:A??b,middlewareNodes:Ip(N),schemaMetadata:Tp(M,i,L),source:{filePath:e,line:Q.line+1,column:Q.character+1,symbolName:A?.getText(i)},middleware:O})}}}}F.forEachChild(f,y=>p(y,h,g))};p(i,o,a);let m=[];for(let f of c){let h=Xt(f.pathExpression),y=[...fy(f.owner,l,u),...f.middlewareNodes,f.handlerNode],v=us(y,i,e,f.method,s.contextProperties);v.parameters.unshift(...h),v.parameters=en(v.parameters);let w=my(v,f.schemaMetadata);m.push({id:"",method:f.method,framework:"fastify",pathExpression:f.pathExpression,resolvedPath:f.resolvedPath,confidence:f.confidence,source:f.source,middleware:f.middleware,params:w.parameters.length>0?w.parameters:void 0,requestBody:w.requestBody,cookies:w.cookies.length>0?w.cookies:void 0,responses:w.responses})}return m}}});function gy(r,e){D.forEachChild(r,t=>yy(t,r,e))}function yy(r,e,t){if(D.isExpressionStatement(r)&&D.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===D.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(D.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&ca(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Bl(s,e);t.push({exportName:o,handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:o}});return}if(i==="module"&&o==="exports"&&ca(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Bl(s,e);t.push({exportName:"handler",handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:"handler"}});return}}}if(D.isVariableStatement(r)&&Np(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!D.isIdentifier(n.name)||!n.initializer)&&ca(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=Bl(n.initializer,e);t.push({exportName:s,handlerNode:o,middlewareNodes:a,location:{filePath:e.fileName,line:i.line+1,column:i.character+1,symbolName:s}})}return}if(D.isFunctionDeclaration(r)&&Np(r)&&r.name&&vy(r)){let n=r.name.text,s=e.getLineAndCharacterOfPosition(r.getStart(e));t.push({exportName:n,handlerNode:r,middlewareNodes:[],location:{filePath:e.fileName,line:s.line+1,column:s.character+1,symbolName:n}})}}function ca(r,e){if(D.isArrowFunction(r)||D.isFunctionExpression(r))return by(r);if(D.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(D.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return ca(r.expression.expression,e)}return D.isIdentifier(r)?/handler/i.test(r.text):!1}function vy(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function by(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Np(r){return(D.getCombinedModifierFlags(r)&D.ModifierFlags.Export)!==0}function Bl(r,e){let t=[],n=r;for(;D.isCallExpression(n)&&D.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return D.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function Sy(r,e,t){return r.map(n=>{let s=xy(n,e),i=e.getLineAndCharacterOfPosition(n.getStart(e));return{name:s,location:{filePath:t,line:i.line+1,column:i.character+1,symbolName:s}}})}function xy(r,e){return D.isIdentifier(r)?r.text:D.isCallExpression(r)&&D.isIdentifier(r.expression)?r.expression.text:D.isCallExpression(r)&&D.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function Ry(r,e,t){let n=Cy(r);if(!n)return[];let s=new Map,i=o=>{if(D.isPropertyAccessExpression(o)||D.isElementAccessExpression(o)){let a=Ai(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=wy[c];if(l==="body"){let u="body::body";if(!s.has(u)){let d=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(u,{name:"body",location:"body",detectionLocation:{filePath:t,line:d.line+1,column:d.character+1}})}}else if(l&&a.length>=3){let u=a[2],d=`${l}::${u}`;if(!s.has(d)){let p=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(d,{name:u,location:l,detectionLocation:{filePath:t,line:p.line+1,column:p.character+1}})}}}}if(D.isCallExpression(o)&&D.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Ai(a,e);if(c.length===2&&c[0]===n&&c[1]==="body"){let l="body::body";if(!s.has(l)){let u=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(l,{name:"body",location:"body",type:"json",detectionLocation:{filePath:t,line:u.line+1,column:u.character+1}})}}}D.forEachChild(o,i)};return i(r),Array.from(s.values())}function Cy(r){if(D.isArrowFunction(r)||D.isFunctionExpression(r)||D.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&D.isIdentifier(e.name))return e.name.text}return D.isIdentifier(r),"event"}function Ai(r,e){return D.isIdentifier(r)?[r.text]:D.isPropertyAccessExpression(r)?[...Ai(r.expression,e),r.name.text]:r.kind===D.SyntaxKind.PropertyAccessExpression||D.isNonNullExpression(r)?Ai(r.expression,e):D.isElementAccessExpression(r)&&D.isStringLiteral(r.argumentExpression)?[...Ai(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var D,ms,wy,Ul=E(()=>{"use strict";D=T(require("typescript")),ms=class{async analyzeFile(e,t,n,s){let i=D.createSourceFile(e,t,D.ScriptTarget.Latest,!0,e.endsWith(".ts")?D.ScriptKind.TS:D.ScriptKind.JS),o=[];return gy(i,o),o.length===0?[]:o.map(a=>{let c=Ry(a.handlerNode,i,e),l=Sy(a.middlewareNodes,i,e);return{id:"",method:"ANY",framework:"lambda",pathExpression:"<unknown-lambda>",resolvedPath:void 0,confidence:"low",source:a.location,middleware:l,params:c.length>0?c:void 0}})}};wy={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var hs=E(()=>{"use strict";oa();Pp();Fp();Ul()});function _p(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Ey(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"express",filePath:t.source.filePath,message:`Express route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"express",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var la,or,Vl=E(()=>{"use strict";la=T(require("fs"));hs();Rn();or=class{id="provider.express";framework="express";analyzer=new ps;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(_p(t)===_p(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.express?{supported:!0,confidence:.95,reasons:["express dependency detected"]}:{supported:!1,confidence:0,reasons:["express dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=la.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=la.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Ey(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["express"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function Mp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function qy(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"fastify",filePath:t.source.filePath,message:`Fastify route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"fastify",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var ua,ar,zl=E(()=>{"use strict";ua=T(require("fs"));hs();Rn();ar=class{id="provider.fastify";framework="fastify";analyzer=new fs;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Mp(t)===Mp(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.fastify?{supported:!0,confidence:.95,reasons:["fastify dependency detected"]}:{supported:!1,confidence:0,reasons:["fastify dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=ua.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=ua.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=qy(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["fastify"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function Dp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Jl(r,e){let t=r.expression;if(pe.isCallExpression(t))return pe.isIdentifier(t.expression)?t.expression.text:t.expression.getText(e);if(pe.isIdentifier(t))return t.text}function jp(r){let e=r.expression;if(pe.isCallExpression(e))return e.arguments[0]}function Ay(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function Lp(r){return pe.canHaveDecorators(r)?pe.getDecorators(r)??[]:[]}function Hp(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=Jl(s,e);if(!i||!t.has(i))continue;let o=s.expression;if(!pe.isCallExpression(o)){n.push({name:i});continue}for(let a of o.arguments)n.push({name:`${i}:${a.getText(e)}`})}return n}function Py(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var da,pe,cr,Gl=E(()=>{"use strict";da=T(require("fs")),pe=T(require("typescript"));aa();Rn();cr=class{id="provider.nestjs";framework="nestjs";fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Dp(t)===Dp(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}["@nestjs/common"]?{supported:!0,confidence:.98,reasons:["@nestjs/common dependency detected"]}:{supported:!1,confidence:0,reasons:["@nestjs/common dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=da.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(g=>structuredClone(g))),s.push(...l.warnings.map(g=>({...g})));continue}let u="";try{u=da.readFileSync(a,"utf-8")}catch{continue}let d=[],p=[],m=pe.createSourceFile(a,u,pe.ScriptTarget.Latest,!0,a.endsWith(".ts")?pe.ScriptKind.TS:pe.ScriptKind.JS),f=ds(m,t.projectRoot,e.envOverrides),h=g=>{if(pe.isClassDeclaration(g)){let y=Lp(g),v=y.find(w=>Jl(w,m)==="Controller");if(v){let w=Ct(jp(v),m,f),b=Hp(y,m);for(let C of g.members){if(!pe.isMethodDeclaration(C))continue;let R=Lp(C),A=R.map(N=>({decorator:N,name:Jl(N,m)})).filter(N=>!!N.name);for(let N of A){let M=Ay(N.name);if(!M)continue;let j=Ct(jp(N.decorator),m,f),U=tn(w.pathExpression,j.pathExpression),O=Hp(R,m),L=C.name?.getText(m),Q=C.name??C,Y=m.getLineAndCharacterOfPosition(Q.getStart(m)),Je=Py(w.confidence,j.confidence);p.push({id:"",method:M,framework:"nestjs",pathExpression:U.pathExpression,resolvedPath:Je==="high"?U.resolvedPath:void 0,confidence:Je,source:{filePath:a,line:Y.line+1,column:Y.character+1,symbolName:L},middleware:[...b,...O]}),Je!=="high"&&d.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${L??"unknown handler"} in ${a}`})}}}}pe.forEachChild(g,h)};h(m),i.push(...p),s.push(...d),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:p.map(g=>structuredClone(g)),warnings:d.map(g=>({...g}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["nestjs"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function ky(r,e,t){let n=[],s=r.functions;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o,c=a.handler;if(!c||typeof c!="string")continue;let{filePath:l,exportName:u}=Vp(c,e),d=zp(l,e);d||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for function '${i}': ${c}`});let p=a.events;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let f=m.http;if(!f||typeof f!="object")continue;let h=f.path,g=f.method;if(!h||!g)continue;let y=Jp(h),v=[];if(f.authorizer){let w=typeof f.authorizer=="string"?f.authorizer:"authorizer";v.push({name:w})}n.push({id:"",method:g.toUpperCase(),framework:"lambda",pathExpression:y,resolvedPath:y,confidence:"high",source:{filePath:d??l,line:1,column:1,symbolName:u},middleware:v})}}return n}function Bp(r,e,t){let n=[],s=r.Resources;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o;if(a.Type!=="AWS::Serverless::Function")continue;let c=a.Properties;if(!c)continue;let l=c.Handler;if(!l||typeof l!="string")continue;let{filePath:u,exportName:d}=Vp(l,e),p=zp(u,e);p||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for SAM resource '${i}': ${l}`});let m=c.Events;if(!(!m||typeof m!="object"))for(let[,f]of Object.entries(m)){if(!f||typeof f!="object")continue;let h=f;if(h.Type!=="Api"&&h.Type!=="HttpApi")continue;let g=h.Properties;if(!g)continue;let y=g.Path,v=g.Method;if(!y||!v)continue;let w=Jp(y),b=g.Auth,C=[];b?.Authorizer&&C.push({name:String(b.Authorizer)}),n.push({id:"",method:v.toUpperCase(),framework:"lambda",pathExpression:w,resolvedPath:w,confidence:"high",source:{filePath:p??u,line:1,column:1,symbolName:d},middleware:C})}}return n}function Vp(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function zp(r,e){let t=[pt.join(e,`${r}.ts`),pt.join(e,`${r}.js`),pt.join(e,r,"index.ts"),pt.join(e,r,"index.js")];for(let n of t)if(Me.existsSync(n))return n}function Jp(r){return r.startsWith("/")?r:`/${r}`}function Kl(r){let e=r.split(`
469
+ `);return Pi(e,0,-1).value}function Pi(r,e,t){let n={},s=[],i=!1,o=e;for(;o<r.length;){let a=r[o],c=a.trimEnd();if(c.trim()===""||c.trimStart().startsWith("#")){o++;continue}let l=Iy(a);if(l<=t)break;let u=c.trimStart();if(u.startsWith("- ")){i=!0;let f=u.slice(2).trim();if(f===""||f.endsWith(":"))if(f.endsWith(":")){let h=f.slice(0,-1).trim(),g=Pi(r,o+1,l),y={};y[h]=g.value,s.push(y),o=g.nextLine}else{let h=Pi(r,o+1,l);s.push(h.value),o=h.nextLine}else if(f.includes(": ")||f.endsWith(":")){let h={},g=f.indexOf(":"),y=f.slice(0,g).trim(),v=f.slice(g+1).trim();if(v===""){let w=Pi(r,o+1,l);h[y]=w.value,s.push(h),o=w.nextLine}else h[y]=Wl(v),s.push(h),o++}else s.push(Wl(f)),o++;continue}let d=u.indexOf(":");if(d===-1){o++;continue}let p=u.slice(0,d).trim(),m=u.slice(d+1).trim();if(m===""||m.startsWith("#")){let f=Pi(r,o+1,l);n[p]=f.value,o=f.nextLine}else n[p]=Wl(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function Iy(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function Wl(r){let e=r.indexOf(" #"),t=e!==-1?r.slice(0,e).trim():r.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t==="true"?!0:t==="false"?!1:t==="null"||t==="~"?null:/^-?\d+(\.\d+)?$/.test(t)?Number(t):t}function Ty(r){return Kl(r)}function Up(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Me,pt,lr,Ql=E(()=>{"use strict";Me=T(require("fs")),pt=T(require("path"));Ul();Rn();lr=class{id="provider.lambda";framework="lambda";analyzer=new ms;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Up(t)===Up(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){let t={...e.packageJson?.dependencies,...e.packageJson?.devDependencies};if(t.express||t.fastify)return{supported:!1,confidence:0,reasons:["express or fastify detected \u2014 deferring to existing provider"]};let n=!!(t["@types/aws-lambda"]||t["aws-lambda"]||t.serverless),s=Me.existsSync(pt.join(e.projectRoot,"serverless.yml"))||Me.existsSync(pt.join(e.projectRoot,"serverless.yaml"))||Me.existsSync(pt.join(e.projectRoot,"template.yaml"))||Me.existsSync(pt.join(e.projectRoot,"template.json"));return n?{supported:!0,confidence:.95,reasons:["lambda-related dependency detected"]}:s?{supported:!0,confidence:.75,reasons:["serverless/SAM config file detected"]}:{supported:!1,confidence:0,reasons:["no lambda indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.projectRoot;for(let a of["serverless.yml","serverless.yaml"]){let c=pt.join(o,a);if(Me.existsSync(c)){try{let l=Me.readFileSync(c,"utf-8"),u=Ty(l),d=ky(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse Serverless Framework config: ${c}`})}break}}if(i.length===0){let a=pt.join(o,"template.yaml"),c=pt.join(o,"template.json");if(Me.existsSync(c))try{let l=Me.readFileSync(c,"utf-8"),u=JSON.parse(l),d=Bp(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse SAM template: ${c}`})}else if(Me.existsSync(a))try{let l=Me.readFileSync(a,"utf-8"),u=Kl(l),d=Bp(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:a,message:`Failed to parse SAM template: ${a}`})}}if(i.length===0){let a=t.sourceFiles??nt(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=Me.statSync(c)}catch{continue}let u=this.fileCache.get(c);if(u&&u.mtimeMs===l.mtimeMs&&u.size===l.size){i.push(...u.endpoints.map(f=>structuredClone(f))),s.push(...u.warnings.map(f=>({...f})));continue}let d="";try{d=Me.readFileSync(c,"utf-8")}catch{continue}let p=await this.analyzer.analyzeFile(c,d,t,e),m=p.map(f=>({code:"seed-endpoint-unmatched",framework:"lambda",filePath:f.source.filePath,message:`Lambda handler '${f.source.symbolName}' found without a config-file route definition. Path is unknown.`}));i.push(...p),s.push(...m),this.fileCache.set(c,{mtimeMs:l.mtimeMs,size:l.size,endpoints:p.map(f=>structuredClone(f)),warnings:m.map(f=>({...f}))})}}return{endpoints:i,warnings:s,stats:{frameworksDetected:["lambda"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});function $y(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=pa.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=Wp.join(s,o.name);o.isDirectory()?Oy.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function ki(r){return $y(r,/\.java$/)}function Ii(r){return pa.promises.readFile(r,"utf-8")}function Zl(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function Yl(r){return r.replace(/\\/g,"/").split("/").pop()||""}function Kp(r,e){let t=Gp.get(e);if(t&&Date.now()-t.ts<Fy)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=ki(r).filter(i=>n.test(Yl(i)));return Gp.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var pa,Wp,Oy,Gp,Fy,fa=E(()=>{"use strict";pa=T(require("fs")),Wp=T(require("path")),Oy=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);Gp=new Map,Fy=3e4});function Ny(r){if(r.includes("/"))return r;if(nn[r])return nn[r];let e=`MediaType.${r}`;if(nn[e])return nn[e];for(let[s,i]of Object.entries(nn))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(nn[i])return nn[i];let o=`MediaType.${s}_VALUE`;if(nn[o])return nn[o]}let n=r.toUpperCase();return n.includes("JSON")?"application/json":n.includes("XML")&&!n.includes("HTML")?"application/xml":n.includes("FORM_URLENCODED")?"application/x-www-form-urlencoded":n.includes("MULTIPART")?"multipart/form-data":n.includes("TEXT_PLAIN")||n.includes("PLAIN_TEXT")?"text/plain":n.includes("OCTET_STREAM")?"application/octet-stream":r}function Ti(r){return r.map(Ny)}function rn(r){if(!r)return r;let e=/^([A-Za-z0-9_]+)<(.+)>$/.exec(r);if(!e)return r;let t=e[1],n=e[2];return _y.has(t)?rn(n.trim()):r}function gs(r){return/MultipartFile/.test(r)}var nn,_y,ma=E(()=>{"use strict";nn={"MediaType.ALL_VALUE":"*/*","MediaType.APPLICATION_ATOM_XML_VALUE":"application/atom+xml","MediaType.APPLICATION_CBOR_VALUE":"application/cbor","MediaType.APPLICATION_FORM_URLENCODED_VALUE":"application/x-www-form-urlencoded","MediaType.APPLICATION_GRAPHQL_VALUE":"application/graphql","MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE":"application/graphql-response+json","MediaType.APPLICATION_JSON_VALUE":"application/json","MediaType.APPLICATION_JSON_UTF8_VALUE":"application/json;charset=UTF-8","MediaType.APPLICATION_NDJSON_VALUE":"application/x-ndjson","MediaType.APPLICATION_OCTET_STREAM_VALUE":"application/octet-stream","MediaType.APPLICATION_PDF_VALUE":"application/pdf","MediaType.APPLICATION_PROBLEM_JSON_VALUE":"application/problem+json","MediaType.APPLICATION_PROBLEM_XML_VALUE":"application/problem+xml","MediaType.APPLICATION_PROTOBUF_VALUE":"application/x-protobuf","MediaType.APPLICATION_RSS_XML_VALUE":"application/rss+xml","MediaType.APPLICATION_STREAM_JSON_VALUE":"application/stream+json","MediaType.APPLICATION_XHTML_XML_VALUE":"application/xhtml+xml","MediaType.APPLICATION_XML_VALUE":"application/xml","MediaType.APPLICATION_YAML_VALUE":"application/yaml","MediaType.IMAGE_GIF_VALUE":"image/gif","MediaType.IMAGE_JPEG_VALUE":"image/jpeg","MediaType.IMAGE_PNG_VALUE":"image/png","MediaType.MULTIPART_FORM_DATA_VALUE":"multipart/form-data","MediaType.MULTIPART_MIXED_VALUE":"multipart/mixed","MediaType.MULTIPART_RELATED_VALUE":"multipart/related","MediaType.TEXT_EVENT_STREAM_VALUE":"text/event-stream","MediaType.TEXT_HTML_VALUE":"text/html","MediaType.TEXT_MARKDOWN_VALUE":"text/markdown","MediaType.TEXT_PLAIN_VALUE":"text/plain","MediaType.TEXT_XML_VALUE":"text/xml"};_y=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var ur,Qp=E(()=>{"use strict";fa();ma();ur=class{constructor(e){this.projectRoot=e}projectRoot;cache=new Map;clearCache(){this.cache.clear()}async generate(e){if(!e)return;let t=this.primitiveSchema(e);if(t)return t;let n=e,s=[],i=/^([^<]+)<(.+)>$/.exec(e);i&&(n=i[1].trim(),s=this.splitGenericArgs(i[2]));let o=n.split("."),a=o.pop(),c=o.length?o.join("."):void 0;if(this.cache.has(e))return this.cache.get(e);let l={type:"object",properties:{},required:[]};this.cache.set(e,l);let u=await Kp(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await Ii(f),g=m.exec(h);if(g&&g[1]===c){u=[f];break}}}if(u.length===0){if(s.length>0){let m=await this.generate(s[0]);if(m&&m.properties&&Object.keys(m.properties).length>0)return Object.assign(l,m),l}return{type:"object"}}let d=await Ii(u[0]),p=this.buildTypeParamMap(d,a,s);return await this.parseClassToSchema(d,a,l,p),l.required&&l.required.length===0&&delete l.required,l}async generateResponseSchema(e){if(!e||e==="void")return;let t=rn(e);if(t==="void")return;let n=/(List|Set|Collection)<([^>]+)>/.exec(t);if(n){let s=n[2].trim();return{type:"array",items:await this.generate(s)||{type:"object"}}}if(t.endsWith("[]")){let s=t.replace(/\[\]$/,"");return{type:"array",items:await this.generate(s)||{type:"object"}}}return this.generate(t)}async parseClassToSchema(e,t,n,s){let i=this.extractFieldsRegex(e,t);for(let o of i){s&&s.size>0&&(o.javaType=this.resolveTypeParams(o.javaType,s));let a=await this.fieldToSchema(o),c=o.jsonPropertyName||o.name;n.properties[c]=a,o.required&&n.required.push(c)}}buildTypeParamMap(e,t,n){let s=new Map;if(n.length===0)return s;let i=new RegExp(`class\\s+${t}\\s*<([^{]+?)>\\s*(?:extends|implements|\\{)`).exec(e);return i&&this.splitGenericArgs(i[1]).map(a=>a.trim().split(/\s+/)[0]).forEach((a,c)=>{c<n.length&&s.set(a,n[c])}),s}splitGenericArgs(e){let t=[],n=0,s="";for(let i of e)i==="<"?(n++,s+=i):i===">"?(n--,s+=i):i===","&&n===0?(t.push(s.trim()),s=""):s+=i;return s.trim()&&t.push(s.trim()),t}resolveTypeParams(e,t){let n=e;for(let[s,i]of t)n=n.replace(new RegExp(`\\b${s}\\b`,"g"),i);return n}extractFieldsRegex(e,t){let n=[],s=e.split(/\r?\n/),i=!1,o=0,a=e.search(new RegExp(`class\\s+${t}\\b`)),c=a>=0?e.substring(Math.max(0,a-500),a):"",l=/@(?:lombok\.)?(?:Data|Getter|Value)\b/.test(c),u=/public\s+\S+\s+(?:get|is)[A-Z]\w*\s*\(/.test(e),d=[];for(let p of s){let m=p.trim();if(!i){new RegExp(`class\\s+${t}\\b`).test(m)&&(i=!0,o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length);continue}let f=o;if(o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length,o<=0)break;if(f>1)continue;if(/^@(\w+)/.exec(m)&&!/(?:private|public|protected)\s/.test(m)&&!m.includes(";")){d.push(m);continue}if(/^public\s+\S+\s+(get|is|set)[A-Z]\w*\s*\(/.test(m)){d=[];continue}let g=/(?:(private|public|protected)\s+)?([A-Za-z0-9_<>,\s\[\]?]+?)\s+([A-Za-z0-9_]+)\s*(?:=.*)?;/.exec(m);if(g){let y=g[2].replace(/\b(final)\b/g,"").trim().replace(/@\w+\s*/g,"").trim(),v=g[3],w=g[1]||"";if(y&&v&&!/^(class|interface|enum|return|if|for|while|void)\b/.test(y)){let b=/\bstatic\b/.test(m),C=/\btransient\b/.test(m),R=[...d,m],A=R.join(" ");!b&&!C&&!/@JsonIgnore\b/.test(A)&&(w==="public"||l||u||/@JsonProperty\b/.test(A))&&n.push(this.parseFieldAnnotations(v,y,R))}}d=[]}return n}parseFieldAnnotations(e,t,n){let s=n.join(" "),i={name:e,javaType:t},o=/\bvalue\s*=\s*"([^"]*)"/.exec(s.match(/@JsonProperty\([^)]*\)/)?.[0]||"")||/@JsonProperty\(\s*"([^"]*)"/.exec(s);o&&o[1]&&(i.jsonPropertyName=o[1]),i.description=this.extractAttr(s,"Schema","description"),i.example=this.extractAttr(s,"Schema","example");let a=this.extractAttr(s,"Schema","type");a&&(i.schemaTypeOverride=a);let c=this.extractAttr(s,"Schema","format");c&&(i.format=c),this.extractAttr(s,"Schema","nullable")==="true"&&(i.nullable=!0),this.extractAttr(s,"Schema","readOnly")==="true"&&(i.readOnly=!0),this.extractAttr(s,"Schema","writeOnly")==="true"&&(i.writeOnly=!0),this.extractAttr(s,"Schema","deprecated")==="true"&&(i.deprecated=!0);let m=this.extractAttr(s,"Schema","title");m&&(i.title=m);let f=this.extractAttr(s,"Schema","defaultValue");f&&(i.defaultValue=f);let h=/allowableValues\s*=\s*\{([^}]*)\}/.exec(s);h&&(i.enumValues=h[1].split(",").map(O=>O.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean));let g=this.extractAttr(s,"Schema","minimum");g&&(i.minimum=Number(g));let y=this.extractAttr(s,"Schema","maximum");y&&(i.maximum=Number(y));let v=this.extractAttr(s,"Schema","minLength");v&&(i.minLength=Number(v));let w=this.extractAttr(s,"Schema","maxLength");w&&(i.maxLength=Number(w));let b=this.extractAttr(s,"Schema","pattern");b&&(i.pattern=b),i.description||(i.description=this.extractAttr(s,"ApiModelProperty","value")),i.example||(i.example=this.extractAttr(s,"ApiModelProperty","example")),(/@NotNull\b/.test(s)||/@NotBlank\b/.test(s)||/@NotEmpty\b/.test(s))&&(i.required=!0);let C=this.extractAttr(s,"Size","min");C&&!i.minLength&&(i.minLength=Number(C));let R=this.extractAttr(s,"Size","max");R&&!i.maxLength&&(i.maxLength=Number(R));let A=this.extractAttr(s,"Min","value")||this.extractSingleArg(s,"Min");A&&i.minimum===void 0&&(i.minimum=Number(A));let N=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");N&&i.maximum===void 0&&(i.maximum=Number(N));let M=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");M&&i.minimum===void 0&&(i.minimum=Number(M));let j=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");j&&i.maximum===void 0&&(i.maximum=Number(j)),/@Email\b/.test(s)&&(i.format=i.format||"email");let U=this.extractAttr(s,"Pattern","regexp");return U&&!i.pattern&&(i.pattern=U),/@PositiveOrZero\b/.test(s)&&i.minimum===void 0&&(i.minimum=0),/@Positive\b/.test(s)&&i.minimum===void 0&&(i.minimum=1),/@NegativeOrZero\b/.test(s)&&i.maximum===void 0&&(i.maximum=0),/@Negative\b/.test(s)&&i.maximum===void 0&&(i.maximum=-1),(/@Past\b/.test(s)||/@PastOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),(/@Future\b/.test(s)||/@FutureOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),i}async fieldToSchema(e){let t={};if(e.schemaTypeOverride?t.type=e.schemaTypeOverride:Object.assign(t,this.javaTypeToJsonSchema(e.javaType)),e.description&&(t.description=e.description),e.title&&(t.title=e.title),e.format&&(t.format=e.format),e.example!==void 0&&(t.example=this.coerceValue(e.example)),e.defaultValue!==void 0&&(t.default=this.coerceValue(e.defaultValue)),e.nullable&&(t.nullable=!0),e.readOnly&&(t.readOnly=!0),e.writeOnly&&(t.writeOnly=!0),e.deprecated&&(t.deprecated=!0),e.enumValues&&(t.enum=e.enumValues),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern),t.type==="object"&&!t.properties){let n=await this.generate(e.javaType);n&&n.properties&&(t.properties=n.properties,n.required&&(t.required=n.required))}if(t.type==="array"&&!t.items){let n=/(List|Set|Collection)<([^>]+)>/.exec(e.javaType);if(n){let s=n[2].trim(),i=this.primitiveSchema(s)||await this.generate(s);t.items=i||{type:"object"}}}return t}javaTypeToJsonSchema(e){if(/^(String|CharSequence|char|Character)$/.test(e))return{type:"string"};if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return{type:"integer",format:"int32"};if(/^(long|Long|BigInteger)$/.test(e))return{type:"integer",format:"int64"};if(/^(float|Float)$/.test(e))return{type:"number",format:"float"};if(/^(double|Double|BigDecimal)$/.test(e))return{type:"number",format:"double"};if(/^(boolean|Boolean)$/.test(e))return{type:"boolean"};if(/^(LocalDate)$/.test(e))return{type:"string",format:"date"};if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return{type:"string",format:"date-time"};if(/^(LocalTime|OffsetTime)$/.test(e))return{type:"string",format:"time"};if(/^UUID$/.test(e))return{type:"string",format:"uuid"};if(/^(URI|URL)$/.test(e))return{type:"string",format:"uri"};if(/^(byte\[\]|Byte\[\])$/.test(e))return{type:"string",format:"binary"};if(/^Map\b/.test(e))return{type:"object",additionalProperties:!0};if(/(List|Set|Collection)</.test(e))return{type:"array"};if(e.endsWith("[]")){let t=e.replace(/\[\]$/,"");return{type:"array",items:this.primitiveSchema(t)||{type:"object"}}}return{type:"object"}}primitiveSchema(e){let t=this.javaTypeToJsonSchema(e);if(t.type!=="object"||/^Map\b/.test(e))return t}static javaTypeToParamType(e){return/^(int|Integer|long|Long|short|Short|byte|Byte|BigInteger)$/.test(e)?"integer":/^(float|Float|double|Double|BigDecimal)$/.test(e)?"number":/^(boolean|Boolean)$/.test(e)?"boolean":/(List|Set|Collection)</.test(e)||e.endsWith("[]")?"array":"string"}static javaTypeToFormat(e){if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return"int32";if(/^(long|Long|BigInteger)$/.test(e))return"int64";if(/^(float|Float)$/.test(e))return"float";if(/^(double|Double|BigDecimal)$/.test(e))return"double";if(/^(LocalDate)$/.test(e))return"date";if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return"date-time";if(/^(LocalTime|OffsetTime)$/.test(e))return"time";if(/^UUID$/.test(e))return"uuid";if(/^(URI|URL)$/.test(e))return"uri"}extractAttr(e,t,n){let i=new RegExp(`@${t}\\b[^)]*\\b${n}\\s*=\\s*"([^"]*)"`,"s").exec(e);return i?i[1]:void 0}extractSingleArg(e,t){let s=new RegExp(`@${t}\\(\\s*([^")]+?)\\s*\\)`).exec(e);if(s&&!/=/.test(s[1]))return s[1].trim()}coerceValue(e){return/^-?\d+$/.test(e)?parseInt(e,10):/^-?\d+\.\d+$/.test(e)?parseFloat(e):e==="true"?!0:e==="false"?!1:e}}});function Xl(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var Zp,ha,Yp=E(()=>{"use strict";Zp=require("java-parser");ma();ha=class extends Zp.BaseJavaCstVisitorWithDefaults{controllers=[];contextStack=[];constructor(){super(),this.validateVisitor()}annotation(e){if(this.contextStack.length===0)return;let t=e.typeName[0].children.Identifier[0].image,n=new Map;if(e.elementValuePairList){let i=e.elementValuePairList[0].children.elementValuePair;for(let o of i){let a=o.children.Identifier[0].image,c=this.extractElementValue(o.children.elementValue[0]);c!==void 0&&n.set(a,c)}}else if(e.elementValue){let i=this.extractElementValue(e.elementValue[0]);i!==void 0&&n.set("value",i)}this.contextStack[this.contextStack.length-1].annotations.push({name:t,attributes:n}),this.visitNestedAnnotations(e)}visitNestedAnnotations(e){let t=[];if(e.elementValue&&t.push(e.elementValue[0]),e.elementValuePairList){let n=e.elementValuePairList[0].children.elementValuePair||[];for(let s of n)s.children.elementValue&&t.push(s.children.elementValue[0])}for(let n of t){if(n.children?.annotation)for(let i of n.children.annotation)this.annotation(i.children);let s=n.children?.elementValueArrayInitializer?.[0];if(s){let i=s.children?.elementValueList?.[0]?.children?.elementValue||[];for(let o of i)if(o.children?.annotation)for(let a of o.children.annotation)this.annotation(a.children)}}}typeIdentifier(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}classDeclaration(e){let t={type:"class",name:"",line:0,annotations:[],endpoints:[]};this.contextStack.push(t);for(let i of e.classModifier||[])this.visit(i);let n=t.annotations.find(i=>i.name==="RequestMapping");if(n){let i=n.attributes.get("value")||n.attributes.get("path");i&&typeof i=="string"&&(t.basePath=i.replace(/^['\"]|['\"]$/g,""))}for(let i of e.normalClassDeclaration||[])this.visit(i);if(this.contextStack.pop(),t.annotations.some(i=>i.name==="RestController"||i.name==="Controller")){let i={name:t.name,basePath:t.basePath||"",file:"",line:t.line,endpoints:t.endpoints};this.controllers.push(i)}}methodDeclarator(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}methodDeclaration(e){if(this.contextStack.length===0||this.contextStack[this.contextStack.length-1].type!=="class")return;let t=this.contextStack[this.contextStack.length-1],n={type:"method",name:"",line:0,annotations:[]};this.contextStack.push(n);for(let i of e.methodHeader||[])this.visit(i);for(let i of e.methodModifier||[])this.visit(i);this.contextStack.pop();let s=n.annotations.filter(i=>/Mapping$/.test(i.name));if(s.length!==0)for(let i of s){let o=this.buildEndpoint(i,n,e,t);o&&t.endpoints.push(o)}}collectTokens(e){if(!e)return[];if(e.image!==void 0)return[e];let t=[];if(e.children)for(let n of Object.keys(e.children))for(let s of e.children[n])t.push(...this.collectTokens(s));return t.sort((n,s)=>n.startOffset-s.startOffset),t}extractElementValue(e){if(!e)return;let t=e.children;if(t){if(t.annotation){let n=this.collectTokens(t.annotation[0]);if(n.length>0)return n.map(s=>s.image).join("")}if(t.elementValueArrayInitializer){let s=t.elementValueArrayInitializer[0].children?.elementValueList?.[0]?.children?.elementValue;return s?s.map(o=>{let a=this.extractElementValue(o);return Array.isArray(a)?a.join(","):a}).filter(o=>typeof o=="string"&&o.length>0):[]}if(t.conditionalExpression){let n=this.collectTokens(t.conditionalExpression[0]);return n.length===0?void 0:n.map(s=>s.image).join("")}}}buildEndpoint(e,t,n,s){let i=e.name.replace("Mapping","").toUpperCase();i==="REQUEST"&&(i="");let o="",a=[],c=[];for(let[m,f]of e.attributes.entries())if(m==="value"||m==="path")typeof f=="string"&&(o=f.replace(/^['\"]|['\"]$/g,""));else if(m==="consumes")Array.isArray(f)?a=Ti(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Ti([f.replace(/^['\"]|['\"]$/g,"")]));else if(m==="produces")Array.isArray(f)?c=f.map(h=>h.replace(/^['\"]|['\"]$/g,"")):typeof f=="string"&&(c=[f.replace(/^['\"]|['\"]$/g,"")]);else if(m==="method"&&e.name==="RequestMapping"&&typeof f=="string"){let h=f.match(/RequestMethod\.([A-Z]+)/);h&&(i=h[1])}!i&&e.name==="RequestMapping"&&(i="GET");let l=o;s.basePath&&(l&&!l.startsWith("/")?l=s.basePath+"/"+l:l=s.basePath+l),l&&!l.startsWith("/")&&(l="/"+l);let u=this.extractParameters(n),d=this.extractReturnType(n),p=this.extractOpenApiAnnotations(t.annotations,s.annotations);return{method:i,path:l,file:"",line:t.line,pathParams:Xl(l),consumes:a,produces:c.length>0?c:void 0,headers:u.headers,queryParams:u.queryParams,hasBody:u.hasBody,bodyType:u.bodyType,formParts:u.formParts.length>0?u.formParts:void 0,modelAttributeType:u.modelAttributeType,returnType:d||void 0,summary:p.summary,description:p.description,operationId:p.operationId,tags:p.tags.length>0?p.tags:void 0,deprecated:p.deprecated||void 0,responses:p.responses.length>0?p.responses:void 0,parameterMeta:u.parameterMeta.length>0?u.parameterMeta:void 0,security:p.security.length>0?p.security:void 0}}extractOpenApiAnnotations(e,t){let n,s,i,o=[],a=!1,c=[],l=[];for(let u of t)if(u.name==="Tag"){let d=this.getAnnotationAttrString(u,"name");d&&o.push(d)}for(let u of e)switch(u.name){case"Operation":{n=this.getAnnotationAttrString(u,"summary")||n,s=this.getAnnotationAttrString(u,"description")||s,i=this.getAnnotationAttrString(u,"operationId")||i;let d=u.attributes.get("deprecated");typeof d=="string"&&d==="true"&&(a=!0);let p=u.attributes.get("tags");if(Array.isArray(p))p.forEach(m=>{let f=m.replace(/^['"]|['"]$/g,"");f&&o.push(f)});else if(typeof p=="string"){let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)}break}case"ApiOperation":{n=this.getAnnotationAttrString(u,"value")||n,s=this.getAnnotationAttrString(u,"notes")||s;let d=u.attributes.get("tags");Array.isArray(d)&&d.forEach(p=>{let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)});break}case"Tag":{let d=this.getAnnotationAttrString(u,"name");d&&o.push(d);break}case"Deprecated":{a=!0;break}case"ApiResponse":{let d=this.parseApiResponse(u);d&&c.push(d);break}case"ApiResponses":break;case"SecurityRequirement":{let d=this.getAnnotationAttrString(u,"name");d&&l.push(d);break}}return{summary:n,description:s,operationId:i,tags:[...new Set(o)],deprecated:a,responses:c,security:l}}parseApiResponse(e){let t=this.getAnnotationAttrString(e,"responseCode")||this.getAnnotationAttrString(e,"code")||"200",n=this.getAnnotationAttrString(e,"description"),s=this.getAnnotationAttrRaw(e,"content"),i=s?this.extractAttrFromRaw(s,"mediaType"):void 0,o=s?this.extractImplementationType(s):this.extractImplementationType(this.getAnnotationAttrRaw(e,"schema")),a=s?this.extractExampleObjects(s):void 0,c=this.getAnnotationAttrRaw(e,"headers"),l=c?this.extractHeaderObjects(c):void 0;return{statusCode:t,description:n,...i&&{contentType:i},...o&&{schemaType:o},...a&&Object.keys(a).length>0&&{examples:a},...l&&Object.keys(l).length>0&&{headers:l}}}getAnnotationAttrRaw(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n;if(Array.isArray(n))return n.join(",")}extractAttrFromRaw(e,t){let n=new RegExp(`${t}\\s*=\\s*(["'])(.*?)\\1`);return e.match(n)?.[2]}extractImplementationType(e){if(!e)return;let t=e.match(/implementation\s*=\s*([A-Za-z0-9_$.<>?]+)\.class/);if(!t?.[1])return;let n=t[1];return n=n.split(".").pop()||n,rn(n)}extractExampleObjects(e){let t={},n=e.match(/@ExampleObject\(([^)]*)\)/g)||[],s=1;for(let i of n){let a=(i.match(/name\s*=\s*"((?:\\.|[^"\\])*)"/)?.[1]||this.extractAttrFromRaw(i,"name")||`example${s++}`).replace(/\\"/g,'"').replace(/\\\\/g,"\\"),c=i.match(/value\s*=\s*"((?:\\.|[^"\\])*)"/),l=c?.[1]?c[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):this.extractAttrFromRaw(i,"value");if(!l)continue;let u=this.parseExampleValue(l);t[a]=u}return Object.keys(t).length>0?t:void 0}extractHeaderObjects(e){let t={},n=e.match(/@Header\(([^)]*)\)/g)||[];for(let s of n){let i=this.extractAttrFromRaw(s,"name")||this.extractAttrFromRaw(s,"value");if(!i)continue;let o={},a=this.extractAttrFromRaw(s,"description");a&&(o.description=a);let c=this.extractAttrFromRaw(s,"format");c&&(o.format=c);let l=s.match(/required\s*=\s*(true|false)/)?.[1];l&&(o.required=l==="true");let u=s.match(/deprecated\s*=\s*(true|false)/)?.[1];u&&(o.deprecated=u==="true");let d=this.extractAttrFromRaw(s,"type")||this.extractImplementationType(s);d&&(o.schemaType=d),t[i]=o}return Object.keys(t).length>0?t:void 0}parseExampleValue(e){let t=e.trim();if(!t)return"";if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return t}return t}getAnnotationAttrString(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n.replace(/^['"]|['"]$/g,"")||void 0}extractReturnType(e){let t=e.methodHeader?.[0]?.children?.result?.[0];if(!t)return"";if(t.children?.Void)return"void";let n=t.children?.unannType?.[0];if(!n)return"";let s=this.extractUnannTypeName(n);return rn(s)}extractParameters(e){let t=[],n=[],s=[],i=[],o=!1,a,c,l=e.methodHeader?.[0]?.children?.methodDeclarator?.[0]?.children?.formalParameterList?.[0]?.children?.formalParameter;if(!l)return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i};for(let u of l){let d=u.children?.variableParaRegularParameter?.[0]?.children;if(!d)continue;let p=d.variableDeclaratorId?.[0]?.children?.Identifier?.[0]?.image||"",m=d.variableModifier||[],f=this.collectAnnotationsFromModifiers(m),h=d.unannType?.[0],g=h?this.extractUnannTypeName(h):"",y=f.find(b=>b.name==="Parameter"),v;for(let b of f)if(b.name==="RequestHeader"){let C=this.getAnnotationStringValue(b)||p;t.push(C),v=this.buildParameterMeta(C,"header",g,y,f);let R=b.attributes.get("required");v&&typeof R=="string"&&(R==="true"||R==="false")&&(v.required=R==="true")}else if(b.name==="RequestParam")if(gs(g)){o=!0;let C=this.getAnnotationStringValue(b)||p;s.push({name:C,type:g,isFile:!0})}else{let C=this.getAnnotationStringValue(b)||p;n.push(C);let R=b.attributes.get("required");v=this.buildParameterMeta(C,"query",g,y,f),v&&typeof R=="string"&&(R==="true"||R==="false")&&(v.required=R==="true")}else if(b.name==="RequestBody")o=!0,g&&(a=rn(g));else if(b.name==="RequestPart"){o=!0;let C=this.getAnnotationStringValue(b)||p,R=gs(g);s.push({name:C,type:g,isFile:R})}else b.name==="ModelAttribute"&&(o=!0,g&&(c=g));let w=f.find(b=>b.name==="PathVariable");if(w){let b=this.getAnnotationStringValue(w)||p;v=this.buildParameterMeta(b,"path",g,y,f)}v&&i.push(v)}return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i}}buildParameterMeta(e,t,n,s,i){let o={name:e,in:t};if(s){let a=this.getAnnotationAttrString(s,"description");a&&(o.description=a);let c=this.getAnnotationAttrString(s,"example");c&&(o.example=c);let l=s.attributes.get("required");typeof l=="string"&&(l==="true"||l==="false")&&(o.required=l==="true");let u=s.attributes.get("deprecated");typeof u=="string"&&u==="true"&&(o.deprecated=!0)}return n&&(o.schemaType=n),i&&this.extractConstraintAnnotations(o,i),o}extractConstraintAnnotations(e,t){for(let n of t)switch(n.name){case"Schema":{let s=this.getAnnotationAttrString(n,"pattern");s&&!e.pattern&&(e.pattern=s);let i=this.getAnnotationAttrString(n,"format");i&&!e.format&&(e.format=i);let o=this.getAnnotationAttrString(n,"minimum");o&&e.minimum===void 0&&(e.minimum=Number(o));let a=this.getAnnotationAttrString(n,"maximum");a&&e.maximum===void 0&&(e.maximum=Number(a));let c=this.getAnnotationAttrString(n,"minLength");c&&e.minLength===void 0&&(e.minLength=Number(c));let l=this.getAnnotationAttrString(n,"maxLength");l&&e.maxLength===void 0&&(e.maxLength=Number(l));let u=n.attributes.get("allowableValues");Array.isArray(u)&&!e.enum&&(e.enum=u.map(d=>d.replace(/^['"]|['"]$/g,"")).filter(Boolean));break}case"Pattern":{let s=this.getAnnotationAttrString(n,"regexp");s&&!e.pattern&&(e.pattern=s);break}case"Size":{let s=this.getAnnotationAttrString(n,"min");s&&e.minLength===void 0&&(e.minLength=Number(s));let i=this.getAnnotationAttrString(n,"max");i&&e.maxLength===void 0&&(e.maxLength=Number(i));break}case"Min":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.minimum===void 0&&(e.minimum=Number(s));break}case"Max":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.maximum===void 0&&(e.maximum=Number(s));break}case"DecimalMin":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=Number(s)):e.minimum===void 0&&(e.minimum=Number(s)));break}case"DecimalMax":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=Number(s)):e.maximum===void 0&&(e.maximum=Number(s)));break}case"Email":{e.format||(e.format="email");break}case"Positive":{e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=0);break}case"PositiveOrZero":{e.minimum===void 0&&(e.minimum=0);break}case"Negative":{e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=0);break}case"NegativeOrZero":{e.maximum===void 0&&(e.maximum=0);break}case"NotNull":case"NotBlank":case"NotEmpty":{e.required===void 0&&(e.required=!0);break}}}getAnnotationStringValue(e){let t=e.attributes.get("value");return typeof t=="string"?t.replace(/^['"]|['"]$/g,""):""}extractUnannTypeName(e){return this.collectTokens(e).map(n=>n.image).join("")}collectAnnotationsFromModifiers(e){let t=[];for(let n of e){let s=n.children?.annotation;if(!s)continue;let i=s[0].children,o=i.typeName[0].children.Identifier[0].image,a=new Map;if(i.elementValuePairList){let c=i.elementValuePairList[0].children.elementValuePair;for(let l of c){let u=l.children.Identifier[0].image,d=this.extractElementValue(l.children.elementValue[0]);d!==void 0&&a.set(u,d)}}else if(i.elementValue){let c=this.extractElementValue(i.elementValue[0]);c!==void 0&&a.set("value",c)}t.push({name:o,attributes:a})}return t}extractTypeName(e){if(!e)return"";if(e.primitiveType)return e.primitiveType[0].children?.literal?.[0]?.image||"";if(e.classOrInterfaceType){let t=e.classOrInterfaceType[0],n="",s=t.Identifier||[];for(let o=0;o<s.length;o++)o>0&&(n+="."),n+=s[o].image;let i=t.typeArguments?.[0]?.typeArgument;return i&&(n+="<",n+=i.map(o=>o.typeType?this.extractTypeName(o.typeType[0]):"?").join(","),n+=">"),n}if(e.typeType&&e.dims){let t=this.extractTypeName(e.typeType[0]),n=e.dims.length;return t+"[]".repeat(n)}return""}}});var ef={};Tt(ef,{EndpointParser:()=>eu});var Xp,eu,tf=E(()=>{"use strict";Xp=require("java-parser");fa();ma();Yp();eu=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>Zl(n.trim()));for(let n of[...this.fileCache.keys()]){let s=Zl(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=ki(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(Yl(a))&&!s.has(a)){if(s.add(a),this.fileCache.has(a)){n.push(...this.fileCache.get(a));continue}i.push(a)}let o=30;for(let a=0;a<i.length;a+=o){let c=i.slice(a,a+o),l=await Promise.all(c.map(u=>this.parseFile(u).then(d=>({filePath:u,ctrls:d})).catch(()=>({filePath:u,ctrls:[]}))));for(let{filePath:u,ctrls:d}of l)this.fileCache.set(u,d),n.push(...d)}for(let a of this.fileCache.keys())s.has(a)||this.fileCache.delete(a);return n}removeFile(e){this.fileCache.delete(e)}static CONTROLLER_HINT_RE=/@(?:RestController|Controller)\b|@(?:Request|Get|Post|Put|Delete|Patch)Mapping\b/;looksLikeController(e){return r.CONTROLLER_HINT_RE.test(e)}async parseFile(e){let t=await Ii(e);if(!this.looksLikeController(t))return[];let n=this.parseWithAst(t);if(n){for(let s of n){s.file=e;for(let i of s.endpoints)i.file=e}return n}return this.parseWithRegex(t,e)}async findEndpoints(e){return(await this.parseControllers(e)).flatMap(n=>n.endpoints)}parseWithAst(e){try{let t=(0,Xp.parse)(e),n=new ha;if(n.visit(t),n.controllers.length>0){for(let s of n.controllers){let i=new Set;s.endpoints=s.endpoints.filter(o=>{let a=`${o.method}:${o.path}:${o.line}`;return i.has(a)?!1:(i.add(a),!0)})}return n.controllers}return null}catch{return null}}parseWithRegex(e,t){let n=[],s=e.split(/\r?\n/),i=[],o=new Map,a=null,c=0,l=!1;for(let u=0;u<s.length;u++){let d=s[u],p=d.trim(),m=/^@(\w+)\s*(?:\(([^)]*)\))?/.exec(p);if(m&&!/\b(class|interface|enum)\b/.test(p)&&(i.push(m[1]),m[2]!==void 0&&o.set(m[1],m[2]),!/(private|public|protected|static|final|void|class)\b/.test(p)))continue;let f=/\bclass\s+(\w+)/.exec(p);if(f){if(a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i.some(v=>v==="RestController"||v==="Controller")){let v="",w=o.get("RequestMapping");w!==void 0&&(v=this.extractPathFromArgs(w)),a={name:f[1],basePath:v,file:t,line:u+1,endpoints:[]}}l=!0,c=0,c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,i=[],o=new Map;continue}if(l&&(c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,c<=0)){l=!1,a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i=[],o=new Map;continue}if(!a){m||(i=[],o=new Map);continue}let h=i.find(y=>/Mapping$/.test(y)),g=/^@(GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping)\s*(?:\(([^)]*)\))?/.exec(p);if(h||g){let y=u,v=this.collectMethodSignature(s,y),w=[];g&&w.push({name:g[1],args:g[2]||""});for(let b of i)/Mapping$/.test(b)&&(!g||b!==g[1])&&w.push({name:b,args:o.get(b)||""});for(let b of w){let C=b.name.replace("Mapping","").toUpperCase();C==="REQUEST"&&(C="");let R="",A=[],N=b.args;if(N){R=this.extractPathFromArgs(N);let U=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(N);if(U){let O=U[1],L=[...O.matchAll(/["']([^"']+)["']/g)].map(Y=>Y[1]),Q=[...O.matchAll(/MediaType\.([A-Z_]+)/g)].map(Y=>`MediaType.${Y[1]}`);A=Ti([...L,...Q])}if(b.name==="RequestMapping"){let O=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(N);O&&(C=O[1])}}!C&&b.name==="RequestMapping"&&(C="GET");let M=R;a.basePath&&(M&&!M.startsWith("/")?M=a.basePath+"/"+M:M=a.basePath+M),M&&!M.startsWith("/")&&(M="/"+M);let j=this.extractParameterMetadataFromSig(v);a.endpoints.push({method:C,path:M,file:t,line:u+1,pathParams:Xl(M),consumes:A,bodyType:j.bodyType,headers:j.headers,queryParams:j.queryParams,hasBody:j.hasBody,formParts:j.formParts.length>0?j.formParts:void 0,modelAttributeType:j.modelAttributeType})}i=[],o=new Map;continue}m||(i=[],o=new Map)}return a&&(this.deduplicateEndpoints(a),n.push(a)),n}extractPathFromArgs(e){let t=/(?:value|path)\s*=\s*["']([^"']+)["']/.exec(e);if(t)return t[1];let n=/^\s*["']([^"']+)["']/.exec(e);return n?n[1]:""}collectMethodSignature(e,t){let n="";for(let s=t;s<e.length&&(n+=e[s]+" ",!e[s].includes("{"));s++);return n}extractParameterMetadataFromSig(e){let t=[],n=[],s=[],i=!1,o,a,c=/@RequestHeader\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+(?:[A-Za-z0-9_<>\[\]]+)\s+(\w+)/g,l;for(;(l=c.exec(e))!==null;)t.push(l[1]||l[2]);let u=/@RequestParam\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=u.exec(e))!==null;){let g=l[2];if(gs(g)){i=!0;let y=l[1]||l[3];s.push({name:y,type:g,isFile:!0})}else n.push(l[1]||l[3])}let p=/@RequestBody\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);p?(i=!0,o=rn(p[1])):/@RequestBody/.test(e)&&(i=!0);let m=/@RequestPart\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=m.exec(e))!==null;){i=!0;let g=l[1]||l[3],y=l[2],v=gs(y);s.push({name:g,type:y,isFile:v})}let h=/@ModelAttribute\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);return h?(i=!0,a=h[1]):/@ModelAttribute/.test(e)&&(i=!0),{headers:t,queryParams:n,hasBody:i,bodyType:o,formParts:s,modelAttributeType:a}}deduplicateEndpoints(e){let t=new Set;e.endpoints=e.endpoints.filter(n=>{let s=`${n.method}:${n.path}:${n.line}`;return t.has(s)?!1:(t.add(s),!0)})}}});function jy(r){let e=[];for(let t of r.parameterMeta??[]){let n=[];t.required&&n.push("required"),t.pattern&&n.push(`pattern=${t.pattern}`),t.format&&n.push(`format=${t.format}`),t.enum&&t.enum.length>0&&n.push(`enum=[${t.enum.join(", ")}]`),t.minimum!==void 0&&n.push(`min=${t.minimum}`),t.maximum!==void 0&&n.push(`max=${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(`exclusiveMin=${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(`exclusiveMax=${t.exclusiveMaximum}`),t.minLength!==void 0&&n.push(`minLength=${t.minLength}`),t.maxLength!==void 0&&n.push(`maxLength=${t.maxLength}`),n.length>0&&e.push(`${t.in==="header"?"header":t.in} ${t.name}: ${n.join(", ")}`)}return e.length>0?e:void 0}var ga,nf,My,Dy,dr,tu=E(()=>{"use strict";ga=T(require("fs")),nf=T(require("path"));fa();Qp();My=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],Dy=/@(?:RestController|Controller)\b/,dr=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of My)if(ga.existsSync(nf.join(e.projectRoot,s)))return{supported:!0,confidence:.95,reasons:[`${s} detected`]};let t=e.sourceFiles?.filter(s=>s.endsWith(".java"))??[];t.length===0&&(t=ki(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=ga.readFileSync(s,"utf-8");if(Dy.test(i))return{supported:!0,confidence:.8,reasons:["Spring controller annotation found"]}}catch{continue}}return{supported:!1,confidence:0,reasons:["no Spring indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=t.projectRoot,o=await this.loadParser(),a=new o.EndpointParser,c=[];try{c=await a.parseControllers(i)}catch(d){let p=d instanceof Error?d.message:String(d);s.push({code:"provider-failed",framework:"spring",message:`Spring discovery failed for ${i}: ${p}`})}let l=new ur(i),u=[];for(let d of c)for(let p of d.endpoints)u.push(await this.endpointToDiscoveredApi(p,l));return{endpoints:u,warnings:s,stats:{frameworksDetected:["spring"],providersRun:[this.id],endpointCount:u.length,unresolvedEndpointCount:u.filter(d=>!d.resolvedPath).length,scanDurationMs:Date.now()-n}}}clearCache(){this.parserModule=void 0}async loadParser(){return this.parserModule||(this.parserModule=await Promise.resolve().then(()=>(tf(),ef))),this.parserModule}async endpointToDiscoveredApi(e,t){let n=await this.buildParams(e,t),s=await this.buildRequestBody(e,t),i=await this.buildResponses(e,t),o=e.security&&e.security.length>0?{required:!0,type:"oauth2",annotation:e.security.join(", ")}:void 0,a=e.line>0?e.line:1;return{id:"",framework:"spring",method:e.method||"GET",pathExpression:e.path||"/",resolvedPath:e.path||"/",confidence:"high",source:{filePath:e.file,line:a,symbolName:`${e.method||"GET"} ${e.path||"/"}`},params:n.length>0?n:void 0,requestBody:s,responses:i,validation:jy(e),auth:o,tags:e.tags,deprecated:e.deprecated,description:e.summary||e.description}}async buildParams(e,t){let n=[],s=(e.consumes??[]).join(" "),i=s.includes("x-www-form-urlencoded"),o=s.includes("multipart");for(let a of e.headers??[])n.push(this.paramFromMeta(a,"header",e.parameterMeta,!0));for(let a of e.queryParams??[]){let c=i||o?"form":"query",l=e.parameterMeta?.find(u=>u.name===a&&u.in==="query");n.push(this.paramFromMeta(a,c,e.parameterMeta,l?.required))}for(let a of e.formParts??[])n.push({name:a.name,location:"form",type:a.isFile?"file":"string",required:!0});return n}paramFromMeta(e,t,n,s){let i=n?.find(a=>a.name===e&&(a.in===t||t==="form"&&a.in==="query")),o={name:e,location:t};return i&&(o.description=i.description,o.required=i.required??s,o.example=i.example,i.schemaType&&(o.type=ur.javaTypeToParamType(i.schemaType)),o.schema=this.constraintsToSchema(i)),o.required=t==="path"?!0:o.required,o.type=o.type??"string",o}constraintsToSchema(e){let t={};if(e.schemaType){t.type=ur.javaTypeToParamType(e.schemaType);let n=ur.javaTypeToFormat(e.schemaType);n&&(t.format=n)}return e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.enum&&e.enum.length>0&&(t.enum=e.enum),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),Object.keys(t).length>0?t:void 0}async buildRequestBody(e,t){let n=e.consumes??[];if(e.formParts&&e.formParts.length>0)return{type:"multipart",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(e.modelAttributeType)return{type:"form",required:!0,schema:await this.maybeSchema(t,e.modelAttributeType)};if(n.some(a=>a.includes("x-www-form-urlencoded"))&&(e.queryParams?.length??0)>0)return{type:"form",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(!e.hasBody)return;let s=e.bodyType??e.modelAttributeType;if(!s)return{type:"json",required:!0};let i=n.some(a=>a.includes("x-www-form-urlencoded"))?"form":n.some(a=>a.includes("multipart"))?"multipart":"json",o=await this.maybeSchema(t,s);return{type:i,required:!0,schema:o}}async buildResponses(e,t){let n=[];for(let s of e.responses??[]){let i={statusCode:parseInt(s.statusCode,10)||200},o=s.schemaType?await this.maybeSchema(t,s.schemaType):void 0;i.body={type:s.contentType??"json"},o&&(i.body.schema=o),n.push(i)}if(n.length===0){let s=e.returnType;if(s&&s!=="void"){let i=await t.generateResponseSchema(s);n.push({statusCode:200,body:{type:"json",schema:i??{type:"object"}}})}else n.push({statusCode:200})}return n}async maybeSchema(e,t){return await e.generate(t)??{type:"object"}}}});function nu(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=va.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=cf.join(n,i.name);if(i.isDirectory()){Ly.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function lf(r){let e=nu(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let d="";try{d=va.readFileSync(u,"utf-8")}catch{continue}let p=By(d,u,t);n.set(u,p);for(let m of p.routers)s.has(m.name)||s.set(m.name,m)}let o=new Map;for(let u of s.values())o.set(u.name,[u.constructorPrefix]);let a=new Map,c=new Set;for(let u of n.values())for(let d of u.includes){let p=sf(u.imports,d.routerName);if(!s.has(p)){i.push(`include_router references unknown router '${d.routerName}' at ${d.line}`);continue}let m=s.get(p);if(d.prefix){c.add(p);let f=o.get(p),h=`${d.prefix.replace(/\/+$/,"")}/${m.constructorPrefix.replace(/^\/+/,"")}`;f.includes(h)||f.push(h)}d.tags&&d.tags.length>0&&a.set(p,[...a.get(p)??[],...d.tags])}let l=[];for(let[u,d]of n.entries())for(let p of d.routes)for(let m of p.decorators){let f=sf(d.imports,m.object),h=d.appNames.has(m.object)||d.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let y=Gy(m.method,m.args);if(y.length===0)continue;let v=Wy(m.args),w=m.unresolved||v.startsWith("f"),b=g?o.get(f)??[g.constructorPrefix]:[""];for(let C of b){if(g&&c.has(f)&&C===g.constructorPrefix)continue;let R=g?tv(C,v):v,A=nv(p.signature,ev(R)),N=g?a.get(f):void 0,j=uf(m.args)??N;l.push({methods:y,path:R,file:u,line:m.line,functionName:p.functionName,statusCode:Ky(m.args),responseModel:Qy(m.args)??zy(p.signature),tags:j,deprecated:Zy(m.args),summary:Yy(m.args),params:A.params,security:Xy(m.args,p.signature),pathUnresolved:w})}}return{endpoints:l,models:t,warnings:i}}function sf(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function sn(r,e){let t=r.trim();if(!t||t==="None")return;let n=/^(?:Optional|Union)\[([^\]]*)\](?:\s*\|\s*None)?$/.exec(t)||/^(.+?)(?:\s*\|\s*None)+$/.exec(t);if(n)return sn(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return sn(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:sn(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:sn(o[2],e)??{}};let a={int:{type:"integer"},float:{type:"number"},Decimal:{type:"number"},bool:{type:"boolean"},str:{type:"string"},datetime:{type:"string",format:"date-time"},date:{type:"string",format:"date"},time:{type:"string",format:"time"},UUID:{type:"string",format:"uuid"},bytes:{type:"string",format:"binary"},UploadFile:{type:"string",format:"binary"}};if(t in a)return{...a[t]};let c=e.get(t);if(c){let l={},u=[];for(let p of c.fields){let m=sn(p.type,e)??{type:"string"};l[p.name]=p.description?{...m,description:p.description}:m,p.required&&u.push(p.name)}let d={type:"object",properties:l};return u.length>0&&(d.required=u),d}return{type:"object"}}function By(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=iv(r).split(/\r?\n/),o=[],a=0;for(;a<i.length;){let c=i[a],l=a+1,u=c.trim();if(a+=1,u==="")continue;let d=/^from\s+[\w.]+(?:\s+import\s+(.+))?$/.exec(u)||/^import\s+([\w.,\s]+)$/.exec(u);if(d){let y=d[1]??"";for(let v of y.split(",")){let w=v.trim();if(!w)continue;let b=/^([\w.]+)\s+as\s+(\w+)$/.exec(w);if(b)n.imports.push({alias:b[2],target:b[1].split(".").pop()});else if(/^[\w.]+$/.test(w)){let C=w.split(".").pop();n.imports.push({alias:C,target:C})}}o=[];continue}if(u.startsWith("@")){let{joined:y,nextIndex:v}=ya(i,a-1),w=Jy(y,l);w&&o.push(w),a=v+1;continue}let p=/^(?:async\s+)?def\s+(\w+)\s*\(/.exec(u);if(p){let{joined:y,nextIndex:v}=ya(i,a-1),w=y.slice(y.indexOf("(")),b=Vy(i,a-1,w);o.length>0&&n.routes.push({decorators:o,functionName:p[1],signature:b,line:l}),o=[],a=v+1;continue}let m=/^class\s+(\w+)\s*\(\s*(\w+)\s*\)\s*:/.exec(u);if(m&&(m[2]==="BaseModel"||m[2].endsWith("BaseModel"))){let{nextIndex:y,fields:v}=Uy(i,a);t.set(m[1],{name:m[1],fields:v}),a=y,o=[];continue}let f=/^(\w+)\s*=\s*(?:fastapi\.)?FastAPI\(/.exec(u);if(f){n.appNames.add(f[1]),o=[];continue}let h=/^(\w+)\s*=\s*(?:fastapi\.)?APIRouter\((.*)$/.exec(u);if(h){let{joined:y}=ya(i,a-1),v=y.slice(y.indexOf("("));n.routers.push({name:h[1],constructorPrefix:af(v)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:y}=ya(i,a-1),v=y.slice(y.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:af(v),tags:uf(v),line:l}),o=[];continue}o=[]}return n}function Uy(r,e){let t=[],n=e,s=(r[e-1]||"").match(/^(\s*)/)[1].length;for(;n<r.length;){let i=r[n];if(i.trim()===""){n+=1;continue}if(i.match(/^(\s*)/)[1].length<=s)break;let a=i.trim();if(a.startsWith("#")){n+=1;continue}let c=/^([A-Za-z_]\w*)\s*:\s*(.+?)\s*(?:=\s*(.*))?$/.exec(a);if(c&&!a.startsWith("def ")&&!a.startsWith("class ")){let l=c[2].replace(/,\s*$/,""),u=(c[3]??"").trim(),d=/^Optional\[/.test(l)||/None\s*\|/.test(l)||u==="None"||u.startsWith("None")||u!==""&&!u.startsWith("Field("),p,m=/Field\(([^)]*)\)/.exec(a);if(m){let f=/description\s*=\s*["']([^"']+)["']/.exec(m[1]);f&&(p=f[1])}t.push({name:c[1],type:l,required:!d,description:p})}n+=1}return{nextIndex:n,fields:t}}function ya(r,e){let t=0,n=r[e]??"",s=e,i=null,o=a=>{for(let c of a){if(i){c===i&&(i=null);continue}c==='"'||c==="'"?i=c:c==="("||c==="["||c==="{"?t+=1:(c===")"||c==="]"||c==="}")&&(t-=1)}};for(o(n);t>0&&s+1<r.length;){s+=1;let a=r[s];o(a),n+=`
470
470
  `+a}return{joined:n,nextIndex:s}}function Vy(r,e,t){let n=0,s=null,i=t,o=e,a=l=>{for(let u of l){if(s){u===s&&(s=null);continue}u==='"'||u==="'"?s=u:u==="("||u==="["||u==="{"?n+=1:(u===")"||u==="]"||u==="}")&&(n-=1)}};for(a(t);n>0&&o+1<r.length;){o+=1;let l=r[o];a(l),i+=`
471
471
  `+l}let c=of(i);if(c!==-1)return i.slice(0,c);for(;o+1<r.length;){o+=1;let l=r[o],u=of(l);if(u!==-1){i+=`
472
472
  `+l.slice(0,u);break}i+=`
473
473
  `+l}return i}function of(r){let e=0,t=null;for(let n=0;n<r.length;n++){let s=r[n];if(t){s===t&&(t=null);continue}if(s==='"'||s==="'"){t=s;continue}if(s==="("||s==="["||s==="{"){e+=1;continue}if(s===")"||s==="]"||s==="}"){e-=1;continue}if(s===":"&&e===0)return n}return-1}function zy(r){let e=/->\s*([^:\n]+?)\s*$/.exec(r.trim());return e?e[1].trim():void 0}function Jy(r,e){let t=/^@([\w.]+)\.(\w+)\((.*)\)$/s.exec(r.trim());if(!t)return null;let n=t[1].split(".")[0],s=t[2];return{object:n,method:s,args:t[3]??"",line:e,unresolved:t[1].includes(".")&&t[1].split(".").length>2}}function Gy(r,e){if(r==="api_route"){let n=/methods\s*=\s*\[([^\]]*)\]/.exec(e);if(n){let s=[...n[1].matchAll(/["']([^"']+)["']/g)].map(i=>i[1].toUpperCase());return s.length>0?s:["GET"]}return["GET"]}if(r==="route")return[];let t=Hy[r.toLowerCase()];return t?[t]:[]}function Wy(r){let e=i=>{let o=i.exec(r);if(!o)return;let a=o[1].length>1?o[1][0]:"";return a==="f"||a==="F"?`f${o[2]}`:o[2]},t=e(/(?:path|url)\s*=\s*([fFrRbB]?["'])([^"']+)["']/);if(t!==void 0)return t;let n=e(/^\s*([fFrRbB]?["'])([^"']+)["']/);if(n!==void 0)return n;let s=/["']([^"']+)["']/.exec(r);return s?s[1]:""}function Ky(r){let e=/status_code\s*=\s*(\d+)/.exec(r);return e?parseInt(e[1],10):void 0}function Qy(r){let e=/response_model\s*=\s*([^\s,]+)/.exec(r);return e?e[1]:void 0}function uf(r){let e=/tags\s*=\s*\[([^\]]*)\]/.exec(r);if(!e)return;let t=[...e[1].matchAll(/["']([^"']+)["']/g)].map(n=>n[1]);return t.length>0?t:void 0}function Zy(r){return/deprecated\s*=\s*True/.test(r)?!0:void 0}function Yy(r){let e=/summary\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:void 0}function Xy(r,e){let t=[],n=/dependencies\s*=\s*\[([^\]]*)\]/.exec(r);if(n)for(let i of n[1].split(",")){let o=/Depends\(([^)]+)\)/.exec(i);o&&t.push(o[1].trim())}let s=/:\s*Security\(([^)]+)\)/.exec(e);return s&&t.push(s[1].trim()),t}function af(r){let e=/prefix\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:""}function ev(r){let e=[],t=/\{([^}:]+)(?::[^}]+)?\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}function tv(r,e){return e?r?`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:e.startsWith("/")?e:"/"+e:r||"/"}function nv(r,e){let t=[],n=new Set(e),s=r.indexOf("("),i=r.lastIndexOf(")");if(s===-1||i===-1)return{params:t};let o=r.slice(s+1,i),a=sv(o,",");for(let c of a){let l=c.trim();if(!l)continue;let u=/^([A-Za-z_]\w*)\s*(?::\s*([^=\n]+))?(?:\s*=\s*(.*))?$/s.exec(l);if(!u)continue;let d=u[1],p=(u[2]??"").trim(),m=(u[3]??"").trim();if(rf.has(d))continue;let f=/^([A-Za-z_]\w*)/.exec(p)?.[1]??"";if(rf.has(f)||/Depends\(|Security\(/.test(m))continue;let h=/^(Path|Query|Header|Cookie|Body|File|Form)\b/.exec(m)?.[1],g;h==="Path"||n.has(d)?g="path":h==="Header"?g="header":h==="Cookie"?g="cookie":h==="Body"?g="body":h==="File"||h==="Form"||f==="UploadFile"?g="form":g="query",g==="query"&&n.has(d)&&(g="path");let y=rv(p,m);t.push({name:d,location:g,type:f||"str",required:!y})}for(let c of n)t.some(l=>l.name===c&&l.location==="path")||t.push({name:c,location:"path",type:"str",required:!0});return{params:t}}function rv(r,e){if(/^Optional\[/.test(r)||/None\s*\|/.test(r))return!0;if(e==="")return!1;if(e==="None")return!0;let t=/^(Path|Query|Header|Cookie|Body|File|Form)\((.*)\)$/s.exec(e);if(t){let n=t[2].trim();return n===""||n.startsWith("...")?!1:(n.startsWith("None")||/default\s*=\s*None\b/.test(n),!0)}return!0}function sv(r,e){let t=[],n=0,s=null,i="";for(let o of r){if(s){i+=o,o===s&&(s=null);continue}if(o==='"'||o==="'"){s=o,i+=o;continue}if(o==="("||o==="["||o==="{"){n+=1,i+=o;continue}if(o===")"||o==="]"||o==="}"){n-=1,i+=o;continue}if(o===e&&n===0){t.push(i),i="";continue}i+=o}return i.trim()!==""&&t.push(i),t}function iv(r){return r.split(/\r?\n/).map(t=>{let n=null;for(let s=0;s<t.length;s++){let i=t[s];if(n){i===n&&(n=null);continue}if(i==='"'||i==="'")n=i;else if(i==="#"&&(s===0||t[s-1]!=="\\"))return t.slice(0,s)}return t}).join(`
474
- `)}var va,cf,Ly,Hy,rf,df=E(()=>{"use strict";va=T(require("fs")),cf=T(require("path")),Ly=new Set(["node_modules",".git",".venv","venv","env","__pycache__","site-packages",".mypy_cache",".pytest_cache",".tox","dist","build","out"]),Hy={get:"GET",post:"POST",put:"PUT",patch:"PATCH",delete:"DELETE",options:"OPTIONS",head:"HEAD"},rf=new Set(["Request","Response","WebSocket","BackgroundTasks","Depends","Header","Cookie"])});function lv(r){return{int:"integer",float:"number",Decimal:"number",bool:"boolean",str:"string",datetime:"string",date:"string",time:"string",UUID:"string",bytes:"string",UploadFile:"string"}[r]}var ba,pf,ov,av,cv,pr,ru=E(()=>{"use strict";ba=T(require("fs")),pf=T(require("path"));df();ov=["requirements.txt","pyproject.toml","poetry.lock","Pipfile","setup.py"],av=/^\s*from\s+fastapi\s+import|^\s*import\s+fastapi/m,cv=/@[\w.]+\.(get|post|put|patch|delete|options|head|api_route)\(/,pr=class{id="provider.fastapi";framework="fastapi";supports(e){for(let s of ov)if(ba.existsSync(pf.join(e.projectRoot,s)))return{supported:!0,confidence:.9,reasons:[`${s} detected`]};let t=e.sourceFiles??nu(e.projectRoot),n=0;for(let s of t)if(s.endsWith(".py")){if(n>=60)break;n+=1;try{let i=ba.readFileSync(s,"utf-8");if(av.test(i)&&cv.test(i))return{supported:!0,confidence:.9,reasons:["fastapi app decorator found"]}}catch{continue}}return{supported:!1,confidence:0,reasons:["no FastAPI indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=t.projectRoot,o;try{o=lf(i)}catch(c){let l=c instanceof Error?c.message:String(c);return s.push({code:"provider-failed",framework:"fastapi",message:`FastAPI discovery failed for ${i}: ${l}`}),{endpoints:[],warnings:s,stats:{frameworksDetected:["fastapi"],providersRun:[this.id],endpointCount:0,unresolvedEndpointCount:0,scanDurationMs:Date.now()-n}}}for(let c of o.warnings)s.push({code:"dynamic-path-unresolved",framework:"fastapi",message:c});let a=o.endpoints.map(c=>this.endpointToDiscoveredApi(c,o.models));return{endpoints:a,warnings:s,stats:{frameworksDetected:["fastapi"],providersRun:[this.id],endpointCount:a.length,unresolvedEndpointCount:a.filter(c=>!c.resolvedPath).length,scanDurationMs:Date.now()-n}}}endpointToDiscoveredApi(e,t){let n=e.methods[0],s=e.pathUnresolved?"low":"high",i=e.params.map(l=>this.paramToDiscovered(l,t)),o=this.buildRequestBody(e,t),a=this.buildResponses(e,t),c=e.security.length>0?{required:!0,type:"jwt",annotation:e.security.join(", ")}:void 0;return{id:"",framework:"fastapi",method:n,pathExpression:e.path,resolvedPath:e.path,confidence:s,source:{filePath:e.file,line:e.line,symbolName:`${n} ${e.path}`},params:i.length>0?i:void 0,requestBody:o,responses:a,auth:c,tags:e.tags,deprecated:e.deprecated,description:e.summary}}paramToDiscovered(e,t){let n=lv(e.type),s=sn(e.type,t)??(n?{type:n}:void 0),i={name:e.name,location:e.location,required:e.location==="path"?!0:e.required};return n&&(i.type=n),s&&(i.schema=s),i}buildRequestBody(e,t){let n=e.params.filter(i=>i.location==="body");if(n.length===0){let i=e.params.filter(o=>o.location==="form");return i.length>0?{type:"multipart",required:i.some(o=>o.required)}:void 0}let s=sn(n[0].type,t);return{type:"json",required:n.some(i=>i.required),schema:s??{type:"object"}}}buildResponses(e,t){let s={statusCode:e.statusCode??200};if(e.responseModel){let i=/^(?:List|list|Sequence)\[/.test(e.responseModel),o=i?/^(?:List|list|Sequence)\[(.+)\]$/.exec(e.responseModel)[1]:e.responseModel,a=sn(o,t);a&&(s.body={type:"json",schema:i?{type:"array",items:a}:a})}return[s]}}});function vs(r){let e;try{let n=(0,hf.execSync)("git rev-parse HEAD",{cwd:r,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim();n&&(e=n)}catch{e=void 0}let t=0;try{let n=[r],s=new Set(["node_modules",".git","target","build","dist","out","__pycache__",".venv","venv"]);for(;n.length>0;){let i=n.shift(),o;try{o=Sa.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){let c=mf.join(i,a.name);if(a.isDirectory()){s.has(a.name)||n.push(c);continue}if(!(!a.isFile()||!uv.some(l=>c.endsWith(l))))try{let l=Sa.statSync(c);l.mtimeMs>t&&(t=l.mtimeMs)}catch{}}}}catch{t=0}return{gitHash:e,maxSourceMtime:t}}function bs(r,e){let t=vs(r);if(!e)return{projectRoot:r,status:"unknown",currentFreshness:t,reason:"no stored index entry"};if(t.gitHash&&e.gitHash)return t.gitHash===e.gitHash?{projectRoot:r,status:"current",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t}:{projectRoot:r,status:"stale",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t,reason:`git HEAD changed: ${e.gitHash.slice(0,8)} \u2192 ${t.gitHash.slice(0,8)}`};let n=new Date(e.scannedAt).getTime();return t.maxSourceMtime>n?{projectRoot:r,status:"stale",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t,reason:`source file newer than last scan (${new Date(t.maxSourceMtime).toISOString()} > ${e.scannedAt})`}:{projectRoot:r,status:"current",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t}}function su(r){let e=r.projects.map(t=>bs(t.projectRoot,t.freshness));return{projects:e,staleCount:e.filter(t=>t.status==="stale").length,checkedAt:new Date().toISOString()}}function ys(r,e){let t=r.split(`
474
+ `)}var va,cf,Ly,Hy,rf,df=E(()=>{"use strict";va=T(require("fs")),cf=T(require("path")),Ly=new Set(["node_modules",".git",".venv","venv","env","__pycache__","site-packages",".mypy_cache",".pytest_cache",".tox","dist","build","out"]),Hy={get:"GET",post:"POST",put:"PUT",patch:"PATCH",delete:"DELETE",options:"OPTIONS",head:"HEAD"},rf=new Set(["Request","Response","WebSocket","BackgroundTasks","Depends","Header","Cookie"])});function lv(r){return{int:"integer",float:"number",Decimal:"number",bool:"boolean",str:"string",datetime:"string",date:"string",time:"string",UUID:"string",bytes:"string",UploadFile:"string"}[r]}var ba,pf,ov,av,cv,pr,ru=E(()=>{"use strict";ba=T(require("fs")),pf=T(require("path"));df();ov=["requirements.txt","pyproject.toml","poetry.lock","Pipfile","setup.py"],av=/^\s*from\s+fastapi\s+import|^\s*import\s+fastapi/m,cv=/@[\w.]+\.(get|post|put|patch|delete|options|head|api_route)\(/,pr=class{id="provider.fastapi";framework="fastapi";supports(e){for(let s of ov)if(ba.existsSync(pf.join(e.projectRoot,s)))return{supported:!0,confidence:.9,reasons:[`${s} detected`]};let t=e.sourceFiles?.filter(s=>s.endsWith(".py"))??[];t.length===0&&(t=nu(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".py")){if(n>=60)break;n+=1;try{let i=ba.readFileSync(s,"utf-8");if(av.test(i)&&cv.test(i))return{supported:!0,confidence:.9,reasons:["fastapi app decorator found"]}}catch{continue}}return{supported:!1,confidence:0,reasons:["no FastAPI indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=t.projectRoot,o;try{o=lf(i)}catch(c){let l=c instanceof Error?c.message:String(c);return s.push({code:"provider-failed",framework:"fastapi",message:`FastAPI discovery failed for ${i}: ${l}`}),{endpoints:[],warnings:s,stats:{frameworksDetected:["fastapi"],providersRun:[this.id],endpointCount:0,unresolvedEndpointCount:0,scanDurationMs:Date.now()-n}}}for(let c of o.warnings)s.push({code:"dynamic-path-unresolved",framework:"fastapi",message:c});let a=o.endpoints.map(c=>this.endpointToDiscoveredApi(c,o.models));return{endpoints:a,warnings:s,stats:{frameworksDetected:["fastapi"],providersRun:[this.id],endpointCount:a.length,unresolvedEndpointCount:a.filter(c=>!c.resolvedPath).length,scanDurationMs:Date.now()-n}}}endpointToDiscoveredApi(e,t){let n=e.methods[0],s=e.pathUnresolved?"low":"high",i=e.params.map(l=>this.paramToDiscovered(l,t)),o=this.buildRequestBody(e,t),a=this.buildResponses(e,t),c=e.security.length>0?{required:!0,type:"jwt",annotation:e.security.join(", ")}:void 0;return{id:"",framework:"fastapi",method:n,pathExpression:e.path,resolvedPath:e.path,confidence:s,source:{filePath:e.file,line:e.line,symbolName:`${n} ${e.path}`},params:i.length>0?i:void 0,requestBody:o,responses:a,auth:c,tags:e.tags,deprecated:e.deprecated,description:e.summary}}paramToDiscovered(e,t){let n=lv(e.type),s=sn(e.type,t)??(n?{type:n}:void 0),i={name:e.name,location:e.location,required:e.location==="path"?!0:e.required};return n&&(i.type=n),s&&(i.schema=s),i}buildRequestBody(e,t){let n=e.params.filter(i=>i.location==="body");if(n.length===0){let i=e.params.filter(o=>o.location==="form");return i.length>0?{type:"multipart",required:i.some(o=>o.required)}:void 0}let s=sn(n[0].type,t);return{type:"json",required:n.some(i=>i.required),schema:s??{type:"object"}}}buildResponses(e,t){let s={statusCode:e.statusCode??200};if(e.responseModel){let i=/^(?:List|list|Sequence)\[/.test(e.responseModel),o=i?/^(?:List|list|Sequence)\[(.+)\]$/.exec(e.responseModel)[1]:e.responseModel,a=sn(o,t);a&&(s.body={type:"json",schema:i?{type:"array",items:a}:a})}return[s]}}});function vs(r){let e;try{let n=(0,hf.execSync)("git rev-parse HEAD",{cwd:r,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim();n&&(e=n)}catch{e=void 0}let t=0;try{let n=[r],s=new Set(["node_modules",".git","target","build","dist","out","__pycache__",".venv","venv"]);for(;n.length>0;){let i=n.shift(),o;try{o=Sa.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){let c=mf.join(i,a.name);if(a.isDirectory()){s.has(a.name)||n.push(c);continue}if(!(!a.isFile()||!uv.some(l=>c.endsWith(l))))try{let l=Sa.statSync(c);l.mtimeMs>t&&(t=l.mtimeMs)}catch{}}}}catch{t=0}return{gitHash:e,maxSourceMtime:t}}function bs(r,e){let t=vs(r);if(!e)return{projectRoot:r,status:"unknown",currentFreshness:t,reason:"no stored index entry"};if(t.gitHash&&e.gitHash)return t.gitHash===e.gitHash?{projectRoot:r,status:"current",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t}:{projectRoot:r,status:"stale",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t,reason:`git HEAD changed: ${e.gitHash.slice(0,8)} \u2192 ${t.gitHash.slice(0,8)}`};let n=new Date(e.scannedAt).getTime();return t.maxSourceMtime>n?{projectRoot:r,status:"stale",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t,reason:`source file newer than last scan (${new Date(t.maxSourceMtime).toISOString()} > ${e.scannedAt})`}:{projectRoot:r,status:"current",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t}}function su(r){let e=r.projects.map(t=>bs(t.projectRoot,t.freshness));return{projects:e,staleCount:e.filter(t=>t.status==="stale").length,checkedAt:new Date().toISOString()}}function ys(r,e){let t=r.split(`
475
475
  `),n=e.split(`
476
476
  `),s=t.length,i=n.length,o=Array.from({length:s+1},()=>new Array(i+1).fill(0));for(let u=s-1;u>=0;u--)for(let d=i-1;d>=0;d--)o[u][d]=t[u]===n[d]?o[u+1][d+1]+1:Math.max(o[u+1][d],o[u][d+1]);let a=[],c=0,l=0;for(;c<s&&l<i;)t[c]===n[l]?(a.push({type:"same",line:c+1,text:t[c]}),c++,l++):o[c+1][l]>=o[c][l+1]?(a.push({type:"removed",line:c+1,text:t[c]}),c++):(a.push({type:"added",line:l+1,text:n[l]}),l++);for(;c<s;)a.push({type:"removed",line:c+1,text:t[c]}),c++;for(;l<i;)a.push({type:"added",line:l+1,text:n[l]}),l++;return a}function xa(r,e,t){let n=ys(r,e),s=ys(r,t),i=n.filter(o=>o.type!=="same").length;return{userChanges:n,regeneratedChanges:s,changed:t!==r,userEditedLineCount:i}}function wa(r,e,t){let n=t.split(`
477
477
  `),s=r.split(`
@@ -760,14 +760,14 @@ ${u.join(`
760
760
  <div class="col-pane exec-meta-box">
761
761
  <div class="pane-title">Execution Metadata</div>
762
762
  <div class="pane-section">${B}</div>
763
- </div>`,ue=`
763
+ </div>`,de=`
764
764
  <div class="pane-section"><div class="pane-section-title">Overview</div>${cn}</div>
765
765
  <div class="pane-section"><div class="pane-section-title">Headers</div>${ft}</div>
766
766
  ${yc?`<div class="pane-section"><div class="pane-section-title">Body</div>${zi}</div>`:""}`,Te=`
767
767
  <div class="pane-section"><div class="pane-section-title">Overview</div>${P}</div>
768
768
  <div class="pane-section"><div class="pane-section-title">Headers</div>${It}</div>
769
769
  <div class="pane-section"><div class="pane-section-title">Cookies</div>${W}</div>
770
- <div class="pane-section"><div class="pane-section-title">Body</div>${k}</div>`,_=ue.length<=Te.length,je=_?ae:"",Le=_?"":ae,be=H?.consoleOutput?.length?`<div class="console-block"><pre class="code console-code">${H.consoleOutput.map(ht=>te(typeof ht=="string"?ht:JSON.stringify(ht))).join(`
770
+ <div class="pane-section"><div class="pane-section-title">Body</div>${k}</div>`,_=de.length<=Te.length,je=_?ae:"",Le=_?"":ae,be=H?.consoleOutput?.length?`<div class="console-block"><pre class="code console-code">${H.consoleOutput.map(ht=>te(typeof ht=="string"?ht:JSON.stringify(ht))).join(`
771
771
  `)}</pre></div>`:"",Se=H?.error?`<div class="error-box">\u26A0 ${te(H.error)}</div>`:"",Tn=H?`<span class="${Ga(H.status)} status-badge">${H.status} ${te(H.statusText??"")}</span>`:"",Lm=`<span class="dur-badge">${st(q.d)}</span>`,Hm=e.config.iterations>1?`<span class="iter-badge">iter ${q.it}</span>`:"";o[`${q.i}-${q.it}`]={d:H??null,method:Ie,s:q.s,ap:q.ap,af:q.af,as:q.as??0,embed:mt};let Bm=te(`${q.n} ${H?.url??""}`.toLowerCase());return`
772
772
  <details class="req-detail ${Pe?"req-pass":"req-fail"}" id="${Ge}" data-key="${q.i}-${q.it}" data-search="${Bm}" style="--border:${ot}">
773
773
  <summary class="req-summary">
@@ -1422,9 +1422,9 @@ ${u.join(`
1422
1422
  `+s.map(i=>` - ${i.name} (id: ${i.id}, path: ${i.path||"/"})`).join(`
1423
1423
  `)+`
1424
1424
  Disambiguate by passing the id or slug.`);this.kind=t;this.value=n;this.candidates=s;this.name="AmbiguousRefError"}kind;value;candidates}});function Os(r){return typeof r=="string"?r:""+JSON.stringify(r)}function br(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function uc(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]=br(n);return e}var Iu=E(()=>{"use strict"});var Bi,hm=E(()=>{"use strict";za();ti();Zr();Di();Ka();Ls();Iu();Eu();Au();Va();Bi=class{constructor(e){this.container=e}container;async execute(e,t,n){let s=this.container,i=t.environment??s.environmentConfig.getSelectedEnvironment(),o=t.iterations??e.config?.iterations??1,a=t.stopOnError??e.config?.stopOnError??!1,c=t.delay??e.config?.delayBetweenRequests??0,l=Math.max(1,Math.min(50,t.concurrency??1)),u=t.requestFilter,d=t.include??[],p=t.reporters??[],m=p.includes("junit"),f=Is(t.variables),h=um(),g=Za(d,p),y=Math.max(1,Math.min(1e4,Number(t.maxNodeLoopIterations??100))),v={vars:{...f}};function w(P){if(typeof P=="string")return P;if(Array.isArray(P))return P.filter(W=>typeof W=="string").join(`
1425
- `)}function b(P){if(!(!P||typeof P!="object")){if(P.script!==void 0)return P.script;if(typeof P.scriptRef=="string"&&P.scriptRef.trim()){let k=e?.scripts;if(k&&typeof k=="object")return k[P.scriptRef]}}}function C(P){return P?.name||P?.label||P?.id||"flow-node"}function R(P,k){let W=s.environmentConfig.getResolvedEnvironment(i),B=uc(v.vars),Te={variables:{get:_=>br(v.vars[_]),set:(_,je)=>{typeof _=="string"&&_.trim()&&(v.vars[_]=Os(je))},unset:_=>{typeof _=="string"&&_.trim()&&delete v.vars[_]},has:_=>Object.prototype.hasOwnProperty.call(v.vars,_),toObject:()=>({...B})},environment:{get:_=>br(W?.variables?.[_]),set:(_,je)=>{typeof _=="string"&&_.trim()&&s.environmentConfig.setEnvironmentVariable(_,Os(je),i)},unset:_=>{typeof _=="string"&&_.trim()&&s.environmentConfig.deleteEnvironmentVariable(_,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:_=>br(s.environmentConfig.getGlobalVariables()?.[_]),set:(_,je)=>{typeof _=="string"&&_.trim()&&s.environmentConfig.setGlobalVariable(_,Os(je))},unset:_=>{typeof _=="string"&&_.trim()&&s.environmentConfig.deleteGlobalVariable(_)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:B,lastResult:v.lastResult,iteration:k,node:P,pm:Te,ctx:Te,hf:Te}}function A(P,k,W){return typeof P!="string"||!P.trim()?!0:!!gt(P,R(k,W))}function N(P){if(!P)return{};let k={};for(let[W,B]of Object.entries(P))k[W]=Array.isArray(B)?B.join("; "):String(B);return k}function M(P){return{executedRequest:P.executedRequest,status:P.response?.status??0,statusText:P.response?.statusText??"",headers:N(P.response?.headers),body:P.response?.body,cookies:P.response?.cookies,responseTime:P.duration,responseSize:typeof P.response?.body=="string"?Buffer.byteLength(P.response.body,"utf8"):0}}async function j(P,k,W,B,J){let ae=w(P);if(!ae||!ae.trim())return;let ue=s.environmentConfig.getResolvedEnvironment(i),Te=s.environmentConfig.getGlobalVariables(),je={request:{url:J?.request?.url??v.lastResult?.executedRequest?.url??"http://flow.local/node",method:J?.request?.method??v.lastResult?.executedRequest?.method??"GET",headers:N(J?.request?.headers),body:J?.request?.body??null,params:J?.request?.params??{},query:J?.request?.query??{}},variables:Is(v.vars),environmentVariables:ue?.variables||{},globals:{...Te},environmentName:i,info:{eventName:B==="post"?"test":"prerequest",requestName:C(k),requestId:String(k?.id??C(k)),collectionName:e.name,iteration:W,iterationCount:o},onEnvironmentChange:(be,Se,Tn)=>{be==="set"&&Se&&Tn!==void 0?s.environmentConfig.setEnvironmentVariable(Se,Tn,i):be==="unset"&&Se?s.environmentConfig.deleteEnvironmentVariable(Se,i):be==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(be,Se,Tn)=>{be==="set"&&Se&&Tn!==void 0?s.environmentConfig.setGlobalVariable(Se,Tn):be==="unset"&&Se?s.environmentConfig.deleteGlobalVariable(Se):be==="clear"&&s.environmentConfig.clearGlobalVariables()}},Le=s.scriptExecutor.createRequestSession(je);try{if(B==="post"&&J?.response){let be=await Le.executePostResponse(ae,J.response),Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(v.vars={...Se})}else{let be=await Le.executePreRequest(ae);if(!be.success)throw new Error(be.error||"Script execution failed");let Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(v.vars={...Se})}}catch(be){let Se=be instanceof Error?be.message:String(be);throw new Error(`Suite ${B}-script failed on node "${C(k)}": ${Se}`)}finally{Le.dispose?.()}}function U(P){let k=P?.type==="request"&&P?.request?P.request:P;if(!(!k||typeof k!="object")&&!(!k.collectionId||!k.requestId||!k.name))return{collectionId:k.collectionId,requestId:k.requestId,name:k.name,folderPath:k.folderPath,enabled:k.enabled}}function O(P){return!P||typeof P!="object"?!1:P.type==="request"?!!U(P):!!(P.collectionId&&P.requestId&&P.name)}function L(P,k){for(let W of k){let B=P?.[W];if(Array.isArray(B))return B}return[]}async function Q(P,k,W){if(me.signal.aborted||k.enabled===!1||u&&!u.some(Le=>k.name.toLowerCase().includes(Le.toLowerCase())))return;let B=s.collection.getCollection(k.collectionId);if(!B)return;let J=Li(B,k.requestId);if(!J)return;let ae=nc(J.request.auth,J.folderAuthChain,B.auth),ue=new _t(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,ft,B.scripts,J.folderScriptsChain,void 0,B.name,B.auth,P,o),Te=tc(ec({...J.request,auth:ae}),{headers:t.headers,query:t.query,body:t.body,variables:{...v.vars,...t.variables}}),_=await ue.execute(Te,Is(v.vars),me.signal);v.lastResult=_,_.modifiedVariables&&typeof _.modifiedVariables=="object"&&(v.vars={..._.modifiedVariables});let je=ws({collectionName:B.name,folderPath:k.folderPath??"",blockLabel:W});_.folderPath=k.folderPath??"",_.collectionName=B.name,_.groupPath=je.groupPath,_.groupType=je.groupType,await X.saveResult(P,_),_.assertions?.length||ot.add(k.name),_.passed?Ge++:Pe++,d.includes("perRequest")&&H.push({name:k.name,iteration:P,status:_.response?.status,ok:(_.response?.status??0)>=200&&(_.response?.status??0)<300,duration:`${_.duration}ms`,allPassed:_.passed,...d.includes("consoleOutput")&&_.consoleOutput?.length?{consoleOutput:_.consoleOutput}:{}}),_.passed||(Ie.push({name:k.name,iteration:P,method:_.executedRequest?.method,url:_.executedRequest?.url,requestBody:Hi(_.executedRequest?.body?.content)??_.executedRequest?.body?.content??null,requestHeaders:lt(_.executedRequest?.headers??{}),status:_.response?.status,duration:`${_.duration}ms`,body:Hi(_.response?.body),headers:Ya(_.response?.headers),cookies:Xa(_.response?.cookies),failedTests:_.assertions?.filter(Le=>!Le.passed).map(Le=>({name:Le.name,...Le.message?{message:Le.message}:{}})),..._.error?{error:_.error}:{},...d.includes("consoleOutput")&&_.consoleOutput?.length?{consoleOutput:_.consoleOutput}:{}}),a&&me.abort()),c>0&&!me.signal.aborted&&await new Promise(Le=>setTimeout(Le,c))}async function Y(P,k,W){for(let B of k){if(me.signal.aborted)break;await Je(P,B,W)}}async function Je(P,k,W){if(!k||typeof k!="object"||k.enabled===!1||!A(k.condition,k,P))return;if(O(k)){let ae=U(k);ae&&await Q(P,ae,W);return}let B=typeof k.type=="string"?k.type.toLowerCase():"",J=L(k,["then","nodes","body"]);if(B==="block"){let ae=typeof k.name=="string"?k.name.trim():"";await Y(P,J,ae||W);return}if(B==="script"){let ae=b(k),ue=k.phase==="post"?"post":"pre";await j(ae,k,P,ue);return}if(B==="if"){let ae=typeof k.if=="string"?k.if:k.condition;if(A(ae,k,P)){await Y(P,J,W);return}if(Array.isArray(k.elseif)){for(let ue of k.elseif)if(A(ue?.condition,ue,P)){await Y(P,L(ue,["then","nodes","body"]),W);return}}await Y(P,L(k,["else","elseNodes"]),W);return}if(B==="switch"){let ae=gt(String(k.expression??""),R(k,P));if(Array.isArray(k.cases)){for(let ue of k.cases)if(Object.prototype.hasOwnProperty.call(ue??{},"equals")?ue.equals===ae:A(ue?.condition,ue,P)){await Y(P,L(ue,["then","nodes","body"]),W);return}}await Y(P,L(k,["default","defaultNodes"]),W);return}if(B==="while"){let ae=typeof k.while=="string"?k.while:k.condition,ue=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),Te=0;for(;A(ae,k,P);){if(Te+=1,Te>ue)throw new Error(`Suite while loop exceeded maxIterations (${ue}) on node "${C(k)}"`);if(await Y(P,J,W),me.signal.aborted)break}return}if(B==="for"){let ae=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),ue=w(k.init),Te=w(k.update),_=typeof k.loopCondition=="string"&&k.loopCondition.trim()?k.loopCondition:typeof k.condition=="string"&&k.condition.trim()?k.condition:"true";ue&&await j(ue,k,P,"pre");let je=0;for(;A(_,k,P);){if(je+=1,je>ae)throw new Error(`Suite for loop exceeded maxIterations (${ae}) on node "${C(k)}"`);if(await Y(P,J,W),me.signal.aborted)break;Te&&await j(Te,k,P,"post")}return}J.length>0&&await Y(P,J,W)}function an(P){let k=0,W=[...P];for(;W.length>0;){let B=W.pop();if(!(!B||typeof B!="object"||B.enabled===!1)){if(O(B)){let J=U(B);J&&(!u||u.some(ae=>J.name.toLowerCase().includes(ae.toLowerCase())))&&(k+=1);continue}for(let J of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(B[J])&&W.push(...B[J]);if(Array.isArray(B.elseif))for(let J of B.elseif)Array.isArray(J?.nodes)&&W.push(...J.nodes),Array.isArray(J?.then)&&W.push(...J.then);if(Array.isArray(B.cases))for(let J of B.cases)Array.isArray(J?.nodes)&&W.push(...J.nodes),Array.isArray(J?.then)&&W.push(...J.then)}}return k}let kt=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(P=>({type:"request",request:P})):[],q=an(kt);if(h){let P=dm(),k=q*o;if(k>P)throw new Error(`Suite "${e.name}" would execute ${k} request calls (${q} requests \xD7 ${o} iterations), which exceeds HTTP_FORGE_MAX_REQUESTS (${P}). Reduce iterations, use requestFilter, or increase HTTP_FORGE_MAX_REQUESTS.`)}let X=new kn(s.config),Ce=await X.initializeRun(e.id,e.name,i,{iterations:o,delayBetweenRequests:c,stopOnError:a},{targetType:n==="suite"?"suite":"collection",targetName:e.name,collectionName:n==="suite"?void 0:e.collectionName,folderPath:n==="suite"?void 0:e.folderPath}),H=[],Ie=[],Ge=0,Pe=0,ot=new Set,me=new AbortController,ft=new An;async function cn(P){await Y(P,kt)}for(let P=1;P<=o&&!me.signal.aborted;P+=l){let k=Math.min(P+l-1,o),W=Array.from({length:k-P+1},(B,J)=>P+J);await Promise.all(W.map(cn))}let ye=await X.finalizeRun("completed",g),Ns=null;if(m)try{Ns=await new Lt(X.getBasePath()).generate(e.id,Ce)}catch(P){console.warn("[direct-execution] JUnit report generation failed:",P)}let wr=n==="collection"?"collection":"suite",mt=X.getCurrentStats()?.stats,zi=mt?{min:mt.minDuration,max:mt.maxDuration,avg:mt.avgDuration,p50:mt.p50??null,p95:mt.p95??null,p99:mt.p99??null}:null,It={[wr]:e.name,environment:i,summary:{total:Ge+Pe,passed:Ge,failed:Pe,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:Pe===0,...zi?{durationMs:zi}:{}}};if((Pe>0||d.includes("failedOnly"))&&(It.failedRequests=Ie),d.includes("perRequest")&&(It.results=H),ye!==null&&(It.report={uri:`file://${ye}`,hint:"Click the URI to open the HTML report in your browser"}),Ns!==null&&(It.junitReport={path:Ns}),ot.size>0){let P=Math.max(q,1),k=ot.size,W=Array.from(ot).slice(0,5);It.noAssertionExamples=W;let B=e.name;if(k/P>.5)It._suggestions=[`${k}/${P} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${B}") for a full coverage analysis and to identify assertion gaps.`];else{let J=W.map(ae=>`"${ae}"`).join(", ");It._suggestions=[`${k} request(s) have no pm.test() assertions: ${J}. Invoke the "suggest-assertions" prompt (collection="${B}") to generate test coverage for them.`]}}return It}}});var Vi={};Tt(Vi,{runCollection:()=>on,runFolder:()=>ib,runRequest:()=>dc,runSuite:()=>Ui});function gm(r,e){if(e.collectionId){let t=r.getCollection(e.collectionId);if(!t)throw new Error(`Collection "${e.collectionId}" not found`);return t}if(e.collectionRef){let{collection:t,tier:n}=ac(r.getAllCollections(),e.collectionRef);return e.onResolve?.({kind:"collection",value:e.collectionRef,tier:n,id:t.id}),t}throw new Error("A collection reference is required (collectionId or collectionRef)")}function ym(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=cc(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function dc(r){let e=it(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=Za(t,n);try{let o=e.collection,a=gm(o,r),c=ym(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let C=lc(a,r.requestRef,c);l=C.request.id,r.onResolve?.({kind:"request",value:r.requestRef,tier:C.tier,id:l,path:C.folderPath?`${C.folderPath}/${C.request.name}`:C.request.name})}let u=Li(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let d=nc(u.request.auth,u.folderAuthChain,a.auth),p=r.environment||e.environmentConfig.getSelectedEnvironment(),m=tc(ec({...u.request,auth:d}),{headers:r.headers,query:r.query,body:r.body,variables:r.variables}),h=await new _t(e.httpRequest,e.scriptExecutor,e.environmentConfig,e.requestPreparer,p,new An,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth).execute(m,Is(r.variables)),g=ws({collectionName:a.name,folderPath:u.folderPath});h.folderPath=u.folderPath,h.collectionName=a.name,h.groupPath=g.groupPath,h.groupType=g.groupType;let y=null,v=null;if(i||s){let C=new kn(e.config),R=`request-${qu(a.id)}-${qu(l)}`,A=`Request: ${u.request.name}`,N=await C.initializeRun(R,A,p,{iterations:1,delayBetweenRequests:0,stopOnError:!0},{targetType:"collection",targetName:a.name,collectionName:a.name,folderPath:u.folderPath||void 0});if(await C.saveResult(1,h),y=await C.finalizeRun("completed",i),s)try{v=await new Lt(C.getBasePath()).generate(R,N)}catch(M){console.warn("[direct-execution] JUnit report generation failed:",M)}}let w=Ya(h.response?.headers),b=Xa(h.response?.cookies);return{request:u.request.name,status:h.response?.status||0,ok:(h.response?.status??0)>=200&&(h.response?.status??0)<300,duration:`${h.duration}ms`,body:Hi(h.response?.body),allPassed:h.passed,assertions:h.assertions?.map(C=>({name:C.name,passed:C.passed,message:C.message})),...t.includes("headers")?{headers:w}:{},...t.includes("cookies")?{cookies:b}:{},...t.includes("tests")?{tests:h.assertions?.map(C=>({name:C.name,passed:C.passed,...C.message?{message:C.message}:{}}))}:{},...Object.keys(h.modifiedVariables??{}).length?{modifiedVariables:h.modifiedVariables}:{},...t.includes("consoleOutput")&&h.consoleOutput?.length?{consoleOutput:h.consoleOutput}:{},...y!==null?{report:{uri:`file://${y}`,hint:"Click the URI to open the HTML report in your browser"}}:{},...v!==null?{junitReport:{path:v}}:{},...h.error?{error:h.error}:{}}}catch(o){throw o}finally{Qa(e)}}async function on(r){let e=it(r.workspaceFolder);try{let t=e.collection,n=gm(t,r),s=ym(n,r),i=Cu(n),o=am(i,s,r.recursive);if(o.length===0&&s)throw new Error(`No requests found under folder "${s}" in collection "${n.name}"`);let a=o.map(({request:l,folderPath:u})=>({id:l.id,slug:l.id.toLowerCase().replace(/\s+/g,"-"),collectionId:n.id,requestId:l.id,name:l.name,method:l.method,collectionName:n.name,folderPath:u,enabled:!0})),c={id:s?`temp-${n.id}-${cm(s)}`:`temp-${n.id}`,name:s?`${n.name} / ${s}`:n.name,requests:a,config:{iterations:1,delay:0,stopOnError:r.stopOnError??!1,readFromSharedSession:!1,writeToSharedSession:!1},isTemporary:!0,createdAt:Date.now(),updatedAt:Date.now()};return new Bi(e).execute(c,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:void 0,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"collection")}catch(t){throw t}finally{Qa(e)}}async function ib(r){return on({recursive:!0,...r})}async function Ui(r){let e=it(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new Bi(e).execute(n,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:r.requestFilter,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"suite")}catch(t){throw t}finally{Qa(e)}}var $s=E(()=>{"use strict";za();ti();Di();Ka();Eu();Au();oc();ku();Va();hm()});var wm={};Tt(wm,{createMcpRuntime:()=>bb});async function At(r){let e=process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS,t=process.env.HTTP_FORGE_GENERATE_REPORTS;process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS="true",process.env.HTTP_FORGE_GENERATE_REPORTS="true";try{return await r()}finally{e===void 0?delete process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS:process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS=e,t===void 0?delete process.env.HTTP_FORGE_GENERATE_REPORTS:process.env.HTTP_FORGE_GENERATE_REPORTS=t}}function Fs(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function cb(r,e){let t=$u.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=Tu.get(r);if(n)return n;let s=(async()=>{let i=e.config.getMcpConfig(),o=(l,u)=>!!l?.length&&(l.includes(u.id)||l.includes(u.name)),a=e.collection.getAllCollections().filter(l=>!o(i.excludedCollections,l)),c=(await e.testSuite.getAllSuites()).filter(l=>!o(i.excludedSuites,l));return Ua(a,c,i,r)})().then(i=>($u.set(r,{tools:i,expiresAt:Date.now()+ab}),i)).finally(()=>Tu.delete(r));return Tu.set(r,s),s}function lb(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function ub(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function vm(r,e,t,n){Sr(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function db(r){return r.config.getMcpConfig().toolPageSize??200}async function pb(r,e){switch(e.method){case"initialize":return{protocolVersion:"2024-11-05",capabilities:{tools:{},prompts:{}},serverInfo:{name:"http-forge",version:"1.0.0"},instructions:"You are assisting with HTTP API testing via HTTP Forge. When a run_suite, run_collection, or run_folder call completes with failures (summary.failed > 0 or allPassed === false), automatically analyze the 'failedRequests' in the response and provide: (1) root cause for each failure, (2) specific fix recommendations, (3) updated pm.test() assertion scripts where relevant. Do not wait for the user to ask \u2014 proactively diagnose and suggest fixes. For async runs (status: 'running'), poll with get_run_status until complete, then call get_run_summary. When get_run_summary returns a _nextStep field you MUST execute it immediately \u2014 the failedRequests array is already included inline so no extra tool call is needed. Analyze the failures and provide diagnosis without waiting for the user."};case"tools/list":{let t=await cb(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=db(r.container);if(i<=0||t.length<=i)return{tools:t};let o=Ba(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=Ha(c)),l}case"tools/call":{let t=e.params??{},n=t.name,s=t.arguments;if(!n)throw new Error("Missing tool name");let i=await Fu(r,n,s??{}),o=i,a=o?.summary;a&&((a.failed??0)>0||a.allPassed===!1)&&(o._nextStep=`${a.failed??"Some"} request(s) failed. Please analyze the 'failedRequests' above: identify the root cause of each failure, suggest specific fixes (URL, auth, body, environment variables), and provide updated pm.test() assertion scripts where the assertions are incorrect.`);let c=JSON.stringify(i,null,2),l=ub(c,r.host,r.port),u=l.match(/"uri"\s*:\s*"(http:\/\/[^"]+\/report\?[^"]+)"/),d=u?`
1425
+ `)}function b(P){if(!(!P||typeof P!="object")){if(P.script!==void 0)return P.script;if(typeof P.scriptRef=="string"&&P.scriptRef.trim()){let k=e?.scripts;if(k&&typeof k=="object")return k[P.scriptRef]}}}function C(P){return P?.name||P?.label||P?.id||"flow-node"}function R(P,k){let W=s.environmentConfig.getResolvedEnvironment(i),B=uc(v.vars),Te={variables:{get:_=>br(v.vars[_]),set:(_,je)=>{typeof _=="string"&&_.trim()&&(v.vars[_]=Os(je))},unset:_=>{typeof _=="string"&&_.trim()&&delete v.vars[_]},has:_=>Object.prototype.hasOwnProperty.call(v.vars,_),toObject:()=>({...B})},environment:{get:_=>br(W?.variables?.[_]),set:(_,je)=>{typeof _=="string"&&_.trim()&&s.environmentConfig.setEnvironmentVariable(_,Os(je),i)},unset:_=>{typeof _=="string"&&_.trim()&&s.environmentConfig.deleteEnvironmentVariable(_,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:_=>br(s.environmentConfig.getGlobalVariables()?.[_]),set:(_,je)=>{typeof _=="string"&&_.trim()&&s.environmentConfig.setGlobalVariable(_,Os(je))},unset:_=>{typeof _=="string"&&_.trim()&&s.environmentConfig.deleteGlobalVariable(_)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:B,lastResult:v.lastResult,iteration:k,node:P,pm:Te,ctx:Te,hf:Te}}function A(P,k,W){return typeof P!="string"||!P.trim()?!0:!!gt(P,R(k,W))}function N(P){if(!P)return{};let k={};for(let[W,B]of Object.entries(P))k[W]=Array.isArray(B)?B.join("; "):String(B);return k}function M(P){return{executedRequest:P.executedRequest,status:P.response?.status??0,statusText:P.response?.statusText??"",headers:N(P.response?.headers),body:P.response?.body,cookies:P.response?.cookies,responseTime:P.duration,responseSize:typeof P.response?.body=="string"?Buffer.byteLength(P.response.body,"utf8"):0}}async function j(P,k,W,B,J){let ae=w(P);if(!ae||!ae.trim())return;let de=s.environmentConfig.getResolvedEnvironment(i),Te=s.environmentConfig.getGlobalVariables(),je={request:{url:J?.request?.url??v.lastResult?.executedRequest?.url??"http://flow.local/node",method:J?.request?.method??v.lastResult?.executedRequest?.method??"GET",headers:N(J?.request?.headers),body:J?.request?.body??null,params:J?.request?.params??{},query:J?.request?.query??{}},variables:Is(v.vars),environmentVariables:de?.variables||{},globals:{...Te},environmentName:i,info:{eventName:B==="post"?"test":"prerequest",requestName:C(k),requestId:String(k?.id??C(k)),collectionName:e.name,iteration:W,iterationCount:o},onEnvironmentChange:(be,Se,Tn)=>{be==="set"&&Se&&Tn!==void 0?s.environmentConfig.setEnvironmentVariable(Se,Tn,i):be==="unset"&&Se?s.environmentConfig.deleteEnvironmentVariable(Se,i):be==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(be,Se,Tn)=>{be==="set"&&Se&&Tn!==void 0?s.environmentConfig.setGlobalVariable(Se,Tn):be==="unset"&&Se?s.environmentConfig.deleteGlobalVariable(Se):be==="clear"&&s.environmentConfig.clearGlobalVariables()}},Le=s.scriptExecutor.createRequestSession(je);try{if(B==="post"&&J?.response){let be=await Le.executePostResponse(ae,J.response),Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(v.vars={...Se})}else{let be=await Le.executePreRequest(ae);if(!be.success)throw new Error(be.error||"Script execution failed");let Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(v.vars={...Se})}}catch(be){let Se=be instanceof Error?be.message:String(be);throw new Error(`Suite ${B}-script failed on node "${C(k)}": ${Se}`)}finally{Le.dispose?.()}}function U(P){let k=P?.type==="request"&&P?.request?P.request:P;if(!(!k||typeof k!="object")&&!(!k.collectionId||!k.requestId||!k.name))return{collectionId:k.collectionId,requestId:k.requestId,name:k.name,folderPath:k.folderPath,enabled:k.enabled}}function O(P){return!P||typeof P!="object"?!1:P.type==="request"?!!U(P):!!(P.collectionId&&P.requestId&&P.name)}function L(P,k){for(let W of k){let B=P?.[W];if(Array.isArray(B))return B}return[]}async function Q(P,k,W){if(me.signal.aborted||k.enabled===!1||u&&!u.some(Le=>k.name.toLowerCase().includes(Le.toLowerCase())))return;let B=s.collection.getCollection(k.collectionId);if(!B)return;let J=Li(B,k.requestId);if(!J)return;let ae=nc(J.request.auth,J.folderAuthChain,B.auth),de=new _t(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,ft,B.scripts,J.folderScriptsChain,void 0,B.name,B.auth,P,o),Te=tc(ec({...J.request,auth:ae}),{headers:t.headers,query:t.query,body:t.body,variables:{...v.vars,...t.variables}}),_=await de.execute(Te,Is(v.vars),me.signal);v.lastResult=_,_.modifiedVariables&&typeof _.modifiedVariables=="object"&&(v.vars={..._.modifiedVariables});let je=ws({collectionName:B.name,folderPath:k.folderPath??"",blockLabel:W});_.folderPath=k.folderPath??"",_.collectionName=B.name,_.groupPath=je.groupPath,_.groupType=je.groupType,await X.saveResult(P,_),_.assertions?.length||ot.add(k.name),_.passed?Ge++:Pe++,d.includes("perRequest")&&H.push({name:k.name,iteration:P,status:_.response?.status,ok:(_.response?.status??0)>=200&&(_.response?.status??0)<300,duration:`${_.duration}ms`,allPassed:_.passed,...d.includes("consoleOutput")&&_.consoleOutput?.length?{consoleOutput:_.consoleOutput}:{}}),_.passed||(Ie.push({name:k.name,iteration:P,method:_.executedRequest?.method,url:_.executedRequest?.url,requestBody:Hi(_.executedRequest?.body?.content)??_.executedRequest?.body?.content??null,requestHeaders:lt(_.executedRequest?.headers??{}),status:_.response?.status,duration:`${_.duration}ms`,body:Hi(_.response?.body),headers:Ya(_.response?.headers),cookies:Xa(_.response?.cookies),failedTests:_.assertions?.filter(Le=>!Le.passed).map(Le=>({name:Le.name,...Le.message?{message:Le.message}:{}})),..._.error?{error:_.error}:{},...d.includes("consoleOutput")&&_.consoleOutput?.length?{consoleOutput:_.consoleOutput}:{}}),a&&me.abort()),c>0&&!me.signal.aborted&&await new Promise(Le=>setTimeout(Le,c))}async function Y(P,k,W){for(let B of k){if(me.signal.aborted)break;await Je(P,B,W)}}async function Je(P,k,W){if(!k||typeof k!="object"||k.enabled===!1||!A(k.condition,k,P))return;if(O(k)){let ae=U(k);ae&&await Q(P,ae,W);return}let B=typeof k.type=="string"?k.type.toLowerCase():"",J=L(k,["then","nodes","body"]);if(B==="block"){let ae=typeof k.name=="string"?k.name.trim():"";await Y(P,J,ae||W);return}if(B==="script"){let ae=b(k),de=k.phase==="post"?"post":"pre";await j(ae,k,P,de);return}if(B==="if"){let ae=typeof k.if=="string"?k.if:k.condition;if(A(ae,k,P)){await Y(P,J,W);return}if(Array.isArray(k.elseif)){for(let de of k.elseif)if(A(de?.condition,de,P)){await Y(P,L(de,["then","nodes","body"]),W);return}}await Y(P,L(k,["else","elseNodes"]),W);return}if(B==="switch"){let ae=gt(String(k.expression??""),R(k,P));if(Array.isArray(k.cases)){for(let de of k.cases)if(Object.prototype.hasOwnProperty.call(de??{},"equals")?de.equals===ae:A(de?.condition,de,P)){await Y(P,L(de,["then","nodes","body"]),W);return}}await Y(P,L(k,["default","defaultNodes"]),W);return}if(B==="while"){let ae=typeof k.while=="string"?k.while:k.condition,de=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),Te=0;for(;A(ae,k,P);){if(Te+=1,Te>de)throw new Error(`Suite while loop exceeded maxIterations (${de}) on node "${C(k)}"`);if(await Y(P,J,W),me.signal.aborted)break}return}if(B==="for"){let ae=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),de=w(k.init),Te=w(k.update),_=typeof k.loopCondition=="string"&&k.loopCondition.trim()?k.loopCondition:typeof k.condition=="string"&&k.condition.trim()?k.condition:"true";de&&await j(de,k,P,"pre");let je=0;for(;A(_,k,P);){if(je+=1,je>ae)throw new Error(`Suite for loop exceeded maxIterations (${ae}) on node "${C(k)}"`);if(await Y(P,J,W),me.signal.aborted)break;Te&&await j(Te,k,P,"post")}return}J.length>0&&await Y(P,J,W)}function an(P){let k=0,W=[...P];for(;W.length>0;){let B=W.pop();if(!(!B||typeof B!="object"||B.enabled===!1)){if(O(B)){let J=U(B);J&&(!u||u.some(ae=>J.name.toLowerCase().includes(ae.toLowerCase())))&&(k+=1);continue}for(let J of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(B[J])&&W.push(...B[J]);if(Array.isArray(B.elseif))for(let J of B.elseif)Array.isArray(J?.nodes)&&W.push(...J.nodes),Array.isArray(J?.then)&&W.push(...J.then);if(Array.isArray(B.cases))for(let J of B.cases)Array.isArray(J?.nodes)&&W.push(...J.nodes),Array.isArray(J?.then)&&W.push(...J.then)}}return k}let kt=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(P=>({type:"request",request:P})):[],q=an(kt);if(h){let P=dm(),k=q*o;if(k>P)throw new Error(`Suite "${e.name}" would execute ${k} request calls (${q} requests \xD7 ${o} iterations), which exceeds HTTP_FORGE_MAX_REQUESTS (${P}). Reduce iterations, use requestFilter, or increase HTTP_FORGE_MAX_REQUESTS.`)}let X=new kn(s.config),Ce=await X.initializeRun(e.id,e.name,i,{iterations:o,delayBetweenRequests:c,stopOnError:a},{targetType:n==="suite"?"suite":"collection",targetName:e.name,collectionName:n==="suite"?void 0:e.collectionName,folderPath:n==="suite"?void 0:e.folderPath}),H=[],Ie=[],Ge=0,Pe=0,ot=new Set,me=new AbortController,ft=new An;async function cn(P){await Y(P,kt)}for(let P=1;P<=o&&!me.signal.aborted;P+=l){let k=Math.min(P+l-1,o),W=Array.from({length:k-P+1},(B,J)=>P+J);await Promise.all(W.map(cn))}let ye=await X.finalizeRun("completed",g),Ns=null;if(m)try{Ns=await new Lt(X.getBasePath()).generate(e.id,Ce)}catch(P){console.warn("[direct-execution] JUnit report generation failed:",P)}let wr=n==="collection"?"collection":"suite",mt=X.getCurrentStats()?.stats,zi=mt?{min:mt.minDuration,max:mt.maxDuration,avg:mt.avgDuration,p50:mt.p50??null,p95:mt.p95??null,p99:mt.p99??null}:null,It={[wr]:e.name,environment:i,summary:{total:Ge+Pe,passed:Ge,failed:Pe,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:Pe===0,...zi?{durationMs:zi}:{}}};if((Pe>0||d.includes("failedOnly"))&&(It.failedRequests=Ie),d.includes("perRequest")&&(It.results=H),ye!==null&&(It.report={uri:`file://${ye}`,hint:"Click the URI to open the HTML report in your browser"}),Ns!==null&&(It.junitReport={path:Ns}),ot.size>0){let P=Math.max(q,1),k=ot.size,W=Array.from(ot).slice(0,5);It.noAssertionExamples=W;let B=e.name;if(k/P>.5)It._suggestions=[`${k}/${P} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${B}") for a full coverage analysis and to identify assertion gaps.`];else{let J=W.map(ae=>`"${ae}"`).join(", ");It._suggestions=[`${k} request(s) have no pm.test() assertions: ${J}. Invoke the "suggest-assertions" prompt (collection="${B}") to generate test coverage for them.`]}}return It}}});var Vi={};Tt(Vi,{runCollection:()=>on,runFolder:()=>ib,runRequest:()=>dc,runSuite:()=>Ui});function gm(r,e){if(e.collectionId){let t=r.getCollection(e.collectionId);if(!t)throw new Error(`Collection "${e.collectionId}" not found`);return t}if(e.collectionRef){let{collection:t,tier:n}=ac(r.getAllCollections(),e.collectionRef);return e.onResolve?.({kind:"collection",value:e.collectionRef,tier:n,id:t.id}),t}throw new Error("A collection reference is required (collectionId or collectionRef)")}function ym(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=cc(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function dc(r){let e=it(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=Za(t,n);try{let o=e.collection,a=gm(o,r),c=ym(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let C=lc(a,r.requestRef,c);l=C.request.id,r.onResolve?.({kind:"request",value:r.requestRef,tier:C.tier,id:l,path:C.folderPath?`${C.folderPath}/${C.request.name}`:C.request.name})}let u=Li(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let d=nc(u.request.auth,u.folderAuthChain,a.auth),p=r.environment||e.environmentConfig.getSelectedEnvironment(),m=tc(ec({...u.request,auth:d}),{headers:r.headers,query:r.query,body:r.body,variables:r.variables}),h=await new _t(e.httpRequest,e.scriptExecutor,e.environmentConfig,e.requestPreparer,p,new An,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth).execute(m,Is(r.variables)),g=ws({collectionName:a.name,folderPath:u.folderPath});h.folderPath=u.folderPath,h.collectionName=a.name,h.groupPath=g.groupPath,h.groupType=g.groupType;let y=null,v=null;if(i||s){let C=new kn(e.config),R=`request-${qu(a.id)}-${qu(l)}`,A=`Request: ${u.request.name}`,N=await C.initializeRun(R,A,p,{iterations:1,delayBetweenRequests:0,stopOnError:!0},{targetType:"collection",targetName:a.name,collectionName:a.name,folderPath:u.folderPath||void 0});if(await C.saveResult(1,h),y=await C.finalizeRun("completed",i),s)try{v=await new Lt(C.getBasePath()).generate(R,N)}catch(M){console.warn("[direct-execution] JUnit report generation failed:",M)}}let w=Ya(h.response?.headers),b=Xa(h.response?.cookies);return{request:u.request.name,status:h.response?.status||0,ok:(h.response?.status??0)>=200&&(h.response?.status??0)<300,duration:`${h.duration}ms`,body:Hi(h.response?.body),allPassed:h.passed,assertions:h.assertions?.map(C=>({name:C.name,passed:C.passed,message:C.message})),...t.includes("headers")?{headers:w}:{},...t.includes("cookies")?{cookies:b}:{},...t.includes("tests")?{tests:h.assertions?.map(C=>({name:C.name,passed:C.passed,...C.message?{message:C.message}:{}}))}:{},...Object.keys(h.modifiedVariables??{}).length?{modifiedVariables:h.modifiedVariables}:{},...t.includes("consoleOutput")&&h.consoleOutput?.length?{consoleOutput:h.consoleOutput}:{},...y!==null?{report:{uri:`file://${y}`,hint:"Click the URI to open the HTML report in your browser"}}:{},...v!==null?{junitReport:{path:v}}:{},...h.error?{error:h.error}:{}}}catch(o){throw o}finally{Qa(e)}}async function on(r){let e=it(r.workspaceFolder);try{let t=e.collection,n=gm(t,r),s=ym(n,r),i=Cu(n),o=am(i,s,r.recursive);if(o.length===0&&s)throw new Error(`No requests found under folder "${s}" in collection "${n.name}"`);let a=o.map(({request:l,folderPath:u})=>({id:l.id,slug:l.id.toLowerCase().replace(/\s+/g,"-"),collectionId:n.id,requestId:l.id,name:l.name,method:l.method,collectionName:n.name,folderPath:u,enabled:!0})),c={id:s?`temp-${n.id}-${cm(s)}`:`temp-${n.id}`,name:s?`${n.name} / ${s}`:n.name,requests:a,config:{iterations:1,delay:0,stopOnError:r.stopOnError??!1,readFromSharedSession:!1,writeToSharedSession:!1},isTemporary:!0,createdAt:Date.now(),updatedAt:Date.now()};return new Bi(e).execute(c,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:void 0,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"collection")}catch(t){throw t}finally{Qa(e)}}async function ib(r){return on({recursive:!0,...r})}async function Ui(r){let e=it(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new Bi(e).execute(n,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:r.requestFilter,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"suite")}catch(t){throw t}finally{Qa(e)}}var $s=E(()=>{"use strict";za();ti();Di();Ka();Eu();Au();oc();ku();Va();hm()});var wm={};Tt(wm,{createMcpRuntime:()=>bb});async function At(r){let e=process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS,t=process.env.HTTP_FORGE_GENERATE_REPORTS;process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS="true",process.env.HTTP_FORGE_GENERATE_REPORTS="true";try{return await r()}finally{e===void 0?delete process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS:process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS=e,t===void 0?delete process.env.HTTP_FORGE_GENERATE_REPORTS:process.env.HTTP_FORGE_GENERATE_REPORTS=t}}function Fs(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function cb(r,e){let t=$u.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=Tu.get(r);if(n)return n;let s=(async()=>{let i=e.config.getMcpConfig(),o=(l,u)=>!!l?.length&&(l.includes(u.id)||l.includes(u.name)),a=e.collection.getAllCollections().filter(l=>!o(i.excludedCollections,l)),c=(await e.testSuite.getAllSuites()).filter(l=>!o(i.excludedSuites,l));return Ua(a,c,i,r)})().then(i=>($u.set(r,{tools:i,expiresAt:Date.now()+ab}),i)).finally(()=>Tu.delete(r));return Tu.set(r,s),s}function lb(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function ub(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function vm(r,e,t,n){Sr(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function db(r){return r.config.getMcpConfig().toolPageSize??200}async function pb(r,e){switch(e.method){case"initialize":return{protocolVersion:"2024-11-05",capabilities:{tools:{},prompts:{}},serverInfo:{name:"http-forge",version:"1.0.0"},instructions:"You are assisting with HTTP API testing via HTTP Forge. When a run_suite, run_collection, or run_folder call completes with failures (summary.failed > 0 or allPassed === false), automatically analyze the 'failedRequests' in the response and provide: (1) root cause for each failure, (2) specific fix recommendations, (3) updated pm.test() assertion scripts where relevant. Do not wait for the user to ask \u2014 proactively diagnose and suggest fixes. For async runs (status: 'running'), poll with get_run_status until complete, then call get_run_summary. When get_run_summary returns a _nextStep field you MUST execute it immediately \u2014 the failedRequests array is already included inline so no extra tool call is needed. Analyze the failures and provide diagnosis without waiting for the user."};case"tools/list":{let t=await cb(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=db(r.container);if(i<=0||t.length<=i)return{tools:t};let o=Ba(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=Ha(c)),l}case"tools/call":{let t=e.params??{},n=t.name,s=t.arguments;if(!n)throw new Error("Missing tool name");let i=await Fu(r,n,s??{}),o=i,a=o?.summary;a&&((a.failed??0)>0||a.allPassed===!1)&&(o._nextStep=`${a.failed??"Some"} request(s) failed. Please analyze the 'failedRequests' above: identify the root cause of each failure, suggest specific fixes (URL, auth, body, environment variables), and provide updated pm.test() assertion scripts where the assertions are incorrect.`);let c=JSON.stringify(i,null,2),l=ub(c,r.host,r.port),u=l.match(/"uri"\s*:\s*"(http:\/\/[^"]+\/report\?[^"]+)"/),d=u?`
1426
1426
 
1427
- [View HTML Report](${u[1]})`:"";return{content:[{type:"text",text:l+d}]}}case"prompts/list":return{prompts:Mi};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=it(r.workspaceFolder);try{return await Ea(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{Fs(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function fb(r,e,t){let n=!r.container,s=r.container??it(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&Fs(s)}let o=e.headers.origin??"",a=i.includes(o)?o:i[0]??"http://localhost";t.setHeader("Access-Control-Allow-Origin",a),t.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Mcp-Session-Id")}function mb(r,e,t){let s=new URL(e.url,`http://${r.host}:${r.port}`).searchParams.get("path");if(!s){t.statusCode=400,t.end("Missing path parameter");return}let i=In.resolve(s),o=r.container?.config.getResultsPath(),a=o?In.dirname(o):In.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+In.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}Sm.readFile(i,"utf-8",(c,l)=>{if(c){t.statusCode=404,t.end("Report not found");return}t.statusCode=200,t.setHeader("content-type","text/html; charset=utf-8"),t.end(l)})}function Ou(r,e,t,n){let s=r.create(e,t);return n().then(i=>{s.status!=="cancelled"&&(s.status="completed",s.completedAt=Date.now(),s.summary=i?.summary??s.summary,i?.failedRequests&&(s.failedRequests=i.failedRequests),i?.noAssertionExamples&&(s.noAssertionExamples=i.noAssertionExamples),s.reportPath=i?.report?.uri?.replace("file://","")??null,s.progress.completed=s.progress.total)}).catch(i=>{s.status!=="cancelled"&&(s.status="failed",s.completedAt=Date.now(),s.error=i.message)}),{runId:s.id,status:"running",total:t,message:"Run started. Use get_run_status to poll."}}function hb(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return At(()=>dc({workspaceFolder:e,collectionId:t.id,requestId:n,environment:s.environment,variables:s.variables,headers:s.headers,query:s.query,body:s.body,include:s.include}))},async runFolder(t,n,s){let i=K(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?Ou(r.runStore,`${t.name} / ${bt(n)}`,i,()=>At(()=>on({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))):At(()=>on({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))},async runCollection(t,n){let s=K(t).length;return n.async===!0?Ou(r.runStore,t.name,s,()=>At(()=>on({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):At(()=>on({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))},async runSuite(t,n,s){let i=it(e),o=0;try{let a=await i.testSuite.getSuite(t);o=(a?.nodes.filter(l=>l.type==="request").length??0)*(s.iterations??a?.config?.iterations??1)}finally{Fs(i)}return s.async===!0?Ou(r.runStore,n,o,()=>At(()=>Ui({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))):At(()=>Ui({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))}}}async function Fu(r,e,t={}){let n=r.workspaceFolder,s=lb(r.container,e);if(Object.values(S).includes(s)){let a=it(n),c=as();try{let l=await Pa(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,hb(r));return gb.has(s)&&$u.delete(n),l}finally{Fs(a)}}let i=Fa(s),o=it(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=mr(m,c),h=f?a.find(g=>g.id===f):void 0;if(!h)throw new Error(`Collection not found for tool: ${e}`);return h};if(i.kind==="request"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed request tool: ${e}`);let h=l(m),g=K(h).map(v=>v.request.id),y=mr(f,g);if(!y)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return At(()=>dc({workspaceFolder:n,collectionId:h.id,requestId:y,environment:t.environment,variables:t.variables,headers:t.headers,query:t.query,body:t.body,include:t.include}))}if(i.kind==="collection"){let[m]=i.tokens;if(!m)throw new Error(`Malformed collection tool: ${e}`);let f=l(m);return At(()=>on({workspaceFolder:n,collectionId:f.id,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}if(i.kind==="folder"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed folder tool: ${e}`);let h=l(m),g=(o.collection.getAllCollections().find(w=>w.id===h.id),void 0),y=K(h).map(w=>w.folderPath).filter((w,b,C)=>w&&C.indexOf(w)===b),v=Na(f,y);if(!v)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return At(()=>on({workspaceFolder:n,collectionId:h.id,folderPath:v,recursive:t.recursive,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}let[u]=i.tokens;if(!u)throw new Error(`Malformed suite tool: ${e}`);let d=await o.testSuite.getAllSuites(),p=mr(u,d.map(m=>m.id));if(!p)throw new Error(`Test suite not found for tool: ${e}`);return At(()=>Ui({workspaceFolder:n,suiteId:p,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,requestFilter:t.requestFilter,include:t.include}))}finally{Fs(o)}}function Sr(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function bm(r){return new Promise((e,t)=>{let n="";r.on("data",s=>{n+=s,n.length>1024*1024&&t(new Error("Request body too large (max 1MB)"))}),r.on("end",()=>{if(!n){e({});return}try{e(JSON.parse(n))}catch{t(new Error("Invalid JSON body"))}}),r.on("error",t)})}function yb(r){return(0,xm.createServer)(async(e,t)=>{try{if(fb(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){Sr(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){mb(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await bm(e)}catch{vm(t,null,-32700,"Parse error");return}try{let s=await pb(r,n);Sr(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){vm(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await bm(e);if(!n||typeof n.name!="string"||n.name.trim()===""){Sr(t,400,{error:'Field "name" is required'});return}let s=await Fu(r,n.name,n.args??{});Sr(t,200,{result:s});return}Sr(t,405,{error:"Method not allowed"})}catch(n){Sr(t,500,{error:n.message})}})}function vb(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new zt(In.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function bb(r){let e=vb(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new Ss};return ob.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=it(s.workspaceFolder));let i=yb(s);await new Promise((o,a)=>{i.once("error",a),i.listen(s.port,s.host,()=>{i.off("error",a),o()})}),s.server=i,s.isRunning=!0},async stop(){if(s.container&&(Fs(s.container),s.container=void 0),!s.server){s.isRunning=!1;return}await new Promise((i,o)=>{s.server.close(a=>{if(a){o(a);return}i()})}),s.server=void 0,s.isRunning=!1},isRunning(){return s.isRunning},getPort(){return s.port},async executeTool(i,o){return Fu(s,i,o??{})}}}var Sm,xm,In,ob,ab,$u,Tu,gb,Rm=E(()=>{"use strict";Sm=T(require("fs")),xm=require("http"),In=T(require("path"));vo();Qo();$s();Ye();gu();qa();yu();bu();La();Ne();oc();ob=new Map;ab=3e3,$u=new Map,Tu=new Map;gb=Aa});var Wb={};Tt(Wb,{AnthropicProvider:()=>os,ApiArchitectService:()=>is,ApiDiscoveryService:()=>fr,AwsSecretResolver:()=>oi,AzureKeyVaultResolver:()=>ai,BODY_FILE_MAP:()=>vc,CACHE_BUSTING_TOOLS:()=>Aa,COLLECTION_INPUT_SCHEMA:()=>bi,CONFIG_FILES:()=>vn,CollectionLoader:()=>$n,CollectionLoaderFactory:()=>Vr,CollectionRequestExecutor:()=>_t,CollectionService:()=>zr,ConfigService:()=>zt,CookieJar:()=>qr,CookieService:()=>Jr,CookieUtils:()=>ne,DEFAULT_CONFIG:()=>de,DEFAULT_REQUEST_SETTINGS:()=>lo,DataFileParser:()=>yn,DopplerResolver:()=>di,EnvironmentConfigService:()=>Wr,EnvironmentResolver:()=>Ot,ExampleGenerator:()=>Gn,ExpressComponentAnalyzer:()=>ps,ExpressDiscoveryProvider:()=>or,FOLDER_INPUT_SCHEMA:()=>Si,FastApiDiscoveryProvider:()=>pr,FastifyComponentAnalyzer:()=>fs,FastifyDiscoveryProvider:()=>ar,FetchHttpClient:()=>_r,FolderCollectionLoader:()=>Cr,FolderCollectionStore:()=>Bt,ForgeContainer:()=>go,ForgeEnv:()=>Ut,FrameworkDetector:()=>rr,GENERIC_TOOL_NAMES:()=>S,GcpSecretResolver:()=>ui,GraphQLSchemaService:()=>Qr,HTTP_METHOD_MAP:()=>Ja,HTTP_METHOD_REVERSE:()=>rt,HashiCorpVaultResolver:()=>ci,HistoryAnalyzer:()=>Jn,HtmlReportGenerator:()=>hr,HttpForgeParser:()=>gn,HttpRequestService:()=>$t,InMemoryCookieJar:()=>An,InterceptorChain:()=>Ft,JUnitReportGenerator:()=>Lt,JsonCollectionLoader:()=>Vn,LambdaComponentAnalyzer:()=>ms,LambdaDiscoveryProvider:()=>lr,MCP_PROMPTS:()=>Mi,METADATA_FILES:()=>Oe,McpRunStore:()=>Ss,ModuleLoader:()=>zs,NestDiscoveryProvider:()=>cr,NodeFileSystem:()=>Dr,NodeHttpClient:()=>mn,OAuth2TokenManager:()=>Hr,OnePasswordResolver:()=>li,OpenAiProvider:()=>yi,OpenApiExporter:()=>Wt,OpenApiImporter:()=>Mt,ParserRegistry:()=>Er,PersistentCookieJar:()=>Gr,REQUEST_INPUT_SCHEMA:()=>vi,ROOT_DIRECTORIES:()=>Vt,RefResolver:()=>Wn,RequestExecutor:()=>Hn,RequestHistoryService:()=>Yr,RequestHistoryStore:()=>Nr,RequestPreparer:()=>Kr,RequestPreprocessor:()=>hn,RequestScriptSession:()=>Fr,ResultStorageService:()=>kn,SCHEMA_FILES:()=>Rr,SCRIPTS_DIR:()=>He,SCRIPT_FILES:()=>_s,SUITE_INPUT_SCHEMA:()=>xi,SchemaInferenceService:()=>Kt,SchemaInferrer:()=>Gt,ScriptAnalyzer:()=>Kn,ScriptExecutor:()=>Nt,SecretResolverRegistry:()=>Xr,ServiceContainer:()=>xn,ServiceIdentifiers:()=>$,SpringDiscoveryProvider:()=>dr,StatisticsService:()=>mc,TestSuiteService:()=>es,TestSuiteStore:()=>hc,UrlBuilder:()=>ct,VariableInterpolator:()=>fn,VariableResolver:()=>pn,analyzeComponentChainMetadata:()=>us,analyzeHandlerMetadata:()=>Ci,applyEnvSuggestionsToItems:()=>Uo,applyExtractionPlan:()=>gd,applyFilterChain:()=>Tr,applyMcpBodyTruncation:()=>jt,applyRegenerated:()=>$i,assembleBusinessContext:()=>rs,buildArchitectPrompt:()=>zo,buildCollectionBusinessContext:()=>Rl,buildCollectionToolDescription:()=>Ma,buildCollectionToolName:()=>Ta,buildExtractionPlan:()=>hd,buildFolderToolDescription:()=>Da,buildFolderToolName:()=>Oa,buildGenericTools:()=>wi,buildMcpToolList:()=>Ua,buildPromptResult:()=>Ea,buildRequestBusinessContext:()=>Do,buildRequestToolDescription:()=>_a,buildRequestToolName:()=>Ia,buildResultFileName:()=>Pn,buildRunResultsContext:()=>Cl,buildSuiteToolDescription:()=>ja,buildSuiteToolName:()=>$a,cleanupOldBodyFiles:()=>xc,clearRegisteredKnowledgeSources:()=>Qd,collectSourceFiles:()=>nt,collectionKnowledgeSource:()=>Dt,collectionToEndpoints:()=>Vo,combineConfidence:()=>Yt,computeProjectFreshness:()=>vs,concatenateScripts:()=>Ks,countRequests:()=>No,createDefaultKnowledgeSources:()=>El,createEnvAiProvider:()=>as,createExpectChain:()=>jn,createMcpRuntime:()=>Cm,createModuleLoader:()=>no,createMomentShim:()=>Js,createNodeContainer:()=>it,createResponseObject:()=>Gs,createTestFunction:()=>so,decodeCursor:()=>Ba,decodeFolderPath:()=>bt,dedupeDiscoveredApiParameters:()=>en,deleteItemFromTree:()=>Ht,deserializeTypedRecord:()=>uc,deserializeTypedValue:()=>br,detectEnvSuggestions:()=>gi,detectIndexDrift:()=>su,detectProjectDrift:()=>bs,diffLines:()=>ys,discoverWorkflows:()=>wn,dispatchGenericTool:()=>Pa,encodeCursor:()=>Ha,encodeFolderName:()=>Ee,enhanceCollection:()=>Im,enumerateFolders:()=>Re,evaluateExpression:()=>gt,exportCollectionToRestClient:()=>ld,extractJsonFromLlm:()=>xt,extractPathParameters:()=>Xt,findItemById:()=>xe,flattenRequests:()=>K,formatConsoleOutput:()=>Ln,gatherWorkspaceKnowledge:()=>ns,generateFlowFromEndpoints:()=>nr,generateId:()=>re,generateReleaseNotes:()=>Du,generateSlug:()=>at,generateSuiteFromEndpoints:()=>tr,getCompletions:()=>_m,getRegisteredKnowledgeSources:()=>Zd,getServiceContainer:()=>xl,harToCollection:()=>Hu,hasChanged:()=>$r,isExpression:()=>dn,isSystemEnvironmentFile:()=>js,loadEnvironmentsFromFolder:()=>Ar,loadHybridSeedEndpoints:()=>Ri,normalizeFolderInput:()=>Qn,normalizeHeaders:()=>io,parseCurlCommand:()=>km,parseFilterChain:()=>Ir,parseHar:()=>gc,parseMcpToolName:()=>Fa,parsePostmanEnvironment:()=>bo,parseQueryContext:()=>Nm,prepareBodyForSave:()=>Sc,proposeSuiteUpdates:()=>Oi,readBodyFromDir:()=>bc,readSchemaFile:()=>wc,readScriptsFromDir:()=>Ms,redactFullResponse:()=>wo,redactFullResultDetails:()=>Ro,redactHeaders:()=>lt,redactHistoryEntry:()=>xo,registerCoreServices:()=>pi,registerKnowledgeSource:()=>Kd,renderArchitectDocs:()=>Il,renderReleaseNotesMarkdown:()=>ju,requestKnowledgeSource:()=>Xe,resolveCollectionRef:()=>ac,resolveFolderRef:()=>cc,resolveFolderToken:()=>Na,resolveProjectName:()=>_l,resolveRegenerated:()=>wa,resolveRequestRef:()=>lc,resolveResultGrouping:()=>ws,resolveToken:()=>mr,reviewSuiteRun:()=>Fi,runCollection:()=>qm,runFolder:()=>Am,runRequest:()=>Em,runResultsKnowledgeSource:()=>fi,runSuite:()=>Pm,scanCollectionForEnvVarsWithAi:()=>Om,searchForItemPath:()=>Wi,searchForItemPathById:()=>Ki,serializeTypedValue:()=>Os,sortItemsByOrder:()=>Cc,suiteIdFromName:()=>ss,threeWayDiff:()=>xa,toReviewRequestResults:()=>Ni,validateDesignedSpec:()=>kl,withAiRetry:()=>tt,workspaceKnowledgeSource:()=>et,writeEnvFile:()=>Un,writeFolderItems:()=>Xs,writeSchemaFiles:()=>Rc,writeScriptFile:()=>Ur,writeScriptsToDir:()=>Ds});module.exports=On(Wb);var $n=class{constructor(e,t){this.fileSystem=e;this.parserRegistry=t}fileSystem;parserRegistry;directory;setDirectory(e){this.directory=e}async loadAll(){return this.directory?this.loadDirectory(this.directory):[]}async load(e,t={}){let n=await this.fileSystem.readFile(e);if(t.format){let i=this.parserRegistry.get(t.format);if(!i)throw new Error(`No parser registered for format: ${t.format}`);return i.parse(n,e)}let s=this.parserRegistry.detect(n);if(!s)throw new Error(`Could not detect collection format for: ${e}. Supported formats: ${this.parserRegistry.getFormats().join(", ")}`);return s.parser.parse(n,e)}async loadDirectory(e,t=["*.json","*.forge.json"]){let n=[],s=await this.fileSystem.glob(t,e);for(let i of s)try{let o=await this.load(i);n.push(o)}catch{}return n}async canLoad(e){try{if(!await this.fileSystem.exists(e))return!1;let t=await this.fileSystem.readFile(e);return this.parserRegistry.detect(t)!==null}catch{return!1}}getSupportedFormats(){return this.parserRegistry.getFormats()}};Qi();ln();function qc(r,e){return{id:r.id,name:r.name,description:r.description,variables:r.variables||{},auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Vu),source:{format:"folder",filePath:e,version:r.version}}}function Vu(r){if(r.type==="folder")return{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Vu)};let e=r;return{type:"request",id:e.id,name:e.name,description:e.description,method:e.method||"GET",url:e.url||"",headers:e.headers||[],query:e.query||[],params:e.params,body:e.body??void 0,auth:e.auth,settings:e.settings,scripts:e.scripts,...e.deprecated&&{deprecated:e.deprecated},...e.doc&&{doc:e.doc},...e.responseSchema&&{responseSchema:e.responseSchema},...e.bodySchema&&{bodySchema:e.bodySchema},...e.operationId&&{operationId:e.operationId},...e.summary&&{summary:e.summary},...e.tags&&e.tags.length>0&&{tags:e.tags},...e.examples&&e.examples.length>0&&{examples:e.examples},...e.responses&&Object.keys(e.responses).length>0&&{responses:e.responses},...e.security&&e.security.length>0&&{security:e.security}}}function Qm(r){return{id:r.id,name:r.name,description:r.description,version:r.source?.version,variables:r.variables,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Ac)}}function Ac(r){return r.type==="folder"?{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Ac)}:{type:"request",id:r.id,name:r.name,description:r.description,method:r.method,url:r.url,headers:r.headers,query:r.query,params:r.params,body:r.body,auth:r.auth,settings:r.settings,scripts:r.scripts,...r.deprecated&&{deprecated:r.deprecated},...r.doc&&{doc:r.doc},...r.responseSchema&&{responseSchema:r.responseSchema},...r.bodySchema&&{bodySchema:r.bodySchema},...r.operationId&&{operationId:r.operationId},...r.summary&&{summary:r.summary},...r.tags&&{tags:r.tags},...r.examples&&{examples:r.examples},...r.responses&&{responses:r.responses},...r.security&&{security:r.security}}}var Cr=class{store;constructor(e){this.store=new Bt(e)}loadAll(){return this.store.loadAll().map(t=>qc(t,this.store.getCollectionPath(t.id)))}getSlugById(e){return this.store.getSlugById(e)}getIdBySlug(e){return this.store.getIdBySlug(e)}load(e){let t=this.store.load(e);if(t)return qc(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return qc(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(Qm(e))}async delete(e){return this.store.delete(e)}exists(e){return this.store.exists(e)}getCollectionPath(e){return this.store.getCollectionPath(e)}async updateCollectionMetadata(e,t){return this.store.updateCollectionMetadata(e,t)}async saveItem(e,t,n){return this.store.saveItem(e,Ac(t),n)}async updateItem(e,t,n){let s={...n};return this.store.updateItem(e,t,s)}async deleteItem(e,t){return this.store.deleteItem(e,t)}async moveItem(e,t,n){return this.store.moveItem(e,t,n)}async reorderItems(e,t,n){return this.store.reorderItems(e,t,n)}async saveScripts(e,t,n){return this.store.saveScripts(e,t,n)}loadScripts(e,t){return this.store.loadScripts(e,t)}};var Er=class{parsers=new Map;register(e,t){this.parsers.set(e.toLowerCase(),t)}get(e){return this.parsers.get(e.toLowerCase())}has(e){return this.parsers.has(e.toLowerCase())}getFormats(){return Array.from(this.parsers.keys())}detect(e){for(let[t,n]of this.parsers)if(n.canParse(e))return{parser:n,format:t};return null}clear(){this.parsers.clear()}};Fn();var qr=class{cookies=new Map;getCookieKey(e,t,n){return ne.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e)}setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}}has(e,t){return this.get(e,t)!==void 0}delete(e,t,n){let s=this.getCookieKey(e,t,n);return this.cookies.delete(s)}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return ne.formatCookieHeader(t)}clear(){this.cookies.clear()}clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n)}parseCookieHeaders(e,t){return ne.parseCookieHeaders(e,t)}isExpired(e){return ne.isExpired(e)}domainMatches(e,t){return ne.domainMatches(e,t)}get count(){return this.cookies.size}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t)}};Yi();var Ot=class r{config;selectedEnvironment;sessionGlobals={};sessionEnvironmentValues=new Map;constructor(e){this.config=e,this.selectedEnvironment=e.selectedEnvironment||Object.keys(e.environments)[0]||"default"}get(e){return this.getVariables()[e]}set(e,t){let n=this.sessionEnvironmentValues.get(this.selectedEnvironment);n||(n={},this.sessionEnvironmentValues.set(this.selectedEnvironment,n)),n[e]=t}getAll(){return this.getVariables()}getEnvironments(){return Object.keys(this.config.environments)}getActive(){return this.selectedEnvironment}setActive(e){if(!this.config.environments[e])throw new Error(`Environment not found: ${e}`);this.selectedEnvironment=e}getVariables(e){let t=e||this.selectedEnvironment,n=this.config.environments[t],s={...this.config.globalVariables||{},...this.sessionGlobals};if(n){if(n.inherits&&this.config.environments[n.inherits]){let o=this.getEnvironmentVariables(n.inherits);s={...s,...o}}s={...s,...n.variables};let i=this.sessionEnvironmentValues.get(t);i&&(s={...s,...i})}return s}getEnvironmentVariables(e){let t=this.config.environments[e];if(!t)return{};let n={};return t.inherits&&this.config.environments[t.inherits]&&(n={...this.getEnvironmentVariables(t.inherits)}),{...n,...t.variables}}getGlobals(){return{...this.config.globalVariables||{},...this.sessionGlobals}}setGlobal(e,t){this.sessionGlobals[e]=t}unsetGlobal(e){delete this.sessionGlobals[e]}clearGlobals(){this.sessionGlobals={}}resolve(e){let t=e||this.selectedEnvironment;return{name:t,merged:this.getVariables(t),globals:this.getGlobals()}}static fromVariables(e,t="default"){return new r({environments:{[t]:{name:t,variables:e}},selectedEnvironment:t})}};Pr();Or();var Ut=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new fn,this.urlBuilder=new ct}get(e){return this.envStore.get(e)}set(e,t){this.envStore.set(e,t)}has(e){return this.envStore.get(e)!==void 0}delete(e){this.envStore.set(e,"")}getAll(){return this.envStore.getAll()}getActiveEnvironment(){return this.envStore.getActive()}setActiveEnvironment(e){this.envStore.setActive(e)}getEnvironments(){let e=this.envStore;return typeof e.getEnvironments=="function"?e.getEnvironments():[]}getGlobals(){let e=this.envStore;return typeof e.getGlobals=="function"?e.getGlobals():{}}setGlobal(e,t){let n=this.envStore;typeof n.setGlobal=="function"&&n.setGlobal(e,t)}unsetGlobal(e){let t=this.envStore;typeof t.unsetGlobal=="function"&&t.unsetGlobal(e)}clearGlobals(){let e=this.envStore;typeof e.clearGlobals=="function"&&e.clearGlobals()}resolve(e){return this.interpolator.interpolate(e,this.getAll())}resolvePath(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t)}buildUrl(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t.params||{},t.query||{})}resolveObject(e){return this.interpolator.interpolateObject(e,this.getAll())}extractVariables(e){return this.interpolator.extractVariables(e)}extractPathParams(e){return this.urlBuilder.extractPathParams(e)}static create(e={}){let t=Ot.fromVariables(e);return new r(t)}static fromResolver(e){return new r(e)}};Or();Us();Vs();Pr();Zs();Qs();var Hn=class{constructor(e,t,n,s,i){this.httpClient=e;this.forgeEnv=t;this.cookieJar=n;this.preprocessor=s;if(i?.scriptExecutor)this.scriptExecutor=i.scriptExecutor;else{let o=i?.forgeRoot?[require("path").join(i.forgeRoot,"modules")]:[],a=new $t(new ct,new Ft,e);this.scriptExecutor=new Nt(a,o,void 0,i?.scriptScope??"shared",i?.scriptTimeout??5e3)}}httpClient;forgeEnv;cookieJar;preprocessor;scriptExecutor;async execute(e,t,n={}){let s=Date.now(),i={...this.forgeEnv.getAll()},o={...this.forgeEnv.getGlobals()},a={...n.additionalVariables||{}},c={...i},l=this.buildHttpRequest(e,n.overrides),u=n.overrides?.body||e.body,d=this.findFolderPath(t,e.id),p=this.buildScriptChain(e,t,d),m={request:{url:l.url,method:l.method,headers:{...l.headers},body:u?typeof u=="string"?{type:"raw",content:u}:u:void 0},variables:a,collectionVariables:t.variables||{},globals:{...o},environmentVariables:c,environmentName:this.forgeEnv.getActiveEnvironment?.()||void 0,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:t?.name},onEnvironmentChange:n.onEnvironmentChange,onGlobalsChange:(y,v,w)=>{y==="set"&&v&&w!==void 0?this.forgeEnv.setGlobal(v,w):y==="unset"&&v?this.forgeEnv.unsetGlobal(v):y==="clear"&&this.forgeEnv.clearGlobals()}},f=this.scriptExecutor.createRequestSession(m),h,g;try{if(!n.skipPreRequest&&p.preRequest.length>0){let b=await f.executePreRequest(p.preRequest);if(h={success:b.success,error:b.error,modifiedVariables:b.modifiedVariables,modifiedEnvironment:b.modifiedEnvironmentVariables,modifiedGlobals:b.modifiedGlobals,modifiedCollectionVariables:b.modifiedCollectionVariables,consoleOutput:b.consoleOutput,modifiedRequest:b.modifiedRequest?{url:b.modifiedRequest.url,method:b.modifiedRequest.method,headers:b.modifiedRequest.headers,body:b.modifiedRequest.body?.content}:void 0},b.modifiedVariables&&(a={...a,...b.localVariables??b.modifiedVariables}),b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables}),b.modifiedRequest){let C=b.modifiedRequest;C.url&&(l.url=C.url),C.method&&(l.method=C.method),C.headers&&(l.headers={...l.headers,...C.headers}),C.body!==void 0&&(l.body=C.body?.content||C.body)}if(!b.success)throw new Error(`Pre-request script failed: ${b.error}`)}let y={...c,...a};l=this.interpolateRequest(l,y);let v=n.overrides?.body||e.body;if(this.preprocessor&&v&&typeof v!="string"&&v.type==="graphql"&&l.body!==void 0){let b=this.preprocessor.encodeBody({type:"graphql",content:l.body});b!=null&&(l.body=typeof b=="string"?b:JSON.stringify(b))}if(u&&typeof u=="object"&&u.type==="form-data"&&Array.isArray(l.body)){let b=this.buildMultipartFormData({type:"form-data",content:l.body});b&&(l.body=b)}let w=await this.httpClient.send(l);if(!n.skipPostResponse&&p.postResponse.length>0){let b=await f.executePostResponse(p.postResponse,{status:w.status,statusText:w.statusText,headers:w.headers,body:w.body,cookies:oo(w.headers,w.cookies,l.url),responseTime:w.time,responseSize:w.size,executedRequest:{url:l.url,method:l.method,headers:l.headers||{},body:l.body?typeof l.body=="string"?{type:"raw",content:l.body}:l.body:{type:"none",content:""},params:{},query:{}}});g={success:!0,assertions:b.testResults,consoleOutput:b.consoleOutput,modifiedEnvironment:b.modifiedEnvironmentVariables},b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables})}return{response:w,preRequestResult:h,postResponseResult:g,totalTime:Date.now()-s,finalRequest:l,variables:{environment:c,local:a}}}finally{f.dispose?.()}}async executeSimple(e,t={}){let n=e,s={...this.forgeEnv.getAll(),...t.variables||{}};return n=this.interpolateRequest(e,s),t.timeout&&(n={...n,timeout:t.timeout}),this.httpClient.send(n)}buildHttpRequest(e,t){let n=e.url;if(e.query&&e.query.length>0){let u=new URLSearchParams;for(let d of e.query)d.enabled!==!1&&u.append(d.key,d.value);n+=(n.includes("?")?"&":"?")+u.toString()}let s=t?.url||n,i=t?.method||e.method,o={};if(e.headers&&Array.isArray(e.headers))for(let u of e.headers)u.enabled!==!1&&(o[u.key]=u.value);let a={...o,...t?.headers||{}},c,l=t?.body||e.body;if(l)if(typeof l=="string")c=l;else if(this.preprocessor&&l.type)if(l.type==="graphql")c=typeof l.content=="string"?l.content:JSON.stringify(l.content);else if(l.type==="form-data")c=this.buildMultipartFormData(l);else{let u=this.preprocessor.encodeBody(l);c=u!=null?String(u):void 0}else l.content&&(c=typeof l.content=="string"?l.content:JSON.stringify(l.content));return this.preprocessor&&l&&l.type!=="form-data"&&this.preprocessor.setContentTypeHeader(a,l),{url:s,method:i,headers:a,body:c,timeout:t?.timeout||e.settings?.timeout,settings:{...e.settings,...t?.settings}}}interpolateRequest(e,t){let n=Ut.create(t),s=e.body,i=s;return typeof s=="string"?i=n.resolve(s):s instanceof FormData||s instanceof URLSearchParams?i=s:s&&typeof s=="object"&&(i=n.resolve(s)),{...e,url:n.resolvePath(e.url),headers:n.resolveObject(e.headers),body:i}}buildMultipartFormData(e){if(!e||e.type!=="form-data"||!Array.isArray(e.content))return;let t=new FormData;for(let n of e.content)!n?.key||n.enabled===!1||t.append(n.key,n.value==null?"":String(n.value));return t}buildScriptChain(e,t,n=[]){let s=[],i=[];t.scripts?.preRequest&&s.push(t.scripts.preRequest),t.scripts?.postResponse&&i.push(t.scripts.postResponse);for(let o of n)o.scripts?.preRequest&&s.push(o.scripts.preRequest),o.scripts?.postResponse&&i.push(o.scripts.postResponse);return e.scripts?.preRequest&&s.push(e.scripts.preRequest),e.scripts?.postResponse&&i.push(e.scripts.postResponse),{preRequest:s,postResponse:i}}findFolderPath(e,t){let n=[],s=(i,o)=>{for(let a of i){if(a.type==="request"&&a.id===t)return n.push(...o),!0;if(a.type==="folder"){let c=[...o,a];if(s(a.items,c))return!0}}return!1};return s(e.items,[]),n}};function Th(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}var Nr=class{entries=new Map;requestIndex=new Map;fullResponses=new Map;maxEntriesPerRequest;storeFullResponses;constructor(e={}){this.maxEntriesPerRequest=e.maxEntriesPerRequest??100,this.storeFullResponses=e.storeFullResponses??!0}getEntries(e,t){let n=this.requestIndex.get(e)||[],s=[];for(let i of n){let o=this.entries.get(i);o&&(!t||o.environment===t)&&s.push(o)}return s}getEntry(e){return this.entries.get(e)}getFullResponse(e){return this.fullResponses.get(e)}get count(){return this.entries.size}addEntry(e,t,n,s,i){let o=Th(),a=Date.now(),c={id:o,timestamp:a,environment:s,method:t.method,ticket:i?.ticket,branch:i?.branch,note:i?.note,sentRequest:{url:t.url,method:t.method,headers:{...t.headers},body:t.body},response:{status:n.status,statusText:n.statusText,time:n.time}};this.entries.set(o,c);let l=this.requestIndex.get(e)||[];for(l.unshift(o);l.length>this.maxEntriesPerRequest;){let u=l.pop();u&&(this.entries.delete(u),this.fullResponses.delete(u))}if(this.requestIndex.set(e,l),this.storeFullResponses){let u={timestamp:a,status:n.status,statusText:n.statusText,headers:{...n.headers},cookies:n.cookies||[],body:n.body,time:n.time};this.fullResponses.set(o,u)}return c}deleteEntry(e){if(!this.entries.get(e))return!1;this.entries.delete(e),this.fullResponses.delete(e);for(let[n,s]of this.requestIndex.entries()){let i=s.indexOf(e);if(i!==-1){s.splice(i,1),s.length===0&&this.requestIndex.delete(n);break}}return!0}clearHistory(e){let t=this.requestIndex.get(e);if(t){for(let n of t)this.entries.delete(n),this.fullResponses.delete(n);this.requestIndex.delete(e)}}clearAll(){this.entries.clear(),this.requestIndex.clear(),this.fullResponses.clear()}};var _r=class{async send(e){let t=Date.now(),n=new AbortController,s=e.timeout??3e4,i=setTimeout(()=>n.abort(),s);try{let o={method:e.method,headers:e.headers,signal:n.signal};e.body!==void 0&&(typeof e.body=="string"||e.body instanceof FormData||e.body instanceof URLSearchParams?o.body=e.body:typeof e.body=="object"&&(o.body=JSON.stringify(e.body),!e.headers?.["Content-Type"]&&!e.headers?.["content-type"]&&(o.headers["Content-Type"]="application/json"))),e.settings?.followRedirects===!1&&(o.redirect="manual");let a=await fetch(e.url,o),c=Date.now(),l;try{l=await a.text()}catch{l=null}let u={};return a.headers.forEach((d,p)=>{let m=u[p];m!==void 0?u[p]=Array.isArray(m)?[...m,d]:[m,d]:u[p]=d}),{status:a.status,statusText:a.statusText,headers:u,cookies:[],body:l,time:c-t}}catch(o){throw o.name==="AbortError"?new Error(`Request timeout after ${s}ms`):o}finally{clearTimeout(i)}}};Us();Vs();fo();mo();Pr();var gn=class{format="http-forge";canParse(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"id"in t&&"name"in t&&"items"in t&&Array.isArray(t.items)&&!t.info?.schema?.includes("postman")&&!t._type}catch{return!1}}parse(e,t){let n=JSON.parse(e);return{id:n.id,name:n.name,description:n.description,variables:n.variables||{},auth:n.auth,scripts:n.scripts?{preRequest:n.scripts.preRequest,postResponse:n.scripts.postResponse}:void 0,items:this.convertItems(n.items),source:{format:"http-forge",filePath:t,version:n.version}}}convertItems(e){return e.map(t=>t.type==="folder"?this.convertFolder(t):this.convertRequest(t))}convertFolder(e){return{type:"folder",id:e.id,name:e.name,description:e.description,auth:e.auth,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0,items:e.items?this.convertItems(e.items):[]}}convertRequest(e){let t={};if(e.headers)for(let s of e.headers)s.enabled!==!1&&(t[s.key]=s.value);let n={};if(e.query)for(let s of e.query)s.enabled!==!1&&(n[s.key]=s.value);return{type:"request",id:e.id,name:e.name,description:e.description,method:e.method||"GET",url:e.url||"",headers:Object.entries(t).map(([s,i])=>({key:s,value:i,enabled:!0})),query:Object.entries(n).map(([s,i])=>({key:s,value:i,enabled:!0})),params:e.params,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0}}};ho();var Qe=T(require("fs/promises")),jr=T(require("path")),Dr=class{async readFile(e){return Qe.readFile(e,"utf-8")}async writeFile(e,t){let n=jr.dirname(e);await this.mkdir(n),await Qe.writeFile(e,t,"utf-8")}async exists(e){try{return await Qe.access(e),!0}catch{return!1}}async mkdir(e){await Qe.mkdir(e,{recursive:!0})}async glob(e,t){let n=t||process.cwd(),s=[];try{await this.walkDirectory(n,i=>{let o=jr.basename(i);for(let a of e)if(this.matchPattern(o,a)){s.push(i);break}})}catch{}return s}async readDir(e){return Qe.readdir(e)}async isDirectory(e){try{return(await Qe.stat(e)).isDirectory()}catch{return!1}}async walkDirectory(e,t){let n=await Qe.readdir(e,{withFileTypes:!0});for(let s of n){let i=jr.join(e,s.name);s.isDirectory()?await this.walkDirectory(i,t):s.isFile()&&t(i)}}matchPattern(e,t){let n=t.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${n}$`,"i").test(e)}};Zs();var go=class r{httpClient;fileSystem;scriptExecutor;interpolator;cookieJar;interceptorChain;preprocessor;dataFileParser;requestHistory;parserRegistry;collectionLoader;environmentStore;forgeEnv;requestExecutor;options;constructor(e={}){if(this.options=e,this.interpolator=e.interpolator||new fn,this.fileSystem=e.fileSystem||new Dr,this.preprocessor=e.preprocessor||new hn,this.dataFileParser=e.dataFileParser||new yn,this.cookieJar=e.cookieJar||new qr,e.enableHistory?this.requestHistory=e.requestHistory||new Nr({maxEntriesPerRequest:e.maxHistoryEntries??100}):this.requestHistory=null,this.interceptorChain=e.interceptorChain||this.createInterceptorChain(e),e.httpClient)this.httpClient=e.httpClient;else if(e.useNativeHttp!==!1){let i={...e.httpSettings,timeout:e.requestTimeout??e.httpSettings?.timeout};this.httpClient=new mn(i)}else this.httpClient=new _r;let t=e.forgeRoot?[require("path").join(e.forgeRoot,"modules")]:[],n=new $t(new ct,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new Nt(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new Er,this.parserRegistry.register("http-forge",new gn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=require("path").join(e.forgeRoot,"collections");this.collectionLoader=new Cr(i)}else this.collectionLoader=new $n(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new Ot(e.environmentConfig):Ot.fromVariables({}),this.forgeEnv=Ut.fromResolver(this.environmentStore),this.requestExecutor=new Hn(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:e.forgeRoot,scriptExecutor:this.scriptExecutor})}createInterceptorChain(e){let t=new Ft;if(e.requestInterceptors)for(let n of e.requestInterceptors)t.addRequestInterceptor(n);if(e.responseInterceptors)for(let n of e.responseInterceptors)t.addResponseInterceptor(n);if(e.errorInterceptors)for(let n of e.errorInterceptors)t.addErrorInterceptor(n);return t}async loadCollection(e){if(this.collectionLoader instanceof $n)return this.collectionLoader.load(e);throw new Error("loadCollection(filePath) is not supported with folder storage format. Use loadAllCollections() instead.")}async loadAllCollections(){return this.collectionLoader.loadAll()}async execute(e,t,n){return this.requestExecutor.execute(e,t,n)}async executeSimple(e,t){return this.requestExecutor.executeSimple(e,t)}registerParser(e,t){this.parserRegistry.register(e,t)}setEnvironmentConfig(e){this.environmentStore=new Ot(e),this.forgeEnv=Ut.fromResolver(this.environmentStore),this.requestExecutor=new Hn(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:this.options.forgeRoot,scriptExecutor:this.scriptExecutor})}static create(e){return new r(e)}static fromForgeRoot(e="./http-forge",t={}){let n=require("path"),s=n.join(e,"environments"),i,o=Ar(s);if(Object.keys(o.environments).length>0||Object.keys(o.globalVariables).length>0){i={globalVariables:{...o.globalVariables,...o.localVariables},environments:{},selectedEnvironment:void 0};for(let[c,l]of Object.entries(o.environments)){let u=o.localCredentials[c]?.variables||{};i.environments[c]={name:c,variables:{...l.variables,...u}}}}else{let c=require("fs"),l=n.join(s,"environments.json");if(c.existsSync(l))try{let u=c.readFileSync(l,"utf-8"),d=JSON.parse(u);if(i={globalVariables:d.globalVariables||{},environments:{},selectedEnvironment:d.selectedEnvironment},d.environments)for(let[p,m]of Object.entries(d.environments)){let f=m;i.environments[p]={name:f.name||p,variables:f.variables||{}}}}catch(u){console.warn(`[ForgeContainer] Failed to load environments from ${l}:`,u)}}return new r({...t,forgeRoot:e,storageFormat:t.storageFormat??"folder",environmentConfig:i})}};Sl();wl();_o();Ye();gu();qa();yu();bu();La();Ne();Va();async function Cm(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(Rm(),wm));return e(r)}async function Em(r){let{runRequest:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}async function qm(r){let{runCollection:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}async function Am(r){let{runFolder:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}async function Pm(r){let{runSuite:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}oc();Gc();Fn();za();Wc();Us();Vs();fo();mo();Pr();Tc();Fc();Zs();Ws();Qs();Zr();Uc();zc();Qi();ln();Bc();Bo();function Sb(r){let e=r.replace(/\\\n/g," "),t=[],n="",s=0;for(;s<e.length;){let i=e[s];if(i==="\\"&&s+1<e.length)n+=e[++s],s++;else if(i==="'"){for(s++;s<e.length&&e[s]!=="'";)n+=e[s++];s++}else if(i==='"'){for(s++;s<e.length&&e[s]!=='"';)if(e[s]==="\\"&&s+1<e.length){let o=e[s+1];o==='"'||o==="\\"||o==="$"||o==="`"?(n+=o,s+=2):n+=e[s++]}else n+=e[s++];s++}else/\s/.test(i)?(n.length>0&&(t.push(n),n=""),s++):(n+=i,s++)}return n.length>0&&t.push(n),t}function xb(r){try{let e="__FV__",t=[],n=r.replace(/\{\{[^}]+\}\}/g,u=>(t.push(u),`${e}${t.length-1}`)),s=n.indexOf("?");if(s===-1)return{cleanUrl:r,params:[]};let i=n.slice(0,s),o=n.slice(s+1),a=u=>u.replace(new RegExp(`${e}(\\d+)`,"g"),(d,p)=>t[parseInt(p,10)]),c=a(i),l=o.split("&").filter(Boolean).map(u=>{let d=a(u),p=d.indexOf("=");return p===-1?{key:d,value:"",enabled:!0}:{key:decodeURIComponent(d.slice(0,p)),value:decodeURIComponent(d.slice(p+1)),enabled:!0}});return{cleanUrl:c,params:l}}catch{return{cleanUrl:r,params:[]}}}function wb(r){try{let e=new URL(r.replace(/\{\{[^}]+\}\}/g,"placeholder")),t=e.pathname.split("/").filter(Boolean),n=t[t.length-1];return n&&!/^\d+$/.test(n)&&!n.startsWith("{")?n.replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):t.length>1?t[t.length-2].replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):e.hostname.replace(/^www\./,"").split(".")[0]??"Request"}catch{return"Request"}}function Rb(r,e,t){let n=[],s=new Set,i=(o,a)=>{s.has(a)||(s.add(a),n.push({key:o,value:a}))};for(let o of r){let a=o.key.toLowerCase();if(a==="authorization"){let c=o.value.match(/^(bearer|basic|token|digest)\s+(.+)$/i);c&&wt(c[2])?i(`${c[1].toUpperCase()}_TOKEN`,c[2]):wt(o.value)&&i("AUTH_TOKEN",o.value)}else Lo.has(a)&&wt(o.value)&&i(Zt(o.key),o.value)}for(let o of e)Ho.has(o.key.toLowerCase())&&wt(o.value)&&i(Zt(o.key),o.value);try{let o=new URL(t.replace(/\{\{[^}]+\}\}/g,"placeholder"));if(!["localhost","127.0.0.1","0.0.0.0","::1"].includes(o.hostname)&&!mi(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function km(r){let e=Sb(r.trim()),t=0;for(;t<e.length&&e[t].toLowerCase()==="curl";)t++;let n=e.slice(t),s="",i="",o=[],a=null,c=!1,l=!1,u=[],d=[],p=0;for(;p<n.length;){let v=n[p];if(v==="-X"||v==="--request")s=n[++p]??"";else if(v==="-H"||v==="--header"){let w=n[++p]??"",b=w.indexOf(":");b>0&&o.push({key:w.slice(0,b).trim(),value:w.slice(b+1).trim()})}else if(v==="-d"||v==="--data"||v==="--data-raw"||v==="--data-binary"||v==="--data-ascii")a=n[++p]??"";else if(v==="--json")a=n[++p]??"",c=!0;else if(v==="-u"||v==="--user"){let w=n[++p]??"",b=btoa(w);o.push({key:"Authorization",value:`Basic ${b}`})}else if(v==="-b"||v==="--cookie")o.push({key:"Cookie",value:n[++p]??""});else if(v==="--url")i=n[++p]??"";else if(v==="-G"||v==="--get")l=!0;else if(v==="-F"||v==="--form"){let w=n[++p]??"",b=w.indexOf("=");b>0&&u.push({key:w.slice(0,b),value:w.slice(b+1)})}else v==="--data-urlencode"?d.push(n[++p]??""):v==="-A"||v==="--user-agent"?o.push({key:"User-Agent",value:n[++p]??""}):v==="-e"||v==="--referer"||v==="--referrer"?o.push({key:"Referer",value:n[++p]??""}):v==="--compressed"||v==="-L"||v==="--location"||v==="-v"||v==="--verbose"||v==="-s"||v==="--silent"||v==="-i"||v==="--include"||v==="-k"||v==="--insecure"||v==="--http1.1"||v==="--http2"||v==="--http3"||(v==="-o"||v==="--output"||v==="--max-time"||v==="--connect-timeout"||v==="-m"||v==="--limit-rate"||v==="--proxy"||v==="-x"?p++:!v.startsWith("-")&&!i&&(i=v));p++}l?s="GET":s||(s=a!==null||u.length>0||d.length>0?"POST":"GET");let{cleanUrl:m,params:f}=xb(i),h=null;if(u.length>0)h={type:"raw",format:"text",content:u.map(w=>`${encodeURIComponent(w.key)}=${encodeURIComponent(w.value)}`).join("&")},o.some(w=>w.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"multipart/form-data"});else if(d.length>0)h={type:"raw",format:"text",content:d.join("&")},o.some(v=>v.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"application/x-www-form-urlencoded"});else if(a!==null){let v=a.trim(),w=c||v.startsWith("{")||v.startsWith("[");h={type:"raw",format:w?"json":"text",content:a},w&&!o.some(b=>b.key.toLowerCase()==="content-type")&&o.push({key:"Content-Type",value:"application/json"})}let g=o.map(v=>({...v,enabled:!0})),y=Rb(o,f,m||i);return{name:wb(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:y}}er();Qo();Xn();er();Xn();var pc=10;async function Im(r,e,t,n){let s=Tm(r.items);if(s.length===0)return;let i=Math.ceil(s.length/pc);for(let o=0;o<s.length;o+=pc){let a=s.slice(o,o+pc),c=Math.floor(o/pc)+1;n?.(`Enhancing requests (batch ${c}/${i})\u2026`,1/i*100);let l=a.map(u=>({id:u.id,name:u.name,method:u.method??"GET",url:u.url??"",bodyContent:Ab(u),responseSchema:u.responseSchema?JSON.stringify(u.responseSchema).slice(0,500):void 0,description:u.description?.slice(0,200),doc:u.doc?u.doc.slice(0,800):void 0,operationId:u.operationId,tags:u.tags?.slice(0,5)}));try{let u=await tt(()=>t.complete(Cb(l,a))),d=Eb(u);qb(a,d)}catch{}}await e.saveCollection(r)}function Cb(r,e){return`You are an API testing expert. For each HTTP request below, return two improvements:
1427
+ [View HTML Report](${u[1]})`:"";return{content:[{type:"text",text:l+d}]}}case"prompts/list":return{prompts:Mi};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=it(r.workspaceFolder);try{return await Ea(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{Fs(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function fb(r,e,t){let n=!r.container,s=r.container??it(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&Fs(s)}let o=e.headers.origin??"",a=i.includes(o)?o:i[0]??"http://localhost";t.setHeader("Access-Control-Allow-Origin",a),t.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Mcp-Session-Id")}function mb(r,e,t){let s=new URL(e.url,`http://${r.host}:${r.port}`).searchParams.get("path");if(!s){t.statusCode=400,t.end("Missing path parameter");return}let i=In.resolve(s),o=r.container?.config.getResultsPath(),a=o?In.dirname(o):In.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+In.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}Sm.readFile(i,"utf-8",(c,l)=>{if(c){t.statusCode=404,t.end("Report not found");return}t.statusCode=200,t.setHeader("content-type","text/html; charset=utf-8"),t.end(l)})}function Ou(r,e,t,n){let s=r.create(e,t);return n().then(i=>{s.status!=="cancelled"&&(s.status="completed",s.completedAt=Date.now(),s.summary=i?.summary??s.summary,i?.failedRequests&&(s.failedRequests=i.failedRequests),i?.noAssertionExamples&&(s.noAssertionExamples=i.noAssertionExamples),s.reportPath=i?.report?.uri?.replace("file://","")??null,s.progress.completed=s.progress.total)}).catch(i=>{s.status!=="cancelled"&&(s.status="failed",s.completedAt=Date.now(),s.error=i.message)}),{runId:s.id,status:"running",total:t,message:"Run started. Use get_run_status to poll."}}function hb(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return At(()=>dc({workspaceFolder:e,collectionId:t.id,requestId:n,environment:s.environment,variables:s.variables,headers:s.headers,query:s.query,body:s.body,include:s.include}))},async runFolder(t,n,s){let i=K(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?Ou(r.runStore,`${t.name} / ${bt(n)}`,i,()=>At(()=>on({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))):At(()=>on({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))},async runCollection(t,n){let s=K(t).length;return n.async===!0?Ou(r.runStore,t.name,s,()=>At(()=>on({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):At(()=>on({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))},async runSuite(t,n,s){let i=it(e),o=0;try{let a=await i.testSuite.getSuite(t);o=(a?.nodes.filter(l=>l.type==="request").length??0)*(s.iterations??a?.config?.iterations??1)}finally{Fs(i)}return s.async===!0?Ou(r.runStore,n,o,()=>At(()=>Ui({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))):At(()=>Ui({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))}}}async function Fu(r,e,t={}){let n=r.workspaceFolder,s=lb(r.container,e);if(Object.values(S).includes(s)){let a=it(n),c=as();try{let l=await Pa(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,hb(r));return gb.has(s)&&$u.delete(n),l}finally{Fs(a)}}let i=Fa(s),o=it(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=mr(m,c),h=f?a.find(g=>g.id===f):void 0;if(!h)throw new Error(`Collection not found for tool: ${e}`);return h};if(i.kind==="request"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed request tool: ${e}`);let h=l(m),g=K(h).map(v=>v.request.id),y=mr(f,g);if(!y)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return At(()=>dc({workspaceFolder:n,collectionId:h.id,requestId:y,environment:t.environment,variables:t.variables,headers:t.headers,query:t.query,body:t.body,include:t.include}))}if(i.kind==="collection"){let[m]=i.tokens;if(!m)throw new Error(`Malformed collection tool: ${e}`);let f=l(m);return At(()=>on({workspaceFolder:n,collectionId:f.id,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}if(i.kind==="folder"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed folder tool: ${e}`);let h=l(m),g=(o.collection.getAllCollections().find(w=>w.id===h.id),void 0),y=K(h).map(w=>w.folderPath).filter((w,b,C)=>w&&C.indexOf(w)===b),v=Na(f,y);if(!v)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return At(()=>on({workspaceFolder:n,collectionId:h.id,folderPath:v,recursive:t.recursive,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}let[u]=i.tokens;if(!u)throw new Error(`Malformed suite tool: ${e}`);let d=await o.testSuite.getAllSuites(),p=mr(u,d.map(m=>m.id));if(!p)throw new Error(`Test suite not found for tool: ${e}`);return At(()=>Ui({workspaceFolder:n,suiteId:p,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,requestFilter:t.requestFilter,include:t.include}))}finally{Fs(o)}}function Sr(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function bm(r){return new Promise((e,t)=>{let n="";r.on("data",s=>{n+=s,n.length>1024*1024&&t(new Error("Request body too large (max 1MB)"))}),r.on("end",()=>{if(!n){e({});return}try{e(JSON.parse(n))}catch{t(new Error("Invalid JSON body"))}}),r.on("error",t)})}function yb(r){return(0,xm.createServer)(async(e,t)=>{try{if(fb(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){Sr(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){mb(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await bm(e)}catch{vm(t,null,-32700,"Parse error");return}try{let s=await pb(r,n);Sr(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){vm(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await bm(e);if(!n||typeof n.name!="string"||n.name.trim()===""){Sr(t,400,{error:'Field "name" is required'});return}let s=await Fu(r,n.name,n.args??{});Sr(t,200,{result:s});return}Sr(t,405,{error:"Method not allowed"})}catch(n){Sr(t,500,{error:n.message})}})}function vb(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new zt(In.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function bb(r){let e=vb(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new Ss};return ob.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=it(s.workspaceFolder));let i=yb(s);await new Promise((o,a)=>{i.once("error",a),i.listen(s.port,s.host,()=>{i.off("error",a),o()})}),s.server=i,s.isRunning=!0},async stop(){if(s.container&&(Fs(s.container),s.container=void 0),!s.server){s.isRunning=!1;return}await new Promise((i,o)=>{s.server.close(a=>{if(a){o(a);return}i()})}),s.server=void 0,s.isRunning=!1},isRunning(){return s.isRunning},getPort(){return s.port},async executeTool(i,o){return Fu(s,i,o??{})}}}var Sm,xm,In,ob,ab,$u,Tu,gb,Rm=E(()=>{"use strict";Sm=T(require("fs")),xm=require("http"),In=T(require("path"));vo();Qo();$s();Ye();gu();qa();yu();bu();La();Ne();oc();ob=new Map;ab=3e3,$u=new Map,Tu=new Map;gb=Aa});var Wb={};Tt(Wb,{AnthropicProvider:()=>os,ApiArchitectService:()=>is,ApiDiscoveryService:()=>fr,AwsSecretResolver:()=>oi,AzureKeyVaultResolver:()=>ai,BODY_FILE_MAP:()=>vc,CACHE_BUSTING_TOOLS:()=>Aa,COLLECTION_INPUT_SCHEMA:()=>bi,CONFIG_FILES:()=>vn,CollectionLoader:()=>$n,CollectionLoaderFactory:()=>Vr,CollectionRequestExecutor:()=>_t,CollectionService:()=>zr,ConfigService:()=>zt,CookieJar:()=>qr,CookieService:()=>Jr,CookieUtils:()=>ne,DEFAULT_CONFIG:()=>ce,DEFAULT_REQUEST_SETTINGS:()=>lo,DataFileParser:()=>yn,DopplerResolver:()=>di,EnvironmentConfigService:()=>Wr,EnvironmentResolver:()=>Ot,ExampleGenerator:()=>Gn,ExpressComponentAnalyzer:()=>ps,ExpressDiscoveryProvider:()=>or,FOLDER_INPUT_SCHEMA:()=>Si,FastApiDiscoveryProvider:()=>pr,FastifyComponentAnalyzer:()=>fs,FastifyDiscoveryProvider:()=>ar,FetchHttpClient:()=>_r,FolderCollectionLoader:()=>Cr,FolderCollectionStore:()=>Bt,ForgeContainer:()=>go,ForgeEnv:()=>Ut,FrameworkDetector:()=>rr,GENERIC_TOOL_NAMES:()=>S,GcpSecretResolver:()=>ui,GraphQLSchemaService:()=>Qr,HTTP_METHOD_MAP:()=>Ja,HTTP_METHOD_REVERSE:()=>rt,HashiCorpVaultResolver:()=>ci,HistoryAnalyzer:()=>Jn,HtmlReportGenerator:()=>hr,HttpForgeParser:()=>gn,HttpRequestService:()=>$t,InMemoryCookieJar:()=>An,InterceptorChain:()=>Ft,JUnitReportGenerator:()=>Lt,JsonCollectionLoader:()=>Vn,LambdaComponentAnalyzer:()=>ms,LambdaDiscoveryProvider:()=>lr,MCP_PROMPTS:()=>Mi,METADATA_FILES:()=>Oe,McpRunStore:()=>Ss,ModuleLoader:()=>zs,NestDiscoveryProvider:()=>cr,NodeFileSystem:()=>Dr,NodeHttpClient:()=>mn,OAuth2TokenManager:()=>Hr,OnePasswordResolver:()=>li,OpenAiProvider:()=>yi,OpenApiExporter:()=>Wt,OpenApiImporter:()=>Mt,ParserRegistry:()=>Er,PersistentCookieJar:()=>Gr,REQUEST_INPUT_SCHEMA:()=>vi,ROOT_DIRECTORIES:()=>Vt,RefResolver:()=>Wn,RequestExecutor:()=>Hn,RequestHistoryService:()=>Yr,RequestHistoryStore:()=>Nr,RequestPreparer:()=>Kr,RequestPreprocessor:()=>hn,RequestScriptSession:()=>Fr,ResultStorageService:()=>kn,SCHEMA_FILES:()=>Rr,SCRIPTS_DIR:()=>He,SCRIPT_FILES:()=>_s,SUITE_INPUT_SCHEMA:()=>xi,SchemaInferenceService:()=>Kt,SchemaInferrer:()=>Gt,ScriptAnalyzer:()=>Kn,ScriptExecutor:()=>Nt,SecretResolverRegistry:()=>Xr,ServiceContainer:()=>xn,ServiceIdentifiers:()=>$,SpringDiscoveryProvider:()=>dr,StatisticsService:()=>mc,TestSuiteService:()=>es,TestSuiteStore:()=>hc,UrlBuilder:()=>ct,VariableInterpolator:()=>fn,VariableResolver:()=>pn,analyzeComponentChainMetadata:()=>us,analyzeHandlerMetadata:()=>Ci,applyEnvSuggestionsToItems:()=>Uo,applyExtractionPlan:()=>gd,applyFilterChain:()=>Tr,applyMcpBodyTruncation:()=>jt,applyRegenerated:()=>$i,assembleBusinessContext:()=>rs,buildArchitectPrompt:()=>zo,buildCollectionBusinessContext:()=>Rl,buildCollectionToolDescription:()=>Ma,buildCollectionToolName:()=>Ta,buildExtractionPlan:()=>hd,buildFolderToolDescription:()=>Da,buildFolderToolName:()=>Oa,buildGenericTools:()=>wi,buildMcpToolList:()=>Ua,buildPromptResult:()=>Ea,buildRequestBusinessContext:()=>Do,buildRequestToolDescription:()=>_a,buildRequestToolName:()=>Ia,buildResultFileName:()=>Pn,buildRunResultsContext:()=>Cl,buildSuiteToolDescription:()=>ja,buildSuiteToolName:()=>$a,cleanupOldBodyFiles:()=>xc,clearRegisteredKnowledgeSources:()=>Qd,collectSourceFiles:()=>nt,collectionKnowledgeSource:()=>Dt,collectionToEndpoints:()=>Vo,combineConfidence:()=>Yt,computeProjectFreshness:()=>vs,concatenateScripts:()=>Ks,countRequests:()=>No,createDefaultKnowledgeSources:()=>El,createEnvAiProvider:()=>as,createExpectChain:()=>jn,createMcpRuntime:()=>Cm,createModuleLoader:()=>no,createMomentShim:()=>Js,createNodeContainer:()=>it,createResponseObject:()=>Gs,createTestFunction:()=>so,decodeCursor:()=>Ba,decodeFolderPath:()=>bt,dedupeDiscoveredApiParameters:()=>en,deleteItemFromTree:()=>Ht,deserializeTypedRecord:()=>uc,deserializeTypedValue:()=>br,detectEnvSuggestions:()=>gi,detectIndexDrift:()=>su,detectProjectDrift:()=>bs,diffLines:()=>ys,discoverWorkflows:()=>wn,dispatchGenericTool:()=>Pa,encodeCursor:()=>Ha,encodeFolderName:()=>Ee,enhanceCollection:()=>Im,enumerateFolders:()=>Re,evaluateExpression:()=>gt,exportCollectionToRestClient:()=>ld,extractJsonFromLlm:()=>xt,extractPathParameters:()=>Xt,findItemById:()=>xe,flattenRequests:()=>K,formatConsoleOutput:()=>Ln,gatherWorkspaceKnowledge:()=>ns,generateFlowFromEndpoints:()=>nr,generateId:()=>re,generateReleaseNotes:()=>Du,generateSlug:()=>at,generateSuiteFromEndpoints:()=>tr,getCompletions:()=>_m,getRegisteredKnowledgeSources:()=>Zd,getServiceContainer:()=>xl,harToCollection:()=>Hu,hasChanged:()=>$r,isExpression:()=>dn,isSystemEnvironmentFile:()=>js,loadEnvironmentsFromFolder:()=>Ar,loadHybridSeedEndpoints:()=>Ri,normalizeFolderInput:()=>Qn,normalizeHeaders:()=>io,parseCurlCommand:()=>km,parseFilterChain:()=>Ir,parseHar:()=>gc,parseMcpToolName:()=>Fa,parsePostmanEnvironment:()=>bo,parseQueryContext:()=>Nm,prepareBodyForSave:()=>Sc,proposeSuiteUpdates:()=>Oi,readBodyFromDir:()=>bc,readSchemaFile:()=>wc,readScriptsFromDir:()=>Ms,redactFullResponse:()=>wo,redactFullResultDetails:()=>Ro,redactHeaders:()=>lt,redactHistoryEntry:()=>xo,registerCoreServices:()=>pi,registerKnowledgeSource:()=>Kd,renderArchitectDocs:()=>Il,renderReleaseNotesMarkdown:()=>ju,requestKnowledgeSource:()=>Xe,resolveCollectionRef:()=>ac,resolveFolderRef:()=>cc,resolveFolderToken:()=>Na,resolveProjectName:()=>_l,resolveRegenerated:()=>wa,resolveRequestRef:()=>lc,resolveResultGrouping:()=>ws,resolveToken:()=>mr,reviewSuiteRun:()=>Fi,runCollection:()=>qm,runFolder:()=>Am,runRequest:()=>Em,runResultsKnowledgeSource:()=>fi,runSuite:()=>Pm,scanCollectionForEnvVarsWithAi:()=>Om,searchForItemPath:()=>Wi,searchForItemPathById:()=>Ki,serializeTypedValue:()=>Os,sortItemsByOrder:()=>Cc,suiteIdFromName:()=>ss,threeWayDiff:()=>xa,toReviewRequestResults:()=>Ni,validateDesignedSpec:()=>kl,withAiRetry:()=>tt,workspaceKnowledgeSource:()=>et,writeEnvFile:()=>Un,writeFolderItems:()=>Xs,writeSchemaFiles:()=>Rc,writeScriptFile:()=>Ur,writeScriptsToDir:()=>Ds});module.exports=On(Wb);var $n=class{constructor(e,t){this.fileSystem=e;this.parserRegistry=t}fileSystem;parserRegistry;directory;setDirectory(e){this.directory=e}async loadAll(){return this.directory?this.loadDirectory(this.directory):[]}async load(e,t={}){let n=await this.fileSystem.readFile(e);if(t.format){let i=this.parserRegistry.get(t.format);if(!i)throw new Error(`No parser registered for format: ${t.format}`);return i.parse(n,e)}let s=this.parserRegistry.detect(n);if(!s)throw new Error(`Could not detect collection format for: ${e}. Supported formats: ${this.parserRegistry.getFormats().join(", ")}`);return s.parser.parse(n,e)}async loadDirectory(e,t=["*.json","*.forge.json"]){let n=[],s=await this.fileSystem.glob(t,e);for(let i of s)try{let o=await this.load(i);n.push(o)}catch{}return n}async canLoad(e){try{if(!await this.fileSystem.exists(e))return!1;let t=await this.fileSystem.readFile(e);return this.parserRegistry.detect(t)!==null}catch{return!1}}getSupportedFormats(){return this.parserRegistry.getFormats()}};Qi();ln();function qc(r,e){return{id:r.id,name:r.name,description:r.description,variables:r.variables||{},auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Vu),source:{format:"folder",filePath:e,version:r.version}}}function Vu(r){if(r.type==="folder")return{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Vu)};let e=r;return{type:"request",id:e.id,name:e.name,description:e.description,method:e.method||"GET",url:e.url||"",headers:e.headers||[],query:e.query||[],params:e.params,body:e.body??void 0,auth:e.auth,settings:e.settings,scripts:e.scripts,...e.deprecated&&{deprecated:e.deprecated},...e.doc&&{doc:e.doc},...e.responseSchema&&{responseSchema:e.responseSchema},...e.bodySchema&&{bodySchema:e.bodySchema},...e.operationId&&{operationId:e.operationId},...e.summary&&{summary:e.summary},...e.tags&&e.tags.length>0&&{tags:e.tags},...e.examples&&e.examples.length>0&&{examples:e.examples},...e.responses&&Object.keys(e.responses).length>0&&{responses:e.responses},...e.security&&e.security.length>0&&{security:e.security}}}function Qm(r){return{id:r.id,name:r.name,description:r.description,version:r.source?.version,variables:r.variables,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Ac)}}function Ac(r){return r.type==="folder"?{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(Ac)}:{type:"request",id:r.id,name:r.name,description:r.description,method:r.method,url:r.url,headers:r.headers,query:r.query,params:r.params,body:r.body,auth:r.auth,settings:r.settings,scripts:r.scripts,...r.deprecated&&{deprecated:r.deprecated},...r.doc&&{doc:r.doc},...r.responseSchema&&{responseSchema:r.responseSchema},...r.bodySchema&&{bodySchema:r.bodySchema},...r.operationId&&{operationId:r.operationId},...r.summary&&{summary:r.summary},...r.tags&&{tags:r.tags},...r.examples&&{examples:r.examples},...r.responses&&{responses:r.responses},...r.security&&{security:r.security}}}var Cr=class{store;constructor(e){this.store=new Bt(e)}loadAll(){return this.store.loadAll().map(t=>qc(t,this.store.getCollectionPath(t.id)))}getSlugById(e){return this.store.getSlugById(e)}getIdBySlug(e){return this.store.getIdBySlug(e)}load(e){let t=this.store.load(e);if(t)return qc(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return qc(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(Qm(e))}async delete(e){return this.store.delete(e)}exists(e){return this.store.exists(e)}getCollectionPath(e){return this.store.getCollectionPath(e)}async updateCollectionMetadata(e,t){return this.store.updateCollectionMetadata(e,t)}async saveItem(e,t,n){return this.store.saveItem(e,Ac(t),n)}async updateItem(e,t,n){let s={...n};return this.store.updateItem(e,t,s)}async deleteItem(e,t){return this.store.deleteItem(e,t)}async moveItem(e,t,n){return this.store.moveItem(e,t,n)}async reorderItems(e,t,n){return this.store.reorderItems(e,t,n)}async saveScripts(e,t,n){return this.store.saveScripts(e,t,n)}loadScripts(e,t){return this.store.loadScripts(e,t)}};var Er=class{parsers=new Map;register(e,t){this.parsers.set(e.toLowerCase(),t)}get(e){return this.parsers.get(e.toLowerCase())}has(e){return this.parsers.has(e.toLowerCase())}getFormats(){return Array.from(this.parsers.keys())}detect(e){for(let[t,n]of this.parsers)if(n.canParse(e))return{parser:n,format:t};return null}clear(){this.parsers.clear()}};Fn();var qr=class{cookies=new Map;getCookieKey(e,t,n){return ne.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e)}setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}}has(e,t){return this.get(e,t)!==void 0}delete(e,t,n){let s=this.getCookieKey(e,t,n);return this.cookies.delete(s)}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return ne.formatCookieHeader(t)}clear(){this.cookies.clear()}clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n)}parseCookieHeaders(e,t){return ne.parseCookieHeaders(e,t)}isExpired(e){return ne.isExpired(e)}domainMatches(e,t){return ne.domainMatches(e,t)}get count(){return this.cookies.size}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t)}};Yi();var Ot=class r{config;selectedEnvironment;sessionGlobals={};sessionEnvironmentValues=new Map;constructor(e){this.config=e,this.selectedEnvironment=e.selectedEnvironment||Object.keys(e.environments)[0]||"default"}get(e){return this.getVariables()[e]}set(e,t){let n=this.sessionEnvironmentValues.get(this.selectedEnvironment);n||(n={},this.sessionEnvironmentValues.set(this.selectedEnvironment,n)),n[e]=t}getAll(){return this.getVariables()}getEnvironments(){return Object.keys(this.config.environments)}getActive(){return this.selectedEnvironment}setActive(e){if(!this.config.environments[e])throw new Error(`Environment not found: ${e}`);this.selectedEnvironment=e}getVariables(e){let t=e||this.selectedEnvironment,n=this.config.environments[t],s={...this.config.globalVariables||{},...this.sessionGlobals};if(n){if(n.inherits&&this.config.environments[n.inherits]){let o=this.getEnvironmentVariables(n.inherits);s={...s,...o}}s={...s,...n.variables};let i=this.sessionEnvironmentValues.get(t);i&&(s={...s,...i})}return s}getEnvironmentVariables(e){let t=this.config.environments[e];if(!t)return{};let n={};return t.inherits&&this.config.environments[t.inherits]&&(n={...this.getEnvironmentVariables(t.inherits)}),{...n,...t.variables}}getGlobals(){return{...this.config.globalVariables||{},...this.sessionGlobals}}setGlobal(e,t){this.sessionGlobals[e]=t}unsetGlobal(e){delete this.sessionGlobals[e]}clearGlobals(){this.sessionGlobals={}}resolve(e){let t=e||this.selectedEnvironment;return{name:t,merged:this.getVariables(t),globals:this.getGlobals()}}static fromVariables(e,t="default"){return new r({environments:{[t]:{name:t,variables:e}},selectedEnvironment:t})}};Pr();Or();var Ut=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new fn,this.urlBuilder=new ct}get(e){return this.envStore.get(e)}set(e,t){this.envStore.set(e,t)}has(e){return this.envStore.get(e)!==void 0}delete(e){this.envStore.set(e,"")}getAll(){return this.envStore.getAll()}getActiveEnvironment(){return this.envStore.getActive()}setActiveEnvironment(e){this.envStore.setActive(e)}getEnvironments(){let e=this.envStore;return typeof e.getEnvironments=="function"?e.getEnvironments():[]}getGlobals(){let e=this.envStore;return typeof e.getGlobals=="function"?e.getGlobals():{}}setGlobal(e,t){let n=this.envStore;typeof n.setGlobal=="function"&&n.setGlobal(e,t)}unsetGlobal(e){let t=this.envStore;typeof t.unsetGlobal=="function"&&t.unsetGlobal(e)}clearGlobals(){let e=this.envStore;typeof e.clearGlobals=="function"&&e.clearGlobals()}resolve(e){return this.interpolator.interpolate(e,this.getAll())}resolvePath(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t)}buildUrl(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t.params||{},t.query||{})}resolveObject(e){return this.interpolator.interpolateObject(e,this.getAll())}extractVariables(e){return this.interpolator.extractVariables(e)}extractPathParams(e){return this.urlBuilder.extractPathParams(e)}static create(e={}){let t=Ot.fromVariables(e);return new r(t)}static fromResolver(e){return new r(e)}};Or();Us();Vs();Pr();Zs();Qs();var Hn=class{constructor(e,t,n,s,i){this.httpClient=e;this.forgeEnv=t;this.cookieJar=n;this.preprocessor=s;if(i?.scriptExecutor)this.scriptExecutor=i.scriptExecutor;else{let o=i?.forgeRoot?[require("path").join(i.forgeRoot,"modules")]:[],a=new $t(new ct,new Ft,e);this.scriptExecutor=new Nt(a,o,void 0,i?.scriptScope??"shared",i?.scriptTimeout??5e3)}}httpClient;forgeEnv;cookieJar;preprocessor;scriptExecutor;async execute(e,t,n={}){let s=Date.now(),i={...this.forgeEnv.getAll()},o={...this.forgeEnv.getGlobals()},a={...n.additionalVariables||{}},c={...i},l=this.buildHttpRequest(e,n.overrides),u=n.overrides?.body||e.body,d=this.findFolderPath(t,e.id),p=this.buildScriptChain(e,t,d),m={request:{url:l.url,method:l.method,headers:{...l.headers},body:u?typeof u=="string"?{type:"raw",content:u}:u:void 0},variables:a,collectionVariables:t.variables||{},globals:{...o},environmentVariables:c,environmentName:this.forgeEnv.getActiveEnvironment?.()||void 0,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:t?.name},onEnvironmentChange:n.onEnvironmentChange,onGlobalsChange:(y,v,w)=>{y==="set"&&v&&w!==void 0?this.forgeEnv.setGlobal(v,w):y==="unset"&&v?this.forgeEnv.unsetGlobal(v):y==="clear"&&this.forgeEnv.clearGlobals()}},f=this.scriptExecutor.createRequestSession(m),h,g;try{if(!n.skipPreRequest&&p.preRequest.length>0){let b=await f.executePreRequest(p.preRequest);if(h={success:b.success,error:b.error,modifiedVariables:b.modifiedVariables,modifiedEnvironment:b.modifiedEnvironmentVariables,modifiedGlobals:b.modifiedGlobals,modifiedCollectionVariables:b.modifiedCollectionVariables,consoleOutput:b.consoleOutput,modifiedRequest:b.modifiedRequest?{url:b.modifiedRequest.url,method:b.modifiedRequest.method,headers:b.modifiedRequest.headers,body:b.modifiedRequest.body?.content}:void 0},b.modifiedVariables&&(a={...a,...b.localVariables??b.modifiedVariables}),b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables}),b.modifiedRequest){let C=b.modifiedRequest;C.url&&(l.url=C.url),C.method&&(l.method=C.method),C.headers&&(l.headers={...l.headers,...C.headers}),C.body!==void 0&&(l.body=C.body?.content||C.body)}if(!b.success)throw new Error(`Pre-request script failed: ${b.error}`)}let y={...c,...a};l=this.interpolateRequest(l,y);let v=n.overrides?.body||e.body;if(this.preprocessor&&v&&typeof v!="string"&&v.type==="graphql"&&l.body!==void 0){let b=this.preprocessor.encodeBody({type:"graphql",content:l.body});b!=null&&(l.body=typeof b=="string"?b:JSON.stringify(b))}if(u&&typeof u=="object"&&u.type==="form-data"&&Array.isArray(l.body)){let b=this.buildMultipartFormData({type:"form-data",content:l.body});b&&(l.body=b)}let w=await this.httpClient.send(l);if(!n.skipPostResponse&&p.postResponse.length>0){let b=await f.executePostResponse(p.postResponse,{status:w.status,statusText:w.statusText,headers:w.headers,body:w.body,cookies:oo(w.headers,w.cookies,l.url),responseTime:w.time,responseSize:w.size,executedRequest:{url:l.url,method:l.method,headers:l.headers||{},body:l.body?typeof l.body=="string"?{type:"raw",content:l.body}:l.body:{type:"none",content:""},params:{},query:{}}});g={success:!0,assertions:b.testResults,consoleOutput:b.consoleOutput,modifiedEnvironment:b.modifiedEnvironmentVariables},b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables})}return{response:w,preRequestResult:h,postResponseResult:g,totalTime:Date.now()-s,finalRequest:l,variables:{environment:c,local:a}}}finally{f.dispose?.()}}async executeSimple(e,t={}){let n=e,s={...this.forgeEnv.getAll(),...t.variables||{}};return n=this.interpolateRequest(e,s),t.timeout&&(n={...n,timeout:t.timeout}),this.httpClient.send(n)}buildHttpRequest(e,t){let n=e.url;if(e.query&&e.query.length>0){let u=new URLSearchParams;for(let d of e.query)d.enabled!==!1&&u.append(d.key,d.value);n+=(n.includes("?")?"&":"?")+u.toString()}let s=t?.url||n,i=t?.method||e.method,o={};if(e.headers&&Array.isArray(e.headers))for(let u of e.headers)u.enabled!==!1&&(o[u.key]=u.value);let a={...o,...t?.headers||{}},c,l=t?.body||e.body;if(l)if(typeof l=="string")c=l;else if(this.preprocessor&&l.type)if(l.type==="graphql")c=typeof l.content=="string"?l.content:JSON.stringify(l.content);else if(l.type==="form-data")c=this.buildMultipartFormData(l);else{let u=this.preprocessor.encodeBody(l);c=u!=null?String(u):void 0}else l.content&&(c=typeof l.content=="string"?l.content:JSON.stringify(l.content));return this.preprocessor&&l&&l.type!=="form-data"&&this.preprocessor.setContentTypeHeader(a,l),{url:s,method:i,headers:a,body:c,timeout:t?.timeout||e.settings?.timeout,settings:{...e.settings,...t?.settings}}}interpolateRequest(e,t){let n=Ut.create(t),s=e.body,i=s;return typeof s=="string"?i=n.resolve(s):s instanceof FormData||s instanceof URLSearchParams?i=s:s&&typeof s=="object"&&(i=n.resolve(s)),{...e,url:n.resolvePath(e.url),headers:n.resolveObject(e.headers),body:i}}buildMultipartFormData(e){if(!e||e.type!=="form-data"||!Array.isArray(e.content))return;let t=new FormData;for(let n of e.content)!n?.key||n.enabled===!1||t.append(n.key,n.value==null?"":String(n.value));return t}buildScriptChain(e,t,n=[]){let s=[],i=[];t.scripts?.preRequest&&s.push(t.scripts.preRequest),t.scripts?.postResponse&&i.push(t.scripts.postResponse);for(let o of n)o.scripts?.preRequest&&s.push(o.scripts.preRequest),o.scripts?.postResponse&&i.push(o.scripts.postResponse);return e.scripts?.preRequest&&s.push(e.scripts.preRequest),e.scripts?.postResponse&&i.push(e.scripts.postResponse),{preRequest:s,postResponse:i}}findFolderPath(e,t){let n=[],s=(i,o)=>{for(let a of i){if(a.type==="request"&&a.id===t)return n.push(...o),!0;if(a.type==="folder"){let c=[...o,a];if(s(a.items,c))return!0}}return!1};return s(e.items,[]),n}};function Th(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}var Nr=class{entries=new Map;requestIndex=new Map;fullResponses=new Map;maxEntriesPerRequest;storeFullResponses;constructor(e={}){this.maxEntriesPerRequest=e.maxEntriesPerRequest??100,this.storeFullResponses=e.storeFullResponses??!0}getEntries(e,t){let n=this.requestIndex.get(e)||[],s=[];for(let i of n){let o=this.entries.get(i);o&&(!t||o.environment===t)&&s.push(o)}return s}getEntry(e){return this.entries.get(e)}getFullResponse(e){return this.fullResponses.get(e)}get count(){return this.entries.size}addEntry(e,t,n,s,i){let o=Th(),a=Date.now(),c={id:o,timestamp:a,environment:s,method:t.method,ticket:i?.ticket,branch:i?.branch,note:i?.note,sentRequest:{url:t.url,method:t.method,headers:{...t.headers},body:t.body},response:{status:n.status,statusText:n.statusText,time:n.time}};this.entries.set(o,c);let l=this.requestIndex.get(e)||[];for(l.unshift(o);l.length>this.maxEntriesPerRequest;){let u=l.pop();u&&(this.entries.delete(u),this.fullResponses.delete(u))}if(this.requestIndex.set(e,l),this.storeFullResponses){let u={timestamp:a,status:n.status,statusText:n.statusText,headers:{...n.headers},cookies:n.cookies||[],body:n.body,time:n.time};this.fullResponses.set(o,u)}return c}deleteEntry(e){if(!this.entries.get(e))return!1;this.entries.delete(e),this.fullResponses.delete(e);for(let[n,s]of this.requestIndex.entries()){let i=s.indexOf(e);if(i!==-1){s.splice(i,1),s.length===0&&this.requestIndex.delete(n);break}}return!0}clearHistory(e){let t=this.requestIndex.get(e);if(t){for(let n of t)this.entries.delete(n),this.fullResponses.delete(n);this.requestIndex.delete(e)}}clearAll(){this.entries.clear(),this.requestIndex.clear(),this.fullResponses.clear()}};var _r=class{async send(e){let t=Date.now(),n=new AbortController,s=e.timeout??3e4,i=setTimeout(()=>n.abort(),s);try{let o={method:e.method,headers:e.headers,signal:n.signal};e.body!==void 0&&(typeof e.body=="string"||e.body instanceof FormData||e.body instanceof URLSearchParams?o.body=e.body:typeof e.body=="object"&&(o.body=JSON.stringify(e.body),!e.headers?.["Content-Type"]&&!e.headers?.["content-type"]&&(o.headers["Content-Type"]="application/json"))),e.settings?.followRedirects===!1&&(o.redirect="manual");let a=await fetch(e.url,o),c=Date.now(),l;try{l=await a.text()}catch{l=null}let u={};return a.headers.forEach((d,p)=>{let m=u[p];m!==void 0?u[p]=Array.isArray(m)?[...m,d]:[m,d]:u[p]=d}),{status:a.status,statusText:a.statusText,headers:u,cookies:[],body:l,time:c-t}}catch(o){throw o.name==="AbortError"?new Error(`Request timeout after ${s}ms`):o}finally{clearTimeout(i)}}};Us();Vs();fo();mo();Pr();var gn=class{format="http-forge";canParse(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"id"in t&&"name"in t&&"items"in t&&Array.isArray(t.items)&&!t.info?.schema?.includes("postman")&&!t._type}catch{return!1}}parse(e,t){let n=JSON.parse(e);return{id:n.id,name:n.name,description:n.description,variables:n.variables||{},auth:n.auth,scripts:n.scripts?{preRequest:n.scripts.preRequest,postResponse:n.scripts.postResponse}:void 0,items:this.convertItems(n.items),source:{format:"http-forge",filePath:t,version:n.version}}}convertItems(e){return e.map(t=>t.type==="folder"?this.convertFolder(t):this.convertRequest(t))}convertFolder(e){return{type:"folder",id:e.id,name:e.name,description:e.description,auth:e.auth,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0,items:e.items?this.convertItems(e.items):[]}}convertRequest(e){let t={};if(e.headers)for(let s of e.headers)s.enabled!==!1&&(t[s.key]=s.value);let n={};if(e.query)for(let s of e.query)s.enabled!==!1&&(n[s.key]=s.value);return{type:"request",id:e.id,name:e.name,description:e.description,method:e.method||"GET",url:e.url||"",headers:Object.entries(t).map(([s,i])=>({key:s,value:i,enabled:!0})),query:Object.entries(n).map(([s,i])=>({key:s,value:i,enabled:!0})),params:e.params,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0}}};ho();var Qe=T(require("fs/promises")),jr=T(require("path")),Dr=class{async readFile(e){return Qe.readFile(e,"utf-8")}async writeFile(e,t){let n=jr.dirname(e);await this.mkdir(n),await Qe.writeFile(e,t,"utf-8")}async exists(e){try{return await Qe.access(e),!0}catch{return!1}}async mkdir(e){await Qe.mkdir(e,{recursive:!0})}async glob(e,t){let n=t||process.cwd(),s=[];try{await this.walkDirectory(n,i=>{let o=jr.basename(i);for(let a of e)if(this.matchPattern(o,a)){s.push(i);break}})}catch{}return s}async readDir(e){return Qe.readdir(e)}async isDirectory(e){try{return(await Qe.stat(e)).isDirectory()}catch{return!1}}async walkDirectory(e,t){let n=await Qe.readdir(e,{withFileTypes:!0});for(let s of n){let i=jr.join(e,s.name);s.isDirectory()?await this.walkDirectory(i,t):s.isFile()&&t(i)}}matchPattern(e,t){let n=t.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${n}$`,"i").test(e)}};Zs();var go=class r{httpClient;fileSystem;scriptExecutor;interpolator;cookieJar;interceptorChain;preprocessor;dataFileParser;requestHistory;parserRegistry;collectionLoader;environmentStore;forgeEnv;requestExecutor;options;constructor(e={}){if(this.options=e,this.interpolator=e.interpolator||new fn,this.fileSystem=e.fileSystem||new Dr,this.preprocessor=e.preprocessor||new hn,this.dataFileParser=e.dataFileParser||new yn,this.cookieJar=e.cookieJar||new qr,e.enableHistory?this.requestHistory=e.requestHistory||new Nr({maxEntriesPerRequest:e.maxHistoryEntries??100}):this.requestHistory=null,this.interceptorChain=e.interceptorChain||this.createInterceptorChain(e),e.httpClient)this.httpClient=e.httpClient;else if(e.useNativeHttp!==!1){let i={...e.httpSettings,timeout:e.requestTimeout??e.httpSettings?.timeout};this.httpClient=new mn(i)}else this.httpClient=new _r;let t=e.forgeRoot?[require("path").join(e.forgeRoot,"modules")]:[],n=new $t(new ct,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new Nt(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new Er,this.parserRegistry.register("http-forge",new gn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=require("path").join(e.forgeRoot,"collections");this.collectionLoader=new Cr(i)}else this.collectionLoader=new $n(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new Ot(e.environmentConfig):Ot.fromVariables({}),this.forgeEnv=Ut.fromResolver(this.environmentStore),this.requestExecutor=new Hn(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:e.forgeRoot,scriptExecutor:this.scriptExecutor})}createInterceptorChain(e){let t=new Ft;if(e.requestInterceptors)for(let n of e.requestInterceptors)t.addRequestInterceptor(n);if(e.responseInterceptors)for(let n of e.responseInterceptors)t.addResponseInterceptor(n);if(e.errorInterceptors)for(let n of e.errorInterceptors)t.addErrorInterceptor(n);return t}async loadCollection(e){if(this.collectionLoader instanceof $n)return this.collectionLoader.load(e);throw new Error("loadCollection(filePath) is not supported with folder storage format. Use loadAllCollections() instead.")}async loadAllCollections(){return this.collectionLoader.loadAll()}async execute(e,t,n){return this.requestExecutor.execute(e,t,n)}async executeSimple(e,t){return this.requestExecutor.executeSimple(e,t)}registerParser(e,t){this.parserRegistry.register(e,t)}setEnvironmentConfig(e){this.environmentStore=new Ot(e),this.forgeEnv=Ut.fromResolver(this.environmentStore),this.requestExecutor=new Hn(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:this.options.forgeRoot,scriptExecutor:this.scriptExecutor})}static create(e){return new r(e)}static fromForgeRoot(e="./http-forge",t={}){let n=require("path"),s=n.join(e,"environments"),i,o=Ar(s);if(Object.keys(o.environments).length>0||Object.keys(o.globalVariables).length>0){i={globalVariables:{...o.globalVariables,...o.localVariables},environments:{},selectedEnvironment:void 0};for(let[c,l]of Object.entries(o.environments)){let u=o.localCredentials[c]?.variables||{};i.environments[c]={name:c,variables:{...l.variables,...u}}}}else{let c=require("fs"),l=n.join(s,"environments.json");if(c.existsSync(l))try{let u=c.readFileSync(l,"utf-8"),d=JSON.parse(u);if(i={globalVariables:d.globalVariables||{},environments:{},selectedEnvironment:d.selectedEnvironment},d.environments)for(let[p,m]of Object.entries(d.environments)){let f=m;i.environments[p]={name:f.name||p,variables:f.variables||{}}}}catch(u){console.warn(`[ForgeContainer] Failed to load environments from ${l}:`,u)}}return new r({...t,forgeRoot:e,storageFormat:t.storageFormat??"folder",environmentConfig:i})}};Sl();wl();_o();Ye();gu();qa();yu();bu();La();Ne();Va();async function Cm(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(Rm(),wm));return e(r)}async function Em(r){let{runRequest:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}async function qm(r){let{runCollection:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}async function Am(r){let{runFolder:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}async function Pm(r){let{runSuite:e}=await Promise.resolve().then(()=>($s(),Vi));return e(r)}oc();Gc();Fn();za();Wc();Us();Vs();fo();mo();Pr();Tc();Fc();Zs();Ws();Qs();Zr();Uc();zc();Qi();ln();Bc();Bo();function Sb(r){let e=r.replace(/\\\n/g," "),t=[],n="",s=0;for(;s<e.length;){let i=e[s];if(i==="\\"&&s+1<e.length)n+=e[++s],s++;else if(i==="'"){for(s++;s<e.length&&e[s]!=="'";)n+=e[s++];s++}else if(i==='"'){for(s++;s<e.length&&e[s]!=='"';)if(e[s]==="\\"&&s+1<e.length){let o=e[s+1];o==='"'||o==="\\"||o==="$"||o==="`"?(n+=o,s+=2):n+=e[s++]}else n+=e[s++];s++}else/\s/.test(i)?(n.length>0&&(t.push(n),n=""),s++):(n+=i,s++)}return n.length>0&&t.push(n),t}function xb(r){try{let e="__FV__",t=[],n=r.replace(/\{\{[^}]+\}\}/g,u=>(t.push(u),`${e}${t.length-1}`)),s=n.indexOf("?");if(s===-1)return{cleanUrl:r,params:[]};let i=n.slice(0,s),o=n.slice(s+1),a=u=>u.replace(new RegExp(`${e}(\\d+)`,"g"),(d,p)=>t[parseInt(p,10)]),c=a(i),l=o.split("&").filter(Boolean).map(u=>{let d=a(u),p=d.indexOf("=");return p===-1?{key:d,value:"",enabled:!0}:{key:decodeURIComponent(d.slice(0,p)),value:decodeURIComponent(d.slice(p+1)),enabled:!0}});return{cleanUrl:c,params:l}}catch{return{cleanUrl:r,params:[]}}}function wb(r){try{let e=new URL(r.replace(/\{\{[^}]+\}\}/g,"placeholder")),t=e.pathname.split("/").filter(Boolean),n=t[t.length-1];return n&&!/^\d+$/.test(n)&&!n.startsWith("{")?n.replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):t.length>1?t[t.length-2].replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):e.hostname.replace(/^www\./,"").split(".")[0]??"Request"}catch{return"Request"}}function Rb(r,e,t){let n=[],s=new Set,i=(o,a)=>{s.has(a)||(s.add(a),n.push({key:o,value:a}))};for(let o of r){let a=o.key.toLowerCase();if(a==="authorization"){let c=o.value.match(/^(bearer|basic|token|digest)\s+(.+)$/i);c&&wt(c[2])?i(`${c[1].toUpperCase()}_TOKEN`,c[2]):wt(o.value)&&i("AUTH_TOKEN",o.value)}else Lo.has(a)&&wt(o.value)&&i(Zt(o.key),o.value)}for(let o of e)Ho.has(o.key.toLowerCase())&&wt(o.value)&&i(Zt(o.key),o.value);try{let o=new URL(t.replace(/\{\{[^}]+\}\}/g,"placeholder"));if(!["localhost","127.0.0.1","0.0.0.0","::1"].includes(o.hostname)&&!mi(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function km(r){let e=Sb(r.trim()),t=0;for(;t<e.length&&e[t].toLowerCase()==="curl";)t++;let n=e.slice(t),s="",i="",o=[],a=null,c=!1,l=!1,u=[],d=[],p=0;for(;p<n.length;){let v=n[p];if(v==="-X"||v==="--request")s=n[++p]??"";else if(v==="-H"||v==="--header"){let w=n[++p]??"",b=w.indexOf(":");b>0&&o.push({key:w.slice(0,b).trim(),value:w.slice(b+1).trim()})}else if(v==="-d"||v==="--data"||v==="--data-raw"||v==="--data-binary"||v==="--data-ascii")a=n[++p]??"";else if(v==="--json")a=n[++p]??"",c=!0;else if(v==="-u"||v==="--user"){let w=n[++p]??"",b=btoa(w);o.push({key:"Authorization",value:`Basic ${b}`})}else if(v==="-b"||v==="--cookie")o.push({key:"Cookie",value:n[++p]??""});else if(v==="--url")i=n[++p]??"";else if(v==="-G"||v==="--get")l=!0;else if(v==="-F"||v==="--form"){let w=n[++p]??"",b=w.indexOf("=");b>0&&u.push({key:w.slice(0,b),value:w.slice(b+1)})}else v==="--data-urlencode"?d.push(n[++p]??""):v==="-A"||v==="--user-agent"?o.push({key:"User-Agent",value:n[++p]??""}):v==="-e"||v==="--referer"||v==="--referrer"?o.push({key:"Referer",value:n[++p]??""}):v==="--compressed"||v==="-L"||v==="--location"||v==="-v"||v==="--verbose"||v==="-s"||v==="--silent"||v==="-i"||v==="--include"||v==="-k"||v==="--insecure"||v==="--http1.1"||v==="--http2"||v==="--http3"||(v==="-o"||v==="--output"||v==="--max-time"||v==="--connect-timeout"||v==="-m"||v==="--limit-rate"||v==="--proxy"||v==="-x"?p++:!v.startsWith("-")&&!i&&(i=v));p++}l?s="GET":s||(s=a!==null||u.length>0||d.length>0?"POST":"GET");let{cleanUrl:m,params:f}=xb(i),h=null;if(u.length>0)h={type:"raw",format:"text",content:u.map(w=>`${encodeURIComponent(w.key)}=${encodeURIComponent(w.value)}`).join("&")},o.some(w=>w.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"multipart/form-data"});else if(d.length>0)h={type:"raw",format:"text",content:d.join("&")},o.some(v=>v.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"application/x-www-form-urlencoded"});else if(a!==null){let v=a.trim(),w=c||v.startsWith("{")||v.startsWith("[");h={type:"raw",format:w?"json":"text",content:a},w&&!o.some(b=>b.key.toLowerCase()==="content-type")&&o.push({key:"Content-Type",value:"application/json"})}let g=o.map(v=>({...v,enabled:!0})),y=Rb(o,f,m||i);return{name:wb(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:y}}Xn();er();Qo();er();Xn();var pc=10;async function Im(r,e,t,n){let s=Tm(r.items);if(s.length===0)return;let i=Math.ceil(s.length/pc);for(let o=0;o<s.length;o+=pc){let a=s.slice(o,o+pc),c=Math.floor(o/pc)+1;n?.(`Enhancing requests (batch ${c}/${i})\u2026`,1/i*100);let l=a.map(u=>({id:u.id,name:u.name,method:u.method??"GET",url:u.url??"",bodyContent:Ab(u),responseSchema:u.responseSchema?JSON.stringify(u.responseSchema).slice(0,500):void 0,description:u.description?.slice(0,200),doc:u.doc?u.doc.slice(0,800):void 0,operationId:u.operationId,tags:u.tags?.slice(0,5)}));try{let u=await tt(()=>t.complete(Cb(l,a))),d=Eb(u);qb(a,d)}catch{}}await e.saveCollection(r)}function Cb(r,e){return`You are an API testing expert. For each HTTP request below, return two improvements:
1428
1428
  1. "body" \u2014 a realistic, human-readable JSON request body string (not schema placeholders like "string" or 0). If the request has no body or is a GET/HEAD/DELETE, return null.
1429
1429
  2. "testScript" \u2014 a JavaScript postResponse test using pm.test() syntax. Always include a status code check. Add response body assertions if a responseSchema is provided.
1430
1430
 
@@ -1460,6 +1460,6 @@ Return ONLY a valid JSON array (no markdown fences):
1460
1460
  $0
1461
1461
  }`,sortOrder:5})}return(!e.prefix||"...".startsWith(e.prefix))&&t.push({label:"...",kind:"snippet",detail:"Fragment spread",insertText:"...${1:FragmentName}",sortOrder:8}),t}function Tb(r,e){if(!e.currentField||!e.parentType)return[];let t=r.types.get(e.parentType);if(!t)return[];let n=t.fields.find(i=>i.name===e.currentField);if(!n)return[];let s=[];for(let i of n.args)(!e.prefix||i.name.toLowerCase().startsWith(e.prefix.toLowerCase()))&&s.push({label:i.name,kind:"argument",detail:i.type,description:i.description,insertText:`${i.name}: `,sortOrder:0});return s}function Ob(r,e){if(!e.currentArg||!e.currentField||!e.parentType)return[];let t=[],n=r.types.get(e.parentType);if(!n)return t;let s=n.fields.find(c=>c.name===e.currentField);if(!s)return t;let i=s.args.find(c=>c.name===e.currentArg);if(!i)return t;let o=i.type.replace(/[!\[\]]/g,""),a=r.types.get(o);if(a&&a.kind==="ENUM")for(let c of a.enumValues)(!e.prefix||c.name.toLowerCase().startsWith(e.prefix.toLowerCase()))&&t.push({label:c.name,kind:"enum",detail:a.name,description:c.description,deprecated:c.isDeprecated,sortOrder:0});else if(o==="Boolean")for(let c of["true","false"])(!e.prefix||c.startsWith(e.prefix.toLowerCase()))&&t.push({label:c,kind:"keyword",detail:"Boolean",sortOrder:0});return t}function $b(r,e){let t=[];for(let n of r.directives)if(!e||n.name.toLowerCase().startsWith(e.toLowerCase())){let s=n.args.length>0?`(${n.args.map(i=>`${i.name}: ${i.type}`).join(", ")})`:"";t.push({label:`@${n.name}`,kind:"directive",detail:s||void 0,description:n.description,insertText:n.args.length>0?`@${n.name}($1)`:`@${n.name}`,sortOrder:0})}return t}function Fb(r,e){let t=[];for(let[n,s]of r.types)(s.kind==="OBJECT"||s.kind==="INTERFACE"||s.kind==="UNION")&&(!e||n.toLowerCase().startsWith(e.toLowerCase()))&&t.push({label:n,kind:"type",detail:s.kind,description:s.description,sortOrder:0});return t}function Nb(r,e){let t=[];for(let[n,s]of r.types)(s.kind==="SCALAR"||s.kind==="INPUT_OBJECT"||s.kind==="ENUM")&&(!e||n.toLowerCase().startsWith(e.toLowerCase()))&&t.push({label:n,kind:"type",detail:s.kind,description:s.description,sortOrder:0});return t}function Mm(r,e,t){let n=r.type.replace(/[!\[\]]/g,""),s=!1;if(t){let o=t.types.get(n);s=!!o&&(o.kind==="OBJECT"||o.kind==="INTERFACE"||o.kind==="UNION")}else s=!new Set(["String","Int","Float","Boolean","ID"]).has(n);let i=r.name;if(r.args.length>0){let o=r.args.filter(a=>a.type.endsWith("!"));if(o.length>0){let a=o.map((c,l)=>`${c.name}: \${${l+1}}`).join(", ");i=`${r.name}(${a})`}}return s&&(i+=` {
1462
1462
  $0
1463
- }`),{label:r.name,kind:"field",detail:r.type,description:r.description,insertText:i,deprecated:r.isDeprecated,sortOrder:e}}function _b(r){return r.replace(/"""[\s\S]*?"""/g,'""').replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/#[^\n]*/g,"")}function _u(r,e,t){let n=0;for(let s of r)s===e?n++:s===t&&n--;return n}function $m(r){return _u(r,"(",")")>0}function Mb(r){if(_u(r,"(",")")<=0)return!1;let t=r.indexOf("{"),n=t>=0?r.slice(0,t):r;return/\$\w+\s*:\s*\w*$/.test(n)}function Fm(r){let e=0;for(let t=r.length-1;t>=0;t--)if(r[t]===")")e++;else if(r[t]==="("){if(e===0){let s=r.slice(0,t).trimEnd().match(/(\w+)$/);return s?s[1]:null}e--}return null}function Nu(r,e){if(!e)return[];let t=[],n=e.queryType,s=r.match(/\b(query|mutation|subscription)\b/);s&&(s[1]==="mutation"&&e.mutationType?n=e.mutationType:s[1]==="subscription"&&e.subscriptionType&&(n=e.subscriptionType)),t.push(n);let i=Db(r),o=e.types.get(n);for(let a=0;a<i.length;a++){let c=i[a];if(c!=="{"){if(c==="}"){t.pop(),o=t.length>0?e.types.get(t[t.length-1]):void 0;continue}if(a+1<i.length&&(i[a+1]==="{"||i[a+1]==="(")){let l=a+1;if(i[l]==="("){let u=1;for(l++;l<i.length&&u>0;)i[l]==="("?u++:i[l]===")"&&u--,l++}if(l<i.length&&i[l]==="{"&&o){let u=o.fields.find(d=>d.name===c);if(u){let d=u.type.replace(/[!\[\]]/g,"");t.push(d),o=e.types.get(d)}}}}}return t}function Db(r){let e=[],t=/([a-zA-Z_]\w*|[{}(),:=@!$\[\].]|\.\.\.|"[^"]*"|\d+)/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}Yc();cl();nl();ll();Eo();ul();Oo();ko();To();Tl();Al();Pl();Nl();Yo();Rn();ea();Ml();Vl();zl();Gl();Ql();tu();ru();hs();Jo();Ko();iu();ou();pu();var Mu=require("child_process"),jb=/^(feat|fix|perf|docs|refactor|test|build|chore)(?:\(([^)]*)\))?(!?):\s*(.+)$/i,Dm=/BREAKING[- ]CHANGE:/i;function Du(r){let{projectRoot:e,from:t,to:n="HEAD"}=r,s=t?`${t}..${n}`:n,i=!0,o,a="";try{a=(0,Mu.execSync)(`git log --no-merges --pretty=format:%h%x09%s ${s}`,{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:5e3,maxBuffer:4*1024*1024}),o=(0,Mu.execSync)("git rev-parse HEAD",{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim()}catch{i=!1}let c=a.split(`
1463
+ }`),{label:r.name,kind:"field",detail:r.type,description:r.description,insertText:i,deprecated:r.isDeprecated,sortOrder:e}}function _b(r){return r.replace(/"""[\s\S]*?"""/g,'""').replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/#[^\n]*/g,"")}function _u(r,e,t){let n=0;for(let s of r)s===e?n++:s===t&&n--;return n}function $m(r){return _u(r,"(",")")>0}function Mb(r){if(_u(r,"(",")")<=0)return!1;let t=r.indexOf("{"),n=t>=0?r.slice(0,t):r;return/\$\w+\s*:\s*\w*$/.test(n)}function Fm(r){let e=0;for(let t=r.length-1;t>=0;t--)if(r[t]===")")e++;else if(r[t]==="("){if(e===0){let s=r.slice(0,t).trimEnd().match(/(\w+)$/);return s?s[1]:null}e--}return null}function Nu(r,e){if(!e)return[];let t=[],n=e.queryType,s=r.match(/\b(query|mutation|subscription)\b/);s&&(s[1]==="mutation"&&e.mutationType?n=e.mutationType:s[1]==="subscription"&&e.subscriptionType&&(n=e.subscriptionType)),t.push(n);let i=Db(r),o=e.types.get(n);for(let a=0;a<i.length;a++){let c=i[a];if(c!=="{"){if(c==="}"){t.pop(),o=t.length>0?e.types.get(t[t.length-1]):void 0;continue}if(a+1<i.length&&(i[a+1]==="{"||i[a+1]==="(")){let l=a+1;if(i[l]==="("){let u=1;for(l++;l<i.length&&u>0;)i[l]==="("?u++:i[l]===")"&&u--,l++}if(l<i.length&&i[l]==="{"&&o){let u=o.fields.find(d=>d.name===c);if(u){let d=u.type.replace(/[!\[\]]/g,"");t.push(d),o=e.types.get(d)}}}}}return t}function Db(r){let e=[],t=/([a-zA-Z_]\w*|[{}(),:=@!$\[\].]|\.\.\.|"[^"]*"|\d+)/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}Yc();cl();nl();ll();Eo();ul();Oo();ko();To();Tl();Al();Pl();hs();ou();iu();ru();Yo();Ml();Vl();zl();Ql();Gl();ea();Rn();tu();Jo();Nl();Ko();pu();var Mu=require("child_process"),jb=/^(feat|fix|perf|docs|refactor|test|build|chore)(?:\(([^)]*)\))?(!?):\s*(.+)$/i,Dm=/BREAKING[- ]CHANGE:/i;function Du(r){let{projectRoot:e,from:t,to:n="HEAD"}=r,s=t?`${t}..${n}`:n,i=!0,o,a="";try{a=(0,Mu.execSync)(`git log --no-merges --pretty=format:%h%x09%s ${s}`,{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:5e3,maxBuffer:4*1024*1024}),o=(0,Mu.execSync)("git rev-parse HEAD",{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim()}catch{i=!1}let c=a.split(`
1464
1464
  `).map(u=>u.trim()).filter(Boolean).map(Lb).filter(u=>u!==null),l={};for(let u of c)l[u.type]=(l[u.type]??0)+1;return{from:t??null,to:n,toHash:o,entries:c,summary:l,gitAvailable:i}}function Lb(r){let e=r.indexOf(" ");if(e<0)return null;let t=r.slice(0,e),n=r.slice(e+1),s=n.match(jb);if(!s)return{type:"other",subject:n,hash:t,breaking:Dm.test(n)};let[,i,o,a,c]=s;return{type:i.toLowerCase(),scope:o||void 0,subject:c,hash:t,breaking:a==="!"||Dm.test(c)}}function ju(r){if(!r.gitAvailable)return"Release notes unavailable: project is not a git work tree.";if(r.entries.length===0)return r.from?`No commits in ${r.from}..${r.to}.`:`No commits found up to ${r.to}.`;let e=["feat","fix","perf","refactor","docs","test","build","chore","other"],t=r.entries.filter(s=>s.breaking),n=[];t.length>0&&n.push("### \u26A0\uFE0F Breaking changes",...t.map(s=>`- **${s.subject}** \`${s.hash}\``));for(let s of e){let i=r.entries.filter(a=>a.type===s&&!a.breaking);if(i.length===0)continue;let o={feat:"### \u2728 Features",fix:"### \u{1F41B} Bug fixes",perf:"### \u26A1 Performance",refactor:"### \u{1F527} Refactors",docs:"### \u{1F4DA} Docs",test:"### \u2705 Tests",build:"### \u{1F4E6} Build",chore:"### \u{1F9F9} Chores",other:"### Other"};n.push(o[s]);for(let a of i){let c=a.scope?`**${a.scope}:** `:"";n.push(`- ${c}${a.subject} \`${a.hash}\``)}}return n.join(`
1465
1465
  `)}Jc();vo();Ru();Di();Rs();Ka();function fc(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,t)]}function Lu(r,e){return{key:r,name:e,count:0,passed:0,failed:0,skipped:0,min:0,max:0,avg:0,p50:0,p90:0,p95:0,p99:0,durations:[]}}function jm(r){if(r.durations.length===0){r.min=0,r.max=0,r.avg=0,r.p50=0,r.p90=0,r.p95=0,r.p99=0;return}let e=[...r.durations].sort((n,s)=>n-s),t=r.durations.reduce((n,s)=>n+s,0);r.min=e[0],r.max=e[e.length-1],r.avg=Math.round(t/r.durations.length),r.p50=fc(e,50),r.p90=fc(e,90),r.p95=fc(e,95),r.p99=fc(e,99)}var mc=class{summary;byRequest;overall;errors;startTime=0;constructor(){this.summary=this.createEmptySummary(),this.byRequest=new Map,this.overall=Lu("overall","Overall"),this.errors=new Map}createEmptySummary(){return{totalRequests:0,passed:0,failed:0,skipped:0,passRate:0,duration:0,isRunning:!1}}start(){this.startTime=Date.now(),this.summary.isRunning=!0}reset(){this.summary=this.createEmptySummary(),this.byRequest.clear(),this.overall=Lu("overall","Overall"),this.errors.clear(),this.startTime=0}complete(){this.summary.isRunning=!1,this.startTime>0&&(this.summary.duration=Date.now()-this.startTime)}addResult(e,t,n,s,i,o){this.summary.totalRequests++,i?this.summary.skipped++:s?this.summary.passed++:this.summary.failed++;let a=this.summary.passed+this.summary.failed;if(this.summary.passRate=a>0?Math.round(this.summary.passed/a*1e3)/10:0,this.startTime>0&&(this.summary.duration=Date.now()-this.startTime),i)return;this.byRequest.has(e)||this.byRequest.set(e,Lu(e,t));let c=this.byRequest.get(e);if(c.name=t,c.count++,s?c.passed++:c.failed++,c.durations.push(n),jm(c),this.overall.count++,s?this.overall.passed++:this.overall.failed++,this.overall.durations.push(n),jm(this.overall),o){let l=this.errors.get(o)||0;this.errors.set(o,l+1)}}getStatistics(){let e=[];return this.errors.forEach((t,n)=>{e.push({message:n,count:t})}),e.sort((t,n)=>n.count-t.count),{summary:{...this.summary},byRequest:new Map(this.byRequest),overall:{...this.overall},errors:e}}getSerializableStatistics(){let e=this.getStatistics();return{summary:e.summary,byRequest:Array.from(e.byRequest.values()),overall:e.overall,errors:e.errors}}};bl();var Pt=T(require("fs")),xr=T(require("path"));ln();var hc=class{constructor(e){this.collectionService=e}collectionService;suite;suiteDir;setSuite(e){this.suite={...e,nodes:Array.isArray(e.nodes)?e.nodes:[]}}setSuiteDir(e){this.suiteDir=e}getSuite(){return this.suite}loadSuiteRequest(e){if(!this.suiteDir)return;let t=xr.join(this.suiteDir,e,"request.json");if(Pt.existsSync(t))try{let n=JSON.parse(Pt.readFileSync(t,"utf-8")),s=xr.join(this.suiteDir,e,"scripts"),i=Ms(s);return i&&(n.scripts=i),n}catch(n){console.error(`[TestSuiteStore] Failed to load request from ${e}:`,n);return}}saveSuiteRequest(e,t){if(!this.suiteDir)return;let n=xr.join(this.suiteDir,e);Pt.mkdirSync(n,{recursive:!0});let s=t.scripts,i={...t};delete i.scripts;let o=xr.join(n,"request.json"),a=`${o}.tmp-${process.pid}-${Date.now()}`;if(Pt.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),Pt.renameSync(a,o),s){let c=xr.join(n,"scripts");Ds(c,{preRequest:s.preRequest||void 0,postResponse:s.postResponse||void 0})}}hasEmbeddedRequest(e){return!this.suiteDir||!e?!1:Pt.existsSync(xr.join(this.suiteDir,e,"request.json"))}resolveRequestEntry(e){let t=e.slug?this.loadSuiteRequest(e.slug):void 0,n=this.collectionService.getCollection(e.collectionId);if(t){let i,o=[],a=[],c;if(n){i=n.scripts;let l=this.findRequestInCollection(n,e.requestId);l&&(o=l.folderScriptsChain,a=l.folderAuthChain,c=l.folderPath)}return{request:t,suiteRequest:e,collectionScripts:i,collectionAuth:n?.auth,folderScriptsChain:o,folderAuthChain:a,resolvedFolderPath:c,resolvedCollectionName:n?.name}}if(!n){console.warn(`[TestSuiteStore] Collection not found: ${e.collectionId}`);return}let s=this.findRequestInCollection(n,e.requestId);if(!s){console.warn(`[TestSuiteStore] Request not found: ${e.requestId}`);return}return{request:s.request,suiteRequest:e,collectionScripts:n.scripts,collectionAuth:n.auth,folderScriptsChain:s.folderScriptsChain,folderAuthChain:s.folderAuthChain,resolvedFolderPath:s.folderPath,resolvedCollectionName:n.name}}findRequestInCollection(e,t,n=[]){let s=e.items||[];return this.searchItems(s,t,n)}searchItems(e,t,n,s=[],i=""){for(let o of e)if(o.type==="folder"){let a=o;if(!a.items)continue;let c=a.scripts?[...n,a.scripts]:n,l=a.auth?[...s,a.auth]:s,u=(a.name||"").replace(/\//g,"%2F"),d=i?`${i}/${u}`:u,p=this.searchItems(a.items||[],t,c,l,d);if(p)return p}else if(o.id===t)return{request:this.normalizeRequest(o),folderScriptsChain:n,folderAuthChain:s,folderPath:i}}normalizeRequest(e){let{type:t,...n}=e;return n}normalizeKeyValues(e){return e?Array.isArray(e)?e.map(t=>({key:t.key||"",value:t.value||"",enabled:t.enabled!==!1})):typeof e=="object"?Object.entries(e).map(([t,n])=>({key:t,value:String(n||""),enabled:!0})):[]:[]}getRequestWithContext(e,t){if(!this.suite)return;let n=this._getRequestNodes().find(s=>s.collectionId===e&&s.requestId===t);if(n)return this.resolveRequestEntry(n)}getRequestBySlug(e){if(!this.suite)return;let t=this._getRequestNodes().find(n=>n.slug===e);if(t)return this.resolveRequestEntry(t)}getAllSuiteRequests(){if(!this.suite)return[];let e=[];for(let t of this._getRequestNodes()){let n=this.resolveRequestEntry(t);n&&e.push(n)}return e}getResolvedRequests(){if(!this.suite)return[];let t=(this.suite.nodes||[]).filter(i=>i.type==="request"),n=t.map(i=>i.request?.slug||"").filter(Boolean),s=[];for(let i of t){let o=i.request;if(!o)continue;o.slug||(o.slug=at(o.name||"request",n),n.push(o.slug));let a=this.resolveRequestEntry(o);if(a){let c=this.collectionService.getCollection(o.collectionId);s.push({id:`${o.collectionId}:${o.requestId}`,collectionId:o.collectionId,requestId:o.requestId,name:a.request.name||"Unknown",method:a.request.method||"GET",url:a.request.url||"",collectionName:c?.name||"Unknown Collection",folderPath:o.folderPath||"",enabled:i.enabled!==!1,hasEmbeddedRequest:this.hasEmbeddedRequest(o.slug),slug:o.slug,description:i.name!==a.request.name?i.name:o.description||void 0})}else console.warn(`[TestSuiteStore] getResolvedRequests: could not resolve request \u2014 collectionId=${o.collectionId} requestId=${o.requestId} slug=${o.slug}`)}return s}getSelectedRequests(e){let t=[];for(let n of e){let[s,i]=n.split(":"),o=this._getRequestNodes().find(a=>a.collectionId===s&&a.requestId===i);if(o){let a=this.resolveRequestEntry(o);a&&t.push(a)}}return t}addRequest(e,t){if(this.suite){if(this.suite.nodes||(this.suite.nodes=[]),this.suiteDir&&t)if(e.slug)e.slug=this.resolveUniqueSlug(e.slug);else{let n=this._getRequestNodes().map(s=>s.slug||"").filter(Boolean);e.slug=at(e.name||t.name||"request",n)}this.suite.nodes.push({type:"request",name:e.description||e.name,request:e,enabled:e.enabled!==!1})}}resolveUniqueSlug(e){if(!this.suite)return e;let t=new Set(this._getRequestNodes().map(s=>s.slug).filter(Boolean));if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}removeRequest(e){this.suite?.nodes&&(this.suite.nodes=this.suite.nodes.filter(t=>!(t.type==="request"&&t.request?.requestId===e)))}reorderRequests(e){if(!this.suite?.nodes)return;let t=new Map;for(let i of this.suite.nodes)if(i.type==="request"&&i.request){let o=i.request;t.set(`${o.collectionId}:${o.requestId}`,i)}let n=this.suite.nodes.filter(i=>i.type!=="request"),s=[];for(let i of e){let o=t.get(i);o&&s.push(o)}this.suite.nodes=[...s,...n]}updateSuiteRequest(e,t){if(!this.suite||!this.suiteDir)return;this.saveSuiteRequest(e,t);let n=this.suite.nodes?.find(s=>s.type==="request"&&s.request?.slug===e);n?.request&&(n.request.name=t.name||n.request.name,n.request.method=t.method||n.request.method)}resyncFromCollection(e){if(!this.suite||!this.suiteDir)return;let t=this.suite.nodes?.find(o=>o.type==="request"&&o.request?.slug===e);if(!t?.request)return;let n=t.request,s=this.collectionService.getCollection(n.collectionId);if(!s)return;let i=this.findRequestInCollection(s,n.requestId);if(i)return this.saveSuiteRequest(e,i.request),t.request.name=i.request.name||n.name,t.request.method=i.request.method||n.method,i.request}_getRequestNodes(){return(this.suite?.nodes||[]).filter(e=>e.type==="request"&&e.request).map(e=>e.request)}};We();function gc(r,e={}){let n=(typeof r=="string"?JSON.parse(r):r)?.log;if(!n||!Array.isArray(n.entries))throw new Error("Invalid HAR: missing log.entries");let s=n.entries.filter(a=>a?.request),i=[];for(let a of s){let c=a.request;if(e.filterHost)try{if(new URL(c.url).hostname!==e.filterHost)continue}catch{continue}let l=a.response?.status;e.skipFailed&&typeof l=="number"&&l>=400||i.push(Hb(a))}let o=Jb(i,e.collectionName??"Imported from HAR");return{requests:i,collection:o}}function Hu(r,e={}){return gc(r,e).collection}function Hb(r){let e=r.request,t=e.method||"GET",n=e.url||"",s=zb(t,n),i=(e.headers??[]).filter(l=>typeof l.name=="string").map(l=>({key:l.name,value:String(l.value),enabled:!0})),o=(e.queryString??[]).map(l=>({key:l.name,value:String(l.value),enabled:!0})),a=(e.cookies??[]).map(l=>({key:l.name,value:String(l.value),enabled:!0})),c=Bb(e.postData,i);return{name:s,method:t,url:n,headers:i,query:o,cookies:a,body:c,responseStatus:r.response?.status,responseTimeMs:typeof r.time=="number"?r.time:void 0,responseContentType:r.response?.content?.mimeType}}function Bb(r,e){if(!r)return null;let t=typeof r.text=="string"?r.text:"",n=r.mimeType||Vb(e);if(!t&&r.params?.length){let s=r.params.map(i=>({key:i.name,value:String(i.value??""),enabled:!0}));return{type:n.includes("json")?"raw":"x-www-form-urlencoded",...n.includes("json")?{format:"json"}:{},content:s}}if(n.includes("json"))return{type:"raw",format:"json",content:t};if(n.includes("xml"))return{type:"raw",format:"xml",content:t};if(n.includes("html"))return{type:"raw",format:"html",content:t};if(n.includes("form-urlencoded")||n.includes("multipart")){let s=Ub(t);if(s.length>0)return{type:"x-www-form-urlencoded",content:s}}return{type:"raw",format:"text",content:t}}function Ub(r){try{return[...new URLSearchParams(r).entries()].map(([t,n])=>({key:t,value:n,enabled:!0}))}catch{return[]}}function Vb(r){return r.find(t=>t.key.toLowerCase()==="content-type")?.value?.split(";")[0].trim()??""}function zb(r,e){try{let t=new URL(e),n=t.pathname.split("/").filter(Boolean).pop();return n?`${r} ${decodeURIComponent(n)}`:`${r} ${t.hostname}`}catch{return`${r} ${e.slice(0,80)}`}}function Jb(r,e){let t=new Map,n=[];for(let s of r){let i="unknown-host";try{i=new URL(s.url).hostname}catch{}let o=t.get(i);o||(o={type:"folder",id:re(`har-${i}`),name:i,items:[]},t.set(i,o),n.push(o)),o.items.push(Gb(s))}return{id:re("har-collection"),name:e,items:n,source:{format:"har",filePath:""},meta:{requestCount:r.length}}}function Gb(r){let e=r.headers.map(n=>({...n}));if(r.cookies.length>0){let n=e.find(s=>s.key.toLowerCase()==="cookie");if(n){let s=r.cookies.map(i=>`${i.key}=${i.value}`).join("; ");n.value=n.value?`${n.value}; ${s}`:s}else e.push({key:"Cookie",value:r.cookies.map(s=>`${s.key}=${s.value}`).join("; "),enabled:!0})}return{type:"request",id:re(`har-${r.method}-${r.url}`),name:r.name,method:r.method,url:r.url,headers:e,query:r.query.map(n=>({...n})),body:r.body??void 0,responseSchema:r.responseStatus?{responses:{[String(r.responseStatus)]:{description:`Observed response (${r.responseTimeMs??"unknown"} ms)`,contentType:r.responseContentType}}}:void 0}}Kc();yo();ho();dl();pl();gl();hl();fl();ml();yl();Ls();to();We();Iu();0&&(module.exports={AnthropicProvider,ApiArchitectService,ApiDiscoveryService,AwsSecretResolver,AzureKeyVaultResolver,BODY_FILE_MAP,CACHE_BUSTING_TOOLS,COLLECTION_INPUT_SCHEMA,CONFIG_FILES,CollectionLoader,CollectionLoaderFactory,CollectionRequestExecutor,CollectionService,ConfigService,CookieJar,CookieService,CookieUtils,DEFAULT_CONFIG,DEFAULT_REQUEST_SETTINGS,DataFileParser,DopplerResolver,EnvironmentConfigService,EnvironmentResolver,ExampleGenerator,ExpressComponentAnalyzer,ExpressDiscoveryProvider,FOLDER_INPUT_SCHEMA,FastApiDiscoveryProvider,FastifyComponentAnalyzer,FastifyDiscoveryProvider,FetchHttpClient,FolderCollectionLoader,FolderCollectionStore,ForgeContainer,ForgeEnv,FrameworkDetector,GENERIC_TOOL_NAMES,GcpSecretResolver,GraphQLSchemaService,HTTP_METHOD_MAP,HTTP_METHOD_REVERSE,HashiCorpVaultResolver,HistoryAnalyzer,HtmlReportGenerator,HttpForgeParser,HttpRequestService,InMemoryCookieJar,InterceptorChain,JUnitReportGenerator,JsonCollectionLoader,LambdaComponentAnalyzer,LambdaDiscoveryProvider,MCP_PROMPTS,METADATA_FILES,McpRunStore,ModuleLoader,NestDiscoveryProvider,NodeFileSystem,NodeHttpClient,OAuth2TokenManager,OnePasswordResolver,OpenAiProvider,OpenApiExporter,OpenApiImporter,ParserRegistry,PersistentCookieJar,REQUEST_INPUT_SCHEMA,ROOT_DIRECTORIES,RefResolver,RequestExecutor,RequestHistoryService,RequestHistoryStore,RequestPreparer,RequestPreprocessor,RequestScriptSession,ResultStorageService,SCHEMA_FILES,SCRIPTS_DIR,SCRIPT_FILES,SUITE_INPUT_SCHEMA,SchemaInferenceService,SchemaInferrer,ScriptAnalyzer,ScriptExecutor,SecretResolverRegistry,ServiceContainer,ServiceIdentifiers,SpringDiscoveryProvider,StatisticsService,TestSuiteService,TestSuiteStore,UrlBuilder,VariableInterpolator,VariableResolver,analyzeComponentChainMetadata,analyzeHandlerMetadata,applyEnvSuggestionsToItems,applyExtractionPlan,applyFilterChain,applyMcpBodyTruncation,applyRegenerated,assembleBusinessContext,buildArchitectPrompt,buildCollectionBusinessContext,buildCollectionToolDescription,buildCollectionToolName,buildExtractionPlan,buildFolderToolDescription,buildFolderToolName,buildGenericTools,buildMcpToolList,buildPromptResult,buildRequestBusinessContext,buildRequestToolDescription,buildRequestToolName,buildResultFileName,buildRunResultsContext,buildSuiteToolDescription,buildSuiteToolName,cleanupOldBodyFiles,clearRegisteredKnowledgeSources,collectSourceFiles,collectionKnowledgeSource,collectionToEndpoints,combineConfidence,computeProjectFreshness,concatenateScripts,countRequests,createDefaultKnowledgeSources,createEnvAiProvider,createExpectChain,createMcpRuntime,createModuleLoader,createMomentShim,createNodeContainer,createResponseObject,createTestFunction,decodeCursor,decodeFolderPath,dedupeDiscoveredApiParameters,deleteItemFromTree,deserializeTypedRecord,deserializeTypedValue,detectEnvSuggestions,detectIndexDrift,detectProjectDrift,diffLines,discoverWorkflows,dispatchGenericTool,encodeCursor,encodeFolderName,enhanceCollection,enumerateFolders,evaluateExpression,exportCollectionToRestClient,extractJsonFromLlm,extractPathParameters,findItemById,flattenRequests,formatConsoleOutput,gatherWorkspaceKnowledge,generateFlowFromEndpoints,generateId,generateReleaseNotes,generateSlug,generateSuiteFromEndpoints,getCompletions,getRegisteredKnowledgeSources,getServiceContainer,harToCollection,hasChanged,isExpression,isSystemEnvironmentFile,loadEnvironmentsFromFolder,loadHybridSeedEndpoints,normalizeFolderInput,normalizeHeaders,parseCurlCommand,parseFilterChain,parseHar,parseMcpToolName,parsePostmanEnvironment,parseQueryContext,prepareBodyForSave,proposeSuiteUpdates,readBodyFromDir,readSchemaFile,readScriptsFromDir,redactFullResponse,redactFullResultDetails,redactHeaders,redactHistoryEntry,registerCoreServices,registerKnowledgeSource,renderArchitectDocs,renderReleaseNotesMarkdown,requestKnowledgeSource,resolveCollectionRef,resolveFolderRef,resolveFolderToken,resolveProjectName,resolveRegenerated,resolveRequestRef,resolveResultGrouping,resolveToken,reviewSuiteRun,runCollection,runFolder,runRequest,runResultsKnowledgeSource,runSuite,scanCollectionForEnvVarsWithAi,searchForItemPath,searchForItemPathById,serializeTypedValue,sortItemsByOrder,suiteIdFromName,threeWayDiff,toReviewRequestResults,validateDesignedSpec,withAiRetry,workspaceKnowledgeSource,writeEnvFile,writeFolderItems,writeSchemaFiles,writeScriptFile,writeScriptsToDir});