@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.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Pa=Object.defineProperty;var gm=Object.getOwnPropertyDescriptor;var ym=Object.getOwnPropertyNames;var vm=Object.prototype.hasOwnProperty;var
|
|
1
|
+
var Pa=Object.defineProperty;var gm=Object.getOwnPropertyDescriptor;var ym=Object.getOwnPropertyNames;var vm=Object.prototype.hasOwnProperty;var le=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var E=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Tt=(r,e)=>{for(var t in e)Pa(r,t,{get:e[t],enumerable:!0})},bm=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ym(e))!vm.call(r,s)&&s!==t&&Pa(r,s,{get:()=>e[s],enumerable:!(n=gm(e,s))||n.enumerable});return r};var Yn=r=>bm(Pa({},"__esModule",{value:!0}),r);function ve(r){return r.replace(/[^a-zA-Z0-9-_]/g,"_").replace(/\s+/g,"-").toLowerCase().substring(0,100)}function se(r){let e=Date.now().toString(36)+(Sm++).toString(36)+Math.random().toString(36).slice(2,7);return r?`${ve(r)}_${e}`:e}function wu(){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)})}function hi(r,e){let t={},n={};for(let[s,i]of Object.entries(r)){let o=s.toLowerCase();n[o]=s,t[s]=i}for(let[s,i]of Object.entries(e)){let o=s.toLowerCase(),a=n[o];a&&delete t[a],n[o]=s,t[s]=i}return t}var Sm,Ge=E(()=>{"use strict";Sm=0});import*as te from"fs";import*as We from"path";function yi(r){if(!te.existsSync(r))return;let e={},t=We.join(r,gi.preRequest);te.existsSync(t)&&(e.preRequest=te.readFileSync(t,"utf-8"));let n=We.join(r,gi.postResponse);return te.existsSync(n)&&(e.postResponse=te.readFileSync(n,"utf-8")),Object.keys(e).length>0?e:void 0}async function vi(r,e){await te.promises.mkdir(r,{recursive:!0});let t=We.join(r,gi.preRequest);e.preRequest?await te.promises.writeFile(t,e.preRequest,"utf-8"):te.existsSync(t)&&await te.promises.unlink(t);let n=We.join(r,gi.postResponse);e.postResponse?await te.promises.writeFile(n,e.postResponse,"utf-8"):te.existsSync(n)&&await te.promises.unlink(n)}function Cu(r){for(let[e,t]of Object.entries(Ru)){let n=We.join(r,e);if(te.existsSync(n))try{let s=te.readFileSync(n,"utf-8"),i;if(t.type==="graphql")try{i=JSON.parse(s)}catch{i=s}else i=s;return{type:t.type,format:t.format,content:i}}catch(s){console.error(`[FolderIO] Failed to load body from ${n}:`,s)}}}function Eu(r){if(!r||r.type==="none")return{bodyForMetadata:r};if(r.type==="raw"){let e=r.format||"json",n={json:"body.json",xml:"body.xml",text:"body.txt",html:"body.html",javascript:"body.js"}[e];if(n){let s=e==="json"?typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2):String(r.content||"");return{bodyForMetadata:{type:r.type,format:r.format},externalBodyFile:{filename:n,content:s}}}}if(r.type==="graphql"){let e=typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2);return{bodyForMetadata:{type:r.type},externalBodyFile:{filename:"body.graphql",content:e}}}return{bodyForMetadata:r}}async function qu(r,e){for(let t of Object.keys(Ru))if(t!==e){let n=We.join(r,t);if(te.existsSync(n))try{await te.promises.unlink(n)}catch{}}}function Au(r){if(te.existsSync(r))try{let e=te.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){console.error(`[FolderIO] Failed to load schema file ${r}:`,e);return}}async function Pu(r,e,t){let n=We.join(r,Kr.responseSchema),s=We.join(r,Kr.bodySchema);e?await te.promises.writeFile(n,JSON.stringify(e,null,2),"utf-8"):te.existsSync(n)&&await te.promises.unlink(n),t?await te.promises.writeFile(s,JSON.stringify(t,null,2),"utf-8"):te.existsSync(s)&&await te.promises.unlink(s)}function we(r,e){for(let t of r){if(t.id===e)return t;if(t.type==="folder"&&t.items){let n=we(t.items,e);if(n)return n}}}function Zt(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(n.id===e)return r.splice(t,1),!0;if(n.type==="folder"&&n.items&&Zt(n.items,e))return!0}return!1}function ku(r,e){let t=new Map(r.map(s=>[s.id,s])),n=[];for(let s of e){let i=t.get(s);i&&(n.push(i),t.delete(s))}for(let s of t.values())n.push(s);return n}function ka(r,e){let t;try{t=te.readdirSync(r,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory()||n.name===Ke)continue;if(n.name===e)return We.join(r,n.name);let s=ka(We.join(r,n.name),e);if(s)return s}}function xm(r){for(let e of[Me.request,Me.folder]){let t=We.join(r,e);if(te.existsSync(t))try{let n=te.readFileSync(t,"utf-8");return JSON.parse(n).id}catch{return}}}function Ia(r,e){let t;try{t=te.readdirSync(r,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory()||n.name===Ke)continue;let s=We.join(r,n.name);if(xm(s)===e)return s;let i=Ia(s,e);if(i)return i}}function ft(r,e=[]){let t=r.toLowerCase().trim(),n=t.match(/^(get|post|put|patch|delete|head|options)[_\s-]/i),s=n?n[1]:"",i=t.match(/t(\d+)/gi)||[],o=0;for(let p of i){let m=parseInt(p.substring(1));m>o&&(o=m)}let a="";if(o>0)a=`t${o}`;else{let p=t.match(/[_\s-](\d+\.\d+)[_\s-]/);p&&(a=`v${p[1].replace(".","_")}`)}let c=t;n&&(c=c.substring(n[0].length)),c=c.replace(/[_\s-]?t\d+(?:\.\d+)?[_\s-]?/gi,"-"),c=c.replace(/[_\s-]?\d+\.\d+[_\s-]?/g,"-"),c=c.replace(/\([^)]+\)/g,""),c=c.replace(/:[a-z_][a-z0-9_]*/gi,""),c=c.replace(/\{[^}]+\}/g,""),c=c.replace(/\?$/g,"").replace(/[_/\\ ]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");let l=c.split("-").filter(p=>p.length>0),u=[];s&&u.push(s),u.push(...l),a&&u.push(a);let d=u.join("-");if(d||(d="item"),e.includes(d)){let p=2;for(;e.includes(`${d}-${p}`);)p++;d=`${d}-${p}`}return d}var gi,Me,Ru,Kr,Ke,Yt=E(()=>{"use strict";gi={preRequest:"pre-request.js",postResponse:"post-response.js"},Me={collection:"collection.json",folder:"folder.json",request:"request.json"},Ru={"body.json":{type:"raw",format:"json"},"body.xml":{type:"raw",format:"xml"},"body.txt":{type:"raw",format:"text"},"body.html":{type:"raw",format:"html"},"body.js":{type:"raw",format:"javascript"},"body.graphql":{type:"graphql"}},Kr={responseSchema:"response.schema.json",bodySchema:"body.schema.json"},Ke="scripts"});import*as U from"fs";import*as J from"path";var Ta,Xt,bi=E(()=>{"use strict";Ge();Yt();Ta={collection:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/collection.schema.json",folder:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/folder.schema.json",request:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/request.schema.json"},Xt=class{collectionsDir;cache=new Map;slugToIdMap=new Map;idToSlugMap=new Map;constructor(e){this.collectionsDir=e,this.ensureDirectory()}getSlugById(e){return this.idToSlugMap.get(e)}getIdBySlug(e){return this.slugToIdMap.get(e)}ensureDirectory(){U.existsSync(this.collectionsDir)||U.mkdirSync(this.collectionsDir,{recursive:!0}),this.ensureAgentsMd()}ensureAgentsMd(){let e=J.resolve(this.collectionsDir,"..",".."),t=J.join(e,"AGENTS.md");if(U.existsSync(t))return;let n="https://raw.githubusercontent.com/hsl1230/http-forge/main/resources",s=`# HTTP Forge \u2014 AI Agent Guide
|
|
2
2
|
|
|
3
3
|
This folder is an **HTTP Forge workspace** (\`.http-forge/\`).
|
|
4
4
|
|
|
@@ -211,7 +211,7 @@ suggest_assertions \u2192 generate pm.test() assertions for a request
|
|
|
211
211
|
> For collection / suite / folder runs, pass \`include: ["report"]\` to generate an HTML report
|
|
212
212
|
> (\`report.uri\`) \u2014 open it in a browser to inspect full response details without consuming tokens.
|
|
213
213
|
> Single \`run_request\` calls do not generate a report unless \`include: ["report"]\` is also passed.
|
|
214
|
-
`;try{U.writeFileSync(t,s,"utf-8")}catch{}}readJsonFileSafe(e,t){let n;try{n=U.readFileSync(e,"utf-8")}catch(s){console.error(`[FolderCollectionStore] Failed to read ${t} ${e}:`,s);return}if(n.trim().length!==0)try{return JSON.parse(n)}catch(s){if(s instanceof SyntaxError&&/Unexpected end of JSON input/.test(s.message))return;console.error(`[FolderCollectionStore] Failed to parse ${t} ${e}:`,s);return}}loadAll(){if(this.cache.clear(),this.slugToIdMap.clear(),this.idToSlugMap.clear(),!U.existsSync(this.collectionsDir))return[];let e=U.readdirSync(this.collectionsDir,{withFileTypes:!0}),t=[];for(let n of e)if(n.isDirectory())try{let s=this.loadCollectionFromFolder(n.name);s&&(this.cache.set(s.id,s),this.slugToIdMap.set(n.name,s.id),this.idToSlugMap.set(s.id,n.name),t.push(s))}catch(s){console.error(`[FolderCollectionStore] Failed to load ${n.name}:`,s)}return t}loadCollectionFromFolder(e){let t=J.join(this.collectionsDir,e),n=J.join(t,Me.collection);if(!U.existsSync(n))return;let s=this.readJsonFileSafe(n,"collection");if(s)try{let i=this.loadScriptsFromDir(J.join(t,Ke)),o=this.loadItemsFromDir(t,s.id,s.order);return{id:s.id,name:s.name,description:s.description,version:s.version,variables:s.variables,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to parse ${n}:`,i);return}}loadItemsFromDir(e,t,n){let s=[],i=new Map,o=U.readdirSync(e,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||a.name===Ke)continue;let c=J.join(e,a.name);if(U.existsSync(J.join(c,Me.folder))){let l=this.loadFolderFromDir(c,a.name);l&&i.set(a.name,l)}else if(U.existsSync(J.join(c,Me.request))){let l=this.loadRequestFromDir(c,a.name);l&&i.set(a.name,l)}}if(n&&n.length>0){for(let a of n){let c=i.get(a);c&&(s.push(c),i.delete(a))}for(let a of i.values())s.push(a)}else for(let a of i.values())s.push(a);return s}loadFolderFromDir(e,t){let n=J.join(e,Me.folder),s=this.readJsonFileSafe(n,"folder");if(s)try{let i=this.loadScriptsFromDir(J.join(e,Ke)),o=this.loadItemsFromDir(e,s.id,s.order);return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"folder",name:s.name,description:s.description,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to load folder ${e}:`,i);return}}loadRequestFromDir(e,t){let n=J.join(e,Me.request),s=this.readJsonFileSafe(n,"request");if(s)try{let i=this.loadScriptsFromDir(J.join(e,Ke)),o=s.body,a=this.loadBodyFromDir(e);a&&(o=a);let c=this.loadSchemaFile(J.join(e,Kr.responseSchema)),l=this.loadSchemaFile(J.join(e,Kr.bodySchema)),u=J.join(e,"doc.md"),d=U.existsSync(u)?U.readFileSync(u,"utf-8"):void 0;return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"request",name:s.name,description:s.description,method:s.method,url:s.url,params:s.params,query:s.query,headers:s.headers,body:o,bodyContentType:s.bodyContentType,auth:s.auth,settings:s.settings,scripts:i,disabled:s.disabled,deprecated:s.deprecated,operationId:s.operationId,summary:s.summary,tags:s.tags,examples:s.examples,responses:s.responses,security:s.security,...d&&{doc:d},...c&&{responseSchema:c},...l&&{bodySchema:l}}}catch(i){console.error(`[FolderCollectionStore] Failed to load request ${e}:`,i);return}}loadScriptsFromDir(e){return yi(e)}loadBodyFromDir(e){return Cu(e)}loadSchemaFile(e){return Au(e)}async saveSchemaFiles(e,t){return Pu(e,t.responseSchema,t.bodySchema)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.idToSlugMap.get(e);if(t){let n=this.loadCollectionFromFolder(t);return n&&this.cache.set(e,n),n}return this.loadAll(),this.cache.get(e)}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");e.id||(e.id=se(e.name));let t=this.idToSlugMap.get(e.id);if(!t){let c=U.readdirSync(this.collectionsDir);t=ft(e.name,c),this.idToSlugMap.set(e.id,t),this.slugToIdMap.set(t,e.id)}let n=J.join(this.collectionsDir,t),s=!U.existsSync(n);await U.promises.mkdir(n,{recursive:!0});let i={id:e.id,name:e.name,description:e.description,version:e.version,variables:e.variables,auth:e.auth},[o]=await Promise.all([this.saveItemsToDir(n,e.items,s),e.scripts?this.saveScriptsToDir(J.join(n,Ke),e.scripts):Promise.resolve()]);o.length>0&&(i.order=o);let a={$schema:Ta.collection,...i};await U.promises.writeFile(J.join(n,Me.collection),JSON.stringify(a,null,2),"utf-8"),this.cache.set(e.id,e)}async saveItemsToDir(e,t,n=!1){let s=[],i=[];for(let o of t){let a=this.idToSlugMap.get(o.id);a||(a=ft(o.name,s),this.idToSlugMap.set(o.id,a),this.slugToIdMap.set(a,o.id)),s.push(a),i.push({item:o,slug:a})}return await Promise.all(i.map(async({item:o,slug:a})=>{let c=J.join(e,a);await U.promises.mkdir(c,{recursive:!0}),o.type==="folder"?await this.saveFolderToDir(c,o,n):await this.saveRequestToDir(c,o,n)})),s}async saveFolderToDir(e,t,n=!1){let s={id:t.id,name:t.name,description:t.description,auth:t.auth},[i]=await Promise.all([t.items?this.saveItemsToDir(e,t.items,n):Promise.resolve([]),t.scripts?this.saveScriptsToDir(J.join(e,Ke),t.scripts):Promise.resolve()]);i.length>0&&(s.order=i);let o={$schema:Ta.folder,...s};await U.promises.writeFile(J.join(e,Me.folder),JSON.stringify(o,null,2),"utf-8")}async saveRequestToDir(e,t,n=!1){let{bodyForMetadata:s,externalBodyFile:i}=this.prepareBodyForSave(t.body),o={id:t.id,name:t.name,method:t.method||"GET",url:t.url||"",description:t.description,params:t.params,query:t.query,headers:t.headers,body:s,bodyContentType:t.bodyContentType,auth:t.auth,settings:t.settings,...t.disabled!==void 0&&{disabled:t.disabled},...t.deprecated&&{deprecated:t.deprecated},...t.operationId&&{operationId:t.operationId},...t.summary&&{summary:t.summary},...t.tags&&t.tags.length>0&&{tags:t.tags},...t.examples&&t.examples.length>0&&{examples:t.examples},...t.responses&&Object.keys(t.responses).length>0&&{responses:t.responses},...t.security&&t.security.length>0&&{security:t.security}},a=[U.promises.writeFile(J.join(e,Me.request),JSON.stringify({$schema:Ta.request,...o},null,2),"utf-8")];i&&a.push(U.promises.writeFile(J.join(e,i.filename),i.content,"utf-8")),n||a.push(this.cleanupOldBodyFiles(e,i?.filename)),(!n||t.responseSchema||t.bodySchema)&&a.push(this.saveSchemaFiles(e,t)),t.doc&&a.push(U.promises.writeFile(J.join(e,"doc.md"),t.doc,"utf-8")),t.scripts&&a.push(this.saveScriptsToDir(J.join(e,Ke),t.scripts)),await Promise.all(a)}prepareBodyForSave(e){return Eu(e)}async cleanupOldBodyFiles(e,t){return qu(e,t)}async saveScriptsToDir(e,t){return vi(e,t)}async delete(e){let t=this.idToSlugMap.get(e);if(!t&&(this.loadAll(),t=this.idToSlugMap.get(e),!t))return!1;let n=J.join(this.collectionsDir,t);if(!U.existsSync(n))return!1;try{return await U.promises.rm(n,{recursive:!0,force:!0}),this.cache.delete(e),this.idToSlugMap.delete(e),this.slugToIdMap.delete(t),!0}catch(s){return console.error(`[FolderCollectionStore] Failed to delete collection ${e}:`,s),!1}}exists(e){let t=this.idToSlugMap.get(e);return t?U.existsSync(J.join(this.collectionsDir,t,Me.collection)):!1}getCollectionPath(e){let t=this.idToSlugMap.get(e)||e;return J.join(this.collectionsDir,t)}getItemPath(e,t){return this.findItemPath(e,t)}async create(e,t){let n={id:t||se(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=this.findItemPath(e,t);if(!i)throw new Error(`Item ${t} not found in collection ${e}`);await this.saveScriptsToDir(J.join(i,Ke),n);let o=this.findItemById(s.items,t);o&&(o.scripts=n)}loadScripts(e,t){let n=this.findItemPath(e,t);if(n)return this.loadScriptsFromDir(J.join(n,Ke))}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);let s=this.idToSlugMap.get(e);if(!s)throw new Error(`Collection slug not found for ${e}`);let i=J.join(this.collectionsDir,s),o=J.join(i,Me.collection),a=U.readFileSync(o,"utf-8"),l={...JSON.parse(a),...t,id:e};await U.promises.writeFile(o,JSON.stringify(l,null,2),"utf-8"),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)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=this.idToSlugMap.get(e);if(!i)throw new Error(`Collection slug not found for ${e}`);let o;if(n){let u=this.findItemPath(e,n);if(!u)throw new Error(`Parent folder ${n} not found`);o=u}else o=J.join(this.collectionsDir,i);let a=this.idToSlugMap.get(t.id);if(!a){let u=U.readdirSync(o).filter(d=>U.statSync(J.join(o,d)).isDirectory()&&d!==Ke);a=ft(t.name,u),this.idToSlugMap.set(t.id,a),this.slugToIdMap.set(a,t.id)}let c=J.join(o,a);await U.promises.mkdir(c,{recursive:!0}),t.type==="folder"?await this.saveFolderToDir(c,t):await this.saveRequestToDir(c,t);let l=this.findItemById(s.items,t.id);if(l)Object.assign(l,t);else if(n){let u=this.findItemById(s.items,n);u&&u.type==="folder"&&(u.items=u.items||[],u.items.push(t))}else s.items.push(t)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=this.findItemPath(e,t);if(!s||!U.existsSync(s))return!1;try{await U.promises.rm(s,{recursive:!0,force:!0}),this.deleteItemFromTree(n.items,t);let i=this.idToSlugMap.get(t);return i&&(this.slugToIdMap.delete(i),this.idToSlugMap.delete(t)),!0}catch(i){return console.error(`[FolderCollectionStore] Failed to delete item ${t}:`,i),!1}}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.findItemPath(e,t);if(!i)return!1;let o=this.findItemById(s.items,t);if(!o)return!1;let{id:a,type:c,items:l,...u}=n;return Object.assign(o,u),o.type==="folder"?await this.saveFolderToDir(i,o):await this.saveRequestToDir(i,o),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=this.findItemPath(e,t);if(!o||!U.existsSync(o))return!1;let a;if(n){let u=this.findItemPath(e,n);if(!u)return!1;a=u}else a=J.join(this.collectionsDir,i);let c=this.idToSlugMap.get(t);if(!c)return!1;let l=J.join(a,c);if(U.existsSync(l))return!1;try{await U.promises.rename(o,l);let u=this.findItemById(s.items,t);if(u){let d=u.type==="folder"?{...u,items:u.items?[...u.items]:[]}:{...u};if(this.deleteItemFromTree(s.items,t),n){let p=this.findItemById(s.items,n);p&&p.type==="folder"&&(p.items=p.items||[],p.items.push(d))}else s.items.push(d)}return!0}catch(u){return console.error(`[FolderCollectionStore] Failed to move item ${t}:`,u),!1}}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=[];for(let a of n){let c=this.idToSlugMap.get(a);c&&o.push(c)}try{if(t){let a=this.findItemPath(e,t);if(!a)return!1;let c=J.join(a,Me.folder),l=U.readFileSync(c,"utf-8"),u=JSON.parse(l);u.order=o,await U.promises.writeFile(c,JSON.stringify(u,null,2),"utf-8");let d=this.findItemById(s.items,t);d&&d.type==="folder"&&d.items&&(d.items=this.sortItemsByOrder(d.items,n))}else{let a=J.join(this.collectionsDir,i,Me.collection),c=U.readFileSync(a,"utf-8"),l=JSON.parse(c);l.order=o,await U.promises.writeFile(a,JSON.stringify(l,null,2),"utf-8"),s.items=this.sortItemsByOrder(s.items,n)}return!0}catch(a){return console.error("[FolderCollectionStore] Failed to reorder items:",a),!1}}sortItemsByOrder(e,t){return ku(e,t)}findItemPath(e,t){let n=this.idToSlugMap.get(e);if(!n)return;let s=J.join(this.collectionsDir,n),i=Ia(s,t);if(i)return i;let o=this.load(e);if(o){let c=this.buildSlugPath(o.items,t);if(c)return J.join(s,...c)}let a=this.idToSlugMap.get(t);if(a)return ka(s,a)}buildSlugPath(e,t){for(let n of e){let s=this.idToSlugMap.get(n.id);if(s){if(n.id===t)return[s];if(n.type==="folder"&&n.items){let i=this.buildSlugPath(n.items,t);if(i)return[s,...i]}}}}findItemById(e,t){return we(e,t)}deleteItemFromTree(e,t){return Zt(e,t)}}});var ne,bn=E(()=>{"use strict";ne=class{static parseSetCookie(e,t){let n=e.split(";").map(u=>u.trim());if(n.length===0)return null;let[s,...i]=n,o=s.indexOf("=");if(o===-1)return null;let a=s.substring(0,o).trim(),c=s.substring(o+1).trim(),l={name:a,value:c,domain:t};for(let u of i){let d=u.indexOf("="),p=(d===-1?u:u.substring(0,d)).toLowerCase(),m=d===-1?"":u.substring(d+1);switch(p){case"domain":l.domain=m.startsWith(".")?m.substring(1):m;break;case"path":l.path=m;break;case"expires":l.expires=m;break;case"max-age":l.maxAge=parseInt(m,10);break;case"httponly":l.httpOnly=!0;break;case"secure":l.secure=!0;break;case"samesite":l.sameSite=m;break}}return l}static parseCookieHeaders(e,t){let n=[],s=e["set-cookie"]||e["Set-Cookie"];if(!s)return n;let i=Array.isArray(s)?s:[s];for(let o of i){let a=this.parseSetCookie(o,t);a&&n.push(a)}return n}static formatCookieHeader(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}static cookieKey(e,t,n){return`${t||"*"}|${n||"/"}|${e}`}static isExpired(e){return!!(e.expires&&new Date(e.expires).getTime()<Date.now()||e.maxAge!==void 0&&e.maxAge<=0)}static domainMatches(e,t){if(t==="*")return!0;let n=e.toLowerCase().split(".").reverse(),s=t.toLowerCase().split(".").reverse();if(s.length>n.length)return!1;for(let i=0;i<s.length;i++)if(s[i]!==n[i])return!1;return!0}static extractDomain(e){try{return new URL(e).hostname}catch{return""}}static extractPath(e){try{return new URL(e).pathname}catch{return"/"}}}});import*as en from"fs";import*as Sn from"path";function xi(r){let e=r.toLowerCase();return e==="_global.json"||e==="_global.local.json"||e.endsWith(".local.json")}function Xr(r){if(!en.existsSync(r))return Rm();let e=Si(Sn.join(r,"_global.json"))||{},t=e.variables||{},n=e.defaultHeaders||{},s=en.readdirSync(r).filter(l=>l.endsWith(".json")).filter(l=>!l.endsWith(".local.json")).filter(l=>!xi(l)),i={};for(let l of s){let u=Si(Sn.join(r,l))||{},d=Sn.basename(l,".json");i[d]={description:u.description,requiresConfirmation:u.requiresConfirmation,variables:u.variables||{},secretVariables:u.secretVariables}}let a=(Si(Sn.join(r,"_global.local.json"))||{}).variables||{},c={};for(let l of Object.keys(i)){let u=Sn.join(r,`${l}.local.json`);if(en.existsSync(u)){let d=Si(u)||{};c[l]={variables:d.variables||{}}}}return{globalVariables:t,defaultHeaders:n,environments:i,localVariables:a,localCredentials:c}}function Rm(){return{globalVariables:{},defaultHeaders:{},environments:{},localVariables:{},localCredentials:{}}}function Si(r){try{if(!en.existsSync(r))return null;let e=en.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){return console.error(`[environment-file-loader] Failed to load JSON from ${r}:`,e),null}}var wi=E(()=>{"use strict"});var mt,er=E(()=>{"use strict";mt=class{buildUrl(e,t={},n={}){let s=e;return s=this.replacePathParams(s,t),s=this.appendQueryParams(s,n),s}replacePathParams(e,t){let n="",s="",i=e,o="",a=e.indexOf("?");a!==-1&&(o=e.substring(a),i=e.substring(0,a));let c=i.match(/^(https?:\/\/)([^\/]*)(\/.*)?$/);c&&(n=c[1],s=c[2],i=c[3]||"/");let l=/:(\w+)(?:\([^)]*\))?(\?)?/g,u=i.replace(l,(d,p,m)=>{let f=t[p];return f!==void 0&&f!==""?encodeURIComponent(f):m?"":(console.warn(`[UrlBuilder] Missing required path parameter: ${p}`),d)});return u=u.replace(/([^:])\/+/g,"$1/"),`${n}${s}${u}${o}`}extractPathParams(e){let t=/:(\w+)(?:\([^)]*\))?(\?)?/g,n=[],s;for(;(s=t.exec(e))!==null;)n.push(s[1]);return[...new Set(n)]}appendQueryParams(e,t){let n=e,s={};if(e.includes("?")){let[c,l]=e.split("?");n=c,l&&new URLSearchParams(l).forEach((d,p)=>{s[p]=d})}let i={...s,...t},o=new URLSearchParams;for(let[c,l]of Object.entries(i))l!=null&&o.append(c,l);let a=o.toString();return a?`${n}?${a}`:n}}});import{v4 as Ou}from"uuid";function Cm(r=0,e=999){return Math.floor(Math.random()*(e-r+1))+r}function Em(){return Date.now()}function Tu(){return Ou()}function qm(){return Ou()}function $u(r=10){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function Am(){let r=$u(8).toLowerCase(),e=["example.com","test.org","mail.dev","sample.net"];return`${r}@${e[Math.floor(Math.random()*e.length)]}`}function Pm(){return Math.random()<.5}function km(r=10){let e="0123456789abcdef",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function Im(){return Math.floor(Date.now()/1e3)}function Tm(){return new Date().toISOString()}function Om(){return new Date().toISOString().split("T")[0]}function $m(){return new Date().toISOString().split("T")[1].split(".")[0]}function Fm(){return new Date().toISOString()}function Nm(r=""){return Buffer.from(String(r)).toString("base64")}function _m(r=""){return Buffer.from(String(r),"base64").toString("utf-8")}function Mm(r=""){return encodeURIComponent(String(r))}function Dm(r=""){return decodeURIComponent(String(r))}function xn(r,e){let t=jm[r];return t?e&&e.length>0?t(...e):t():null}function tr(r,e){let t=/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,n=null,s;for(;(s=t.exec(r))!==null;){let i=s[0],o=s[1];if(!(i in e)){let a=xn(o);a!==null&&(n||(n={...e}),n[i]=a)}}return n??e}var jm,Fa=E(()=>{"use strict";jm={randomInt:Cm,timestamp:Em,guid:qm,uuid:Tu,randomUUID:Tu,randomString:$u,randomHexadecimal:km,randomEmail:Am,randomBoolean:Pm,isoTimestamp:Fm,timestamp_s:Im,datetime:Tm,date:Om,time:$m,base64Encode:Nm,base64Decode:_m,urlEncode:Mm,urlDecode:Dm}});import*as Ri from"vm";function wn(r){let e=r.trim();return!e||/^(\$?)[a-zA-Z_][a-zA-Z0-9_]*(\([^)]*\))?$/.test(e)||/(?<!\|)\|(?!\|)/.test(e)?!1:/[+\-*/%<>=!&|?:~^()[\]{}.,`]/.test(e)}function Pt(r,e={}){try{let t={...e,Math,Date,JSON,Number,String,Boolean,Array,Object,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,undefined:void 0,null:null,true:!0,false:!1,NaN:NaN,Infinity:1/0},n=Ri.createContext(t);return Ri.runInContext(r,n,{timeout:Lm,displayErrors:!1})}catch{return}}var Lm,es=E(()=>{"use strict";Lm=100});import*as Ci from"crypto";function Hm(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function ns(r){if(!r||!r.includes("|"))return null;let e=Bm(r);if(e.length<2)return null;let t=e[0].trim(),n=[];for(let s=1;s<e.length;s++){let i=e[s].trim();if(!i)continue;let o=Um(i);o&&n.push(o)}return n.length===0?null:{input:t,filters:n}}function Bm(r){let e=[],t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o],c=o>0?r[o-1]:"",l=o<r.length-1?r[o+1]:"";if(c==="\\"){t+=a;continue}if(a==="'"&&!i)s=!s;else if(a==='"'&&!s)i=!i;else if(a==="("&&!s&&!i)n++;else if(a===")"&&!s&&!i)n--;else if(a==="|"&&n===0&&!s&&!i){if(l==="|"){t+="||",o++;continue}e.push(t),t="";continue}t+=a}return t&&e.push(t),e}function Um(r){let e=r.indexOf("(");if(e===-1)return{name:r.trim(),args:[]};let t=r.substring(0,e).trim(),n=r.substring(e+1,r.lastIndexOf(")"));return{name:t,args:Vm(n)}}function Vm(r){if(!r||!r.trim())return[];let e=[],t="",n=!1,s=!1;for(let i=0;i<r.length;i++){let o=r[i];if((i>0?r[i-1]:"")==="\\"){t+=o;continue}if(o==="'"&&!s){n=!n,t+=o;continue}else if(o==='"'&&!n){s=!s,t+=o;continue}else if(o===","&&!n&&!s){e.push(t.trim()),t="";continue}t+=o}return t.trim()&&e.push(t.trim()),e}function he(r,e){if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=Number(r);if(!isNaN(t)&&r!=="")return t;if(r==="true")return!0;if(r==="false")return!1;if(e&&r in e){let n=Hm(e[r]),s=Number(n);return!isNaN(s)&&n!==""?s:n}return r}function rs(r,e,t={}){let n=r;for(let s of e)n=zm(n,s.name,s.args,t);return n}function zm(r,e,t,n){switch(e){case"upper":return String(r).toUpperCase();case"lower":return String(r).toLowerCase();case"trim":return String(r).trim();case"length":return Array.isArray(r)?r.length:String(r).length;case"substring":{let s=he(t[0],n),i=t[1]!==void 0?he(t[1],n):void 0;return String(r).substring(s<0?String(r).length+s:s,i!==void 0?i<0?String(r).length+i:i:void 0)}case"replace":{let s=t[0]!==void 0?String(he(t[0],n)):"",i=t[1]!==void 0?String(he(t[1],n)):"";return String(r).replace(new RegExp(Gm(s),"g"),i)}case"split":{let s=t[0]!==void 0?String(he(t[0],n)):",";return String(r).split(s)}case"join":{let s=t[0]!==void 0?String(he(t[0],n)):",";return Array.isArray(r)?r.join(s):String(r)}case"removeQuotes":return String(r).replace(/["']/g,"");case"removeSpaces":return String(r).replace(/\s/g,"");case"format":{let s=t[0]!==void 0?String(he(t[0],n)):"{0}";s=s.replace("{0}",String(r));for(let i=1;i<t.length;i++){let o=he(t[i],n);s=s.replace(`{${i}}`,String(o))}return s}case"add":{let s=he(t[0],n);return Number(r)+s}case"subtract":{let s=he(t[0],n);return Number(r)-s}case"multiply":{let s=he(t[0],n);return Number(r)*s}case"abs":return Math.abs(Number(r));case"btoa":return Buffer.from(String(r)).toString("base64");case"atob":return Buffer.from(String(r),"base64").toString("utf-8");case"urlEncode":return encodeURIComponent(String(r));case"urlDecode":return decodeURIComponent(String(r));case"hash":{let s=String(t[0]!==void 0?he(t[0],n):"md5").toLowerCase(),i=String(t[1]!==void 0?he(t[1],n):"base64"),a={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[s]||"md5";return Ci.createHash(a).update(String(r)).digest(i)}case"hmac":{let s=t[0]?String(he(t[0],n)):"",i=String(t[1]!==void 0?he(t[1],n):"sha256").toLowerCase(),o=String(t[2]!==void 0?he(t[2],n):"base64"),c={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[i]||"sha256";return Ci.createHmac(c,s).update(String(r)).digest(o)}case"first":return Array.isArray(r)?r[0]:r;case"last":return Array.isArray(r)?r[r.length-1]:r;case"at":{let s=he(t[0],n);return Array.isArray(r)?r.at(s):r}case"slice":{let s=he(t[0],n),i=t[1]!==void 0?he(t[1],n):void 0;return Array.isArray(r)?r.slice(s,i):String(r).slice(s,i)}case"unique":return Array.isArray(r)?[...new Set(r)]:r;case"filter":return!Array.isArray(r)||!t[0]?r:Jm(r,t[0],n);case"map":{if(!Array.isArray(r))return r;let s=t.map(i=>String(he(i,n)));return s.length===1?r.map(i=>ts(i,s[0])):r.map(i=>{let o={};for(let a of s){let c=ts(i,a);c!==void 0&&(o[a]=c)}return o})}case"prop":{let s=t[0]!==void 0?String(he(t[0],n)):"";if(Array.isArray(r)){let i=r.map(o=>ts(o,s)).filter(o=>o!==void 0);return i.length===1?i[0]:i.join(",")}return r&&typeof r=="object"?ts(r,s):r}case"parseJSON":try{return JSON.parse(String(r))}catch{return r}case"stringify":try{return JSON.stringify(r)}catch{return String(r)}case"isEmail":return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(r));case"isUrl":try{return new URL(String(r)),!0}catch{return!1}case"setIfValue":return r||void 0;case"setNull":return r===null?null:r;default:return r}}function Jm(r,e,t){let n=e.match(/^([\w.]+)\s*(>=|<=|!=|\*=|\^=|\$=|>|<|=)\s*(.+)$/);if(!n)return r;let[,s,i,o]=n,a=he(o,t);return r.filter(c=>{let l=ts(c,s);if(l===void 0)return!1;switch(i){case">":return Number(l)>Number(a);case">=":return Number(l)>=Number(a);case"<":return Number(l)<Number(a);case"<=":return Number(l)<=Number(a);case"=":return String(l)===String(a);case"!=":return String(l)!==String(a);case"*=":return String(l).includes(String(a));case"^=":return String(l).startsWith(String(a));case"$=":return String(l).endsWith(String(a));default:return!0}})}function ts(r,e){if(!(!r||typeof r!="object"))return e in r?r[e]:e.split(".").reduce((t,n)=>t?.[n],r)}function Gm(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ei=E(()=>{"use strict"});function ss(r,e){if(r)return r.split(",").map(t=>{let n=t.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let s=Number(n);if(!isNaN(s)&&n!=="")return s;if(e&&n in e){let i=e[n],o=Number(i);return!isNaN(o)&&i!==""?o:i}return n})}var Rn,Cn,nr=E(()=>{"use strict";Fa();es();Ei();Rn=class r{allVariables;static MAX_RESOLUTION_DEPTH=20;constructor(e){this.allVariables={...e.globals,...e.collectionVariables,...e.environmentVariables,...e.variables}}resolveString(e,t=!1){return typeof e!="string"?e:this.resolveUntilStable(e,this.allVariables,t)}resolveStringWithExtra(e,t,n=!1){if(typeof e!="string")return e;let s={...this.allVariables,...t};return this.resolveUntilStable(e,s,n)}resolveUntilStable(e,t,n){let s=e;for(let i=0;i<r.MAX_RESOLUTION_DEPTH;i++){let o=this.resolveSinglePass(s,t,n);if(o===s)break;s=o}return s}resolveSinglePass(e,t,n){if(!n)return e.replace(/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,(c,l)=>this.resolveTemplateContent(l.trim(),t,c));let s="",i=0,o=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,a;for(;(a=o.exec(e))!==null;){let c=a[1].trim(),l=this.resolveTemplateContent(c,t,a[0]);if(l!==a[0]){s+=e.slice(i,a.index);let u=this.getStringContext(e,a.index);s+=u?this.escapeForString(String(l),u):String(l)}else s+=e.slice(i,a.index+a[0].length);i=a.index+a[0].length}return s+=e.slice(i),s}resolveObject(e,t=!1){if(typeof e=="string")return this.resolveString(e,t);if(Array.isArray(e))return e.map(n=>this.resolveObject(n,t));if(e!==null&&typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveObject(i,t);return n}return e}resolveObjectWithExtra(e,t,n=!1){if(typeof e=="string")return this.resolveStringWithExtra(e,t,n);if(Array.isArray(e))return e.map(s=>this.resolveObjectWithExtra(s,t,n));if(e!==null&&typeof e=="object"){let s={};for(let[i,o]of Object.entries(e))s[i]=this.resolveObjectWithExtra(o,t,n);return s}return e}resolveTemplateContent(e,t,n){let s=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(s){let a=ss(s[2],t),c=xn(s[1],a);return c!==null?String(c):n}let i=ns(e);if(i){let a=this.resolveFilterInput(i.input,t);if(a!==void 0){let c=rs(a,i.filters,t);return c!==void 0?String(c):n}return n}let o=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(o){let a=o[1];if(t[a]!==void 0){let c=this.deserializeValue(t[a]),l=o[2],u=this.resolvePropertyAccess(c,l);if(u!==void 0)return typeof u=="object"?JSON.stringify(u):String(u)}}if(t[e]!==void 0){let a=t[e];if(typeof a=="string"&&a.charCodeAt(0)===30){let c=a.slice(1);return c==="undefined"?"":c}return String(a)}if(wn(e)){let a=this.deserializeVariables(t),c=tr(e,a),l=Pt(e,c);if(l!==void 0)return String(l)}return n}resolveFilterInput(e,t){if(e==="@")return"";if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);let n=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(n){let i=ss(n[2],t),o=xn(n[1],i);return o!==null?o:void 0}let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(s){let i=s[1];if(t[i]!==void 0){let o=this.deserializeValue(t[i]),a=this.resolvePropertyAccess(o,s[2]);if(a!==void 0)return a}}if(t[e]!==void 0)return this.deserializeValue(t[e]);if(wn(e)){let i=this.deserializeVariables(t),o=tr(e,i),a=Pt(e,o);if(a!==void 0)return a}}deserializeValue(e){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{return e}}return e}deserializeVariables(e){let t={};for(let[n,s]of Object.entries(e))t[n]=this.deserializeValue(s);return t}resolvePropertyAccess(e,t){let n=e,s=/\[(\d+|"[^"]*"|'[^']*')\]|\.([a-zA-Z_][a-zA-Z0-9_]*)/g,i;for(;(i=s.exec(t))!==null;){if(n==null)return;if(i[1]!==void 0){let o=i[1];/^\d+$/.test(o)?n=n[Number(o)]:n=n[o.slice(1,-1)]}else i[2]!==void 0&&(n=n[i[2]])}return n}escapeForString(e,t){let n=e.replace(/\\/g,"\\\\");return t==='"'?n=n.replace(/"/g,'\\"'):n=n.replace(/'/g,"\\'"),n.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}getStringContext(e,t){let n=null;for(let s=0;s<t;s++){let i=e[s];(s>0?e[s-1]:"")!=="\\"&&(i==='"'||i==="'")&&(n===null?n=i:n===i&&(n=null))}return n}},Cn=class{interpolate(e,t){return!e||typeof e!="string"?e:new Rn({globals:{},collectionVariables:{},environmentVariables:{},variables:t}).resolveString(e,!0)}extractVariables(e){if(!e||typeof e!="string")return[];let t=[],n,s=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g;for(;(n=s.exec(e))!==null;){let i=n[1].trim();!i.startsWith("$")&&!i.includes("|")&&/^[a-zA-Z_]\w*$/.test(i)&&(t.includes(i)||t.push(i))}return t}interpolateObject(e,t){if(e==null)return e;if(typeof e=="string")return this.interpolate(e,t);if(Array.isArray(e))return e.map(n=>this.interpolateObject(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.interpolateObject(i,t);return n}return e}}});var $t,is=E(()=>{"use strict";$t=class{constructor(e,t,n){this.urlBuilder=e;this.interceptors=t;this.httpClient=n}urlBuilder;interceptors;httpClient;async execute(e){let t={},n;try{n=await this.interceptors.executeRequestInterceptors(e,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,e,t);if(i)return i;throw s}try{let s=await this.httpClient.send(n);return await this.interceptors.executeResponseInterceptors(s,n,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,n,t);if(i)return i;throw s}}buildUrl(e,t={},n={}){return this.urlBuilder.buildUrl(e,t,n)}}});var Ft,os=E(()=>{"use strict";Ft=class{requestInterceptors=[];responseInterceptors=[];errorInterceptors=[];addRequestInterceptor(e){return this.requestInterceptors.push(e),this.sortByPriority(this.requestInterceptors),this}addResponseInterceptor(e){return this.responseInterceptors.push(e),this.sortByPriority(this.responseInterceptors),this}addErrorInterceptor(e){return this.errorInterceptors.push(e),this.sortByPriority(this.errorInterceptors),this}removeRequestInterceptor(e){let t=this.requestInterceptors.findIndex(n=>n.name===e);return t>=0?(this.requestInterceptors.splice(t,1),!0):!1}removeResponseInterceptor(e){let t=this.responseInterceptors.findIndex(n=>n.name===e);return t>=0?(this.responseInterceptors.splice(t,1),!0):!1}removeErrorInterceptor(e){let t=this.errorInterceptors.findIndex(n=>n.name===e);return t>=0?(this.errorInterceptors.splice(t,1),!0):!1}async executeRequestInterceptors(e,t){let n=e;for(let s of this.requestInterceptors)try{n=await s.intercept(n,t)}catch(i){throw console.error(`[InterceptorChain] Request interceptor '${s.name}' failed:`,i),i}return n}async executeResponseInterceptors(e,t,n){let s=e;for(let i of this.responseInterceptors)try{s=await i.intercept(s,t,n)}catch(o){throw console.error(`[InterceptorChain] Response interceptor '${i.name}' failed:`,o),o}return s}async executeErrorInterceptors(e,t,n){for(let s of this.errorInterceptors)try{let i=await s.handle(e,t,n);if(i)return i}catch(i){console.error(`[InterceptorChain] Error interceptor '${s.name}' failed:`,i)}}clear(){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[]}getRegisteredInterceptors(){return{request:this.requestInterceptors.map(e=>e.name),response:this.responseInterceptors.map(e=>e.name),error:this.errorInterceptors.map(e=>e.name)}}sortByPriority(e){e.sort((t,n)=>(t.priority??100)-(n.priority??100))}}});import*as Oe from"crypto";function Fu(r,e,t,n){let s=Buffer.concat([Buffer.from(r,"utf8"),n||Buffer.alloc(0)]),i=[],o=Buffer.alloc(0);for(;Buffer.concat(i).length<e+t;)o=Oe.createHash("md5").update(Buffer.concat([o,s])).digest(),i.push(o);let a=Buffer.concat(i);return{key:a.subarray(0,e),iv:a.subarray(e,e+t)}}function Na(r,e,t){let n=s=>r==="aes"?`aes-${s*8}-cbc`:r==="des"?"des-cbc":r==="des-ede3"?"des-ede3-cbc":r;return{encrypt(s,i,o){let a=s instanceof X?s.toBuffer():Buffer.from(String(s),"utf8");if(typeof i=="string"){let c=Oe.randomBytes(8),{key:l,iv:u}=Fu(i,e,t,c),d=Oe.createCipheriv(n(e),l,u),p=Buffer.concat([d.update(a),d.final()]),m=Buffer.concat([Buffer.from("Salted__"),c,p]);return{ciphertext:new X(p),salt:new X(c),toString:f=>f?f.stringify(new X(m)):m.toString("base64")}}else{let c=i.toBuffer(),l=o?.iv&&o.iv instanceof X?o.iv.toBuffer():Buffer.alloc(t),u=Oe.createCipheriv(n(c.length),c,l);o?.padding===!1&&u.setAutoPadding(!1);let d=Buffer.concat([u.update(a),u.final()]);return{ciphertext:new X(d),toString:p=>p?p.stringify(new X(d)):d.toString("base64")}}},decrypt(s,i,o){if(typeof i=="string"){let a=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext.toBuffer(),c,l;a.subarray(0,8).toString()==="Salted__"?(l=a.subarray(8,16),c=a.subarray(16)):(l=Buffer.alloc(0),c=a);let{key:u,iv:d}=Fu(i,e,t,l),p=Oe.createDecipheriv(n(e),u,d);return new X(Buffer.concat([p.update(c),p.final()]))}else{let a=i.toBuffer(),c=o?.iv&&o.iv instanceof X?o.iv.toBuffer():Buffer.alloc(t),l=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext?s.ciphertext.toBuffer():Buffer.from(s),u=Oe.createDecipheriv(n(a.length),a,c);return o?.padding===!1&&u.setAutoPadding(!1),new X(Buffer.concat([u.update(l),u.final()]))}}}}function Nu(){let r=t=>n=>{let s=n instanceof X?n.toBuffer():Buffer.from(String(n),"utf8");return new X(Oe.createHash(t).update(s).digest())},e=t=>(n,s)=>{let i=n instanceof X?n.toBuffer():Buffer.from(String(n),"utf8"),o=s instanceof X?s.toBuffer():Buffer.from(String(s),"utf8");return new X(Oe.createHmac(t,o).update(i).digest())};return{MD5:r("md5"),SHA1:r("sha1"),SHA224:r("sha224"),SHA256:r("sha256"),SHA384:r("sha384"),SHA512:r("sha512"),SHA3:r("sha3-256"),RIPEMD160:r("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:Na("aes",32,16),DES:Na("des",8,8),TripleDES:Na("des-ede3",24,8),PBKDF2(t,n,s){let i=t instanceof X?t.toBuffer():Buffer.from(String(t),"utf8"),o=n instanceof X?n.toBuffer():Buffer.from(String(n),"utf8"),a=(s?.keySize||4)*4,c=s?.iterations||1;return new X(Oe.pbkdf2Sync(i,o,c,a,"sha1"))},enc:{Base64:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("base64"),parse:t=>X.fromBase64(t)},Utf8:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("utf8"),parse:t=>X.fromUtf8(t)},Hex:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("hex"),parse:t=>X.fromHex(t)},Latin1:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("latin1"),parse:t=>new X(Buffer.from(t,"latin1"))},Utf16:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("utf16le"),parse:t=>new X(Buffer.from(t,"utf16le"))},Utf16BE:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).swap16().toString("utf16le"),parse:t=>new X(Buffer.from(t,"utf16le").swap16())}},lib:{WordArray:{create:t=>t?typeof t=="string"?new X(Buffer.from(t,"utf8")):Buffer.isBuffer(t)?new X(t):new X(Buffer.from(String(t))):new X(Buffer.alloc(0)),random:t=>new X(Oe.randomBytes(t))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var X,_u=E(()=>{"use strict";X=class r{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new r(Buffer.from(e,"hex"))}static fromBase64(e){return new r(Buffer.from(e,"base64"))}static fromUtf8(e){return new r(Buffer.from(e,"utf8"))}}});import*as Wm from"crypto";import*as En from"fs";import{createRequire as Km}from"module";import*as ht from"path";import{v4 as Qm}from"uuid";function Ai(){return{format:(r,e)=>{let t=r?new Date(r):new Date;return e==="YYYY-MM-DD"?t.toISOString().split("T")[0]:t.toISOString()},unix:()=>Math.floor(Date.now()/1e3),utc:()=>{let r=new Date;return{format:()=>r.toISOString(),toISOString:()=>r.toISOString()}},__isShim:!0,__warning:"This is a lightweight shim. For full features, install moment.js via modules/package.json"}}function Zm(){return{get:(r,e,t)=>{let n=e.split("."),s=r;for(let i of n)if(s=s?.[i],s===void 0)return t;return s},set:(r,e,t)=>{let n=e.split("."),s=r;for(let i=0;i<n.length-1;i++)s[n[i]]||(s[n[i]]={}),s=s[n[i]];return s[n[n.length-1]]=t,r},cloneDeep:r=>JSON.parse(JSON.stringify(r)),keys:r=>Object.keys(r??{}),values:r=>Object.values(r??{}),entries:r=>Object.entries(r??{}),each(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},forEach(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},map:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).map(t=>e(t)),filter:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).filter(t=>e(t)),find:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).find(t=>e(t)),reduce:(r,e,t)=>(Array.isArray(r)?r:Object.values(r??{})).reduce((n,s)=>e(n,s),t),includes:(r,e)=>Array.isArray(r)?r.includes(e):Object.values(r??{}).includes(e),isObject:r=>r!==null&&typeof r=="object"&&!Array.isArray(r),isArray:r=>Array.isArray(r),isString:r=>typeof r=="string",isNumber:r=>typeof r=="number",isFunction:r=>typeof r=="function",isNil:r=>r==null,isEmpty:r=>r==null?!0:Array.isArray(r)||typeof r=="string"?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1,assign:(r,...e)=>Object.assign(r,...e),merge:(r,...e)=>{let t={...r};for(let n of e)for(let[s,i]of Object.entries(n??{}))t[s]=i&&typeof i=="object"&&!Array.isArray(i)?{...t[s]??{},...i}:i;return t},omit:(r,e)=>{let t={...r};for(let n of e)delete t[n];return t},pick:(r,e)=>{let t={};for(let n of e)n in(r??{})&&(t[n]=r[n]);return t}}}function _a(r,e){return new qi(r,e)}var qi,Ma=E(()=>{"use strict";qi=class{availableModules=new Set;customModulesRequire;globalSetupExports;options;modulesPath=null;moduleCache=new Map;resolveStack=new Set;builtinModules={uuid:()=>({v4:Qm}),crypto:()=>Wm,path:()=>ht,querystring:()=>ce("querystring"),lodash:()=>this.loadOptionalModule("lodash",()=>ce("lodash"),Zm),moment:()=>this.loadOptionalModule("moment",()=>ce("moment"),Ai),tv4:()=>this.loadOptionalModule("tv4",()=>ce("tv4")),ajv:()=>this.loadOptionalModule("ajv",()=>ce("ajv")),"crypto-js":()=>this.loadOptionalModule("crypto-js",()=>ce("crypto-js"),()=>{throw new Error('crypto-js npm module is not installed. The built-in CryptoJS global is already available in scripts with AES/DES/TripleDES/hash/HMAC/PBKDF2 support. If you need the exact npm package, add "crypto-js" to your modules/package.json and run npm install.')})};constructor(e=[],t={}){this.options={allowCustomModules:!0,maxResolveDepth:10,...t,outputChannel:t.outputChannel||{appendLine:n=>{console.log(`[ModuleLoader] ${n}`)}}};for(let n of e){let s=ht.resolve(n);if(this.initializeModules(s)){this.modulesPath=s;break}}}loadOptionalModule(e,t,n){try{return t()}catch{if(this.customModulesRequire)try{return console.debug(`[ModuleLoader] ${e} not in core, trying user modules`),this.customModulesRequire(e)}catch{this.logModuleWarning(e,"user")}else this.logModuleWarning(e,"core");if(n)return console.warn(`[ModuleLoader] Using shim for ${e}. Some features may be limited.`),n();throw new Error(this.getModuleInstallInstructions(e))}}logModuleWarning(e,t){let s={moment:"Date/time manipulation",lodash:"Utility functions",tv4:"JSON Schema validation (v4)",ajv:"JSON Schema validation"}[e]||e;console.warn(`[ModuleLoader] ${s} functionality (${e}) is not available.
|
|
214
|
+
`;try{U.writeFileSync(t,s,"utf-8")}catch{}}readJsonFileSafe(e,t){let n;try{n=U.readFileSync(e,"utf-8")}catch(s){console.error(`[FolderCollectionStore] Failed to read ${t} ${e}:`,s);return}if(n.trim().length!==0)try{return JSON.parse(n)}catch(s){if(s instanceof SyntaxError&&/Unexpected end of JSON input/.test(s.message))return;console.error(`[FolderCollectionStore] Failed to parse ${t} ${e}:`,s);return}}loadAll(){if(this.cache.clear(),this.slugToIdMap.clear(),this.idToSlugMap.clear(),!U.existsSync(this.collectionsDir))return[];let e=U.readdirSync(this.collectionsDir,{withFileTypes:!0}),t=[];for(let n of e)if(n.isDirectory())try{let s=this.loadCollectionFromFolder(n.name);s&&(this.cache.set(s.id,s),this.slugToIdMap.set(n.name,s.id),this.idToSlugMap.set(s.id,n.name),t.push(s))}catch(s){console.error(`[FolderCollectionStore] Failed to load ${n.name}:`,s)}return t}loadCollectionFromFolder(e){let t=J.join(this.collectionsDir,e),n=J.join(t,Me.collection);if(!U.existsSync(n))return;let s=this.readJsonFileSafe(n,"collection");if(s)try{let i=this.loadScriptsFromDir(J.join(t,Ke)),o=this.loadItemsFromDir(t,s.id,s.order);return{id:s.id,name:s.name,description:s.description,version:s.version,variables:s.variables,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to parse ${n}:`,i);return}}loadItemsFromDir(e,t,n){let s=[],i=new Map,o=U.readdirSync(e,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||a.name===Ke)continue;let c=J.join(e,a.name);if(U.existsSync(J.join(c,Me.folder))){let l=this.loadFolderFromDir(c,a.name);l&&i.set(a.name,l)}else if(U.existsSync(J.join(c,Me.request))){let l=this.loadRequestFromDir(c,a.name);l&&i.set(a.name,l)}}if(n&&n.length>0){for(let a of n){let c=i.get(a);c&&(s.push(c),i.delete(a))}for(let a of i.values())s.push(a)}else for(let a of i.values())s.push(a);return s}loadFolderFromDir(e,t){let n=J.join(e,Me.folder),s=this.readJsonFileSafe(n,"folder");if(s)try{let i=this.loadScriptsFromDir(J.join(e,Ke)),o=this.loadItemsFromDir(e,s.id,s.order);return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"folder",name:s.name,description:s.description,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to load folder ${e}:`,i);return}}loadRequestFromDir(e,t){let n=J.join(e,Me.request),s=this.readJsonFileSafe(n,"request");if(s)try{let i=this.loadScriptsFromDir(J.join(e,Ke)),o=s.body,a=this.loadBodyFromDir(e);a&&(o=a);let c=this.loadSchemaFile(J.join(e,Kr.responseSchema)),l=this.loadSchemaFile(J.join(e,Kr.bodySchema)),u=J.join(e,"doc.md"),d=U.existsSync(u)?U.readFileSync(u,"utf-8"):void 0;return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"request",name:s.name,description:s.description,method:s.method,url:s.url,params:s.params,query:s.query,headers:s.headers,body:o,bodyContentType:s.bodyContentType,auth:s.auth,settings:s.settings,scripts:i,disabled:s.disabled,deprecated:s.deprecated,operationId:s.operationId,summary:s.summary,tags:s.tags,examples:s.examples,responses:s.responses,security:s.security,...d&&{doc:d},...c&&{responseSchema:c},...l&&{bodySchema:l}}}catch(i){console.error(`[FolderCollectionStore] Failed to load request ${e}:`,i);return}}loadScriptsFromDir(e){return yi(e)}loadBodyFromDir(e){return Cu(e)}loadSchemaFile(e){return Au(e)}async saveSchemaFiles(e,t){return Pu(e,t.responseSchema,t.bodySchema)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.idToSlugMap.get(e);if(t){let n=this.loadCollectionFromFolder(t);return n&&this.cache.set(e,n),n}return this.loadAll(),this.cache.get(e)}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");e.id||(e.id=se(e.name));let t=this.idToSlugMap.get(e.id);if(!t){let c=U.readdirSync(this.collectionsDir);t=ft(e.name,c),this.idToSlugMap.set(e.id,t),this.slugToIdMap.set(t,e.id)}let n=J.join(this.collectionsDir,t),s=!U.existsSync(n);await U.promises.mkdir(n,{recursive:!0});let i={id:e.id,name:e.name,description:e.description,version:e.version,variables:e.variables,auth:e.auth},[o]=await Promise.all([this.saveItemsToDir(n,e.items,s),e.scripts?this.saveScriptsToDir(J.join(n,Ke),e.scripts):Promise.resolve()]);o.length>0&&(i.order=o);let a={$schema:Ta.collection,...i};await U.promises.writeFile(J.join(n,Me.collection),JSON.stringify(a,null,2),"utf-8"),this.cache.set(e.id,e)}async saveItemsToDir(e,t,n=!1){let s=[],i=[];for(let o of t){let a=this.idToSlugMap.get(o.id);a||(a=ft(o.name,s),this.idToSlugMap.set(o.id,a),this.slugToIdMap.set(a,o.id)),s.push(a),i.push({item:o,slug:a})}return await Promise.all(i.map(async({item:o,slug:a})=>{let c=J.join(e,a);await U.promises.mkdir(c,{recursive:!0}),o.type==="folder"?await this.saveFolderToDir(c,o,n):await this.saveRequestToDir(c,o,n)})),s}async saveFolderToDir(e,t,n=!1){let s={id:t.id,name:t.name,description:t.description,auth:t.auth},[i]=await Promise.all([t.items?this.saveItemsToDir(e,t.items,n):Promise.resolve([]),t.scripts?this.saveScriptsToDir(J.join(e,Ke),t.scripts):Promise.resolve()]);i.length>0&&(s.order=i);let o={$schema:Ta.folder,...s};await U.promises.writeFile(J.join(e,Me.folder),JSON.stringify(o,null,2),"utf-8")}async saveRequestToDir(e,t,n=!1){let{bodyForMetadata:s,externalBodyFile:i}=this.prepareBodyForSave(t.body),o={id:t.id,name:t.name,method:t.method||"GET",url:t.url||"",description:t.description,params:t.params,query:t.query,headers:t.headers,body:s,bodyContentType:t.bodyContentType,auth:t.auth,settings:t.settings,...t.disabled!==void 0&&{disabled:t.disabled},...t.deprecated&&{deprecated:t.deprecated},...t.operationId&&{operationId:t.operationId},...t.summary&&{summary:t.summary},...t.tags&&t.tags.length>0&&{tags:t.tags},...t.examples&&t.examples.length>0&&{examples:t.examples},...t.responses&&Object.keys(t.responses).length>0&&{responses:t.responses},...t.security&&t.security.length>0&&{security:t.security}},a=[U.promises.writeFile(J.join(e,Me.request),JSON.stringify({$schema:Ta.request,...o},null,2),"utf-8")];i&&a.push(U.promises.writeFile(J.join(e,i.filename),i.content,"utf-8")),n||a.push(this.cleanupOldBodyFiles(e,i?.filename)),(!n||t.responseSchema||t.bodySchema)&&a.push(this.saveSchemaFiles(e,t)),t.doc&&a.push(U.promises.writeFile(J.join(e,"doc.md"),t.doc,"utf-8")),t.scripts&&a.push(this.saveScriptsToDir(J.join(e,Ke),t.scripts)),await Promise.all(a)}prepareBodyForSave(e){return Eu(e)}async cleanupOldBodyFiles(e,t){return qu(e,t)}async saveScriptsToDir(e,t){return vi(e,t)}async delete(e){let t=this.idToSlugMap.get(e);if(!t&&(this.loadAll(),t=this.idToSlugMap.get(e),!t))return!1;let n=J.join(this.collectionsDir,t);if(!U.existsSync(n))return!1;try{return await U.promises.rm(n,{recursive:!0,force:!0}),this.cache.delete(e),this.idToSlugMap.delete(e),this.slugToIdMap.delete(t),!0}catch(s){return console.error(`[FolderCollectionStore] Failed to delete collection ${e}:`,s),!1}}exists(e){let t=this.idToSlugMap.get(e);return t?U.existsSync(J.join(this.collectionsDir,t,Me.collection)):!1}getCollectionPath(e){let t=this.idToSlugMap.get(e)||e;return J.join(this.collectionsDir,t)}getItemPath(e,t){return this.findItemPath(e,t)}async create(e,t){let n={id:t||se(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=this.findItemPath(e,t);if(!i)throw new Error(`Item ${t} not found in collection ${e}`);await this.saveScriptsToDir(J.join(i,Ke),n);let o=this.findItemById(s.items,t);o&&(o.scripts=n)}loadScripts(e,t){let n=this.findItemPath(e,t);if(n)return this.loadScriptsFromDir(J.join(n,Ke))}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);let s=this.idToSlugMap.get(e);if(!s)throw new Error(`Collection slug not found for ${e}`);let i=J.join(this.collectionsDir,s),o=J.join(i,Me.collection),a=U.readFileSync(o,"utf-8"),l={...JSON.parse(a),...t,id:e};await U.promises.writeFile(o,JSON.stringify(l,null,2),"utf-8"),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)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=this.idToSlugMap.get(e);if(!i)throw new Error(`Collection slug not found for ${e}`);let o;if(n){let u=this.findItemPath(e,n);if(!u)throw new Error(`Parent folder ${n} not found`);o=u}else o=J.join(this.collectionsDir,i);let a=this.idToSlugMap.get(t.id);if(!a){let u=U.readdirSync(o).filter(d=>U.statSync(J.join(o,d)).isDirectory()&&d!==Ke);a=ft(t.name,u),this.idToSlugMap.set(t.id,a),this.slugToIdMap.set(a,t.id)}let c=J.join(o,a);await U.promises.mkdir(c,{recursive:!0}),t.type==="folder"?await this.saveFolderToDir(c,t):await this.saveRequestToDir(c,t);let l=this.findItemById(s.items,t.id);if(l)Object.assign(l,t);else if(n){let u=this.findItemById(s.items,n);u&&u.type==="folder"&&(u.items=u.items||[],u.items.push(t))}else s.items.push(t)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=this.findItemPath(e,t);if(!s||!U.existsSync(s))return!1;try{await U.promises.rm(s,{recursive:!0,force:!0}),this.deleteItemFromTree(n.items,t);let i=this.idToSlugMap.get(t);return i&&(this.slugToIdMap.delete(i),this.idToSlugMap.delete(t)),!0}catch(i){return console.error(`[FolderCollectionStore] Failed to delete item ${t}:`,i),!1}}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.findItemPath(e,t);if(!i)return!1;let o=this.findItemById(s.items,t);if(!o)return!1;let{id:a,type:c,items:l,...u}=n;return Object.assign(o,u),o.type==="folder"?await this.saveFolderToDir(i,o):await this.saveRequestToDir(i,o),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=this.findItemPath(e,t);if(!o||!U.existsSync(o))return!1;let a;if(n){let u=this.findItemPath(e,n);if(!u)return!1;a=u}else a=J.join(this.collectionsDir,i);let c=this.idToSlugMap.get(t);if(!c)return!1;let l=J.join(a,c);if(U.existsSync(l))return!1;try{await U.promises.rename(o,l);let u=this.findItemById(s.items,t);if(u){let d=u.type==="folder"?{...u,items:u.items?[...u.items]:[]}:{...u};if(this.deleteItemFromTree(s.items,t),n){let p=this.findItemById(s.items,n);p&&p.type==="folder"&&(p.items=p.items||[],p.items.push(d))}else s.items.push(d)}return!0}catch(u){return console.error(`[FolderCollectionStore] Failed to move item ${t}:`,u),!1}}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=[];for(let a of n){let c=this.idToSlugMap.get(a);c&&o.push(c)}try{if(t){let a=this.findItemPath(e,t);if(!a)return!1;let c=J.join(a,Me.folder),l=U.readFileSync(c,"utf-8"),u=JSON.parse(l);u.order=o,await U.promises.writeFile(c,JSON.stringify(u,null,2),"utf-8");let d=this.findItemById(s.items,t);d&&d.type==="folder"&&d.items&&(d.items=this.sortItemsByOrder(d.items,n))}else{let a=J.join(this.collectionsDir,i,Me.collection),c=U.readFileSync(a,"utf-8"),l=JSON.parse(c);l.order=o,await U.promises.writeFile(a,JSON.stringify(l,null,2),"utf-8"),s.items=this.sortItemsByOrder(s.items,n)}return!0}catch(a){return console.error("[FolderCollectionStore] Failed to reorder items:",a),!1}}sortItemsByOrder(e,t){return ku(e,t)}findItemPath(e,t){let n=this.idToSlugMap.get(e);if(!n)return;let s=J.join(this.collectionsDir,n),i=Ia(s,t);if(i)return i;let o=this.load(e);if(o){let c=this.buildSlugPath(o.items,t);if(c)return J.join(s,...c)}let a=this.idToSlugMap.get(t);if(a)return ka(s,a)}buildSlugPath(e,t){for(let n of e){let s=this.idToSlugMap.get(n.id);if(s){if(n.id===t)return[s];if(n.type==="folder"&&n.items){let i=this.buildSlugPath(n.items,t);if(i)return[s,...i]}}}}findItemById(e,t){return we(e,t)}deleteItemFromTree(e,t){return Zt(e,t)}}});var ne,bn=E(()=>{"use strict";ne=class{static parseSetCookie(e,t){let n=e.split(";").map(u=>u.trim());if(n.length===0)return null;let[s,...i]=n,o=s.indexOf("=");if(o===-1)return null;let a=s.substring(0,o).trim(),c=s.substring(o+1).trim(),l={name:a,value:c,domain:t};for(let u of i){let d=u.indexOf("="),p=(d===-1?u:u.substring(0,d)).toLowerCase(),m=d===-1?"":u.substring(d+1);switch(p){case"domain":l.domain=m.startsWith(".")?m.substring(1):m;break;case"path":l.path=m;break;case"expires":l.expires=m;break;case"max-age":l.maxAge=parseInt(m,10);break;case"httponly":l.httpOnly=!0;break;case"secure":l.secure=!0;break;case"samesite":l.sameSite=m;break}}return l}static parseCookieHeaders(e,t){let n=[],s=e["set-cookie"]||e["Set-Cookie"];if(!s)return n;let i=Array.isArray(s)?s:[s];for(let o of i){let a=this.parseSetCookie(o,t);a&&n.push(a)}return n}static formatCookieHeader(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}static cookieKey(e,t,n){return`${t||"*"}|${n||"/"}|${e}`}static isExpired(e){return!!(e.expires&&new Date(e.expires).getTime()<Date.now()||e.maxAge!==void 0&&e.maxAge<=0)}static domainMatches(e,t){if(t==="*")return!0;let n=e.toLowerCase().split(".").reverse(),s=t.toLowerCase().split(".").reverse();if(s.length>n.length)return!1;for(let i=0;i<s.length;i++)if(s[i]!==n[i])return!1;return!0}static extractDomain(e){try{return new URL(e).hostname}catch{return""}}static extractPath(e){try{return new URL(e).pathname}catch{return"/"}}}});import*as en from"fs";import*as Sn from"path";function xi(r){let e=r.toLowerCase();return e==="_global.json"||e==="_global.local.json"||e.endsWith(".local.json")}function Xr(r){if(!en.existsSync(r))return Rm();let e=Si(Sn.join(r,"_global.json"))||{},t=e.variables||{},n=e.defaultHeaders||{},s=en.readdirSync(r).filter(l=>l.endsWith(".json")).filter(l=>!l.endsWith(".local.json")).filter(l=>!xi(l)),i={};for(let l of s){let u=Si(Sn.join(r,l))||{},d=Sn.basename(l,".json");i[d]={description:u.description,requiresConfirmation:u.requiresConfirmation,variables:u.variables||{},secretVariables:u.secretVariables}}let a=(Si(Sn.join(r,"_global.local.json"))||{}).variables||{},c={};for(let l of Object.keys(i)){let u=Sn.join(r,`${l}.local.json`);if(en.existsSync(u)){let d=Si(u)||{};c[l]={variables:d.variables||{}}}}return{globalVariables:t,defaultHeaders:n,environments:i,localVariables:a,localCredentials:c}}function Rm(){return{globalVariables:{},defaultHeaders:{},environments:{},localVariables:{},localCredentials:{}}}function Si(r){try{if(!en.existsSync(r))return null;let e=en.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){return console.error(`[environment-file-loader] Failed to load JSON from ${r}:`,e),null}}var wi=E(()=>{"use strict"});var mt,er=E(()=>{"use strict";mt=class{buildUrl(e,t={},n={}){let s=e;return s=this.replacePathParams(s,t),s=this.appendQueryParams(s,n),s}replacePathParams(e,t){let n="",s="",i=e,o="",a=e.indexOf("?");a!==-1&&(o=e.substring(a),i=e.substring(0,a));let c=i.match(/^(https?:\/\/)([^\/]*)(\/.*)?$/);c&&(n=c[1],s=c[2],i=c[3]||"/");let l=/:(\w+)(?:\([^)]*\))?(\?)?/g,u=i.replace(l,(d,p,m)=>{let f=t[p];return f!==void 0&&f!==""?encodeURIComponent(f):m?"":(console.warn(`[UrlBuilder] Missing required path parameter: ${p}`),d)});return u=u.replace(/([^:])\/+/g,"$1/"),`${n}${s}${u}${o}`}extractPathParams(e){let t=/:(\w+)(?:\([^)]*\))?(\?)?/g,n=[],s;for(;(s=t.exec(e))!==null;)n.push(s[1]);return[...new Set(n)]}appendQueryParams(e,t){let n=e,s={};if(e.includes("?")){let[c,l]=e.split("?");n=c,l&&new URLSearchParams(l).forEach((d,p)=>{s[p]=d})}let i={...s,...t},o=new URLSearchParams;for(let[c,l]of Object.entries(i))l!=null&&o.append(c,l);let a=o.toString();return a?`${n}?${a}`:n}}});import{v4 as Ou}from"uuid";function Cm(r=0,e=999){return Math.floor(Math.random()*(e-r+1))+r}function Em(){return Date.now()}function Tu(){return Ou()}function qm(){return Ou()}function $u(r=10){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function Am(){let r=$u(8).toLowerCase(),e=["example.com","test.org","mail.dev","sample.net"];return`${r}@${e[Math.floor(Math.random()*e.length)]}`}function Pm(){return Math.random()<.5}function km(r=10){let e="0123456789abcdef",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function Im(){return Math.floor(Date.now()/1e3)}function Tm(){return new Date().toISOString()}function Om(){return new Date().toISOString().split("T")[0]}function $m(){return new Date().toISOString().split("T")[1].split(".")[0]}function Fm(){return new Date().toISOString()}function Nm(r=""){return Buffer.from(String(r)).toString("base64")}function _m(r=""){return Buffer.from(String(r),"base64").toString("utf-8")}function Mm(r=""){return encodeURIComponent(String(r))}function Dm(r=""){return decodeURIComponent(String(r))}function xn(r,e){let t=jm[r];return t?e&&e.length>0?t(...e):t():null}function tr(r,e){let t=/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,n=null,s;for(;(s=t.exec(r))!==null;){let i=s[0],o=s[1];if(!(i in e)){let a=xn(o);a!==null&&(n||(n={...e}),n[i]=a)}}return n??e}var jm,Fa=E(()=>{"use strict";jm={randomInt:Cm,timestamp:Em,guid:qm,uuid:Tu,randomUUID:Tu,randomString:$u,randomHexadecimal:km,randomEmail:Am,randomBoolean:Pm,isoTimestamp:Fm,timestamp_s:Im,datetime:Tm,date:Om,time:$m,base64Encode:Nm,base64Decode:_m,urlEncode:Mm,urlDecode:Dm}});import*as Ri from"vm";function wn(r){let e=r.trim();return!e||/^(\$?)[a-zA-Z_][a-zA-Z0-9_]*(\([^)]*\))?$/.test(e)||/(?<!\|)\|(?!\|)/.test(e)?!1:/[+\-*/%<>=!&|?:~^()[\]{}.,`]/.test(e)}function Pt(r,e={}){try{let t={...e,Math,Date,JSON,Number,String,Boolean,Array,Object,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,undefined:void 0,null:null,true:!0,false:!1,NaN:NaN,Infinity:1/0},n=Ri.createContext(t);return Ri.runInContext(r,n,{timeout:Lm,displayErrors:!1})}catch{return}}var Lm,es=E(()=>{"use strict";Lm=100});import*as Ci from"crypto";function Hm(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function ns(r){if(!r||!r.includes("|"))return null;let e=Bm(r);if(e.length<2)return null;let t=e[0].trim(),n=[];for(let s=1;s<e.length;s++){let i=e[s].trim();if(!i)continue;let o=Um(i);o&&n.push(o)}return n.length===0?null:{input:t,filters:n}}function Bm(r){let e=[],t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o],c=o>0?r[o-1]:"",l=o<r.length-1?r[o+1]:"";if(c==="\\"){t+=a;continue}if(a==="'"&&!i)s=!s;else if(a==='"'&&!s)i=!i;else if(a==="("&&!s&&!i)n++;else if(a===")"&&!s&&!i)n--;else if(a==="|"&&n===0&&!s&&!i){if(l==="|"){t+="||",o++;continue}e.push(t),t="";continue}t+=a}return t&&e.push(t),e}function Um(r){let e=r.indexOf("(");if(e===-1)return{name:r.trim(),args:[]};let t=r.substring(0,e).trim(),n=r.substring(e+1,r.lastIndexOf(")"));return{name:t,args:Vm(n)}}function Vm(r){if(!r||!r.trim())return[];let e=[],t="",n=!1,s=!1;for(let i=0;i<r.length;i++){let o=r[i];if((i>0?r[i-1]:"")==="\\"){t+=o;continue}if(o==="'"&&!s){n=!n,t+=o;continue}else if(o==='"'&&!n){s=!s,t+=o;continue}else if(o===","&&!n&&!s){e.push(t.trim()),t="";continue}t+=o}return t.trim()&&e.push(t.trim()),e}function he(r,e){if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=Number(r);if(!isNaN(t)&&r!=="")return t;if(r==="true")return!0;if(r==="false")return!1;if(e&&r in e){let n=Hm(e[r]),s=Number(n);return!isNaN(s)&&n!==""?s:n}return r}function rs(r,e,t={}){let n=r;for(let s of e)n=zm(n,s.name,s.args,t);return n}function zm(r,e,t,n){switch(e){case"upper":return String(r).toUpperCase();case"lower":return String(r).toLowerCase();case"trim":return String(r).trim();case"length":return Array.isArray(r)?r.length:String(r).length;case"substring":{let s=he(t[0],n),i=t[1]!==void 0?he(t[1],n):void 0;return String(r).substring(s<0?String(r).length+s:s,i!==void 0?i<0?String(r).length+i:i:void 0)}case"replace":{let s=t[0]!==void 0?String(he(t[0],n)):"",i=t[1]!==void 0?String(he(t[1],n)):"";return String(r).replace(new RegExp(Gm(s),"g"),i)}case"split":{let s=t[0]!==void 0?String(he(t[0],n)):",";return String(r).split(s)}case"join":{let s=t[0]!==void 0?String(he(t[0],n)):",";return Array.isArray(r)?r.join(s):String(r)}case"removeQuotes":return String(r).replace(/["']/g,"");case"removeSpaces":return String(r).replace(/\s/g,"");case"format":{let s=t[0]!==void 0?String(he(t[0],n)):"{0}";s=s.replace("{0}",String(r));for(let i=1;i<t.length;i++){let o=he(t[i],n);s=s.replace(`{${i}}`,String(o))}return s}case"add":{let s=he(t[0],n);return Number(r)+s}case"subtract":{let s=he(t[0],n);return Number(r)-s}case"multiply":{let s=he(t[0],n);return Number(r)*s}case"abs":return Math.abs(Number(r));case"btoa":return Buffer.from(String(r)).toString("base64");case"atob":return Buffer.from(String(r),"base64").toString("utf-8");case"urlEncode":return encodeURIComponent(String(r));case"urlDecode":return decodeURIComponent(String(r));case"hash":{let s=String(t[0]!==void 0?he(t[0],n):"md5").toLowerCase(),i=String(t[1]!==void 0?he(t[1],n):"base64"),a={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[s]||"md5";return Ci.createHash(a).update(String(r)).digest(i)}case"hmac":{let s=t[0]?String(he(t[0],n)):"",i=String(t[1]!==void 0?he(t[1],n):"sha256").toLowerCase(),o=String(t[2]!==void 0?he(t[2],n):"base64"),c={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[i]||"sha256";return Ci.createHmac(c,s).update(String(r)).digest(o)}case"first":return Array.isArray(r)?r[0]:r;case"last":return Array.isArray(r)?r[r.length-1]:r;case"at":{let s=he(t[0],n);return Array.isArray(r)?r.at(s):r}case"slice":{let s=he(t[0],n),i=t[1]!==void 0?he(t[1],n):void 0;return Array.isArray(r)?r.slice(s,i):String(r).slice(s,i)}case"unique":return Array.isArray(r)?[...new Set(r)]:r;case"filter":return!Array.isArray(r)||!t[0]?r:Jm(r,t[0],n);case"map":{if(!Array.isArray(r))return r;let s=t.map(i=>String(he(i,n)));return s.length===1?r.map(i=>ts(i,s[0])):r.map(i=>{let o={};for(let a of s){let c=ts(i,a);c!==void 0&&(o[a]=c)}return o})}case"prop":{let s=t[0]!==void 0?String(he(t[0],n)):"";if(Array.isArray(r)){let i=r.map(o=>ts(o,s)).filter(o=>o!==void 0);return i.length===1?i[0]:i.join(",")}return r&&typeof r=="object"?ts(r,s):r}case"parseJSON":try{return JSON.parse(String(r))}catch{return r}case"stringify":try{return JSON.stringify(r)}catch{return String(r)}case"isEmail":return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(r));case"isUrl":try{return new URL(String(r)),!0}catch{return!1}case"setIfValue":return r||void 0;case"setNull":return r===null?null:r;default:return r}}function Jm(r,e,t){let n=e.match(/^([\w.]+)\s*(>=|<=|!=|\*=|\^=|\$=|>|<|=)\s*(.+)$/);if(!n)return r;let[,s,i,o]=n,a=he(o,t);return r.filter(c=>{let l=ts(c,s);if(l===void 0)return!1;switch(i){case">":return Number(l)>Number(a);case">=":return Number(l)>=Number(a);case"<":return Number(l)<Number(a);case"<=":return Number(l)<=Number(a);case"=":return String(l)===String(a);case"!=":return String(l)!==String(a);case"*=":return String(l).includes(String(a));case"^=":return String(l).startsWith(String(a));case"$=":return String(l).endsWith(String(a));default:return!0}})}function ts(r,e){if(!(!r||typeof r!="object"))return e in r?r[e]:e.split(".").reduce((t,n)=>t?.[n],r)}function Gm(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ei=E(()=>{"use strict"});function ss(r,e){if(r)return r.split(",").map(t=>{let n=t.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let s=Number(n);if(!isNaN(s)&&n!=="")return s;if(e&&n in e){let i=e[n],o=Number(i);return!isNaN(o)&&i!==""?o:i}return n})}var Rn,Cn,nr=E(()=>{"use strict";Fa();es();Ei();Rn=class r{allVariables;static MAX_RESOLUTION_DEPTH=20;constructor(e){this.allVariables={...e.globals,...e.collectionVariables,...e.environmentVariables,...e.variables}}resolveString(e,t=!1){return typeof e!="string"?e:this.resolveUntilStable(e,this.allVariables,t)}resolveStringWithExtra(e,t,n=!1){if(typeof e!="string")return e;let s={...this.allVariables,...t};return this.resolveUntilStable(e,s,n)}resolveUntilStable(e,t,n){let s=e;for(let i=0;i<r.MAX_RESOLUTION_DEPTH;i++){let o=this.resolveSinglePass(s,t,n);if(o===s)break;s=o}return s}resolveSinglePass(e,t,n){if(!n)return e.replace(/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,(c,l)=>this.resolveTemplateContent(l.trim(),t,c));let s="",i=0,o=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,a;for(;(a=o.exec(e))!==null;){let c=a[1].trim(),l=this.resolveTemplateContent(c,t,a[0]);if(l!==a[0]){s+=e.slice(i,a.index);let u=this.getStringContext(e,a.index);s+=u?this.escapeForString(String(l),u):String(l)}else s+=e.slice(i,a.index+a[0].length);i=a.index+a[0].length}return s+=e.slice(i),s}resolveObject(e,t=!1){if(typeof e=="string")return this.resolveString(e,t);if(Array.isArray(e))return e.map(n=>this.resolveObject(n,t));if(e!==null&&typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveObject(i,t);return n}return e}resolveObjectWithExtra(e,t,n=!1){if(typeof e=="string")return this.resolveStringWithExtra(e,t,n);if(Array.isArray(e))return e.map(s=>this.resolveObjectWithExtra(s,t,n));if(e!==null&&typeof e=="object"){let s={};for(let[i,o]of Object.entries(e))s[i]=this.resolveObjectWithExtra(o,t,n);return s}return e}resolveTemplateContent(e,t,n){let s=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(s){let a=ss(s[2],t),c=xn(s[1],a);return c!==null?String(c):n}let i=ns(e);if(i){let a=this.resolveFilterInput(i.input,t);if(a!==void 0){let c=rs(a,i.filters,t);return c!==void 0?String(c):n}return n}let o=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(o){let a=o[1];if(t[a]!==void 0){let c=this.deserializeValue(t[a]),l=o[2],u=this.resolvePropertyAccess(c,l);if(u!==void 0)return typeof u=="object"?JSON.stringify(u):String(u)}}if(t[e]!==void 0){let a=t[e];if(typeof a=="string"&&a.charCodeAt(0)===30){let c=a.slice(1);return c==="undefined"?"":c}return String(a)}if(wn(e)){let a=this.deserializeVariables(t),c=tr(e,a),l=Pt(e,c);if(l!==void 0)return String(l)}return n}resolveFilterInput(e,t){if(e==="@")return"";if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);let n=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(n){let i=ss(n[2],t),o=xn(n[1],i);return o!==null?o:void 0}let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(s){let i=s[1];if(t[i]!==void 0){let o=this.deserializeValue(t[i]),a=this.resolvePropertyAccess(o,s[2]);if(a!==void 0)return a}}if(t[e]!==void 0)return this.deserializeValue(t[e]);if(wn(e)){let i=this.deserializeVariables(t),o=tr(e,i),a=Pt(e,o);if(a!==void 0)return a}}deserializeValue(e){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{return e}}return e}deserializeVariables(e){let t={};for(let[n,s]of Object.entries(e))t[n]=this.deserializeValue(s);return t}resolvePropertyAccess(e,t){let n=e,s=/\[(\d+|"[^"]*"|'[^']*')\]|\.([a-zA-Z_][a-zA-Z0-9_]*)/g,i;for(;(i=s.exec(t))!==null;){if(n==null)return;if(i[1]!==void 0){let o=i[1];/^\d+$/.test(o)?n=n[Number(o)]:n=n[o.slice(1,-1)]}else i[2]!==void 0&&(n=n[i[2]])}return n}escapeForString(e,t){let n=e.replace(/\\/g,"\\\\");return t==='"'?n=n.replace(/"/g,'\\"'):n=n.replace(/'/g,"\\'"),n.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}getStringContext(e,t){let n=null;for(let s=0;s<t;s++){let i=e[s];(s>0?e[s-1]:"")!=="\\"&&(i==='"'||i==="'")&&(n===null?n=i:n===i&&(n=null))}return n}},Cn=class{interpolate(e,t){return!e||typeof e!="string"?e:new Rn({globals:{},collectionVariables:{},environmentVariables:{},variables:t}).resolveString(e,!0)}extractVariables(e){if(!e||typeof e!="string")return[];let t=[],n,s=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g;for(;(n=s.exec(e))!==null;){let i=n[1].trim();!i.startsWith("$")&&!i.includes("|")&&/^[a-zA-Z_]\w*$/.test(i)&&(t.includes(i)||t.push(i))}return t}interpolateObject(e,t){if(e==null)return e;if(typeof e=="string")return this.interpolate(e,t);if(Array.isArray(e))return e.map(n=>this.interpolateObject(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.interpolateObject(i,t);return n}return e}}});var $t,is=E(()=>{"use strict";$t=class{constructor(e,t,n){this.urlBuilder=e;this.interceptors=t;this.httpClient=n}urlBuilder;interceptors;httpClient;async execute(e){let t={},n;try{n=await this.interceptors.executeRequestInterceptors(e,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,e,t);if(i)return i;throw s}try{let s=await this.httpClient.send(n);return await this.interceptors.executeResponseInterceptors(s,n,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,n,t);if(i)return i;throw s}}buildUrl(e,t={},n={}){return this.urlBuilder.buildUrl(e,t,n)}}});var Ft,os=E(()=>{"use strict";Ft=class{requestInterceptors=[];responseInterceptors=[];errorInterceptors=[];addRequestInterceptor(e){return this.requestInterceptors.push(e),this.sortByPriority(this.requestInterceptors),this}addResponseInterceptor(e){return this.responseInterceptors.push(e),this.sortByPriority(this.responseInterceptors),this}addErrorInterceptor(e){return this.errorInterceptors.push(e),this.sortByPriority(this.errorInterceptors),this}removeRequestInterceptor(e){let t=this.requestInterceptors.findIndex(n=>n.name===e);return t>=0?(this.requestInterceptors.splice(t,1),!0):!1}removeResponseInterceptor(e){let t=this.responseInterceptors.findIndex(n=>n.name===e);return t>=0?(this.responseInterceptors.splice(t,1),!0):!1}removeErrorInterceptor(e){let t=this.errorInterceptors.findIndex(n=>n.name===e);return t>=0?(this.errorInterceptors.splice(t,1),!0):!1}async executeRequestInterceptors(e,t){let n=e;for(let s of this.requestInterceptors)try{n=await s.intercept(n,t)}catch(i){throw console.error(`[InterceptorChain] Request interceptor '${s.name}' failed:`,i),i}return n}async executeResponseInterceptors(e,t,n){let s=e;for(let i of this.responseInterceptors)try{s=await i.intercept(s,t,n)}catch(o){throw console.error(`[InterceptorChain] Response interceptor '${i.name}' failed:`,o),o}return s}async executeErrorInterceptors(e,t,n){for(let s of this.errorInterceptors)try{let i=await s.handle(e,t,n);if(i)return i}catch(i){console.error(`[InterceptorChain] Error interceptor '${s.name}' failed:`,i)}}clear(){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[]}getRegisteredInterceptors(){return{request:this.requestInterceptors.map(e=>e.name),response:this.responseInterceptors.map(e=>e.name),error:this.errorInterceptors.map(e=>e.name)}}sortByPriority(e){e.sort((t,n)=>(t.priority??100)-(n.priority??100))}}});import*as Oe from"crypto";function Fu(r,e,t,n){let s=Buffer.concat([Buffer.from(r,"utf8"),n||Buffer.alloc(0)]),i=[],o=Buffer.alloc(0);for(;Buffer.concat(i).length<e+t;)o=Oe.createHash("md5").update(Buffer.concat([o,s])).digest(),i.push(o);let a=Buffer.concat(i);return{key:a.subarray(0,e),iv:a.subarray(e,e+t)}}function Na(r,e,t){let n=s=>r==="aes"?`aes-${s*8}-cbc`:r==="des"?"des-cbc":r==="des-ede3"?"des-ede3-cbc":r;return{encrypt(s,i,o){let a=s instanceof X?s.toBuffer():Buffer.from(String(s),"utf8");if(typeof i=="string"){let c=Oe.randomBytes(8),{key:l,iv:u}=Fu(i,e,t,c),d=Oe.createCipheriv(n(e),l,u),p=Buffer.concat([d.update(a),d.final()]),m=Buffer.concat([Buffer.from("Salted__"),c,p]);return{ciphertext:new X(p),salt:new X(c),toString:f=>f?f.stringify(new X(m)):m.toString("base64")}}else{let c=i.toBuffer(),l=o?.iv&&o.iv instanceof X?o.iv.toBuffer():Buffer.alloc(t),u=Oe.createCipheriv(n(c.length),c,l);o?.padding===!1&&u.setAutoPadding(!1);let d=Buffer.concat([u.update(a),u.final()]);return{ciphertext:new X(d),toString:p=>p?p.stringify(new X(d)):d.toString("base64")}}},decrypt(s,i,o){if(typeof i=="string"){let a=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext.toBuffer(),c,l;a.subarray(0,8).toString()==="Salted__"?(l=a.subarray(8,16),c=a.subarray(16)):(l=Buffer.alloc(0),c=a);let{key:u,iv:d}=Fu(i,e,t,l),p=Oe.createDecipheriv(n(e),u,d);return new X(Buffer.concat([p.update(c),p.final()]))}else{let a=i.toBuffer(),c=o?.iv&&o.iv instanceof X?o.iv.toBuffer():Buffer.alloc(t),l=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext?s.ciphertext.toBuffer():Buffer.from(s),u=Oe.createDecipheriv(n(a.length),a,c);return o?.padding===!1&&u.setAutoPadding(!1),new X(Buffer.concat([u.update(l),u.final()]))}}}}function Nu(){let r=t=>n=>{let s=n instanceof X?n.toBuffer():Buffer.from(String(n),"utf8");return new X(Oe.createHash(t).update(s).digest())},e=t=>(n,s)=>{let i=n instanceof X?n.toBuffer():Buffer.from(String(n),"utf8"),o=s instanceof X?s.toBuffer():Buffer.from(String(s),"utf8");return new X(Oe.createHmac(t,o).update(i).digest())};return{MD5:r("md5"),SHA1:r("sha1"),SHA224:r("sha224"),SHA256:r("sha256"),SHA384:r("sha384"),SHA512:r("sha512"),SHA3:r("sha3-256"),RIPEMD160:r("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:Na("aes",32,16),DES:Na("des",8,8),TripleDES:Na("des-ede3",24,8),PBKDF2(t,n,s){let i=t instanceof X?t.toBuffer():Buffer.from(String(t),"utf8"),o=n instanceof X?n.toBuffer():Buffer.from(String(n),"utf8"),a=(s?.keySize||4)*4,c=s?.iterations||1;return new X(Oe.pbkdf2Sync(i,o,c,a,"sha1"))},enc:{Base64:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("base64"),parse:t=>X.fromBase64(t)},Utf8:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("utf8"),parse:t=>X.fromUtf8(t)},Hex:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("hex"),parse:t=>X.fromHex(t)},Latin1:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("latin1"),parse:t=>new X(Buffer.from(t,"latin1"))},Utf16:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).toString("utf16le"),parse:t=>new X(Buffer.from(t,"utf16le"))},Utf16BE:{stringify:t=>(t instanceof X?t.toBuffer():Buffer.from(String(t))).swap16().toString("utf16le"),parse:t=>new X(Buffer.from(t,"utf16le").swap16())}},lib:{WordArray:{create:t=>t?typeof t=="string"?new X(Buffer.from(t,"utf8")):Buffer.isBuffer(t)?new X(t):new X(Buffer.from(String(t))):new X(Buffer.alloc(0)),random:t=>new X(Oe.randomBytes(t))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var X,_u=E(()=>{"use strict";X=class r{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new r(Buffer.from(e,"hex"))}static fromBase64(e){return new r(Buffer.from(e,"base64"))}static fromUtf8(e){return new r(Buffer.from(e,"utf8"))}}});import*as Wm from"crypto";import*as En from"fs";import{createRequire as Km}from"module";import*as ht from"path";import{v4 as Qm}from"uuid";function Ai(){return{format:(r,e)=>{let t=r?new Date(r):new Date;return e==="YYYY-MM-DD"?t.toISOString().split("T")[0]:t.toISOString()},unix:()=>Math.floor(Date.now()/1e3),utc:()=>{let r=new Date;return{format:()=>r.toISOString(),toISOString:()=>r.toISOString()}},__isShim:!0,__warning:"This is a lightweight shim. For full features, install moment.js via modules/package.json"}}function Zm(){return{get:(r,e,t)=>{let n=e.split("."),s=r;for(let i of n)if(s=s?.[i],s===void 0)return t;return s},set:(r,e,t)=>{let n=e.split("."),s=r;for(let i=0;i<n.length-1;i++)s[n[i]]||(s[n[i]]={}),s=s[n[i]];return s[n[n.length-1]]=t,r},cloneDeep:r=>JSON.parse(JSON.stringify(r)),keys:r=>Object.keys(r??{}),values:r=>Object.values(r??{}),entries:r=>Object.entries(r??{}),each(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},forEach(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},map:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).map(t=>e(t)),filter:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).filter(t=>e(t)),find:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).find(t=>e(t)),reduce:(r,e,t)=>(Array.isArray(r)?r:Object.values(r??{})).reduce((n,s)=>e(n,s),t),includes:(r,e)=>Array.isArray(r)?r.includes(e):Object.values(r??{}).includes(e),isObject:r=>r!==null&&typeof r=="object"&&!Array.isArray(r),isArray:r=>Array.isArray(r),isString:r=>typeof r=="string",isNumber:r=>typeof r=="number",isFunction:r=>typeof r=="function",isNil:r=>r==null,isEmpty:r=>r==null?!0:Array.isArray(r)||typeof r=="string"?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1,assign:(r,...e)=>Object.assign(r,...e),merge:(r,...e)=>{let t={...r};for(let n of e)for(let[s,i]of Object.entries(n??{}))t[s]=i&&typeof i=="object"&&!Array.isArray(i)?{...t[s]??{},...i}:i;return t},omit:(r,e)=>{let t={...r};for(let n of e)delete t[n];return t},pick:(r,e)=>{let t={};for(let n of e)n in(r??{})&&(t[n]=r[n]);return t}}}function _a(r,e){return new qi(r,e)}var qi,Ma=E(()=>{"use strict";qi=class{availableModules=new Set;customModulesRequire;globalSetupExports;options;modulesPath=null;moduleCache=new Map;resolveStack=new Set;builtinModules={uuid:()=>({v4:Qm}),crypto:()=>Wm,path:()=>ht,querystring:()=>le("querystring"),lodash:()=>this.loadOptionalModule("lodash",()=>le("lodash"),Zm),moment:()=>this.loadOptionalModule("moment",()=>le("moment"),Ai),tv4:()=>this.loadOptionalModule("tv4",()=>le("tv4")),ajv:()=>this.loadOptionalModule("ajv",()=>le("ajv")),"crypto-js":()=>this.loadOptionalModule("crypto-js",()=>le("crypto-js"),()=>{throw new Error('crypto-js npm module is not installed. The built-in CryptoJS global is already available in scripts with AES/DES/TripleDES/hash/HMAC/PBKDF2 support. If you need the exact npm package, add "crypto-js" to your modules/package.json and run npm install.')})};constructor(e=[],t={}){this.options={allowCustomModules:!0,maxResolveDepth:10,...t,outputChannel:t.outputChannel||{appendLine:n=>{console.log(`[ModuleLoader] ${n}`)}}};for(let n of e){let s=ht.resolve(n);if(this.initializeModules(s)){this.modulesPath=s;break}}}loadOptionalModule(e,t,n){try{return t()}catch{if(this.customModulesRequire)try{return console.debug(`[ModuleLoader] ${e} not in core, trying user modules`),this.customModulesRequire(e)}catch{this.logModuleWarning(e,"user")}else this.logModuleWarning(e,"core");if(n)return console.warn(`[ModuleLoader] Using shim for ${e}. Some features may be limited.`),n();throw new Error(this.getModuleInstallInstructions(e))}}logModuleWarning(e,t){let s={moment:"Date/time manipulation",lodash:"Utility functions",tv4:"JSON Schema validation (v4)",ajv:"JSON Schema validation"}[e]||e;console.warn(`[ModuleLoader] ${s} functionality (${e}) is not available.
|
|
215
215
|
${this.getModuleInstallInstructions(e)}`)}getModuleInstallInstructions(e){let n={moment:"^2.30.1",lodash:"^4.17.21",tv4:"^1.3.0",ajv:"^8.17.1"}[e]||"latest";return`To use ${e}, add it to http-forge/modules/package.json:
|
|
216
216
|
{
|
|
217
217
|
"dependencies": {
|
|
@@ -233,14 +233,14 @@ ${s}
|
|
|
233
233
|
|
|
234
234
|
// --- Next Script ---
|
|
235
235
|
|
|
236
|
-
`)}function cs(r,e){return JSON.stringify(r)!==JSON.stringify(e)}function sr(r){return r.map(e=>{let t=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${t}`})}function ja(r){let e=[],t=(n,s)=>{try{let i=s();if(i&&typeof i.then=="function"){let o=i.then(()=>{r.push({name:n,passed:!0})},a=>{r.push({name:n,passed:!1,message:a.message||String(a)})});e.push(o)}else r.push({name:n,passed:!0})}catch(i){r.push({name:n,passed:!1,message:i.message})}};return t.skip=(n,s)=>{r.push({name:n,passed:!0,skipped:!0})},t.fail=n=>{r.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},t.index=()=>r.length,t._pendingTests=e,t}function La(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Array.isArray(n)?n.join(", "):n;return e}function Ti(r,e,t){let n;if(t)try{n=new URL(t).hostname}catch{n=void 0}let s=ne.parseCookieHeaders(r||{},n);return s.length>0?s:Array.isArray(e)&&e.length>0?e.filter(i=>i&&i.name).map(i=>({name:i.name,value:i.value,domain:i.domain??n,path:i.path,expires:i.expires,maxAge:i.maxAge,httpOnly:i.httpOnly,secure:i.secure,sameSite:i.sameSite})):[]}var ls=E(()=>{"use strict";bn()});import*as Ha from"vm";var us,Ba=E(()=>{"use strict";Du();Hu();as();ls();us=class{constructor(e,t){this.deps=e;this.initialContext=t;this.timerRegistry=Mu(n=>{let s=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${s}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,t={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,t,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,t=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let s;try{s=new URL(e.request.url).hostname}catch{}let i={get:a=>e.cookieJar?e.cookieJar.get(a,s)?.value:void 0,set:(a,c)=>{e.cookieJar&&e.cookieJar.set({name:a,value:c,domain:s})},has:a=>e.cookieJar?e.cookieJar.has(a,s):!1,list:()=>e.cookieJar?e.cookieJar.getAll(s).map(a=>({name:a.name,value:a.value})):[],toObject:()=>{if(!e.cookieJar)return{};let a=e.cookieJar.getAll(s),c={};for(let l of a)c[l.name]=l.value;return c},jar:()=>{let a=e.cookieJar,c=l=>{if(l==null)return;let u=typeof l=="string"?l:typeof l=="object"||typeof l=="number"||typeof l=="boolean"?String(l):void 0;if(!u)return;let d=u.trim();if(d)try{return new URL(d).hostname}catch{return d}};return{getAll(l,u){try{if(!a){u(null,[]);return}let d=c(l),p=a.getAll(d).map(m=>({name:m.name,value:m.value,domain:m.domain,path:m.path,httpOnly:m.httpOnly,secure:m.secure}));u(null,p)}catch(d){u(d,[])}},get(l,u,d){try{if(!a){d(null,void 0);return}let p=c(l),m=a.get(u,p);d(null,m?{name:m.name,value:m.value,domain:m.domain}:void 0)}catch(p){d(p,void 0)}},set(l,u,d,p){try{if(!a){(p||d)?.(null);return}let m=c(l);typeof u=="string"&&typeof d=="string"?(a.set({name:u,value:d,domain:m}),p?.(null)):typeof u=="object"&&(a.set({...u,domain:m}),d?.(null))}catch(m){(p||d)?.(m)}},unset(l,u,d){try{if(!a){d?.(null);return}let p=c(l);a.delete(u,p),d?.(null)}catch(p){d?.(p)}},clear(l,u){try{let d=typeof l=="function"?l:u;if(!a){d?.(null);return}let p=typeof l=="function"?void 0:c(l);p&&typeof a.clearDomain=="function"?a.clearDomain(p):a.clear(),d?.(null)}catch(d){(typeof l=="function"?l:u)?.(d)}}}},remove:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},unset:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:Da(t,e),response:null,test:ja(this.assertions),expect:rr,cookies:i,execution:{setNextRequest(a){o._nextRequest=a},skipRequest(){o._skipRequest=!0},runRequest(a,c){let u=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let d=typeof a=="string"?{url:a,method:"GET"}:a,p=await n.sendRequest(d),m=Array.isArray(p?.cookies)?p.cookies.filter(g=>g?.name):[],f=p?.body,h=0;if(typeof f=="string")h=Buffer.byteLength(f,"utf8");else if(Buffer.isBuffer(f))h=f.length;else if(f!=null)try{h=Buffer.byteLength(JSON.stringify(f),"utf8")}catch{}return ki({executedRequest:null,status:p?.status??0,statusText:p?.statusText??"",headers:p?.headers??{},body:f,cookies:m,responseTime:p?.time,responseSize:h})})();if(typeof c=="function"){u.then(d=>c(null,d),d=>c(d));return}return u},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(a){o._nextRequest=a},visualizer:{set(a,c){o._visualizerData={template:a,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}injectLegacyGlobals(e,t){let n=this.vmContext;if(!n)return;let s=this.initialContext,i=e==="test"&&t?.executedRequest?t.executedRequest:this.modifiedRequest,o={};for(let[m,f]of Object.entries(i?.headers||{}))typeof f=="string"&&(o[m]=f);let a=i?.body,c=a==null?null:typeof a=="object"&&"content"in a?a.content:a,l=s.request;if(n.request={id:l?.id??"",name:l?.name??"",description:l?.description??"",url:typeof i?.url=="string"?i.url:String(i?.url??""),method:i?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...s.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!t)return;let u=t.body;n.responseBody=u==null?"":typeof u=="string"?u:JSON.stringify(u);let d=t.statusText||"";n.responseCode={code:t.status,name:d,detail:d},n.responseHeaders={...t.headers||{}},n.responseTime=t.responseTime??0,n.responseCookies=(t.cookies||[]).map(m=>({...m}));let p=this;n.tests=new Proxy({},{set(m,f,h){return p.assertions.push({name:String(f),passed:!!h,message:h?void 0:`"${String(f)}" was false`}),!0}})}async executePreRequest(e){let t=Ii(e,this.deps.isolateScripts);if(!t||!t.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(t),s=this.deps.scriptTimeoutMs??5e3,i=Ha.runInContext(n,this.vmContext,{timeout:s});this.deps.isolateScripts&&i&&typeof i.then=="function"&&await i,(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let a=sr(this.consoleMessages),c=this.initialContext.request.body,l=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:cs(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:l?this.modifiedRequest.body:void 0,params:cs(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:cs(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:a.length>0?a:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let s=[...sr(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,t){let n=Ii(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=ki(t),this.ctx.request=Da(t.executedRequest,this.initialContext),this.injectLegacyGlobals("test",t);let s=this.ctx.variables.replaceIn(n),i=this.deps.scriptTimeoutMs??5e3,o=Ha.runInContext(s,this.vmContext,{timeout:i});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let c=sr(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(s){this.assertions.push({name:"Script Execution",passed:!1,message:s.message||"Script execution failed"});let i=[...sr(this.consoleMessages),`[error] Script execution failed: ${s.message}`];return{testResults:[...this.assertions],consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,t){return e===t||!e&&!t?!0:!e||!t?!1:e.type===t.type&&e.format===t.format&&JSON.stringify(e.content)===JSON.stringify(t.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});function Uu(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function nh(r,e){if(r==="@")return"";if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=r.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(t){let n=ss(t[2],e),s=xn(t[1],n);return s!==null?s:void 0}if(e[r]!==void 0)return Uu(e[r]);if(wn(r)){let n=tr(r,e),s=Pt(r,n);if(s!==void 0)return s}}var Bu,Oi,Vu=E(()=>{"use strict";Fa();es();Ei();nr();Bu="";Oi=class{serializeValue(e){return typeof e=="string"?e:e===void 0?Bu+"undefined":Bu+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{}}return e}}createVariableScope(e){return{get:t=>this.deserializeValue(e[t]),set:(t,n)=>{e[t]=this.serializeValue(n)},has(t){return t in e},unset(t){delete e[t]},clear(){Object.keys(e).forEach(t=>delete e[t])},toObject(){return{...e}}}}createGlobalsScope(e,t){let n=(s,i,o)=>{t&&t(s,i,o)};return{get:s=>this.deserializeValue(e[s]),set:(s,i)=>{let o=this.serializeValue(i);e[s]=o,n("set",s,o)},has(s){return s in e},unset(s){delete e[s],n("unset",s)},clear(){Object.keys(e).forEach(s=>delete e[s]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,t,n,s,i={}){let o={get:a=>a in e?this.deserializeValue(e[a]):a in i?i[a]:a in t?this.deserializeValue(t[a]):a in n?this.deserializeValue(n[a]):this.deserializeValue(s[a]),set:(a,c)=>{e[a]=this.serializeValue(c)},has(a){return a in e||a in i||a in t||a in t||a in n||a in s},unset(a){delete e[a]},clear(){Object.keys(e).forEach(a=>delete e[a])},toObject(){return{...s,...n,...t,...i,...e}},toLocalObject(){return{...n,...t,...i,...e}},replaceIn(a){if(!a||typeof a!="string")return a;let c=o.toObject(),l=20,u=p=>p.replace(/\{\{([^}]+)\}\}/g,(m,f)=>{let h=f.trim(),g=h.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(g)try{let v=ss(g[2],c),w=xn(g[1],v);return w!==null?String(w):m}catch{return m}let y=ns(h);if(y){let v=nh(y.input,c);if(v!==void 0){let w=rs(v,y.filters,c);return w!==void 0?String(w):m}return m}if(o.has(h)){let v=o.get(h);return v===void 0?"":String(v)}if(wn(h)){let v={};for(let[C,R]of Object.entries(c))v[C]=Uu(R);let w=tr(h,v),b=Pt(h,w);if(b!==void 0)return String(b)}return m}),d=a;for(let p=0;p<l;p++){let m=u(d);if(m===d)break;d=m}return d}};return o}createEnvironmentScope(e,t,n,s){let i=(o,a,c)=>{n&&(s?n(o,a,c):n(a||"",o==="set"?c:void 0))};return{name:t||"",get:o=>this.deserializeValue(e[o]),set:(o,a)=>{let c=this.serializeValue(a);e[o]=c,i("set",o,c)},has(o){return o in e},unset(o){delete e[o],i("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),i("clear")},toObject(){return{...e}}}}}});import*as rh from"crypto";import*as sh from"querystring";import*as zu from"vm";var Nt,ds=E(()=>{"use strict";_u();Ma();Ba();as();Vu();Nt=class{constructor(e,t=[],n,s="shared",i=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=s;this.scriptTimeoutMs=i;this.moduleLoader=_a(t)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;variableScopes=new Oi;createRequestSession(e){return new us({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,t,n){let s=this.moduleLoader.getGlobalSetupExports(),i=this.moduleLoader.createRequireFunction();e.require=i,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:t,...s||{},global:s,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:a=>Buffer.from(a,"base64").toString("binary"),btoa:a=>Buffer.from(a,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:rh,_:i("lodash"),require:i,moment:Ai(),querystring:sh,CryptoJS:Nu(),tv4:(()=>{try{return i("tv4")}catch{return}})(),postman:{setNextRequest:a=>e.setNextRequest?.(a),setGlobalVariable:(a,c)=>e.globals?.set(a,c),getGlobalVariable:a=>e.globals?.get(a),clearGlobalVariable:a=>e.globals?.unset(a),setEnvironmentVariable:(a,c)=>e.environment?.set(a,c),getEnvironmentVariable:a=>e.environment?.get(a),clearEnvironmentVariable:a=>e.environment?.unset(a),getResponseHeader:a=>{let c=e.response?.headers?.get?.(a);return c===void 0?null:c},getResponseCookie:a=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let l of c)if(l?.name&&l.name.toLowerCase()===a.toLowerCase())return{...l}}return null}},jsonStringify:(a,c,l)=>JSON.stringify(a,c,l),jsonParse:a=>JSON.parse(a),xml2Json:a=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),l;return c.parseString(a,{explicitArray:!1},(u,d)=>{if(u)throw u;l=d}),l}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return zu.createContext(o)}createCommonContext(e,t){let n={...e.variables},s={...e.collectionVariables||{}},i={...e.globals||{}},o={...e.environmentVariables||{}},a=e.iterationData||{},c=this.variableScopes.createMergedVariableScope(n,o,s,i,a),l=this.variableScopes.createGlobalsScope(i,e.onGlobalsChange),u=this.variableScopes.createVariableScope(s),d=this.variableScopes.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),p={...d,set:(h,g)=>{let y=this.variableScopes.serializeValue(g);d.set(h,y),n[h]=y},unset(h){d.unset(h),delete n[h]},clear(){let h=Object.keys(o);d.clear();for(let g of h)delete n[g]}},m={...l,set:(h,g)=>{let y=this.variableScopes.serializeValue(g);l.set(h,y),n[h]=y},unset(h){l.unset(h),delete n[h]},clear(){let h=Object.keys(i);l.clear();for(let g of h)delete n[g]}};return m.replaceIn=c.replaceIn,u.replaceIn=c.replaceIn,p.replaceIn=c.replaceIn,{globals:m,collectionVariables:u,variables:c,environment:p,iterationData:{get:h=>a[h],has:h=>h in a,toObject:()=>({...a}),toJSON:()=>JSON.stringify(a)},sendRequest:this.createSendRequest(),expect:rr,info:e.info||{eventName:t,requestName:void 0,requestId:void 0}}}createVault(){let e=this.secretRegistry,t=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let s=`secret:${n}`;return(await e.resolveSecretTokens(`{{${s}}}`))[s]},set:t,unset:t}}createSendRequest(){return this.httpService?(e,t)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,s=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(t){s.then(i=>t(null,i)).catch(i=>t(i,null));return}return s}:(e,t)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(t){t(n,null);return}return Promise.reject(n)}}}});function Ua(r){return r?String(r).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}function $i(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Ua(String(n));return e}var Va=E(()=>{"use strict"});import*as Ju from"fs";import*as Ga from"http";import*as hs from"https";import*as za from"net";import*as Fi from"path";import*as Gu from"tls";import{URL as ms}from"url";import*as Ni from"zlib";var Ja,An,_i=E(()=>{"use strict";Va();Ja={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},An=class{resolveDefaults;resolveProxy;version;basePath;constructor(e,t=process.cwd(),n){if(typeof e=="function")this.resolveDefaults=()=>({...Ja,...e()??{}});else{let s={...Ja,...e};this.resolveDefaults=()=>s}this.basePath=t,typeof n=="function"?this.resolveProxy=n:this.resolveProxy=()=>n;try{this.version=ce("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}}get settings(){return this.resolveDefaults()}async send(e){let t=this.mergeSettings(e.settings);return await this.executeInternal(e,t,0)}mergeSettings(e){let t=this.settings;return{timeout:e?.timeout??t.timeout,followRedirects:e?.followRedirects??t.followRedirects,followOriginalMethod:e?.followOriginalMethod??t.followOriginalMethod,followAuthHeader:e?.followAuthHeader??t.followAuthHeader,maxRedirects:e?.maxRedirects??t.maxRedirects,strictSSL:e?.strictSSL??t.strictSSL,decompress:e?.decompress??t.decompress,includeCookies:e?.includeCookies??t.includeCookies,tls:e?.tls??t.tls??{},certificates:e?.certificates??t.certificates??[]}}async executeInternal(e,t,n,s){let i=Date.now(),o=new ms(e.url),a=o.protocol==="https:",c=$i(e.headers||{});Object.keys(c).some(g=>g.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let u={hostname:o.hostname,port:o.port||(a?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:t.timeout||void 0},d;if(e.body!==void 0&&e.body!==null){typeof e.body=="string"||e.body instanceof Buffer?d=e.body:e.body instanceof URLSearchParams?d=e.body.toString():typeof e.body=="object"?d=JSON.stringify(e.body):d=String(e.body);let g=u.headers;!Object.keys(g).some(v=>v.toLowerCase()==="content-length")&&d!==void 0&&(g["Content-Length"]=Buffer.byteLength(d).toString())}t.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(u.headers["Accept-Encoding"]="gzip, deflate");let p=this.resolveProxy(),m=p&&p.enabled!==!1,f=o.hostname,h=o.port?parseInt(o.port,10):a?443:80;if(a){let g=this.resolveTlsSettings(o,t),y=u;y.rejectUnauthorized=t.strictSSL;let v={rejectUnauthorized:t.strictSSL},w=this.readOptionalFile(g.caPath,"CA certificate");w&&(v.ca=w);let b=this.readOptionalFile(g.certPath,"client certificate");b&&(v.cert=b);let C=this.readOptionalFile(g.keyPath,"client private key");C&&(v.key=C);let R=this.readOptionalFile(g.pfxPath,"client pfx");R&&(v.pfx=R),g.passphrase&&(v.passphrase=g.passphrase),g.servername&&(y.servername=g.servername),m&&(p.https||p.http)?y.agent=this.buildHttpsProxyAgent(p.https||p.http,f,h,v):y.agent=new hs.Agent(v)}else if(m&&p.http){let g=new ms(p.http);u.hostname=g.hostname,u.port=g.port||80,u.path=o.toString(),u.agent=this.buildHttpProxyAgent(p.http,f,h)}if(m&&p.bypass?.length&&p.bypass.some(y=>this.hostMatchesBypass(f,y)))if(u.hostname=o.hostname,u.port=o.port||(a?443:80),u.path=o.pathname+o.search,!a)delete u.agent;else{let y=this.resolveTlsSettings(o,t),v={rejectUnauthorized:t.strictSSL},w=this.readOptionalFile(y.caPath,"CA certificate");w&&(v.ca=w),u.agent=new hs.Agent(v)}return new Promise((g,y)=>{if(s?.aborted){let b=new Error("Request cancelled");b.name="AbortError",y(b);return}let w=(a?hs:Ga).request(u,async b=>{let C=b.statusCode||0;if(t.followRedirects&&[301,302,303,307,308].includes(C)){if(n>=t.maxRedirects){y(new Error(`Maximum redirects (${t.maxRedirects}) exceeded`));return}let A=b.headers.location;if(!A){y(new Error("Redirect response missing Location header"));return}let F=new ms(A,e.url).toString(),_=e.method;!t.followOriginalMethod&&[301,302,303].includes(C)&&(_="GET");let D={...e.headers};t.followAuthHeader||(delete D.authorization,delete D.Authorization);try{let B=await this.executeInternal({...e,url:F,method:_,headers:D,body:_==="GET"?void 0:e.body},t,n+1,s),T=Date.now();B.time=T-i,g(B)}catch(B){y(B)}return}let R=[];b.on("data",A=>R.push(A)),b.on("end",()=>{let A=Date.now(),F=Buffer.concat(R),_=b.headers["content-encoding"];if(t.decompress&&_)try{_==="gzip"?F=Ni.gunzipSync(F):_==="deflate"&&(F=Ni.inflateSync(F))}catch(j){console.warn("[NodeHttpClient] Decompression failed:",j)}let D=F.toString("utf-8"),B={};for(let[j,W]of Object.entries(b.headers))(typeof W=="string"||Array.isArray(W))&&(B[j]=W);let T=this.parseCookies(b.headers["set-cookie"],o.hostname);g({status:b.statusCode||0,statusText:b.statusMessage||"",headers:B,cookies:T,body:D,time:A-i,size:F.length})})});s&&s.addEventListener("abort",()=>{w.destroy();let b=new Error("Request cancelled");b.name="AbortError",y(b)}),w.on("error",b=>{y(b)}),w.on("timeout",()=>{w.destroy(),y(new Error("Request timeout"))}),d!==void 0&&w.write(d),w.end()})}buildHttpProxyAgent(e,t,n){let s=new ms(e),i=s.hostname,o=parseInt(s.port||"8080",10),a=new Ga.Agent;return a.createConnection=(c,l)=>za.createConnection({host:i,port:o},l),a}buildHttpsProxyAgent(e,t,n,s){let i=new ms(e),o=i.hostname,a=parseInt(i.port||"8080",10),c=i.username?"Basic "+Buffer.from(`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`).toString("base64"):void 0,l=new hs.Agent(s);return l.createConnection=(u,d)=>{let p=za.createConnection({host:o,port:a});p.once("connect",()=>{let m=[`CONNECT ${t}:${n} HTTP/1.1`,`Host: ${t}:${n}`];c&&m.push(`Proxy-Authorization: ${c}`),p.write(m.join(`\r
|
|
236
|
+
`)}function cs(r,e){return JSON.stringify(r)!==JSON.stringify(e)}function sr(r){return r.map(e=>{let t=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${t}`})}function ja(r){let e=[],t=(n,s)=>{try{let i=s();if(i&&typeof i.then=="function"){let o=i.then(()=>{r.push({name:n,passed:!0})},a=>{r.push({name:n,passed:!1,message:a.message||String(a)})});e.push(o)}else r.push({name:n,passed:!0})}catch(i){r.push({name:n,passed:!1,message:i.message})}};return t.skip=(n,s)=>{r.push({name:n,passed:!0,skipped:!0})},t.fail=n=>{r.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},t.index=()=>r.length,t._pendingTests=e,t}function La(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Array.isArray(n)?n.join(", "):n;return e}function Ti(r,e,t){let n;if(t)try{n=new URL(t).hostname}catch{n=void 0}let s=ne.parseCookieHeaders(r||{},n);return s.length>0?s:Array.isArray(e)&&e.length>0?e.filter(i=>i&&i.name).map(i=>({name:i.name,value:i.value,domain:i.domain??n,path:i.path,expires:i.expires,maxAge:i.maxAge,httpOnly:i.httpOnly,secure:i.secure,sameSite:i.sameSite})):[]}var ls=E(()=>{"use strict";bn()});import*as Ha from"vm";var us,Ba=E(()=>{"use strict";Du();Hu();as();ls();us=class{constructor(e,t){this.deps=e;this.initialContext=t;this.timerRegistry=Mu(n=>{let s=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${s}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,t={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,t,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,t=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let s;try{s=new URL(e.request.url).hostname}catch{}let i={get:a=>e.cookieJar?e.cookieJar.get(a,s)?.value:void 0,set:(a,c)=>{e.cookieJar&&e.cookieJar.set({name:a,value:c,domain:s})},has:a=>e.cookieJar?e.cookieJar.has(a,s):!1,list:()=>e.cookieJar?e.cookieJar.getAll(s).map(a=>({name:a.name,value:a.value})):[],toObject:()=>{if(!e.cookieJar)return{};let a=e.cookieJar.getAll(s),c={};for(let l of a)c[l.name]=l.value;return c},jar:()=>{let a=e.cookieJar,c=l=>{if(l==null)return;let u=typeof l=="string"?l:typeof l=="object"||typeof l=="number"||typeof l=="boolean"?String(l):void 0;if(!u)return;let d=u.trim();if(d)try{return new URL(d).hostname}catch{return d}};return{getAll(l,u){try{if(!a){u(null,[]);return}let d=c(l),p=a.getAll(d).map(m=>({name:m.name,value:m.value,domain:m.domain,path:m.path,httpOnly:m.httpOnly,secure:m.secure}));u(null,p)}catch(d){u(d,[])}},get(l,u,d){try{if(!a){d(null,void 0);return}let p=c(l),m=a.get(u,p);d(null,m?{name:m.name,value:m.value,domain:m.domain}:void 0)}catch(p){d(p,void 0)}},set(l,u,d,p){try{if(!a){(p||d)?.(null);return}let m=c(l);typeof u=="string"&&typeof d=="string"?(a.set({name:u,value:d,domain:m}),p?.(null)):typeof u=="object"&&(a.set({...u,domain:m}),d?.(null))}catch(m){(p||d)?.(m)}},unset(l,u,d){try{if(!a){d?.(null);return}let p=c(l);a.delete(u,p),d?.(null)}catch(p){d?.(p)}},clear(l,u){try{let d=typeof l=="function"?l:u;if(!a){d?.(null);return}let p=typeof l=="function"?void 0:c(l);p&&typeof a.clearDomain=="function"?a.clearDomain(p):a.clear(),d?.(null)}catch(d){(typeof l=="function"?l:u)?.(d)}}}},remove:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},unset:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:Da(t,e),response:null,test:ja(this.assertions),expect:rr,cookies:i,execution:{setNextRequest(a){o._nextRequest=a},skipRequest(){o._skipRequest=!0},runRequest(a,c){let u=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let d=typeof a=="string"?{url:a,method:"GET"}:a,p=await n.sendRequest(d),m=Array.isArray(p?.cookies)?p.cookies.filter(g=>g?.name):[],f=p?.body,h=0;if(typeof f=="string")h=Buffer.byteLength(f,"utf8");else if(Buffer.isBuffer(f))h=f.length;else if(f!=null)try{h=Buffer.byteLength(JSON.stringify(f),"utf8")}catch{}return ki({executedRequest:null,status:p?.status??0,statusText:p?.statusText??"",headers:p?.headers??{},body:f,cookies:m,responseTime:p?.time,responseSize:h})})();if(typeof c=="function"){u.then(d=>c(null,d),d=>c(d));return}return u},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(a){o._nextRequest=a},visualizer:{set(a,c){o._visualizerData={template:a,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}injectLegacyGlobals(e,t){let n=this.vmContext;if(!n)return;let s=this.initialContext,i=e==="test"&&t?.executedRequest?t.executedRequest:this.modifiedRequest,o={};for(let[m,f]of Object.entries(i?.headers||{}))typeof f=="string"&&(o[m]=f);let a=i?.body,c=a==null?null:typeof a=="object"&&"content"in a?a.content:a,l=s.request;if(n.request={id:l?.id??"",name:l?.name??"",description:l?.description??"",url:typeof i?.url=="string"?i.url:String(i?.url??""),method:i?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...s.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!t)return;let u=t.body;n.responseBody=u==null?"":typeof u=="string"?u:JSON.stringify(u);let d=t.statusText||"";n.responseCode={code:t.status,name:d,detail:d},n.responseHeaders={...t.headers||{}},n.responseTime=t.responseTime??0,n.responseCookies=(t.cookies||[]).map(m=>({...m}));let p=this;n.tests=new Proxy({},{set(m,f,h){return p.assertions.push({name:String(f),passed:!!h,message:h?void 0:`"${String(f)}" was false`}),!0}})}async executePreRequest(e){let t=Ii(e,this.deps.isolateScripts);if(!t||!t.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(t),s=this.deps.scriptTimeoutMs??5e3,i=Ha.runInContext(n,this.vmContext,{timeout:s});this.deps.isolateScripts&&i&&typeof i.then=="function"&&await i,(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let a=sr(this.consoleMessages),c=this.initialContext.request.body,l=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:cs(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:l?this.modifiedRequest.body:void 0,params:cs(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:cs(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:a.length>0?a:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let s=[...sr(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,t){let n=Ii(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=ki(t),this.ctx.request=Da(t.executedRequest,this.initialContext),this.injectLegacyGlobals("test",t);let s=this.ctx.variables.replaceIn(n),i=this.deps.scriptTimeoutMs??5e3,o=Ha.runInContext(s,this.vmContext,{timeout:i});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let c=sr(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(s){this.assertions.push({name:"Script Execution",passed:!1,message:s.message||"Script execution failed"});let i=[...sr(this.consoleMessages),`[error] Script execution failed: ${s.message}`];return{testResults:[...this.assertions],consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,t){return e===t||!e&&!t?!0:!e||!t?!1:e.type===t.type&&e.format===t.format&&JSON.stringify(e.content)===JSON.stringify(t.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});function Uu(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function nh(r,e){if(r==="@")return"";if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=r.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(t){let n=ss(t[2],e),s=xn(t[1],n);return s!==null?s:void 0}if(e[r]!==void 0)return Uu(e[r]);if(wn(r)){let n=tr(r,e),s=Pt(r,n);if(s!==void 0)return s}}var Bu,Oi,Vu=E(()=>{"use strict";Fa();es();Ei();nr();Bu="";Oi=class{serializeValue(e){return typeof e=="string"?e:e===void 0?Bu+"undefined":Bu+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{}}return e}}createVariableScope(e){return{get:t=>this.deserializeValue(e[t]),set:(t,n)=>{e[t]=this.serializeValue(n)},has(t){return t in e},unset(t){delete e[t]},clear(){Object.keys(e).forEach(t=>delete e[t])},toObject(){return{...e}}}}createGlobalsScope(e,t){let n=(s,i,o)=>{t&&t(s,i,o)};return{get:s=>this.deserializeValue(e[s]),set:(s,i)=>{let o=this.serializeValue(i);e[s]=o,n("set",s,o)},has(s){return s in e},unset(s){delete e[s],n("unset",s)},clear(){Object.keys(e).forEach(s=>delete e[s]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,t,n,s,i={}){let o={get:a=>a in e?this.deserializeValue(e[a]):a in i?i[a]:a in t?this.deserializeValue(t[a]):a in n?this.deserializeValue(n[a]):this.deserializeValue(s[a]),set:(a,c)=>{e[a]=this.serializeValue(c)},has(a){return a in e||a in i||a in t||a in t||a in n||a in s},unset(a){delete e[a]},clear(){Object.keys(e).forEach(a=>delete e[a])},toObject(){return{...s,...n,...t,...i,...e}},toLocalObject(){return{...n,...t,...i,...e}},replaceIn(a){if(!a||typeof a!="string")return a;let c=o.toObject(),l=20,u=p=>p.replace(/\{\{([^}]+)\}\}/g,(m,f)=>{let h=f.trim(),g=h.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(g)try{let v=ss(g[2],c),w=xn(g[1],v);return w!==null?String(w):m}catch{return m}let y=ns(h);if(y){let v=nh(y.input,c);if(v!==void 0){let w=rs(v,y.filters,c);return w!==void 0?String(w):m}return m}if(o.has(h)){let v=o.get(h);return v===void 0?"":String(v)}if(wn(h)){let v={};for(let[C,R]of Object.entries(c))v[C]=Uu(R);let w=tr(h,v),b=Pt(h,w);if(b!==void 0)return String(b)}return m}),d=a;for(let p=0;p<l;p++){let m=u(d);if(m===d)break;d=m}return d}};return o}createEnvironmentScope(e,t,n,s){let i=(o,a,c)=>{n&&(s?n(o,a,c):n(a||"",o==="set"?c:void 0))};return{name:t||"",get:o=>this.deserializeValue(e[o]),set:(o,a)=>{let c=this.serializeValue(a);e[o]=c,i("set",o,c)},has(o){return o in e},unset(o){delete e[o],i("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),i("clear")},toObject(){return{...e}}}}}});import*as rh from"crypto";import*as sh from"querystring";import*as zu from"vm";var Nt,ds=E(()=>{"use strict";_u();Ma();Ba();as();Vu();Nt=class{constructor(e,t=[],n,s="shared",i=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=s;this.scriptTimeoutMs=i;this.moduleLoader=_a(t)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;variableScopes=new Oi;createRequestSession(e){return new us({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,t,n){let s=this.moduleLoader.getGlobalSetupExports(),i=this.moduleLoader.createRequireFunction();e.require=i,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:t,...s||{},global:s,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:a=>Buffer.from(a,"base64").toString("binary"),btoa:a=>Buffer.from(a,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:rh,_:i("lodash"),require:i,moment:Ai(),querystring:sh,CryptoJS:Nu(),tv4:(()=>{try{return i("tv4")}catch{return}})(),postman:{setNextRequest:a=>e.setNextRequest?.(a),setGlobalVariable:(a,c)=>e.globals?.set(a,c),getGlobalVariable:a=>e.globals?.get(a),clearGlobalVariable:a=>e.globals?.unset(a),setEnvironmentVariable:(a,c)=>e.environment?.set(a,c),getEnvironmentVariable:a=>e.environment?.get(a),clearEnvironmentVariable:a=>e.environment?.unset(a),getResponseHeader:a=>{let c=e.response?.headers?.get?.(a);return c===void 0?null:c},getResponseCookie:a=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let l of c)if(l?.name&&l.name.toLowerCase()===a.toLowerCase())return{...l}}return null}},jsonStringify:(a,c,l)=>JSON.stringify(a,c,l),jsonParse:a=>JSON.parse(a),xml2Json:a=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),l;return c.parseString(a,{explicitArray:!1},(u,d)=>{if(u)throw u;l=d}),l}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return zu.createContext(o)}createCommonContext(e,t){let n={...e.variables},s={...e.collectionVariables||{}},i={...e.globals||{}},o={...e.environmentVariables||{}},a=e.iterationData||{},c=this.variableScopes.createMergedVariableScope(n,o,s,i,a),l=this.variableScopes.createGlobalsScope(i,e.onGlobalsChange),u=this.variableScopes.createVariableScope(s),d=this.variableScopes.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),p={...d,set:(h,g)=>{let y=this.variableScopes.serializeValue(g);d.set(h,y),n[h]=y},unset(h){d.unset(h),delete n[h]},clear(){let h=Object.keys(o);d.clear();for(let g of h)delete n[g]}},m={...l,set:(h,g)=>{let y=this.variableScopes.serializeValue(g);l.set(h,y),n[h]=y},unset(h){l.unset(h),delete n[h]},clear(){let h=Object.keys(i);l.clear();for(let g of h)delete n[g]}};return m.replaceIn=c.replaceIn,u.replaceIn=c.replaceIn,p.replaceIn=c.replaceIn,{globals:m,collectionVariables:u,variables:c,environment:p,iterationData:{get:h=>a[h],has:h=>h in a,toObject:()=>({...a}),toJSON:()=>JSON.stringify(a)},sendRequest:this.createSendRequest(),expect:rr,info:e.info||{eventName:t,requestName:void 0,requestId:void 0}}}createVault(){let e=this.secretRegistry,t=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let s=`secret:${n}`;return(await e.resolveSecretTokens(`{{${s}}}`))[s]},set:t,unset:t}}createSendRequest(){return this.httpService?(e,t)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,s=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(t){s.then(i=>t(null,i)).catch(i=>t(i,null));return}return s}:(e,t)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(t){t(n,null);return}return Promise.reject(n)}}}});function Ua(r){return r?String(r).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}function $i(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Ua(String(n));return e}var Va=E(()=>{"use strict"});import*as Ju from"fs";import*as Ga from"http";import*as hs from"https";import*as za from"net";import*as Fi from"path";import*as Gu from"tls";import{URL as ms}from"url";import*as Ni from"zlib";var Ja,An,_i=E(()=>{"use strict";Va();Ja={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},An=class{resolveDefaults;resolveProxy;version;basePath;constructor(e,t=process.cwd(),n){if(typeof e=="function")this.resolveDefaults=()=>({...Ja,...e()??{}});else{let s={...Ja,...e};this.resolveDefaults=()=>s}this.basePath=t,typeof n=="function"?this.resolveProxy=n:this.resolveProxy=()=>n;try{this.version=le("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}}get settings(){return this.resolveDefaults()}async send(e){let t=this.mergeSettings(e.settings);return await this.executeInternal(e,t,0)}mergeSettings(e){let t=this.settings;return{timeout:e?.timeout??t.timeout,followRedirects:e?.followRedirects??t.followRedirects,followOriginalMethod:e?.followOriginalMethod??t.followOriginalMethod,followAuthHeader:e?.followAuthHeader??t.followAuthHeader,maxRedirects:e?.maxRedirects??t.maxRedirects,strictSSL:e?.strictSSL??t.strictSSL,decompress:e?.decompress??t.decompress,includeCookies:e?.includeCookies??t.includeCookies,tls:e?.tls??t.tls??{},certificates:e?.certificates??t.certificates??[]}}async executeInternal(e,t,n,s){let i=Date.now(),o=new ms(e.url),a=o.protocol==="https:",c=$i(e.headers||{});Object.keys(c).some(g=>g.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let u={hostname:o.hostname,port:o.port||(a?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:t.timeout||void 0},d;if(e.body!==void 0&&e.body!==null){typeof e.body=="string"||e.body instanceof Buffer?d=e.body:e.body instanceof URLSearchParams?d=e.body.toString():typeof e.body=="object"?d=JSON.stringify(e.body):d=String(e.body);let g=u.headers;!Object.keys(g).some(v=>v.toLowerCase()==="content-length")&&d!==void 0&&(g["Content-Length"]=Buffer.byteLength(d).toString())}t.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(u.headers["Accept-Encoding"]="gzip, deflate");let p=this.resolveProxy(),m=p&&p.enabled!==!1,f=o.hostname,h=o.port?parseInt(o.port,10):a?443:80;if(a){let g=this.resolveTlsSettings(o,t),y=u;y.rejectUnauthorized=t.strictSSL;let v={rejectUnauthorized:t.strictSSL},w=this.readOptionalFile(g.caPath,"CA certificate");w&&(v.ca=w);let b=this.readOptionalFile(g.certPath,"client certificate");b&&(v.cert=b);let C=this.readOptionalFile(g.keyPath,"client private key");C&&(v.key=C);let R=this.readOptionalFile(g.pfxPath,"client pfx");R&&(v.pfx=R),g.passphrase&&(v.passphrase=g.passphrase),g.servername&&(y.servername=g.servername),m&&(p.https||p.http)?y.agent=this.buildHttpsProxyAgent(p.https||p.http,f,h,v):y.agent=new hs.Agent(v)}else if(m&&p.http){let g=new ms(p.http);u.hostname=g.hostname,u.port=g.port||80,u.path=o.toString(),u.agent=this.buildHttpProxyAgent(p.http,f,h)}if(m&&p.bypass?.length&&p.bypass.some(y=>this.hostMatchesBypass(f,y)))if(u.hostname=o.hostname,u.port=o.port||(a?443:80),u.path=o.pathname+o.search,!a)delete u.agent;else{let y=this.resolveTlsSettings(o,t),v={rejectUnauthorized:t.strictSSL},w=this.readOptionalFile(y.caPath,"CA certificate");w&&(v.ca=w),u.agent=new hs.Agent(v)}return new Promise((g,y)=>{if(s?.aborted){let b=new Error("Request cancelled");b.name="AbortError",y(b);return}let w=(a?hs:Ga).request(u,async b=>{let C=b.statusCode||0;if(t.followRedirects&&[301,302,303,307,308].includes(C)){if(n>=t.maxRedirects){y(new Error(`Maximum redirects (${t.maxRedirects}) exceeded`));return}let A=b.headers.location;if(!A){y(new Error("Redirect response missing Location header"));return}let F=new ms(A,e.url).toString(),_=e.method;!t.followOriginalMethod&&[301,302,303].includes(C)&&(_="GET");let D={...e.headers};t.followAuthHeader||(delete D.authorization,delete D.Authorization);try{let B=await this.executeInternal({...e,url:F,method:_,headers:D,body:_==="GET"?void 0:e.body},t,n+1,s),T=Date.now();B.time=T-i,g(B)}catch(B){y(B)}return}let R=[];b.on("data",A=>R.push(A)),b.on("end",()=>{let A=Date.now(),F=Buffer.concat(R),_=b.headers["content-encoding"];if(t.decompress&&_)try{_==="gzip"?F=Ni.gunzipSync(F):_==="deflate"&&(F=Ni.inflateSync(F))}catch(j){console.warn("[NodeHttpClient] Decompression failed:",j)}let D=F.toString("utf-8"),B={};for(let[j,W]of Object.entries(b.headers))(typeof W=="string"||Array.isArray(W))&&(B[j]=W);let T=this.parseCookies(b.headers["set-cookie"],o.hostname);g({status:b.statusCode||0,statusText:b.statusMessage||"",headers:B,cookies:T,body:D,time:A-i,size:F.length})})});s&&s.addEventListener("abort",()=>{w.destroy();let b=new Error("Request cancelled");b.name="AbortError",y(b)}),w.on("error",b=>{y(b)}),w.on("timeout",()=>{w.destroy(),y(new Error("Request timeout"))}),d!==void 0&&w.write(d),w.end()})}buildHttpProxyAgent(e,t,n){let s=new ms(e),i=s.hostname,o=parseInt(s.port||"8080",10),a=new Ga.Agent;return a.createConnection=(c,l)=>za.createConnection({host:i,port:o},l),a}buildHttpsProxyAgent(e,t,n,s){let i=new ms(e),o=i.hostname,a=parseInt(i.port||"8080",10),c=i.username?"Basic "+Buffer.from(`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`).toString("base64"):void 0,l=new hs.Agent(s);return l.createConnection=(u,d)=>{let p=za.createConnection({host:o,port:a});p.once("connect",()=>{let m=[`CONNECT ${t}:${n} HTTP/1.1`,`Host: ${t}:${n}`];c&&m.push(`Proxy-Authorization: ${c}`),p.write(m.join(`\r
|
|
237
237
|
`)+`\r
|
|
238
238
|
\r
|
|
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=Gu.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=Fi.isAbsolute(e)?e:Fi.resolve(this.basePath,e);try{return Ju.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 Wa,Pn,Mi=E(()=>{"use strict";Va();Wa={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"},Pn=class{sanitizeHeaderValue(e){return Ua(e)}sanitizeHeaders(e){return $i(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=Wa["x-www-form-urlencoded"];break;case"raw":i=t.format?Wa[t.format]:"text/plain",i||(i="text/plain");break;case"graphql":i=Wa.graphql;break;case"binary":i="application/octet-stream";break}i&&(e["Content-Type"]=i)}}});var In,Di=E(()=>{"use strict";In=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}}});import*as ar from"crypto";var oh,ys,Qa=E(()=>{"use strict";oh=3e4,ys=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||ar.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||ar.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 ar.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return ar.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,t){try{await this.secretStore.store(`oauth2_refresh_${e}`,t)}catch{}}}});import*as Tn from"fs";import*as cr from"path";function lr(r,e={}){let t=[];Object.entries(e).forEach(([n,s])=>{t.push(`${n}=${s}`)}),t.length&&Tn.writeFileSync(r,t.join(`
|
|
241
241
|
`),"utf-8")}function vs(r,e,t){t&&(t.preRequest&&t.preRequest.trim()&&Tn.writeFileSync(cr.join(r,`${e}.pre.js`),t.preRequest,"utf-8"),t.postResponse&&t.postResponse.trim()&&Tn.writeFileSync(cr.join(r,`${e}.post.js`),t.postResponse,"utf-8"))}async function ah(r,e,t,n,s){await r.exportCollectionAsRestClientFolder(t,n),e.exportEnvironmentsToFolder(n,s)}function ji(r,e,t){r.forEach(n=>{if(n.type==="folder"){let s=cr.join(e,ve(n.name));Tn.mkdirSync(s,{recursive:!0}),vs(s,ve(n.name),n.scripts),ji(n.items||[],s,t)}else if(n.type==="request"){let s=n,i=ve(s.name)+".http",o=cr.join(e,i),a=ch(s,t);Tn.writeFileSync(o,a,"utf-8"),vs(e,ve(s.name),s.scripts)}})}function ch(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=lh(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 lh(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 Li=E(()=>{"use strict";Ge()});import*as $e from"fs";import*as Za from"path";var ur,Ya=E(()=>{"use strict";Ge();Yt();ur=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e,this.ensureDirectory()}ensureDirectory(){$e.existsSync(this.collectionsDir)||$e.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!$e.existsSync(this.collectionsDir))return[];let e=$e.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=Za.join(this.collectionsDir,n),i=$e.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($e.existsSync(t))try{let n=$e.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=se(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await $e.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!$e.existsSync(t))return!1;try{return await $e.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return $e.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return Za.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||se(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=we(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?we(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=we(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=we(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=Zt(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=we(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=we(s.items,t);if(!i)return!1;let o={...i};if(!Zt(s.items,t))return!1;if(n){let a=we(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=we(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=we(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 bs,Xa=E(()=>{"use strict";bi();Ya();bs=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new Xt(n):new ur(n)}static createForFormat(e,t){return e==="folder"?new Xt(t):new ur(t)}}});import*as le from"fs";import*as gt from"path";function Wu(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 uh(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=>Ku(e)),event:ec(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function Ku(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(Ku):[],event:ec(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(dh),url:ph(e),body:fh(e),auth:mh(e.auth),description:e.description},event:ec(e.scripts),protocolProfileBehavior:hh(e.settings)}}}function dh(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 ph(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 fh(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=Wu(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||Wu(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 mh(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 hh(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 ec(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 Ss,tc=E(()=>{"use strict";Ge();Li();Xa();Yt();Ss=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=bs.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=se(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=se(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:se(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=se(t),i=this.loader.getCollectionPath(e),o=gt.join(this.collectionsDir,s);if(!le.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=gt.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:se(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&&Zt(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=we(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=gt.dirname(i),a=se(n),c=gt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=gt.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?we(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||se(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=we(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=we(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=we(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=gt.join(e,n.name),i=gt.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||se(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:se(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:se(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:se(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=uh(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=gt.join(t,ve(n.name));le.mkdirSync(s,{recursive:!0});let i=n.variables||{};lr(gt.join(s,`${ve(n.name)}.env`),i),vs(s,ve(n.name),n.scripts),ji(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var pe,On,nn,nc=E(()=>{"use strict";pe={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"}}}},On={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},nn={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});import*as fe from"fs";import*as ge from"path";var rn,Hi=E(()=>{"use strict";nc();rn=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,On.preferred);if(fe.existsSync(e))return e;let t=ge.join(this.workspacePath,On.legacy);return fe.existsSync(t)?t:e}loadConfig(){if(this.configPath=this.resolveConfigPath(),!fe.existsSync(this.configPath))return{...pe};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.`),{...pe}}}mergeWithDefaults(e){return{version:e.version??pe.version,storage:{...pe.storage,...e.storage},request:{...pe.request,...e.request},scripts:{...pe.scripts,...e.scripts},runner:{...pe.runner,...e.runner,report:{...pe.runner.report,...e.runner?.report}},environments:{...pe.environments,...e.environments},restClientExport:{...pe.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:pe.proxy,mcp:{...pe.mcp,...e.mcp,cors:{...pe.mcp.cors,...e.mcp?.cors}},secrets:{...pe.secrets,...e.secrets,providers:{...pe.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let t of[On.preferred,On.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??pe.runner.report,n=["all","failed","none"];return{...e,report:{maxBodyChars:Math.max(1e3,Math.floor(t.maxBodyChars??pe.runner.report.maxBodyChars)),embedBodies:n.includes(t.embedBodies)?t.embedBodies:pe.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??pe.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,nn.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(),nn.collections)}getEnvironmentsPath(){return ge.join(this.getRootPath(),nn.environments)}getFlowsPath(){return ge.join(this.getRootPath(),nn.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(),nn.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(pe,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 gh,xs,rc=E(()=>{"use strict";bn();gh="httpForge.cookies",xs=class{constructor(e,t=gh){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 ws,sc=E(()=>{"use strict";bn();ws=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 ic(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 oc=E(()=>{"use strict"});import*as Pe from"fs";import*as Ze from"path";var Rs,Cs,ac=E(()=>{"use strict";Ge();oc();Li();wi();nr();Rs={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},Cs=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(Rs.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||!Pe.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(!Pe.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(Rs.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`${Rs.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=hi(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");lr(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`);lr(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 Pe.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=Pe.readFileSync(e,"utf-8"),n=ic(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=Xr(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 Rn({globals:i,collectionVariables:{},environmentVariables:s,variables:{...o,...t||{}}})}saveFolderSharedConfig(e){Pe.existsSync(this.environmentsPath)||Pe.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=Pe.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!xi(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=Ze.basename(i,".json");if(!s.has(o))try{Pe.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 Rn({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(Rs.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(Rs.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);Pe.existsSync(n)||Pe.mkdirSync(n,{recursive:!0}),Pe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var _t,Es=E(()=>{"use strict";ls();_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 T=await u.executePreRequest(i);if(T.consoleOutput&&T.consoleOutput.length>0&&this.onConsoleOutput?.(T.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),T.nextRequest!==void 0&&(f=T.nextRequest),T.skipRequest){let j={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:j,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}}T.success&&(T.modifiedRequest&&(T.modifiedRequest.url&&(m.url=T.modifiedRequest.url),T.modifiedRequest.headers&&(m.headers=T.modifiedRequest.headers),T.modifiedRequest.params&&(m.params=T.modifiedRequest.params),T.modifiedRequest.query&&(m.query=T.modifiedRequest.query),T.modifiedRequest.body!==void 0&&(m.body=T.modifiedRequest.body)),(T.localVariables??T.modifiedVariables)&&(p=T.localVariables??T.modifiedVariables))}d=await this.requestPreparer.prepareRequest(m,this.environment,a,p);let{url:h,headers:g,body:y,method:v}=d,w={};for(let T in g)Object.prototype.hasOwnProperty.call(g,T)&&(w[T.toUpperCase()]=g[T]);if(!w.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let j=this.cookieJar.getCookieHeader(h);j&&(w.COOKIE=j)}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=[],F={},_;if(o.length>0){let T=0;if(C.body)if(typeof C.body=="string")T=Buffer.byteLength(C.body,"utf8");else if(Buffer.isBuffer(C.body))T=C.body.length;else try{T=Buffer.byteLength(JSON.stringify(C.body),"utf8")}catch{T=0}let j=Ti(C.headers,C.cookies,d.url),W={executedRequest:d,status:C.status,statusText:C.statusText,headers:La(C.headers||{}),body:C.body,cookies:j,responseTime:C.time,responseSize:T},Z=await u.executePostResponse(o,W);A=Z.testResults,F=Z.modifiedEnvironmentVariables||{},_=Z.visualizerData,(Z.localVariables??Z.modifiedVariables)&&(p=Z.localVariables??Z.modifiedVariables),Z.nextRequest!==void 0&&(f=Z.nextRequest),Z.consoleOutput&&Z.consoleOutput.length>0&&this.onConsoleOutput?.(Z.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let D=A.length===0||A.every(T=>T.passed),B=A.length>0?D: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:B,assertions:A,modifiedVariables:p,modifiedEnvironmentVariables:F,nextRequest:f,visualizerData:_}}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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");return`<!doctype html>
|
|
242
|
+
`)}function lh(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 Li=E(()=>{"use strict";Ge()});import*as $e from"fs";import*as Za from"path";var ur,Ya=E(()=>{"use strict";Ge();Yt();ur=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e,this.ensureDirectory()}ensureDirectory(){$e.existsSync(this.collectionsDir)||$e.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!$e.existsSync(this.collectionsDir))return[];let e=$e.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=Za.join(this.collectionsDir,n),i=$e.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($e.existsSync(t))try{let n=$e.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=se(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await $e.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!$e.existsSync(t))return!1;try{return await $e.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return $e.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return Za.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||se(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=we(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?we(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=we(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=we(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=Zt(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=we(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=we(s.items,t);if(!i)return!1;let o={...i};if(!Zt(s.items,t))return!1;if(n){let a=we(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=we(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=we(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 bs,Xa=E(()=>{"use strict";bi();Ya();bs=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new Xt(n):new ur(n)}static createForFormat(e,t){return e==="folder"?new Xt(t):new ur(t)}}});import*as ue from"fs";import*as gt from"path";function Wu(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 uh(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=>Ku(e)),event:ec(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function Ku(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(Ku):[],event:ec(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(dh),url:ph(e),body:fh(e),auth:mh(e.auth),description:e.description},event:ec(e.scripts),protocolProfileBehavior:hh(e.settings)}}}function dh(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 ph(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 fh(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=Wu(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||Wu(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 mh(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 hh(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 ec(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 Ss,tc=E(()=>{"use strict";Ge();Li();Xa();Yt();Ss=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=bs.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=se(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=se(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:se(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=se(t),i=this.loader.getCollectionPath(e),o=gt.join(this.collectionsDir,s);if(!ue.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=gt.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:se(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&&Zt(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=we(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=gt.dirname(i),a=se(n),c=gt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=gt.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?we(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||se(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=we(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=we(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=we(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=gt.join(e,n.name),i=gt.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||se(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:se(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:se(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:se(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=uh(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=gt.join(t,ve(n.name));ue.mkdirSync(s,{recursive:!0});let i=n.variables||{};lr(gt.join(s,`${ve(n.name)}.env`),i),vs(s,ve(n.name),n.scripts),ji(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var ae,On,nn,nc=E(()=>{"use strict";ae={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"}}}},On={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},nn={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});import*as fe from"fs";import*as ge from"path";var rn,Hi=E(()=>{"use strict";nc();rn=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,On.preferred);if(fe.existsSync(e))return e;let t=ge.join(this.workspacePath,On.legacy);return fe.existsSync(t)?t:e}loadConfig(){if(this.configPath=this.resolveConfigPath(),!fe.existsSync(this.configPath))return{...ae};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.`),{...ae}}}mergeWithDefaults(e){return{version:e.version??ae.version,storage:{...ae.storage,...e.storage},request:{...ae.request,...e.request},scripts:{...ae.scripts,...e.scripts},runner:{...ae.runner,...e.runner,report:{...ae.runner.report,...e.runner?.report}},environments:{...ae.environments,...e.environments},restClientExport:{...ae.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:ae.proxy,discovery:{...ae.discovery,...e.discovery},mcp:{...ae.mcp,...e.mcp,cors:{...ae.mcp.cors,...e.mcp?.cors}},secrets:{...ae.secrets,...e.secrets,providers:{...ae.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let t of[On.preferred,On.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??ae.runner.report,n=["all","failed","none"];return{...e,report:{maxBodyChars:Math.max(1e3,Math.floor(t.maxBodyChars??ae.runner.report.maxBodyChars)),embedBodies:n.includes(t.embedBodies)?t.embedBodies:ae.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??ae.discovery;return{customSeedLoaderModulePath:e.customSeedLoaderModulePath,frameworks:e.frameworks??ae.discovery.frameworks,contextProperties:e.contextProperties??ae.discovery.contextProperties,skipComponentAnalysis:e.skipComponentAnalysis??ae.discovery.skipComponentAnalysis}}getMcpConfig(){let e=this.config.mcp??ae.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,nn.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(),nn.collections)}getEnvironmentsPath(){return ge.join(this.getRootPath(),nn.environments)}getFlowsPath(){return ge.join(this.getRootPath(),nn.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(),nn.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(ae,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 gh,xs,rc=E(()=>{"use strict";bn();gh="httpForge.cookies",xs=class{constructor(e,t=gh){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 ws,sc=E(()=>{"use strict";bn();ws=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 ic(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 oc=E(()=>{"use strict"});import*as Pe from"fs";import*as Ze from"path";var Rs,Cs,ac=E(()=>{"use strict";Ge();oc();Li();wi();nr();Rs={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},Cs=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(Rs.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||!Pe.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(!Pe.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(Rs.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`${Rs.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=hi(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");lr(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`);lr(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 Pe.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=Pe.readFileSync(e,"utf-8"),n=ic(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=Xr(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 Rn({globals:i,collectionVariables:{},environmentVariables:s,variables:{...o,...t||{}}})}saveFolderSharedConfig(e){Pe.existsSync(this.environmentsPath)||Pe.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=Pe.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!xi(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=Ze.basename(i,".json");if(!s.has(o))try{Pe.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 Rn({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(Rs.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(Rs.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);Pe.existsSync(n)||Pe.mkdirSync(n,{recursive:!0}),Pe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var _t,Es=E(()=>{"use strict";ls();_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 T=await u.executePreRequest(i);if(T.consoleOutput&&T.consoleOutput.length>0&&this.onConsoleOutput?.(T.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),T.nextRequest!==void 0&&(f=T.nextRequest),T.skipRequest){let j={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:j,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}}T.success&&(T.modifiedRequest&&(T.modifiedRequest.url&&(m.url=T.modifiedRequest.url),T.modifiedRequest.headers&&(m.headers=T.modifiedRequest.headers),T.modifiedRequest.params&&(m.params=T.modifiedRequest.params),T.modifiedRequest.query&&(m.query=T.modifiedRequest.query),T.modifiedRequest.body!==void 0&&(m.body=T.modifiedRequest.body)),(T.localVariables??T.modifiedVariables)&&(p=T.localVariables??T.modifiedVariables))}d=await this.requestPreparer.prepareRequest(m,this.environment,a,p);let{url:h,headers:g,body:y,method:v}=d,w={};for(let T in g)Object.prototype.hasOwnProperty.call(g,T)&&(w[T.toUpperCase()]=g[T]);if(!w.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let j=this.cookieJar.getCookieHeader(h);j&&(w.COOKIE=j)}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=[],F={},_;if(o.length>0){let T=0;if(C.body)if(typeof C.body=="string")T=Buffer.byteLength(C.body,"utf8");else if(Buffer.isBuffer(C.body))T=C.body.length;else try{T=Buffer.byteLength(JSON.stringify(C.body),"utf8")}catch{T=0}let j=Ti(C.headers,C.cookies,d.url),W={executedRequest:d,status:C.status,statusText:C.statusText,headers:La(C.headers||{}),body:C.body,cookies:j,responseTime:C.time,responseSize:T},Z=await u.executePostResponse(o,W);A=Z.testResults,F=Z.modifiedEnvironmentVariables||{},_=Z.visualizerData,(Z.localVariables??Z.modifiedVariables)&&(p=Z.localVariables??Z.modifiedVariables),Z.nextRequest!==void 0&&(f=Z.nextRequest),Z.consoleOutput&&Z.consoleOutput.length>0&&this.onConsoleOutput?.(Z.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let D=A.length===0||A.every(T=>T.passed),B=A.length>0?D: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:B,assertions:A,modifiedVariables:p,modifiedEnvironmentVariables:F,nextRequest:f,visualizerData:_}}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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");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>
|
|
@@ -283,7 +283,7 @@ fragment TypeRef on __Type {
|
|
|
283
283
|
`)){try{let i=new URLSearchParams(s);for(let[o,a]of i)if(Mt.test(o)&&a&&!sn(a)){let c=$n(o),l=2;for(;t.has(c);)c=`${$n(o)}_${l++}`;t.add(c),e.push({location:"body",field:o,path:n?`${n}.${o}`:o,value:a,variableName:c})}}catch{}return}return}if(Array.isArray(r)){r.forEach((s,i)=>Bi(s,e,t,`${n}[${i}]`));return}if(typeof r=="object")for(let[s,i]of Object.entries(r)){let o=n?`${n}.${s}`:s;if(Mt.test(s)&&i&&typeof i=="string"&&!sn(i)){let a=$n(s),c=2;for(;t.has(a);)a=`${$n(s)}_${c++}`;t.add(a),e.push({location:"body",field:s,path:o,value:i,variableName:a})}else typeof i=="object"&&i!==null&&Bi(i,e,t,o)}}}function xh(r,e){let t=JSON.parse(JSON.stringify(r));for(let n of e){let s=`{{${n.variableName}}}`;switch(n.location){case"url":t.url&&(t.url=t.url.replace(new RegExp(`([?&])${Rh(n.field)}=[^&]*`),`$1${n.field}=${s}`));break;case"header":if(Array.isArray(t.headers)){let i=t.headers.find(o=>o.key===n.field&&o.value===n.value);i&&(i.value=s)}else t.headers&&t.headers[n.field]===n.value&&(t.headers[n.field]=s);break;case"query":if(Array.isArray(t.query)){let i=t.query.find(o=>o.key===n.field&&o.value===n.value);i&&(i.value=s)}else t.query&&t.query[n.field]===n.value&&(t.query[n.field]=s);break;case"auth":if(t.auth){if(n.field==="bearerToken")t.auth.bearerToken=s;else if(n.field==="basicAuth.password"&&t.auth.basicAuth)t.auth.basicAuth.password=s;else if(n.field==="apiKey.value"){let i=t.auth.apikey||t.auth.apiKey;i&&(i.value=s)}}break;case"body":wh(t,n.field,n.path,n.value,s);break}}return t}function wh(r,e,t,n,s){let i=typeof r.body=="object"&&r.body!==null&&"content"in r.body?r.body:null,o=i?i.content:r.body;if(o){if(typeof o=="string"){let a=o.trim();if(a.startsWith("{")||a.startsWith("[")){try{let c=JSON.parse(a);Qu(c,e,t||e,n,s);let l=JSON.stringify(c,null,2);i?i.content=l:r.body=l}catch{}return}if(a.includes("=")&&!a.includes(`
|
|
284
284
|
`)){let c=new URLSearchParams(a);if(c.get(e)===n){c.set(e,s);let l=c.toString();i?i.content=l:r.body=l}return}return}typeof o=="object"&&o!==null&&Qu(o,e,t||e,n,s)}}function Qu(r,e,t,n,s){let i=t.split("."),o=r;for(let c=0;c<i.length-1;c++){let l=i[c],u=l.match(/^(.+)\[(\d+)\]$/);if(u?o=o?.[u[1]]?.[parseInt(u[2])]:o=o?.[l],o==null)return}let a=i[i.length-1];o&&o[a]===n&&(o[a]=s)}function Rh(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var on,Zu,Mt,bh,dr=E(()=>{"use strict";on="***",Zu=/^(authorization|proxy-authorization|www-authenticate)$|(token|cookie|secret|credential|api[_\-]?key|bearer|session[_\-]?id)/i,Mt=/(password|passwd|pwd|token|cookie|secret|credential|api[_\-]?key|apikey|access[_\-]?token|refresh[_\-]?token|client[_\-]?secret|private[_\-]?key|auth[_\-]?code|bearer|session[_\-]?id|jwt)/i;bh=/\{\{[^}]+\}\}/});import*as K from"fs";import*as He from"path";var ks,hc=E(()=>{"use strict";Ge();dr();ks=class{historyPath;sharedHistoryPath;constructor(e,t){this.historyPath=e,this.sharedHistoryPath=t}getEnvironmentHistoryPath(e){return He.join(this.historyPath,ve(e))}getCollectionHistoryPath(e,t){return He.join(this.getEnvironmentHistoryPath(e),t)}getRequestPath(e,t,n){return He.join(this.getCollectionHistoryPath(e,t),ve(n))}getSharedEnvironmentHistoryPath(e){return He.join(this.sharedHistoryPath,ve(e))}getSharedCollectionHistoryPath(e,t){return He.join(this.getSharedEnvironmentHistoryPath(e),t)}getSharedRequestPath(e,t,n){return He.join(this.getSharedCollectionHistoryPath(e,t),ve(n))}getHistoryFilePath(e,t,n){return He.join(this.getRequestPath(e,t,n),"transactions.json")}getSharedHistoryFilePath(e,t,n){return He.join(this.getSharedRequestPath(e,t,n),"transactions.json")}getResponseFilePath(e,t,n,s){return He.join(this.getRequestPath(e,t,n),`${s}.json`)}getSharedResponseFilePath(e,t,n,s){return He.join(this.getSharedRequestPath(e,t,n),`${s}.json`)}loadHistory(e,t,n){let s=this.getHistoryFilePath(e,t,n);try{if(!K.existsSync(s))return null;let i=K.readFileSync(s,"utf-8"),o=JSON.parse(i);return{environment:e||o.environment,requestPath:t||o.requestPath,requestId:n||o.requestId,method:o.method,requests:o.requests}}catch(i){return console.error(`Failed to load history for ${n}:`,i),null}}loadSharedHistory(e,t,n){let s=this.getSharedHistoryFilePath(e,t,n);try{if(!K.existsSync(s))return null;let i=K.readFileSync(s,"utf-8"),o=JSON.parse(i);return{environment:e||o.environment,requestPath:t||o.requestPath,requestId:n||o.requestId,method:o.method,requests:o.requests}}catch(i){return console.error(`Failed to load shared history for ${n}:`,i),null}}getEntriesForEnvironment(e,t,n){let s=this.loadHistory(e,t,n);return s?s.requests:[]}getEntriesGroupedByTicket(e,t,n){let s=this.getEntriesForEnvironment(e,t,n),i=new Map;for(let o of s){let a=o.ticket||o.branch||"";i.has(a)||i.set(a,[]),i.get(a).push(o)}return i}getSharedEntriesGroupedByTicket(e,t,n){let s=this.loadSharedHistory(e,t,n)?.requests??[],i=new Map;for(let o of s){let a=o.ticket||o.branch||"";i.has(a)||i.set(a,[]),i.get(a).push(o)}return i}saveHistory(e){let t=this.getRequestPath(e.environment,e.requestPath,e.requestId),n=this.getHistoryFilePath(e.environment,e.requestPath,e.requestId);try{K.existsSync(t)||K.mkdirSync(t,{recursive:!0}),K.writeFileSync(n,JSON.stringify(e,null,2),"utf-8")}catch(s){throw console.error(`Failed to save history for ${e.requestId}:`,s),s}}saveSharedHistory(e){let t=this.getSharedRequestPath(e.environment,e.requestPath,e.requestId),n=this.getSharedHistoryFilePath(e.environment,e.requestPath,e.requestId);try{K.existsSync(t)||K.mkdirSync(t,{recursive:!0}),K.writeFileSync(n,JSON.stringify(e,null,2),"utf-8")}catch(s){throw console.error(`Failed to save shared history for ${e.requestId}:`,s),s}}addEntry(e,t,n,s,i){let o=this.loadHistory(e,t,n);o||(o={environment:e,requestPath:t,requestId:n,method:s,requests:[]});let a=pc({...i,method:s,id:wu(),timestamp:Date.now()});return o.requests.unshift(a),o.requests.length>100&&(o.requests=o.requests.slice(0,100)),this.saveHistory(o),a}deleteEntry(e,t,n,s){let i=this.loadHistory(e,t,n);if(!i)return!1;let o=i.requests.length;if(i.requests=i.requests.filter(a=>a.id!==s),i.requests.length!==o){this.saveHistory(i);let a=this.getResponseFilePath(e,t,n,s);return K.existsSync(a)&&K.unlinkSync(a),!0}return!1}deleteSharedEntry(e,t,n,s){let i=this.loadSharedHistory(e,t,n);if(!i)return!1;let o=i.requests.length;if(i.requests=i.requests.filter(a=>a.id!==s),i.requests.length!==o){this.saveSharedHistory(i);let a=this.getSharedResponseFilePath(e,t,n,s);return K.existsSync(a)&&K.unlinkSync(a),!0}return!1}shareEntry(e,t,n,s,i){let o=(i||"").trim();if(!o)return!1;let a=this.loadHistory(e,t,n);if(!a)return!1;let c=a.requests.findIndex(m=>m.id===s);if(c===-1)return!1;let[l]=a.requests.splice(c,1);this.saveHistory(a);let u=this.loadSharedHistory(e,t,n)||{environment:e,requestPath:t,requestId:n,method:a.method,requests:[]};if(!u.requests.some(m=>m.id===s)){let m={...l,ticket:null,branch:o};u.requests.unshift(m),u.requests.length>100&&(u.requests=u.requests.slice(0,100)),this.saveSharedHistory(u)}let d=this.getResponseFilePath(e,t,n,s),p=this.getSharedResponseFilePath(e,t,n,s);if(K.existsSync(d)){let m=He.dirname(p);K.existsSync(m)||K.mkdirSync(m,{recursive:!0});try{K.renameSync(d,p)}catch{try{K.copyFileSync(d,p)}catch(h){return console.error(`Failed to copy full response from ${d} to ${p}:`,h),!0}try{K.unlinkSync(d)}catch(h){console.warn(`Failed to remove original full response after copy: ${d}`,h)}}}return!0}moveSharedEntry(e,t,n,s,i){let o=(i||"").trim();if(!o)return!1;let a=this.loadSharedHistory(e,t,n);if(!a)return!1;let c=!1;return a.requests=a.requests.map(l=>l.id===s?(c=!0,{...l,ticket:null,branch:o}):l),c?(this.saveSharedHistory(a),!0):!1}renameSharedGroup(e,t,n,s,i){let o=(s||"").trim(),a=(i||"").trim();if(!o||!a||o===a)return!1;let c=this.loadSharedHistory(e,t,n);if(!c)return!1;let l=!1;return c.requests=c.requests.map(u=>!u.ticket&&u.branch===o?(l=!0,{...u,branch:a}):u),l?(this.saveSharedHistory(c),!0):!1}clearHistory(e,t,n){let s=this.getRequestPath(e,t,n);if(K.existsSync(s)){let i=K.readdirSync(s);for(let o of i)K.unlinkSync(He.join(s,o));K.rmdirSync(s)}}saveFullResponse(e,t,n,s,i){let o=this.getRequestPath(e,t,n),a=this.getResponseFilePath(e,t,n,s);try{K.existsSync(o)||K.mkdirSync(o,{recursive:!0});let c=fc(i);K.writeFileSync(a,JSON.stringify(c,null,2),"utf-8")}catch(c){throw console.error(`Failed to save full response for ${s}:`,c),c}}loadFullResponse(e,t,n,s){let i=this.getResponseFilePath(e,t,n,s);try{if(!K.existsSync(i))return null;let o=K.readFileSync(i,"utf-8");return JSON.parse(o)}catch(o){return console.error(`Failed to load full response for ${s}:`,o),null}}loadSharedFullResponse(e,t,n,s){let i=this.getSharedResponseFilePath(e,t,n,s);try{if(!K.existsSync(i))return null;let o=K.readFileSync(i,"utf-8");return JSON.parse(o)}catch(o){return console.error(`Failed to load shared full response for ${s}:`,o),null}}}});var pr,gc=E(()=>{"use strict";pr=class{constructor(e,t){this.historyService=e;this.inferrer=t}historyService;inferrer;async analyze(e,t,n){let s=n?.environment||"default",i=n?.maxSamples||50,o=this.historyService.loadHistory(s,e,t),a=this.historyService.loadSharedHistory(s,e,t),c=[...o?.requests||[],...a?.requests||[]];if(c.length===0)return{responses:{}};let l=c.slice(0,i),u=new Map;for(let p of l){let m=this.historyService.loadFullResponse(s,e,t,p.id);if(m||(m=this.historyService.loadSharedFullResponse(s,e,t,p.id)),m){let f=m.status;u.has(f)||u.set(f,[]),u.get(f).push(m)}}let d={};for(let[p,m]of u){let f=this.buildResponseDefinition(m);d[String(p)]=f}return{responses:d}}buildResponseDefinition(e){let t={};if(e.length===0)return t;let n=e[0];t.description=n.statusText||`Status ${n.status}`;let s=this.extractContentType(n.headers);if(s&&(t.contentType=s),s&&this.isJsonContentType(s)){let o=this.inferBodySchema(n);for(let a=1;a<e.length;a++){let c=this.inferBodySchema(e[a]);c&&o?o=this.inferrer.mergeSchemas(o,c):c&&(o=c)}if(o&&(t.schema=o),n.body!==void 0&&n.body!==null){let a=typeof n.body=="string"?this.tryParseJson(n.body):n.body;a!==void 0&&(t.examples={default:{summary:"Captured from history",value:a}})}}let i=this.findConsistentHeaders(e);return Object.keys(i).length>0&&(t.headers=i),t}inferBodySchema(e){if(e.body===void 0||e.body===null)return;let t=e.body;if(!(typeof t=="string"&&(t=this.tryParseJson(t),t===void 0)))return this.inferrer.inferFromValue(t)}extractContentType(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()==="content-type")return(Array.isArray(n)?n[0]:n).split(";")[0].trim()}isJsonContentType(e){return e.includes("json")||e.includes("+json")||e==="application/json"}findConsistentHeaders(e){if(e.length===0)return{};let t=new Set(["content-type","content-length","content-encoding","transfer-encoding","connection","date","server","set-cookie","vary","cache-control","expires","pragma","etag","last-modified","age"]),n=new Map,s=new Map;for(let a of e)for(let[c,l]of Object.entries(a.headers)){let u=c.toLowerCase();t.has(u)||(n.set(u,(n.get(u)||0)+1),s.has(u)||s.set(u,Array.isArray(l)?l.join(", "):l))}let i=Math.ceil(e.length/2),o={};for(let[a,c]of n)if(c>=i){let l=s.get(a);o[a]={schema:this.inferHeaderSchema(l)}}return o}inferHeaderSchema(e){return e?/^\d+$/.test(e)?{type:"integer"}:{type:"string"}:{type:"string"}}tryParseJson(e){try{return JSON.parse(e)}catch{return}}}});function td(r){let e=r,t=null,n=e.match(/^\{\{(\w+)\}\}/);return n&&(t=n[1],e=e.slice(n[0].length)),e=e.replace(/:([a-zA-Z_]\w*)/g,"{$1}"),e=e.replace(/\{\{(\w+)\}\}/g,"{$1}"),e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e=e.replace(/\/\//g,"/"),{path:e,hostVar:t}}function Xu(r){return/^-?\d+$/.test(r)?"integer":/^-?\d+\.\d+$/.test(r)?"number":r==="true"||r==="false"?"boolean":"string"}function Ui(r,e){if(r==="integer"&&e==="number"||r==="number"&&e==="integer")return"number"}function nd(r){return r.replace(/\{\{(\w+)\}\}/g,"<$1>")}function yc(r,e){let t=nd(r);switch(e){case"integer":return parseInt(t,10)||t;case"number":return parseFloat(t)||t;case"boolean":return t==="true";default:return t}}function vc(r){if(typeof r=="string")return nd(r);if(Array.isArray(r))return r.map(e=>vc(e));if(r!==null&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=vc(n);return e}return r}function Is(r){if(!r||!r.content)return;let e;if(typeof r.content=="string")try{e=JSON.parse(r.content)}catch{e=r.content}else e=r.content;return vc(e)}function bc(r){if(!r)return"application/json";switch(r.type){case"raw":switch(r.format){case"json":return"application/json";case"xml":return"application/xml";case"html":return"text/html";case"text":return"text/plain";default:return"text/plain"}case"form-data":return"multipart/form-data";case"x-www-form-urlencoded":return"application/x-www-form-urlencoded";case"binary":return"application/octet-stream";case"graphql":return"application/json";default:return"application/json"}}function Sc(r){let e={type:"object",properties:{}},t=r.formData||r.urlencoded||[];for(let n of t)n.enabled!==!1&&(n.type==="file"?e.properties[n.key]={type:"string",format:"binary"}:e.properties[n.key]={type:"string"});return e}function ed(r,e){let t={name:r.key,in:e,schema:{}};return r.oneOf?(t.schema.oneOf=r.oneOf,r.type&&(t.schema.type=r.type)):(t.schema.type=r.type||"string",r.format&&(t.schema.format=r.format),r.enum&&(t.schema.enum=r.enum),r.pattern&&(t.schema.pattern=r.pattern),r.minimum!==void 0&&(t.schema.minimum=r.minimum),r.maximum!==void 0&&(t.schema.maximum=r.maximum),r.exclusiveMinimum!==void 0&&(t.schema.exclusiveMinimum=r.exclusiveMinimum),r.exclusiveMaximum!==void 0&&(t.schema.exclusiveMaximum=r.exclusiveMaximum),r.multipleOf!==void 0&&(t.schema.multipleOf=r.multipleOf),r.minLength!==void 0&&(t.schema.minLength=r.minLength),r.maxLength!==void 0&&(t.schema.maxLength=r.maxLength),r.minItems!==void 0&&(t.schema.minItems=r.minItems),r.maxItems!==void 0&&(t.schema.maxItems=r.maxItems),r.uniqueItems&&(t.schema.uniqueItems=!0),r.nullable&&(t.schema.nullable=!0)),r.required&&(t.required=!0),r.description&&(t.description=r.description),r.deprecated&&(t.deprecated=!0),r.value&&(t.example=yc(r.value,t.schema.type||"string")),t}function Eh(r){let e=[],t=r.split(";").map(n=>n.trim()).filter(Boolean);for(let n of t){let s=n.indexOf("=");if(s>0){let i=n.substring(0,s).trim(),o=n.substring(s+1).trim();e.push({name:i,in:"cookie",schema:{type:"string"},example:o})}}return e}function rd(r){let e=[];if(r.params)for(let[t,n]of Object.entries(r.params)){let s={name:t,in:"path",required:!0};if(typeof n=="string")s.schema={type:Xu(n)},s.example=yc(n,s.schema.type);else{let i=n;i.oneOf?(s.schema={oneOf:i.oneOf},i.type&&(s.schema.type=i.type)):(s.schema={type:i.type||Xu(i.value)},i.format&&(s.schema.format=i.format),i.enum&&(s.schema.enum=i.enum),i.pattern&&(s.schema.pattern=i.pattern),i.minimum!==void 0&&(s.schema.minimum=i.minimum),i.maximum!==void 0&&(s.schema.maximum=i.maximum),i.exclusiveMinimum!==void 0&&(s.schema.exclusiveMinimum=i.exclusiveMinimum),i.exclusiveMaximum!==void 0&&(s.schema.exclusiveMaximum=i.exclusiveMaximum),i.multipleOf!==void 0&&(s.schema.multipleOf=i.multipleOf),i.minLength!==void 0&&(s.schema.minLength=i.minLength),i.maxLength!==void 0&&(s.schema.maxLength=i.maxLength),i.minItems!==void 0&&(s.schema.minItems=i.minItems),i.maxItems!==void 0&&(s.schema.maxItems=i.maxItems),i.uniqueItems&&(s.schema.uniqueItems=!0),i.nullable&&(s.schema.nullable=!0)),i.description&&(s.description=i.description),i.deprecated&&(s.deprecated=!0),s.example=yc(i.value,s.schema.type||"string")}e.push(s)}if(r.query)for(let t of r.query){if(!t.key)continue;let n=ed(t,"query");e.push(n)}if(r.headers){let t=r.headers.find(n=>n.key.toLowerCase()==="cookie");if(t){let n=Eh(t.value);e.push(...n)}for(let n of r.headers){if(!n.key||Ch.has(n.key.toLowerCase()))continue;let s=ed(n,"header");e.push(s)}}return e}function sd(r){return r.replace(/[^a-zA-Z0-9]+(.)/g,(e,t)=>t.toUpperCase()).replace(/^[A-Z]/,e=>e.toLowerCase()).replace(/[^a-zA-Z0-9]/g,"")}function id(r){return r.replace(/^\[DEPRECATED\]\s*/i,"")}function xc(r){return/^\[DEPRECATED\]/i.test(r)}function Ts(r){let e={};for(let t of r.split(/\s+/))t&&(e[t]="");return e}var Ch,Os=E(()=>{"use strict";Ch=new Set(["content-type","authorization","accept","cookie","host","content-length"])});var qh,Ah,Ph,kh,Ih,Th,Oh,an,Vi=E(()=>{"use strict";Os();qh=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,Ah=/^\d{4}-\d{2}-\d{2}$/,Ph=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,kh=/^https?:\/\/[^\s]+$/,Ih=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Th=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Oh=/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/,an=class{inferFromValue(e){if(e==null)return{nullable:!0};if(Array.isArray(e))return this.inferArraySchema(e);switch(typeof e){case"string":return this.inferStringSchema(e);case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":return this.inferObjectSchema(e);default:return{}}}mergeSchemas(e,t){if(!e||Object.keys(e).length===0)return{...t};if(!t||Object.keys(t).length===0)return{...e};let n=e.nullable||t.nullable;if(!e.type&&e.nullable)return{...t,nullable:!0};if(!t.type&&t.nullable)return{...e,nullable:!0};if(e.type!==t.type){let i=Ui(e.type,t.type);return i?{type:i,...n&&{nullable:!0}}:{...n&&{nullable:!0}}}let s={type:e.type};return n&&(s.nullable=!0),e.type==="object"&&t.type==="object"?this.mergeObjectSchemas(e,t,n):e.type==="array"&&t.type==="array"?this.mergeArraySchemas(e,t,n):(e.format&&e.format===t.format&&(s.format=e.format),s)}inferStringFormat(e){if(qh.test(e))return"date-time";if(Ah.test(e))return"date";if(Ph.test(e))return"email";if(Ih.test(e))return"uuid";if(kh.test(e))return"uri";if(Th.test(e))return"ipv4";if(Oh.test(e))return"ipv6"}inferStringSchema(e){let t={type:"string"},n=this.inferStringFormat(e);return n&&(t.format=n),t}inferArraySchema(e){let t={type:"array"};if(e.length===0)return t;let n=this.inferFromValue(e[0]);for(let s=1;s<e.length;s++)n=this.mergeSchemas(n,this.inferFromValue(e[s]));return t.items=n,t}inferObjectSchema(e){let t={type:"object",properties:{}},n=Object.keys(e);for(let s of n)t.properties[s]=this.inferFromValue(e[s]);return t}mergeObjectSchemas(e,t,n){let s={type:"object",properties:{},...n&&{nullable:!0}},i=e.properties||{},o=t.properties||{},a=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of a)i[d]&&o[d]?s.properties[d]=this.mergeSchemas(i[d],o[d]):i[d]?s.properties[d]={...i[d]}:s.properties[d]={...o[d]};let c=new Set(e.required||Object.keys(i)),l=new Set(t.required||Object.keys(o)),u=[...a].filter(d=>c.has(d)&&l.has(d));return u.length>0&&(s.required=u),s}mergeArraySchemas(e,t,n){let s={type:"array",...n&&{nullable:!0}};return e.items&&t.items?s.items=this.mergeSchemas(e.items,t.items):e.items?s.items={...e.items}:t.items&&(s.items={...t.items}),s}}});var zi,od=E(()=>{"use strict";Os();zi=class{constructor(e){this.inferrer=e}inferrer;async buildOperation(e,t,n,s,i,o,a,c,l){let u={};u.operationId=e.operationId||this.generateOperationId(e,t,n,s),u.summary=e.summary||id(e.name),e.description&&(u.description=e.description),(e.deprecated||xc(e.name))&&(u.deprecated=!0,xc(e.name)&&(u.summary=e.name.replace(/^\[DEPRECATED\]\s*/i,"")));let d=e.tags;if(d&&d.length>0){u.tags=d;for(let g of d)o.add(g)}else a&&(u.tags=[a]);let p=rd(e);p.length>0&&(u.parameters=p);let m=await this.buildRequestBody(e,l);m&&(u.requestBody=m);let f=e.responses;f&&Object.keys(f).length>0?u.responses=this.mapResponseDefinitions(f):u.responses=await this.buildResponses(e,c.id,l);let h=e.security;if(h&&h.length>0)u.security=h;else{let g=this.buildOperationSecurity(e,c,i);g!==void 0&&(u.security=g)}return u}generateOperationId(e,t,n,s){let i=sd(e.name),o=this.collectOperationIds(s);if(o.has(i)&&(i=`${i}${t.charAt(0).toUpperCase()}${t.slice(1)}`),!i||o.has(i)){let a=n.split("/").filter(c=>c&&!c.startsWith("{"));i=t+a.map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}return i}collectOperationIds(e){let t=new Set;if(e.paths)for(let n of Object.values(e.paths))for(let s of Object.values(n))s.operationId&&t.add(s.operationId);return t}async buildRequestBody(e,t){if(!e.body||e.body.type==="none")return null;let n=e.body,s={required:!0,content:{}},i,o,a,c;if(e.bodySchema){if(e.bodySchema.content){for(let[d,p]of Object.entries(e.bodySchema.content)){let m={};p.schema&&(m.schema=p.schema),p.examples&&(m.examples=p.examples),p.encoding&&(m.encoding=p.encoding),s.content[d]=m}let u=e.bodySchema.contentType||Object.keys(e.bodySchema.content)[0];if(u&&n.content){let d=Is(n);d!==void 0&&s.content[u]&&(s.content[u].example=d)}return s}i=e.bodySchema.contentType||bc(n),o=e.bodySchema.schema,a=Is(n),e.bodySchema.encoding&&(c=e.bodySchema.encoding)}else switch(i=bc(n),n.type){case"raw":{if(n.format==="json"&&n.content){let u=Is(n);u!==void 0?(o=this.inferrer.inferFromValue(u),a=u):o={type:"string"}}else o={type:"string"},a=typeof n.content=="string"?n.content:void 0;break}case"form-data":{o=Sc(n);break}case"x-www-form-urlencoded":{o=Sc(n);break}case"binary":{o={type:"string",format:"binary"};break}case"graphql":{o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a=Is(n);break}default:return null}let l={};return o&&(l.schema=o),a!==void 0&&(l.example=a),c&&(l.encoding=c),s.content[i]=l,s}async buildResponses(e,t,n){let s={};if(e.responseSchema)for(let[i,o]of Object.entries(e.responseSchema.responses)){let a={description:o.description||`Status ${i}`};if(o.content){a.content={};for(let[c,l]of Object.entries(o.content)){let u={};l.schema&&(u.schema=l.schema),l.examples&&(u.examples=l.examples),a.content[c]=u}}else if(o.schema){let c=o.contentType||"application/json",l={schema:o.schema};o.examples&&(l.examples=o.examples),a.content={[c]:l}}if(o.headers){a.headers={};for(let[c,l]of Object.entries(o.headers))a.headers[c]={...l.description&&{description:l.description},schema:l.schema}}s[i]=a}return Object.keys(s).length===0&&(s[200]={description:"Successful response"}),s}mapResponseDefinitions(e){let t={};for(let[n,s]of Object.entries(e)){let i={description:s.description||`Status ${n}`};if(s.schema||s.examples){let o=s.contentType||"application/json",a={};s.schema&&(a.schema=s.schema),s.examples&&Object.keys(s.examples).length>0&&(a.examples=s.examples),i.content={[o]:a}}if(s.headers&&Object.keys(s.headers).length>0){i.headers={};for(let[o,a]of Object.entries(s.headers)){let c=a;i.headers[o]={...c.description&&{description:c.description},...c.schema&&{schema:c.schema}}}}t[n]=i}return Object.keys(t).length===0&&(t[200]={description:"Successful response"}),t}buildOperationSecurity(e,t,n){if(!e.auth||e.auth.type==="inherit")return;if(e.auth.type==="none")return[];let s=this.mapAuthToSecurityScheme(e.auth);if(!s)return;let{schemeName:i,scheme:o,requirement:a}=s;return n.set(i,o),[a]}mapAuthToSecurityScheme(e){switch(e.type){case"bearer":return{schemeName:"BearerAuth",scheme:{type:"http",scheme:"bearer"},requirement:{BearerAuth:[]}};case"basic":return{schemeName:"BasicAuth",scheme:{type:"http",scheme:"basic"},requirement:{BasicAuth:[]}};case"apikey":{let t=e.apikey||{key:"X-Api-Key",value:"",in:"header"},n=`ApiKey_${t.key||"key"}`;return{schemeName:n,scheme:{type:"apiKey",in:t.in||"header",name:t.key||"X-Api-Key"},requirement:{[n]:[]}}}case"oauth2":{let t=e.oauth2;if(!t)return;let n={};switch(t.grantType){case"client_credentials":n.clientCredentials={tokenUrl:t.tokenUrl||"",scopes:t.scope?Ts(t.scope):{}};break;case"authorization_code":n.authorizationCode={authorizationUrl:t.authUrl||"",tokenUrl:t.tokenUrl||"",scopes:t.scope?Ts(t.scope):{}};break;case"password":n.password={tokenUrl:t.tokenUrl||"",scopes:t.scope?Ts(t.scope):{}};break;case"implicit":n.implicit={authorizationUrl:t.authUrl||"",scopes:t.scope?Ts(t.scope):{}};break;default:n.clientCredentials={tokenUrl:t.tokenUrl||"",scopes:{}}}return{schemeName:"OAuth2",scheme:{type:"oauth2",flows:n},requirement:{OAuth2:[]}}}default:return{schemeName:"BearerAuth",scheme:{type:"http",scheme:"bearer"},requirement:{BearerAuth:[]}}}}}});var Ji,ad=E(()=>{"use strict";Os();Ji=class{mergeOperation(e,t,n){if(t.summary&&t.summary!==e.summary&&(e.description=(e.description||e.summary||"")+`
|
|
285
285
|
|
|
286
|
-
Variant: **${n}**`+(t.description?` \u2014 ${t.description}`:"")),t.tags){let s=new Set(e.tags||[]);for(let i of t.tags)s.add(i);e.tags=[...s]}if(t.parameters){e.parameters||(e.parameters=[]);for(let s of t.parameters){let i=e.parameters.find(o=>o.name===s.name&&o.in===s.in);i?this.mergeParameterSchema(i,s,n):e.parameters.push(s)}}if(t.responses){e.responses||(e.responses={});for(let[s,i]of Object.entries(t.responses))e.responses[s]||(e.responses[s]=i)}if(t.requestBody?.content&&e.requestBody?.content)for(let[s,i]of Object.entries(t.requestBody.content))e.requestBody.content[s]||(e.requestBody.content[s]=i);else t.requestBody&&!e.requestBody&&(e.requestBody=t.requestBody)}mergeParameterSchema(e,t,n){e.schema||(e.schema={});let s=e.schema,i=t.schema||{},o=this.getConstraintKind(s),a=this.getConstraintKind(i);if(o==="none"&&a==="none")this.widenType(s,i);else if(o==="none")Object.assign(s,this.extractConstraints(i)),this.widenType(s,i);else if(a==="none")this.widenType(s,i);else if(o===a)this.mergeSameKindConstraints(s,i,o),this.widenType(s,i);else{if(s.oneOf){let c=this.buildVariantSchema(i);s.oneOf.some(l=>JSON.stringify(l)===JSON.stringify(c))||s.oneOf.push(c)}else if(i.oneOf){let c=this.buildVariantSchema(s);s.oneOf=[c,...i.oneOf]}else{let c=this.buildVariantSchema(s),l=this.buildVariantSchema(i);s.oneOf=[c,l]}this.stripConstraints(s)}if(t.description&&t.description!==e.description&&(e.description=(e.description||"")+(e.description?"; ":"")+t.description),t.example!==void 0&&t.example!==e.example){e.examples||(e.examples={},e.example!==void 0&&(e.examples.variant1={value:e.example}));let c=`variant_${n.replace(/[^a-zA-Z0-9_]/g,"_")}`;e.examples[c]={value:t.example},delete e.example}}getConstraintKind(e){return e.oneOf?"oneOf":e.enum&&e.enum.length>0?"enum":e.pattern?"pattern":e.minimum!==void 0||e.maximum!==void 0||e.exclusiveMinimum!==void 0||e.exclusiveMaximum!==void 0||e.multipleOf!==void 0?"range":e.minLength!==void 0||e.maxLength!==void 0?"length":e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems?"array":e.format?"format":"none"}mergeSameKindConstraints(e,t,n){switch(n){case"enum":{let s=new Set(e.enum||[]);for(let i of t.enum||[])s.add(i);e.enum=[...s];break}case"pattern":{t.pattern&&t.pattern!==e.pattern&&(e.pattern=`(?:${e.pattern})|(?:${t.pattern})`);break}case"range":{t.minimum!==void 0&&(e.minimum=e.minimum!==void 0?Math.min(e.minimum,t.minimum):t.minimum),t.maximum!==void 0&&(e.maximum=e.maximum!==void 0?Math.max(e.maximum,t.maximum):t.maximum),t.exclusiveMinimum&&(e.exclusiveMinimum=!0),t.exclusiveMaximum&&(e.exclusiveMaximum=!0),t.multipleOf!==void 0&&(e.multipleOf=e.multipleOf!==void 0?Math.min(e.multipleOf,t.multipleOf):t.multipleOf);break}case"length":{t.minLength!==void 0&&(e.minLength=e.minLength!==void 0?Math.min(e.minLength,t.minLength):t.minLength),t.maxLength!==void 0&&(e.maxLength=e.maxLength!==void 0?Math.max(e.maxLength,t.maxLength):t.maxLength);break}case"array":{t.minItems!==void 0&&(e.minItems=e.minItems!==void 0?Math.min(e.minItems,t.minItems):t.minItems),t.maxItems!==void 0&&(e.maxItems=e.maxItems!==void 0?Math.max(e.maxItems,t.maxItems):t.maxItems),t.uniqueItems&&(e.uniqueItems=!0);break}case"format":{if(t.format&&t.format!==e.format){let s={type:e.type||"string",format:e.format},i={type:t.type||"string",format:t.format};delete e.format,e.oneOf=[s,i]}break}case"oneOf":{if(t.oneOf)for(let s of t.oneOf)e.oneOf.some(i=>JSON.stringify(i)===JSON.stringify(s))||e.oneOf.push(s);break}}}buildVariantSchema(e){let t={};return e.type&&(t.type=e.type),e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),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.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}stripConstraints(e){delete e.enum,delete e.pattern,delete e.format,delete e.minimum,delete e.maximum,delete e.exclusiveMinimum,delete e.exclusiveMaximum,delete e.multipleOf,delete e.minLength,delete e.maxLength,delete e.minItems,delete e.maxItems,delete e.uniqueItems,delete e.nullable}extractConstraints(e){let t={};return e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),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.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}widenType(e,t){if(!(!t.type||t.type===e.type))if(!e.type)e.type=t.type;else{let n=Ui(e.type,t.type);n&&(e.type=n)}}}});import*as cd from"yaml";var Gi,ld=E(()=>{"use strict";Gi=class{finalize(e,t,n,s){if(t.size>0)for(let[i,o]of t)e.components.securitySchemes[i]=o;else delete e.components.securitySchemes;return e.tags=[...n].map(i=>({name:i})),e.tags.length===0&&delete e.tags,this.deduplicateComponents(e),Object.keys(e.components.schemas).length===0&&delete e.components.schemas,Object.keys(e.components).length===0&&delete e.components,s.format==="yaml"?cd.stringify(e,{indent:2}):JSON.stringify(e,null,2)}deduplicateComponents(e){let t=new Map,n=new Map;if(e.paths)for(let[s,i]of Object.entries(e.paths))for(let[o,a]of Object.entries(i)){let c=a;if(c.responses){for(let[l,u]of Object.entries(c.responses))if(u.content)for(let d of Object.values(u.content))d.schema&&this.trackSchema(d.schema,`${o}${s}Response${l}`,t,n)}if(c.requestBody?.content)for(let l of Object.values(c.requestBody.content))l.schema&&this.trackSchema(l.schema,`${o}${s}Request`,t,n)}for(let[s,i]of t)if((n.get(s)||0)>=2){let a=this.sanitizeComponentName(i.name);e.components.schemas[a]=i.schema,this.replaceInlineSchema(e,i.schema,`#/components/schemas/${a}`)}}trackSchema(e,t,n,s){if(!e||e.type!=="object"||!e.properties)return;let i=JSON.stringify(e);n.has(i)||n.set(i,{name:t,schema:e}),s.set(i,(s.get(i)||0)+1)}replaceInlineSchema(e,t,n){let s=JSON.stringify(t);if(e.paths)for(let i of Object.values(e.paths))for(let o of Object.values(i)){if(o.responses){for(let a of Object.values(o.responses))if(a.content)for(let c of Object.values(a.content))c.schema&&JSON.stringify(c.schema)===s&&(c.schema={$ref:n})}if(o.requestBody?.content)for(let a of Object.values(o.requestBody.content))a.schema&&JSON.stringify(a.schema)===s&&(a.schema={$ref:n})}}sanitizeComponentName(e){return e.replace(/[^a-zA-Z0-9._-]/g,"").replace(/^[^a-zA-Z]/,"Schema")}}});var cn,Wi=E(()=>{"use strict";Vi();od();ad();ld();Os();cn=class{constructor(e,t,n){this.collectionService=e;this.envConfigService=t;this.inferenceService=n;let s=new an;this.merger=new Ji,this.operationBuilder=new zi(s),this.specWriter=new Gi}collectionService;envConfigService;inferenceService;merger;operationBuilder;specWriter;async export(e,t){let n=this.collectionService.getCollection(e);if(!n)throw new Error(`Collection ${e} not found`);let s={openapi:"3.0.3",info:this.buildInfo(n,t),servers:this.buildServers(t),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},i=new Map;if(n.auth&&n.auth.type!=="none"&&n.auth.type!=="inherit"){let c=this.operationBuilder.mapAuthToSecurityScheme(n.auth);if(c){let{schemeName:l,scheme:u,requirement:d}=c;i.set(l,u),s.security=[d]}}let o=new Set,a=new Set;return await this.processItems(n.items,s,i,o,a,void 0,n,t),this.augmentServersFromHostVars(a,s.servers,t),this.specWriter.finalize(s,i,o,t)}buildInfo(e,t){return{title:t.info?.title||e.name,description:t.info?.description||e.description||"",version:t.info?.version||e.version||"1.0.0"}}buildServers(e){let t=[],n=e.environments||[];if(n.length===0){let s=this.envConfigService.getSelectedEnvironment();if(s){let i=this.envConfigService.resolveVariables("{{baseUrl}}",s);i&&i!=="{{baseUrl}}"&&t.push({url:i,description:s})}}else{let s=new Set;for(let i of n){let o=this.envConfigService.resolveVariables("{{baseUrl}}",i);o&&o!=="{{baseUrl}}"&&!s.has(o)&&(s.add(o),t.push({url:o,description:i}))}}return t.length===0&&t.push({url:"http://localhost",description:"Default server"}),t}async processItems(e,t,n,s,i,o,a,c){for(let l of e)if(l.type==="folder"){let u=l,d=o||u.name;s.add(d),u.items&&await this.processItems(u.items,t,n,s,i,d,a,c)}else{let u=l;await this.processRequest(u,t,n,s,i,o,a,c)}}async processRequest(e,t,n,s,i,o,a,c){let{path:l,hostVar:u}=td(e.url);u&&i.add(u);let d=(e.method||"GET").toLowerCase();t.paths[l]||(t.paths[l]={});let p=await this.operationBuilder.buildOperation(e,d,l,t,n,s,o,a,c),m=t.paths[l][d];m?this.merger.mergeOperation(m,p,e.name):t.paths[l][d]=p}augmentServersFromHostVars(e,t,n){if(e.size===0)return;let s=new Set(t.map(o=>o.url)),i=n.environments?.length?n.environments:[this.envConfigService.getSelectedEnvironment()].filter(o=>!!o);for(let o of e){let a=`{{${o}}}`,c=!1;for(let l of i){let u=this.envConfigService.resolveVariables(a,l);u&&u!==a&&!s.has(u)&&(t.push({url:u,description:l}),s.add(u),c=!0)}if(!c){let l=`{${o}}`;s.has(l)||(t.push({url:l,variables:{[o]:{default:""}}}),s.add(l))}}}}});var fr,wc=E(()=>{"use strict";fr=class{generate(e,t){if(!e)return;let n=t||{};if(e.$ref){let s=this.resolveLocalRef(e.$ref,n.components);return s?this.generate(s,n):{}}if(e.nullable&&!e.type)return null;if(e.enum&&e.enum.length>0)return e.enum[0];if(e.default!==void 0)return e.default;if(e.example!==void 0)return e.example;if(e.allOf)return this.generateFromAllOf(e.allOf,e.discriminator,n);if(e.oneOf)return this.generateFromOneOfAnyOf(e.oneOf,e.discriminator,n);if(e.anyOf)return this.generateFromOneOfAnyOf(e.anyOf,e.discriminator,n);switch(e.type){case"string":return this.generateString(e);case"integer":return this.generateInteger(e);case"number":return this.generateNumber(e);case"boolean":return!1;case"array":return this.generateArray(e,n);case"object":return this.generateObject(e,n);default:return e.properties?this.generateObject(e,n):{}}}generateString(e){switch(e.format){case"email":return"user@example.com";case"date-time":return"2026-01-01T00:00:00Z";case"date":return"2026-01-01";case"time":return"00:00:00";case"uri":case"url":return"https://example.com";case"uuid":return"00000000-0000-0000-0000-000000000000";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"hostname":return"example.com";case"binary":return"";case"byte":return"c3RyaW5n";case"password":return"********";default:return"string"}}generateInteger(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+1:0}generateNumber(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+.1:0}generateArray(e,t){return e.items?[this.generate(e.items,t)]:[]}generateObject(e,t){let n={},s=e.properties||{};for(let[i,o]of Object.entries(s))t.omitReadOnly&&o.readOnly||(n[i]=this.generate(o,t));return n}generateFromAllOf(e,t,n){let s={type:"object",properties:{},required:[]};for(let o of e){let a=o.$ref?this.resolveLocalRef(o.$ref,n.components)||{}:o;a.properties&&Object.assign(s.properties,a.properties),a.required&&(s.required=[...s.required||[],...a.required])}let i=this.generateObject(s,n);return t?.propertyName&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}generateFromOneOfAnyOf(e,t,n){if(e.length===0)return{};let s=e[0].$ref&&this.resolveLocalRef(e[0].$ref,n.components)||e[0],i=this.generate(s,n);return t?.propertyName&&typeof i=="object"&&i!==null&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}guessDiscriminatorValue(e,t){if(e.length===0)return"unknown";let n=e[0];if(n.$ref){let s=n.$ref.split("/");return s[s.length-1]}return"variant1"}resolveLocalRef(e,t){if(!e||!t)return;let n=e.match(/^#\/components\/(?:schemas\/)?(.+)$/);if(n)return t[n[1]];let s=e.match(/^#\/components\/(.+)$/);if(s)return t[s[1]]}}});import Rc from"@apidevtools/json-schema-ref-parser";var mr,Cc=E(()=>{"use strict";mr=class{async resolve(e){try{return await Rc.dereference(e,{dereference:{circular:"ignore"}})}catch(t){return console.error("[RefResolver] Failed to fully resolve $ref pointers:",t),e}}async bundle(e){try{return await Rc.bundle(e)}catch(t){return console.error("[RefResolver] Failed to bundle $ref pointers:",t),e}}async resolveFile(e){try{return await Rc.dereference(e,{dereference:{circular:"ignore"}})}catch(t){throw console.error(`[RefResolver] Failed to resolve file ${e}:`,t),t}}}});import*as ud from"fs";import*as dd from"yaml";var $h,Dt,Ki=E(()=>{"use strict";Ge();wc();Cc();$h=["application/json","text/plain","text/html","multipart/form-data","application/x-www-form-urlencoded"],Dt=class{constructor(e,t){this.collectionService=e;this.envConfigService=t;this.exampleGenerator=new fr,this.refResolver=new mr}collectionService;envConfigService;exampleGenerator;refResolver;async import(e,t){let n=await ud.promises.readFile(e,"utf-8"),s=this.parseSpec(n,e);return this.importFromSpec(s,t)}async importFromUrl(e,t){let n=await fetch(e,{headers:{Accept:"application/json, application/yaml, text/yaml"}});if(!n.ok)throw new Error(`Failed to fetch OpenAPI spec from ${e}: HTTP ${n.status} ${n.statusText}`);let s=await n.text(),i=this.parseSpec(s,e);return this.importFromSpec(i,t)}async importFromString(e,t){let n=this.parseSpec(e,"spec");return this.importFromSpec(n,t)}parseSpec(e,t){let n=e.trim();if(!n)throw new Error(`OpenAPI spec is empty (${t})`);return n.startsWith("{")||n.startsWith("[")?JSON.parse(e):dd.parse(e)}async importFromSpec(e,t){let n=e;n=await this.refResolver.resolve(n);let s=n.components?.schemas||{},i=t?.collectionName||n.info?.title||"Imported API",a={id:se(i),name:i,description:n.info?.description||"",version:n.info?.version||"1.0.0",variables:{},items:[]};if(n.servers&&n.servers.length>0&&(a.variables.baseUrl=n.servers[0].url),n.security&&n.security.length>0&&n.components?.securitySchemes){let u=this.mapSecurityToAuth(n.security[0],n.components.securitySchemes);u&&(a.auth=u)}let c=new Map;if(n.tags)for(let u of n.tags){let d={type:"folder",id:se(u.name),name:u.name,description:u.description,items:[]};c.set(u.name,d),a.items.push(d)}if(n.paths)for(let[u,d]of Object.entries(n.paths))for(let p of["get","post","put","patch","delete","head","options","trace"]){let m=d[p];if(!m)continue;let f=this.processOperation(p,u,m,d,n,s),h=m.tags?.[0];if(h&&c.has(h))c.get(h).items.push(f);else if(h){let g={type:"folder",id:se(h),name:h,items:[f]};c.set(h,g),a.items.push(g)}else a.items.push(f)}await this.collectionService.saveCollection(a);let l;return t?.environmentName&&n.servers&&(l=await this.createEnvironmentFromServers(n.servers,t.environmentName)),{collection:a,environmentCreated:l}}processOperation(e,t,n,s,i,o){let a=se(n.operationId||`${e}-${t}`),c=`{{baseUrl}}${this.convertPathParams(t)}`,l=n.summary||n.operationId||`${e.toUpperCase()} ${t}`,u=n.deprecated===!0;u&&(l=`[DEPRECATED] ${l}`);let d={type:"request",id:a,name:l,method:e.toUpperCase(),url:c,description:n.description||"",deprecated:u};n.operationId&&(d.operationId=n.operationId),n.summary&&(d.summary=n.summary),n.tags?.length&&(d.tags=[...n.tags]);let p=[...s.parameters||[],...n.parameters||[]];if(this.processParameters(d,p,o),n.requestBody&&this.processRequestBody(d,n.requestBody,o),n.responses&&(d.responseSchema=this.processResponses(n.responses,o)),n.security!==void 0&&i.components?.securitySchemes){if(Array.isArray(n.security)&&n.security.length===0)d.auth={type:"none"};else if(n.security&&n.security.length>0){let m=this.mapSecurityToAuth(n.security[0],i.components.securitySchemes);m&&(d.auth=m)}}return d}convertPathParams(e){return e.replace(/\{(\w+)\}/g,":$1")}processParameters(e,t,n){let s=[],i=[],o={},a=[];for(let c of t){let l=c.name,u=c.in,d=c.schema||{},p=c.example!==void 0?String(c.example):this.generateExampleForParam(d,n),m=c.deprecated===!0;switch(u){case"path":{if(c.description||d.type||d.format||d.enum||m||d.pattern||d.minimum!==void 0||d.maximum!==void 0||d.minLength!==void 0||d.maxLength!==void 0||d.multipleOf!==void 0||d.minItems!==void 0||d.maxItems!==void 0||d.uniqueItems||d.nullable||d.oneOf){let h={value:p};d.oneOf?(h.oneOf=d.oneOf,this.applyOneOfHints(h,d.oneOf)):(d.type&&(h.type=d.type),d.format&&(h.format=d.format),d.enum&&(h.enum=d.enum.map(String)),d.pattern&&(h.pattern=d.pattern),d.minimum!==void 0&&(h.minimum=d.minimum),d.maximum!==void 0&&(h.maximum=d.maximum),d.exclusiveMinimum!==void 0&&(h.exclusiveMinimum=d.exclusiveMinimum),d.exclusiveMaximum!==void 0&&(h.exclusiveMaximum=d.exclusiveMaximum),d.multipleOf!==void 0&&(h.multipleOf=d.multipleOf),d.minLength!==void 0&&(h.minLength=d.minLength),d.maxLength!==void 0&&(h.maxLength=d.maxLength),d.minItems!==void 0&&(h.minItems=d.minItems),d.maxItems!==void 0&&(h.maxItems=d.maxItems),d.uniqueItems&&(h.uniqueItems=!0),d.nullable&&(h.nullable=!0)),c.description&&(h.description=c.description),m&&(h.deprecated=!0),o[l]=h}else o[l]=p;break}case"query":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),i.push(f);break}case"header":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),s.push(f);break}case"cookie":{a.push(`${l}={{${l}}}`);break}}}a.length>0&&s.push({key:"Cookie",value:a.join("; ")}),Object.keys(o).length>0&&(e.params=o),i.length>0&&(e.query=i),s.length>0&&(e.headers=s)}applySchemaConstraints(e,t,n,s){t.oneOf?(e.oneOf=t.oneOf,this.applyOneOfHints(e,t.oneOf)):(t.type&&(e.type=t.type),t.format&&(e.format=t.format),t.enum&&(e.enum=t.enum.map(String)),t.pattern&&(e.pattern=t.pattern),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.exclusiveMinimum!==void 0&&(e.exclusiveMinimum=t.exclusiveMinimum),t.exclusiveMaximum!==void 0&&(e.exclusiveMaximum=t.exclusiveMaximum),t.multipleOf!==void 0&&(e.multipleOf=t.multipleOf),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.minItems!==void 0&&(e.minItems=t.minItems),t.maxItems!==void 0&&(e.maxItems=t.maxItems),t.uniqueItems&&(e.uniqueItems=!0),t.nullable&&(e.nullable=!0)),n.required&&(e.required=!0),n.description&&(e.description=n.description),s&&(e.deprecated=!0)}applyOneOfHints(e,t){let n=[],s=new Set;for(let i of t)i.type&&s.add(i.type),i.enum&&n.push(...i.enum.map(String));s.size===1&&(e.type=[...s][0]),n.length>0&&(e.enum=[...new Set(n)])}generateExampleForParam(e,t){if(!e)return"";let n=this.exampleGenerator.generate(e,{components:t});return n==null?"":String(n)}processRequestBody(e,t,n){if(!t.content)return;let s=Object.keys(t.content);if(s.length===0)return;let i=this.selectPrimaryContentType(s),o=t.content[i],{bodyType:a,bodyFormat:c}=this.mapContentTypeToBodyType(i);if(e.body={type:a,...c&&{format:c},content:""},o){let u=this.generateBodyContent(o,i,n);u!==void 0&&(e.body.content=typeof u=="string"?u:JSON.stringify(u,null,2)),a==="form-data"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n)),a==="x-www-form-urlencoded"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n))}let l=this.buildBodySchema(t,i,n);l&&(e.bodySchema=l)}selectPrimaryContentType(e){for(let s of $h)if(e.includes(s))return s;let t=e.find(s=>s.includes("json"));if(t)return t;let n=e.find(s=>s.startsWith("text/"));return n||e[0]}mapContentTypeToBodyType(e){return e.includes("json")?{bodyType:"raw",bodyFormat:"json"}:e==="application/xml"||e==="text/xml"?{bodyType:"raw",bodyFormat:"xml"}:e==="text/html"?{bodyType:"raw",bodyFormat:"html"}:e.startsWith("text/")?{bodyType:"raw",bodyFormat:"text"}:e==="multipart/form-data"?{bodyType:"form-data"}:e==="application/x-www-form-urlencoded"?{bodyType:"x-www-form-urlencoded"}:e==="application/octet-stream"?{bodyType:"binary"}:{bodyType:"raw",bodyFormat:"text"}}generateBodyContent(e,t,n){if(e.example!==void 0)return e.example;if(e.examples){let s=Object.values(e.examples)[0];if(s?.value!==void 0)return s.value}if(e.schema)return this.exampleGenerator.generate(e.schema,{omitReadOnly:!0,components:n})}buildFormDataEntries(e,t){let n=[],s=e.properties||{},i=new Set(e.required||[]);for(let[o,a]of Object.entries(s)){let c=a,l=c.type==="string"&&c.format==="binary",u={key:o,value:l?"":String(this.exampleGenerator.generate(c,{components:t})||""),type:l?"file":"text",enabled:!0};n.push(u)}return n}buildBodySchema(e,t,n){let s=Object.keys(e.content),i=e.content[t];if(!i?.schema)return;let o={contentType:t,schema:i.schema};if(s.length>1){o.content={};for(let c of s){let l=e.content[c],u={};l.schema&&(u.schema=l.schema),l.examples&&(u.examples=l.examples),l.encoding&&(u.encoding=l.encoding),o.content[c]=u}}i.encoding&&(o.encoding=i.encoding);let a=this.extractUsedComponents(i.schema,n);return Object.keys(a).length>0&&(o.components=a),o}processResponses(e,t){let n={responses:{}},s={};for(let[i,o]of Object.entries(e)){let a=o,c={description:a.description||`Status ${i}`};if(a.content){let l=Object.keys(a.content);if(l.length===1){let u=l[0],d=a.content[u];c.contentType=u,d.schema&&(c.schema=d.schema),d.examples&&(c.examples=d.examples),d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}else{c.content={};for(let u of l){let d=a.content[u],p={};d.schema&&(p.schema=d.schema),d.examples&&(p.examples=d.examples),c.content[u]=p,d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}}}if(a.headers){c.headers={};for(let[l,u]of Object.entries(a.headers)){let d=u;c.headers[l]={...d.description&&{description:d.description},schema:d.schema||{type:"string"}}}}n.responses[i]=c}return Object.keys(s).length>0&&(n.components=s),n}mapSecurityToAuth(e,t){let n=Object.keys(e)[0];if(!n)return;let s=t[n];if(s)switch(s.type){case"http":if(s.scheme==="bearer")return{type:"bearer",bearerToken:""};if(s.scheme==="basic")return{type:"basic",basicAuth:{username:"",password:""}};break;case"apiKey":return{type:"apikey",apikey:{key:s.name||"X-Api-Key",value:"",in:s.in||"header"}};case"oauth2":{let i=s.flows||{},o=i.authorizationCode||i.clientCredentials||i.password||i.implicit||{},a="client_credentials";return i.authorizationCode?a="authorization_code":i.password?a="password":i.implicit&&(a="implicit"),{type:"oauth2",oauth2:{grantType:a,tokenUrl:o.tokenUrl||"",authUrl:o.authorizationUrl||"",clientId:"",clientSecret:"",scope:Object.keys(o.scopes||{}).join(" ")}}}}}async createEnvironmentFromServers(e,t){if(e.length>0){let n=e[0].url;this.envConfigService.setEnvironmentVariable("baseUrl",n)}return t}extractUsedComponents(e,t,n){let s=n||{};if(!e)return s;if(e.$ref){let i=this.extractRefName(e.$ref);i&&t[i]&&!s[i]&&(s[i]=t[i],this.extractUsedComponents(t[i],t,s))}if(e.properties)for(let i of Object.values(e.properties))this.extractUsedComponents(i,t,s);e.items&&this.extractUsedComponents(e.items,t,s);for(let i of["allOf","oneOf","anyOf"])if(e[i])for(let o of e[i])this.extractUsedComponents(o,t,s);return e.additionalProperties&&typeof e.additionalProperties=="object"&&this.extractUsedComponents(e.additionalProperties,t,s),s}extractRefName(e){return e.match(/^#\/components\/schemas\/(.+)$/)?.[1]}}});var ln,Qi=E(()=>{"use strict";ln=class{constructor(e,t,n){this.historyAnalyzer=e;this.scriptAnalyzer=t;this.inferrer=n}historyAnalyzer;scriptAnalyzer;inferrer;async infer(e,t,n,s){let i=await this.historyAnalyzer.analyze(e,t,{environment:s?.environment}),o;return s?.postResponseScript&&(o=this.scriptAnalyzer.analyze(s.postResponseScript)),this.mergeResponseSchemas(n,i,o)}async inferBodySchema(e,t,n,s,i){let o,a;if(t==="raw"&&n==="json"&&e){let c=e;if(typeof e=="string")try{c=JSON.parse(e)}catch{return}o=this.inferrer.inferFromValue(c),a="application/json"}else t==="form-data"&&s?(o=this.buildFormDataSchema(s),a="multipart/form-data"):t==="x-www-form-urlencoded"&&s?(o=this.buildFormDataSchema(s),a="application/x-www-form-urlencoded"):t==="raw"&&n==="xml"?(o={type:"string"},a="application/xml"):t==="raw"&&(n==="text"||n==="html")?(o={type:"string"},a=n==="html"?"text/html":"text/plain"):t==="binary"?(o={type:"string",format:"binary"},a="application/octet-stream"):t==="graphql"&&(o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a="application/json");if(o)return i?this.mergeBodySchemaWithExisting(o,i):{contentType:a,schema:o}}buildFormDataSchema(e){let t={type:"object",properties:{}},n=[];for(let s of e){if(!s.enabled&&s.enabled!==void 0)continue;let i={};s.type?i.type=s.type:i.type="string",s.description&&(i.description=s.description),s.format&&(i.format=s.format),s.enum&&(i.enum=s.enum),s.type==="file"&&(i.type="string",i.format="binary"),t.properties[s.key]=i,s.required&&n.push(s.key)}return n.length>0&&(t.required=n),t}mergeResponseSchemas(e,t,n){let s={responses:{}};for(let[i,o]of Object.entries(t.responses))s.responses[i]={...o};if(n&&this.applyScriptHints(s,n),e){for(let[i,o]of Object.entries(e.responses))s.responses[i]?s.responses[i]=this.mergeResponseDefinitions(s.responses[i],o):s.responses[i]={...o};e.components&&(s.components={...e.components})}return s}applyScriptHints(e,t){for(let n of t.expectedStatuses){let s=String(n);e.responses[s]||(e.responses[s]={description:`Status ${n}`})}for(let[,n]of Object.entries(e.responses))n.schema&&this.augmentSchemaWithHints(n.schema,t)}augmentSchemaWithHints(e,t){if(!(e.type!=="object"||!e.properties))for(let n of t.fieldPaths){let s=n.split(".");this.ensureFieldPath(e,s,t)}}ensureFieldPath(e,t,n,s=""){if(t.length===0||e.type!=="object")return;e.properties||(e.properties={});let i=t[0],o=i.endsWith("[]"),a=o?i.slice(0,-2):i,c=s?`${s}.${i}`:i,l=t.slice(1);if(!e.properties[a])if(o)e.properties[a]={type:"array",items:{type:"object"}};else if(l.length>0)e.properties[a]={type:"object",properties:{}};else{let u=n.typeHints[c];e.properties[a]={type:u||"string"};return}if(l.length>0){let u=o?e.properties[a].items:e.properties[a];u&&this.ensureFieldPath(u,l,n,c)}}mergeResponseDefinitions(e,t){let n={...e};return t.description&&(n.description=t.description),t.contentType&&(n.contentType=t.contentType),t.schema&&e.schema?n.schema=this.inferrer.mergeSchemas(e.schema,t.schema):t.schema&&(n.schema=t.schema),t.examples&&(n.examples={...e.examples||{},...t.examples}),t.content&&(n.content={...e.content||{},...t.content}),t.headers&&(n.headers={...e.headers||{},...t.headers}),n}mergeBodySchemaWithExisting(e,t){let n={...t};return t.schema?n.schema=this.inferrer.mergeSchemas(e,t.schema):n.schema=e,n}}});var pd,Zi,fd,md,hd,gd,yd,hr,Ec=E(()=>{"use strict";pd=/(?:jsonData|responseJson|data|json|body|response\.json\(\))\.([a-zA-Z_][\w.\[\]]*)/g,Zi="(?:pm|hf|ctx)",fd=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(?:a|an)\\(['"](\\w+)['"]\\)`,"g"),md=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.(?:equal|eql)\\((.+?)\\)`,"g"),hd=/(?:to\.have\.status|response\.code.*?equal)\((\d+)\)/g,gd=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(true|false)`,"g"),yd=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.have\\.(?:lengthOf|length\\.above|length\\.below)`,"g"),hr=class{analyze(e){let t={fieldPaths:[],typeHints:{},valueHints:{},expectedStatuses:[]};if(!e||e.trim().length===0)return t;let n=this.stripComments(e);return this.extractFieldPaths(n,t),this.extractTypeAssertions(n,t),this.extractEqualityAssertions(n,t),this.extractBooleanAssertions(n,t),this.extractLengthAssertions(n,t),this.extractStatusAssertions(n,t),t.fieldPaths=[...new Set(t.fieldPaths)],t.expectedStatuses=[...new Set(t.expectedStatuses)],t}stripComments(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"");return t=t.replace(/\/\/.*$/gm,""),t}extractFieldPaths(e,t){let n,s=new RegExp(pd.source,pd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&!this.isCommonMethodCall(i)&&t.fieldPaths.push(i)}}extractTypeAssertions(e,t){let n,s=new RegExp(fd.source,fd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].toLowerCase();i&&(t.typeHints[i]=this.mapAssertionType(o),t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractEqualityAssertions(e,t){let n,s=new RegExp(md.source,md.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].trim();if(i){let a=this.parseAssertionValue(o);a!==void 0&&(t.valueHints[i]=a,typeof a=="string"?t.typeHints[i]=t.typeHints[i]||"string":typeof a=="number"?t.typeHints[i]=t.typeHints[i]||(Number.isInteger(a)?"integer":"number"):typeof a=="boolean"&&(t.typeHints[i]=t.typeHints[i]||"boolean")),t.fieldPaths.includes(i)||t.fieldPaths.push(i)}}}extractBooleanAssertions(e,t){let n,s=new RegExp(gd.source,gd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]="boolean",t.valueHints[i]=n[2]==="true",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractLengthAssertions(e,t){let n,s=new RegExp(yd.source,yd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]=t.typeHints[i]||"array",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractStatusAssertions(e,t){let n,s=new RegExp(hd.source,hd.flags);for(;(n=s.exec(e))!==null;){let i=parseInt(n[1],10);!isNaN(i)&&i>=100&&i<600&&t.expectedStatuses.push(i)}}normalizeFieldPath(e){let t=e.replace(/^\./,"");return t=t.replace(/\[\d+\]/g,"[]"),t}isCommonMethodCall(e){return new Set(["to","be","have","not","deep","any","all","that","is","has","include","includes","equal","eql","above","below","least","most","within","length","lengthOf","match","string","keys","key","property","ownProperty","status","header","json","text"]).has(e.split(".")[0])}mapAssertionType(e){return{string:"string",number:"number",object:"object",array:"array",boolean:"boolean",null:"null",undefined:"null",int:"integer",integer:"integer",float:"number",double:"number"}[e]||"string"}parseAssertionValue(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);let t=Number(e);return!isNaN(t)&&e.trim().length>0?t:e==="true"?!0:e==="false"?!1:e==="null"?null:e}}});var vd={};Tt(vd,{AwsSecretResolver:()=>Yi});var Yi,qc=E(()=>{"use strict";Yi=class{providerName="aws";region;moduleRequire;constructor(e,t){this.region=e.region??process.env.AWS_DEFAULT_REGION??process.env.AWS_REGION,this.moduleRequire=t??(n=>ce(n))}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0;try{let{SecretsManagerClient:i,GetSecretValueCommand:o}=this.moduleRequire("@aws-sdk/client-secrets-manager"),c=await new i(this.region?{region:this.region}:{}).send(new o({SecretId:n})),l=c.SecretString??(c.SecretBinary?Buffer.from(c.SecretBinary).toString("utf-8"):void 0);if(l===void 0)return;if(s)try{let u=JSON.parse(l);return u[s]!==void 0?String(u[s]):void 0}catch{return}return l}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] AWS secret resolver requires @aws-sdk/client-secrets-manager. Install it in your project: npm install @aws-sdk/client-secrets-manager"):i}}}});var bd={};Tt(bd,{AzureKeyVaultResolver:()=>Xi});var Xi,Ac=E(()=>{"use strict";Xi=class{providerName="azure";vaultUrl;moduleRequire;constructor(e,t){let n=(e.vaultUrl||process.env.AZURE_KEYVAULT_URL)??"";this.vaultUrl=n.replace(/\/$/,""),this.moduleRequire=t??(s=>ce(s))}async resolve(e){if(!this.vaultUrl)throw new Error("[HTTP Forge] Azure Key Vault resolver: no vault URL configured. Set secrets.providers.<alias>.vaultUrl or the AZURE_KEYVAULT_URL env var.");let t=e.split("/"),n=t[0],s=t[1];try{let{SecretClient:i}=this.moduleRequire("@azure/keyvault-secrets"),{DefaultAzureCredential:o}=this.moduleRequire("@azure/identity"),a=new o;return(await new i(this.vaultUrl,a).getSecret(n,s?{version:s}:{})).value}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] Azure Key Vault resolver requires @azure/keyvault-secrets and @azure/identity. Install them: npm install @azure/keyvault-secrets @azure/identity"):i}}}});var Sd={};Tt(Sd,{HashiCorpVaultResolver:()=>eo});var eo,Pc=E(()=>{"use strict";eo=class{providerName="vault";address;mountPath;namespace;constructor(e){this.address=(e.address??process.env.VAULT_ADDR??"http://127.0.0.1:8200").replace(/\/$/,""),this.mountPath=e.mountPath??"secret",this.namespace=e.namespace??process.env.VAULT_NAMESPACE}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0,i=process.env.VAULT_TOKEN;if(!i)throw new Error("[HTTP Forge] HashiCorp Vault resolver requires VAULT_TOKEN environment variable to be set.");let o=`${this.address}/v1/${this.mountPath}/data/${n}`,a={"X-Vault-Token":i};this.namespace&&(a["X-Vault-Namespace"]=this.namespace);let c;try{c=await fetch(o,{headers:a})}catch(p){throw new Error(`[HTTP Forge] Vault request failed: ${p?.message??p}`)}if(c.status===404)return;if(!c.ok)throw new Error(`[HTTP Forge] Vault returned HTTP ${c.status} for path: ${n}`);let u=(await c.json())?.data?.data;if(!u)return;if(s)return u[s]!==void 0?String(u[s]):void 0;if("value"in u)return String(u.value);let d=Object.keys(u);return d.length===1?String(u[d[0]]):void 0}}});var xd={};Tt(xd,{OnePasswordResolver:()=>to});import{execFile as Fh}from"child_process";import{promisify as Nh}from"util";var _h,to,kc=E(()=>{"use strict";_h=Nh(Fh),to=class{providerName="1password";defaultVault;constructor(e){this.defaultVault=e.vault}async resolve(e){let t=e.split("/"),n,s,i;if(this.defaultVault){if(t.length<2)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<item>/<field>" when vault is set in config.`);n=this.defaultVault,s=t.slice(0,t.length-1).join("/"),i=t[t.length-1]}else{if(t.length<3)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<vault>/<item>/<field>".`);n=t[0],s=t.slice(1,t.length-1).join("/"),i=t[t.length-1]}let o=await this.tryResolveSdk(n,s,i);return o!==null?o:this.resolveViaCli(n,s,i)}async tryResolveSdk(e,t,n){let s=process.env.OP_SERVICE_ACCOUNT_TOKEN;if(!s)return null;try{let{createClient:i}=ce("@1password/sdk"),o=await i({auth:s,integrationName:"HTTP Forge",integrationVersion:"1.0.0"}),a=`op://${e}/${t}/${n}`;return await o.secrets.resolve(a)}catch(i){if(i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND")return null;throw new Error(`[HTTP Forge] 1Password SDK error for "${e}/${t}/${n}": ${i?.message??i}`)}}async resolveViaCli(e,t,n){try{let{stdout:s}=await _h("op",["item","get",t,"--vault",e,"--field",n,"--format","json"],{env:{...process.env},timeout:1e4}),i=JSON.parse(s.trim());return typeof i=="string"?i:i&&typeof i.value=="string"?i.value:void 0}catch(s){if(s?.code==="ENOENT")throw new Error("[HTTP Forge] 1Password resolver requires either the @1password/sdk npm package or the `op` CLI to be installed.\n Service Account: set OP_SERVICE_ACCOUNT_TOKEN and install @1password/sdk\n CLI: install 1Password CLI and run `op signin`");if(s?.stderr?.includes("not found")||s?.code===1)return;throw new Error(`[HTTP Forge] 1Password CLI error: ${s?.message??s}`)}}}});var wd={};Tt(wd,{GcpSecretResolver:()=>no});var no,Ic=E(()=>{"use strict";no=class{providerName="gcp";projectId;moduleRequire;constructor(e,t){this.projectId=e.projectId??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT??process.env.GCP_PROJECT,this.moduleRequire=t??(n=>ce(n))}async resolve(e){let t=e.split("/"),n=t[0],s=t[1]==="versions"&&t[2]?t[2]:"latest";if(!this.projectId)throw new Error("[HTTP Forge] GCP secret resolver: no projectId configured and GOOGLE_CLOUD_PROJECT env var is not set.");try{let{SecretManagerServiceClient:i}=this.moduleRequire("@google-cloud/secret-manager"),o=new i,a=`projects/${this.projectId}/secrets/${n}/versions/${s}`,[c]=await o.accessSecretVersion({name:a}),l=c.payload?.data;return l?Buffer.isBuffer(l)?l.toString("utf-8"):Buffer.from(l).toString("utf-8"):void 0}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] GCP secret resolver requires @google-cloud/secret-manager. Install it: npm install @google-cloud/secret-manager"):i}}}});var Cd={};Tt(Cd,{DopplerResolver:()=>ro});import*as Rd from"https";var ro,Tc=E(()=>{"use strict";ro=class{providerName="doppler";token;constructor(e){this.token=e.serviceToken??process.env.DOPPLER_TOKEN}async resolve(e){let t=e.trim().toUpperCase(),n=this.token;if(!n)throw new Error("[HTTP Forge] Doppler secret resolver: no service token found. Set DOPPLER_TOKEN env var or add serviceToken to config.");let s=`https://api.doppler.com/v3/configs/config/secret?name=${encodeURIComponent(t)}`;return new Promise((i,o)=>{let a=Rd.request(s,{method:"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}},c=>{let l=[];c.on("data",u=>l.push(u)),c.on("end",()=>{let u=Buffer.concat(l).toString("utf-8");if(c.statusCode===404){i(void 0);return}if(c.statusCode!==200){o(new Error(`[HTTP Forge] Doppler API returned ${c.statusCode} for secret "${t}": ${u}`));return}try{let p=JSON.parse(u)?.value?.computed;i(p!=null?String(p):void 0)}catch{o(new Error(`[HTTP Forge] Doppler API returned non-JSON response for secret "${t}"`))}})});a.on("error",o),a.end()})}}});import*as so from"fs";import{createRequire as Mh}from"module";import*as Ed from"path";var $s,Oc=E(()=>{"use strict";$s=class{resolvers=new Map;moduleRequire;constructor(e){if(this.moduleRequire=this.buildModuleRequire(e),!e)return;let t;try{t=e.getConfig().secrets}catch{return}if(!(!t?.providers||typeof t.providers!="object"))for(let[n,s]of Object.entries(t.providers))try{let i=this.createResolver(s);i&&this.resolvers.set(n,i)}catch{}}async resolveSecretTokens(e,t){let n=t??new Map,s=new Set;if(this.collectTokens(e,s),s.size===0)return{};await Promise.all(Array.from(s).map(async o=>{if(n.has(o))return;let a=o.slice(7),c=a.indexOf("/");if(c<0)return;let l=a.slice(0,c),u=a.slice(c+1),d=this.resolvers.get(l);if(d)try{let p=await d.resolve(u);p!==void 0&&n.set(o,p)}catch(p){let m=p?.message??String(p);console.warn(`[HTTP Forge] {{${o}}} could not be resolved: ${m}`)}}));let i={};for(let[o,a]of n.entries())i[o]=a;return i}get hasProviders(){return this.resolvers.size>0}collectTokens(e,t){if(typeof e=="string"){let n=/\{\{(secret:[^}]+)\}\}/g,s;for(;(s=n.exec(e))!==null;)t.add(s[1])}else Array.isArray(e)?e.forEach(n=>this.collectTokens(n,t)):e!==null&&typeof e=="object"&&Object.values(e).forEach(n=>this.collectTokens(n,t))}createResolver(e){switch(e.provider){case"aws":{let{AwsSecretResolver:t}=(qc(),Yn(vd));return new t(e,this.moduleRequire)}case"azure":{let{AzureKeyVaultResolver:t}=(Ac(),Yn(bd));return new t(e,this.moduleRequire)}case"vault":{let{HashiCorpVaultResolver:t}=(Pc(),Yn(Sd));return new t(e)}case"1password":{let{OnePasswordResolver:t}=(kc(),Yn(xd));return new t(e)}case"gcp":{let{GcpSecretResolver:t}=(Ic(),Yn(wd));return new t(e,this.moduleRequire)}case"doppler":{let{DopplerResolver:t}=(Tc(),Yn(Cd));return new t(e)}default:return}}buildModuleRequire(e){let t=s=>ce(s);if(!e)return t;let n=[];try{n=e.getModulePaths()??[]}catch{return t}for(let s of n)try{let i=Ed.resolve(s,"package.json");if(so.existsSync(i)){let o=so.realpathSync(i),a=Mh(o);return c=>{try{return a(c)}catch{return t(c)}}}}catch{}return t}}});function ke(r){return r.replace(/\//g,"%2F")}function Dh(r){return r.replace(/%2F/gi,"/")}function kt(r){return r?r.split("/").map(Dh).join(" / "):""}function gr(r){return r.includes(" / ")?r.split(" / ").map(e=>ke(e.trim())).join("/"):ke(r)}function Q(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="request")n.push({request:s,folderPath:t});else{let i=s,o=ke(i.name),a=t?`${t}/${o}`:o;n.push(...Q(r,i.items??[],a))}return n}function Ce(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="folder"){let i=s,o=ke(i.name),a=t?`${t}/${o}`:o;n.push({folderId:i.id,folderPath:a,requestCount:$c(i.items??[])}),n.push(...Ce(r,i.items??[],a))}return n}function $c(r){let e=0;for(let t of r)t.type==="request"?e++:e+=$c(t.items??[]);return e}var Ye=E(()=>{"use strict"});var jt,Fc=E(()=>{"use strict";jt={iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1}});import*as ie from"fs";import*as vt from"path";var Fs,Nc=E(()=>{"use strict";Ye();Ge();Fc();Fs=class{constructor(e,t,n){this.collectionService=e;this.configService=t;this.suitesDir=t.getSuitesPath(),this.onSuitesChanged=n?.onSuitesChanged,this.ensureSuitesDir(),this.loadSuites(),n?.watch!==!1&&this.setupFileWatcher()}collectionService;configService;suitesDir;suites=new Map;fileWatcher=null;debounceTimer=null;onSuitesChanged;ensureSuitesDir(){ie.existsSync(this.suitesDir)||ie.mkdirSync(this.suitesDir,{recursive:!0})}setupFileWatcher(){try{this.fileWatcher=ie.watch(this.suitesDir,(e,t)=>{t&&!t.endsWith(".suite.json")||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.loadSuites(),this.onSuitesChanged?.()},200))}),this.fileWatcher.on("error",()=>{})}catch{}}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.close(),this.fileWatcher=null}loadSuites(){if(this.suites.clear(),!ie.existsSync(this.suitesDir))return;let e=ie.readdirSync(this.suitesDir);for(let t of e)if(t.endsWith(".suite.json"))try{let n=vt.join(this.suitesDir,t),s=ie.readFileSync(n,"utf-8"),i=JSON.parse(s),o=Array.isArray(i.nodes)&&i.nodes.length>0?i.nodes:(Array.isArray(i.requests)?i.requests:[]).map(c=>({type:"request",name:c.description||c.name,request:c,enabled:c.enabled!==!1})),a={id:i.id,name:i.name,description:i.description,scripts:i.scripts,nodes:o,config:i.config??{...jt},isTemporary:i.isTemporary,ai_generated:i.ai_generated===!0,derived_from:Array.isArray(i.derived_from)?i.derived_from:void 0,createdAt:i.createdAt??Date.now(),updatedAt:i.updatedAt??Date.now()};a.id&&a.name&&this.suites.set(a.id,a)}catch(n){console.error(`[TestSuiteService] Failed to load ${t}:`,n)}}async getAllSuites(){return Array.from(this.suites.values())}async getSuite(e){return this.suites.get(e)}async createSuite(e){let t=Date.now(),n={id:se(e),name:e,nodes:[],config:{...jt},createdAt:t,updatedAt:t};return await this.saveSuiteToDisk(n),this.suites.set(n.id,n),n}async updateSuite(e){e.updatedAt=Date.now(),await this.saveSuiteToDisk(e),this.suites.set(e.id,e)}async duplicateSuite(e,t){let n=this.suites.get(e);if(!n)throw new Error(`Suite not found: ${e}`);let s=n.nodes||[],i=await this.createSuite(t);i.nodes=s.map(c=>({...c})),i.config={...n.config},i.description=n.description;let o=vt.join(this.suitesDir,e),a=vt.join(this.suitesDir,i.id);return ie.existsSync(o)&&this.copyDirRecursive(o,a),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}copyDirRecursive(e,t){ie.existsSync(t)||ie.mkdirSync(t,{recursive:!0});for(let n of ie.readdirSync(e,{withFileTypes:!0})){let s=vt.join(e,n.name),i=vt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):ie.copyFileSync(s,i)}}async deleteSuite(e){let t=this.suites.get(e);if(!t)return!1;let n=`${t.id}.suite.json`,s=vt.join(this.suitesDir,n),i=vt.join(this.suitesDir,t.id);try{return ie.existsSync(s)&&ie.unlinkSync(s),ie.existsSync(i)&&ie.rmSync(i,{recursive:!0,force:!0}),this.suites.delete(e),!0}catch(o){return console.error("[TestSuiteService] Failed to delete suite:",o),!1}}async createTempSuiteFromCollection(e){let t=this.collectionService.getCollection(e);if(!t){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let n=[];this.extractRequestsFromCollection(t,e,t.name,"",n);let s=n.map(a=>({type:"request",name:a.description||a.name,request:a,enabled:a.enabled!==!1})),i=Date.now();return{id:`temp-${e}`,name:t.name,nodes:s,config:{...jt},isTemporary:!0,createdAt:i,updatedAt:i}}async createTempSuiteFromFolder(e,t,n=!0){let s=this.collectionService.getCollection(e);if(!s){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let i=[];this.extractRequestsFromCollection(s,e,s.name,"",i);let o=t.replace(/\/+$/,""),a=i.filter(d=>n?d.folderPath===o||d.folderPath.startsWith(`${o}/`):d.folderPath===o);if(a.length===0){console.error(`[TestSuiteService] No requests under folder "${t}" in collection: ${e}`);return}let c=a.map(d=>({type:"request",name:d.description||d.name,request:d,enabled:d.enabled!==!1})),l=Date.now();return{id:`temp-${e}-${this.slugifyFolderPath(o)}`,name:`${s.name} / ${kt(o)}`,nodes:c,config:{...jt},isTemporary:!0,createdAt:l,updatedAt:l}}async createTempSuiteFromRequest(e,t){let n=this.collectionService.getCollection(e);if(!n){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let s=[];this.extractRequestsFromCollection(n,e,n.name,"",s);let i=s.find(u=>u.requestId===t);if(!i){console.error(`[TestSuiteService] Request not found: ${t} in collection: ${e}`);return}let a={type:"for",name:"Performance Loop (100 iterations)",init:'hf.variables.set("__i", 0)',loopCondition:'hf.variables.get("__i") < 100',update:'hf.variables.set("__i", hf.variables.get("__i") + 1)',maxIterations:100,nodes:[{type:"request",name:i.description||i.name,request:i,enabled:!0}],enabled:!0},c=Date.now();return{id:`temp-perf-${e}-${t}`,name:`${i.name} \u2014 Performance Test`,nodes:[a],config:{...jt},isTemporary:!0,createdAt:c,updatedAt:c}}slugifyFolderPath(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async saveTempSuite(e,t){let n=Date.now(),s=vt.join(this.suitesDir,e.id),i={...e,id:se(t),name:t,isTemporary:!1,createdAt:n,updatedAt:n},o=vt.join(this.suitesDir,i.id);return ie.existsSync(s)&&(ie.existsSync(o)&&ie.rmSync(o,{recursive:!0,force:!0}),ie.renameSync(s,o)),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}getAllAvailableRequests(){let e=[],t=this.collectionService.getAllCollections();for(let n of t)this.extractRequestsFromCollection(n,n.id,n.name,"",e);return e}extractRequestsFromCollection(e,t,n,s,i){if(e.requests)for(let o of e.requests)i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.items)for(let o of e.items)if(o.items||o.folders||o.requests){let a=s?`${s}/${ke(o.name)}`:ke(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}else i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.folders)for(let o of e.folders){let a=s?`${s}/${ke(o.name)}`:ke(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}}async saveSuiteToDisk(e){this.ensureSuitesDir();let t=`${e.id}.suite.json`,n=vt.join(this.suitesDir,t),s=`${n}.tmp-${process.pid}-${Date.now()}`,i={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/suite.schema.json",id:e.id,name:e.name,description:e.description,scripts:e.scripts,nodes:Array.isArray(e.nodes)?e.nodes:[],config:e.config??{...jt},isTemporary:e.isTemporary,ai_generated:e.ai_generated,derived_from:e.derived_from,createdAt:e.createdAt??Date.now(),updatedAt:e.updatedAt??Date.now()},o=JSON.stringify(i,null,2);ie.writeFileSync(s,o,"utf-8"),ie.renameSync(s,n)}}});var O,io=E(()=>{"use strict";O={Config:Symbol.for("IConfigService"),Console:Symbol.for("IConsoleService"),EnvironmentConfig:Symbol.for("IEnvironmentConfigService"),Collection:Symbol.for("ICollectionService"),HttpRequest:Symbol.for("IHttpRequestService"),HttpClient:Symbol.for("IHttpClient"),Cookie:Symbol.for("ICookieService"),RequestHistory:Symbol.for("IRequestHistoryService"),TestSuite:Symbol.for("ITestSuiteService"),UrlBuilder:Symbol.for("IUrlBuilder"),RequestPreprocessor:Symbol.for("IRequestPreprocessor"),RequestPreparer:Symbol.for("IRequestPreparer"),InterceptorChain:Symbol.for("IInterceptorChain"),ScriptExecutor:Symbol.for("IScriptExecutor"),DataFileParser:Symbol.for("IDataFileParser"),CollectionRequestExecutor:Symbol.for("ICollectionRequestExecutor"),WorkspaceFolder:Symbol.for("WorkspaceFolder"),PersistentCookieJar:Symbol.for("PersistentCookieJar"),OAuth2TokenManager:Symbol.for("IOAuth2TokenManager"),GraphQLSchemaService:Symbol.for("IGraphQLSchemaService"),SchemaInferrer:Symbol.for("SchemaInferrer"),HistoryAnalyzer:Symbol.for("HistoryAnalyzer"),ScriptAnalyzer:Symbol.for("ScriptAnalyzer"),SchemaInferenceService:Symbol.for("SchemaInferenceService"),OpenApiExporter:Symbol.for("OpenApiExporter"),OpenApiImporter:Symbol.for("OpenApiImporter"),SecretResolverRegistry:Symbol.for("SecretResolverRegistry")}});import*as qd from"path";function oo(r,e){let{workspaceFolder:t,fileWatcherFactory:n,notificationService:s,workspaceStore:i,globalStore:o,secretStore:a,browserService:c,applicationInfo:l,consoleService:u}=e;r.registerValue(O.WorkspaceFolder,t),r.registerSingleton(O.Config,()=>new rn(t,n,s)),r.registerSingleton(O.Console,()=>u??jh),r.registerSingleton(O.EnvironmentConfig,p=>new Cs(t,i,p.resolve(O.Config),n,a,e.persistOverrides??!0)),r.registerSingleton(O.Cookie,()=>new xs(o)),r.registerSingleton(O.Collection,p=>new Ss(p.resolve(O.Config),n)),r.registerSingleton(O.TestSuite,p=>new Fs(p.resolve(O.Collection),p.resolve(O.Config))),r.registerSingleton(O.HttpClient,p=>{let m=p.resolve(O.Config),f=p.resolve(O.EnvironmentConfig);return new An(()=>f.getResolvedConfig().request,t,()=>f.getResolvedConfig()?.proxy??null)}),r.registerSingleton(O.UrlBuilder,()=>new mt),r.registerSingleton(O.InterceptorChain,()=>new Ft),r.registerSingleton(O.HttpRequest,p=>new $t(p.resolve(O.UrlBuilder),p.resolve(O.InterceptorChain),p.resolve(O.HttpClient))),r.registerSingleton(O.RequestPreprocessor,()=>new Pn),r.registerSingleton(O.RequestHistory,p=>{let m=p.resolve(O.EnvironmentConfig);return new ks(m.getHistoriesPath(),qd.join(m.getRootPath(),"shared-histories"))}),a&&c&&r.registerSingleton(O.OAuth2TokenManager,p=>new ys(a,c,p.resolve(O.EnvironmentConfig),p.resolve(O.HttpRequest))),r.registerSingleton(O.GraphQLSchemaService,p=>new As(p.resolve(O.HttpClient))),r.registerSingleton(O.SecretResolverRegistry,p=>new $s(p.resolve(O.Config)));let d=l??{name:"HttpForge",version:"0.0.0"};r.registerSingleton(O.RequestPreparer,p=>new qs(p.resolve(O.EnvironmentConfig),p.resolve(O.HttpRequest),p.resolve(O.RequestPreprocessor),p.has(O.OAuth2TokenManager)?p.resolve(O.OAuth2TokenManager):void 0,d,p.resolve(O.SecretResolverRegistry))),r.registerSingleton(O.ScriptExecutor,p=>{let m=p.resolve(O.Config);return new Nt(p.resolve(O.HttpRequest),m.getModulePaths(),p.resolve(O.SecretResolverRegistry),m.getScriptScope(),m.getScriptTimeout())}),r.registerSingleton(O.DataFileParser,()=>new In),r.registerSingleton(O.CollectionRequestExecutor,p=>new _t(p.resolve(O.HttpRequest),p.resolve(O.ScriptExecutor),p.resolve(O.EnvironmentConfig),p.resolve(O.RequestPreparer),"")),r.registerSingleton(O.PersistentCookieJar,p=>new ws(p.resolve(O.Cookie))),r.registerSingleton(O.SchemaInferrer,()=>new an),r.registerSingleton(O.HistoryAnalyzer,p=>new pr(p.resolve(O.RequestHistory),p.resolve(O.SchemaInferrer))),r.registerSingleton(O.ScriptAnalyzer,()=>new hr),r.registerSingleton(O.SchemaInferenceService,p=>new ln(p.resolve(O.HistoryAnalyzer),p.resolve(O.ScriptAnalyzer),p.resolve(O.SchemaInferrer))),r.registerSingleton(O.OpenApiExporter,p=>new cn(p.resolve(O.Collection),p.resolve(O.EnvironmentConfig),p.resolve(O.SchemaInferenceService))),r.registerSingleton(O.OpenApiImporter,p=>new Dt(p.resolve(O.Collection),p.resolve(O.EnvironmentConfig)))}var jh,_c=E(()=>{"use strict";Qa();tc();Hi();rc();sc();ac();Es();cc();lc();hc();is();os();_i();Mi();er();gc();Wi();Ki();Qi();Vi();Ec();Di();ds();Oc();Nc();io();jh={log:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},logBatch:()=>{},logRawLines:()=>{},show:()=>{},clear:()=>{},dispose:()=>{}}});function Ad(){return Fn.instance}var Fn,Mc=E(()=>{"use strict";io();Fn=class r{static _instance;services=new Map;primitives=new Map;constructor(){}static get instance(){return r._instance||(r._instance=new r),r._instance}static createFresh(){return new r}static reset(){r._instance&&r._instance.clear(),r._instance=void 0}registerValue(e,t){return this.primitives.set(e,t),this}registerSingleton(e,t){return this.services.set(e,{factory:t,singleton:!0}),this}registerTransient(e,t){return this.services.set(e,{factory:t,singleton:!1}),this}registerInstance(e,t){return this.services.set(e,{factory:()=>t,singleton:!0,instance:t}),this}resolve(e){if(this.primitives.has(e))return this.primitives.get(e);let t=this.services.get(e);if(!t)throw new Error(`Service not registered: ${e.toString()}`);return t.singleton?(t.instance||(t.instance=t.factory(this)),t.instance):t.factory(this)}has(e){return this.services.has(e)||this.primitives.has(e)}dispose(){for(let e of this.services.values())if(e.singleton&&e.instance){let t=e.instance;if(typeof t.dispose=="function")try{t.dispose()}catch{}}this.clear()}clear(){this.services.clear(),this.primitives.clear()}get config(){return this.resolve(O.Config)}get console(){return this.resolve(O.Console)}get environmentConfig(){return this.resolve(O.EnvironmentConfig)}get collection(){return this.resolve(O.Collection)}get httpRequest(){return this.resolve(O.HttpRequest)}get httpClient(){return this.resolve(O.HttpClient)}get cookie(){return this.resolve(O.Cookie)}get requestHistory(){return this.resolve(O.RequestHistory)}get dataFileParser(){return this.resolve(O.DataFileParser)}get scriptExecutor(){return this.resolve(O.ScriptExecutor)}get requestPreparer(){return this.resolve(O.RequestPreparer)}get persistentCookieJar(){return this.resolve(O.PersistentCookieJar)}get oauth2TokenManager(){return this.has(O.OAuth2TokenManager)?this.resolve(O.OAuth2TokenManager):void 0}get graphqlSchemaService(){return this.resolve(O.GraphQLSchemaService)}get testSuite(){return this.resolve(O.TestSuite)}}});import*as _n from"fs";import*as yr from"path";function Lt(r){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Collection",body:kd(r),generatedAt:Date.now()}),freshness:()=>r.items.length>0?"fresh":"stale"}}function tt(r,e){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Request",body:Dc(r,e),generatedAt:Date.now()}),freshness:()=>Dc(r,e)?"fresh":"stale"}}function nt(r){return{kind:"workspace-knowledge",snapshot:()=>({kind:"workspace-knowledge",heading:"Business Knowledge",body:Ns(r),generatedAt:Date.now()}),freshness:()=>Ns(r)?"fresh":"stale"}}function co(r,e){return{kind:"run-results",snapshot:()=>({kind:"run-results",heading:"Test Results",body:Id(r,e),generatedAt:Date.now()}),freshness:()=>{if(!e||!r)return"stale";let t=r.get(e);return t?t.status==="running"?"stale":"fresh":"stale"}}}function Uh(r){lo.push(r)}function Vh(){lo.length=0}function zh(){return lo.slice()}function Dc(r,e){let t=[],n=e&&e!=="(root)"?`${e} / ${r.name}`:r.name;return r.description?.trim()&&t.push(`Description: ${Nn(r.description,400)}`),r.doc?.trim()&&t.push(`Docs (doc.md): ${Nn(r.doc,Lh)}`),r.operationId&&t.push(`OpenAPI operationId: ${r.operationId}`),r.summary?.trim()&&t.push(`OpenAPI summary: ${Nn(r.summary,200)}`),r.tags?.length&&t.push(`OpenAPI tags: ${r.tags.join(", ")}`),r.deprecated&&t.push("Deprecated: true"),r.responseSchema&&t.push(`Response schema: ${Nn(JSON.stringify(r.responseSchema),400)}`),r.bodySchema&&t.push(`Request body schema: ${Nn(JSON.stringify(r.bodySchema),300)}`),r.settings?.timeout!==void 0&&t.push(`Timeout: ${r.settings.timeout}ms`),t.length===0?"":`[${r.method??"GET"} ${r.url??""}] ${n}
|
|
286
|
+
Variant: **${n}**`+(t.description?` \u2014 ${t.description}`:"")),t.tags){let s=new Set(e.tags||[]);for(let i of t.tags)s.add(i);e.tags=[...s]}if(t.parameters){e.parameters||(e.parameters=[]);for(let s of t.parameters){let i=e.parameters.find(o=>o.name===s.name&&o.in===s.in);i?this.mergeParameterSchema(i,s,n):e.parameters.push(s)}}if(t.responses){e.responses||(e.responses={});for(let[s,i]of Object.entries(t.responses))e.responses[s]||(e.responses[s]=i)}if(t.requestBody?.content&&e.requestBody?.content)for(let[s,i]of Object.entries(t.requestBody.content))e.requestBody.content[s]||(e.requestBody.content[s]=i);else t.requestBody&&!e.requestBody&&(e.requestBody=t.requestBody)}mergeParameterSchema(e,t,n){e.schema||(e.schema={});let s=e.schema,i=t.schema||{},o=this.getConstraintKind(s),a=this.getConstraintKind(i);if(o==="none"&&a==="none")this.widenType(s,i);else if(o==="none")Object.assign(s,this.extractConstraints(i)),this.widenType(s,i);else if(a==="none")this.widenType(s,i);else if(o===a)this.mergeSameKindConstraints(s,i,o),this.widenType(s,i);else{if(s.oneOf){let c=this.buildVariantSchema(i);s.oneOf.some(l=>JSON.stringify(l)===JSON.stringify(c))||s.oneOf.push(c)}else if(i.oneOf){let c=this.buildVariantSchema(s);s.oneOf=[c,...i.oneOf]}else{let c=this.buildVariantSchema(s),l=this.buildVariantSchema(i);s.oneOf=[c,l]}this.stripConstraints(s)}if(t.description&&t.description!==e.description&&(e.description=(e.description||"")+(e.description?"; ":"")+t.description),t.example!==void 0&&t.example!==e.example){e.examples||(e.examples={},e.example!==void 0&&(e.examples.variant1={value:e.example}));let c=`variant_${n.replace(/[^a-zA-Z0-9_]/g,"_")}`;e.examples[c]={value:t.example},delete e.example}}getConstraintKind(e){return e.oneOf?"oneOf":e.enum&&e.enum.length>0?"enum":e.pattern?"pattern":e.minimum!==void 0||e.maximum!==void 0||e.exclusiveMinimum!==void 0||e.exclusiveMaximum!==void 0||e.multipleOf!==void 0?"range":e.minLength!==void 0||e.maxLength!==void 0?"length":e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems?"array":e.format?"format":"none"}mergeSameKindConstraints(e,t,n){switch(n){case"enum":{let s=new Set(e.enum||[]);for(let i of t.enum||[])s.add(i);e.enum=[...s];break}case"pattern":{t.pattern&&t.pattern!==e.pattern&&(e.pattern=`(?:${e.pattern})|(?:${t.pattern})`);break}case"range":{t.minimum!==void 0&&(e.minimum=e.minimum!==void 0?Math.min(e.minimum,t.minimum):t.minimum),t.maximum!==void 0&&(e.maximum=e.maximum!==void 0?Math.max(e.maximum,t.maximum):t.maximum),t.exclusiveMinimum&&(e.exclusiveMinimum=!0),t.exclusiveMaximum&&(e.exclusiveMaximum=!0),t.multipleOf!==void 0&&(e.multipleOf=e.multipleOf!==void 0?Math.min(e.multipleOf,t.multipleOf):t.multipleOf);break}case"length":{t.minLength!==void 0&&(e.minLength=e.minLength!==void 0?Math.min(e.minLength,t.minLength):t.minLength),t.maxLength!==void 0&&(e.maxLength=e.maxLength!==void 0?Math.max(e.maxLength,t.maxLength):t.maxLength);break}case"array":{t.minItems!==void 0&&(e.minItems=e.minItems!==void 0?Math.min(e.minItems,t.minItems):t.minItems),t.maxItems!==void 0&&(e.maxItems=e.maxItems!==void 0?Math.max(e.maxItems,t.maxItems):t.maxItems),t.uniqueItems&&(e.uniqueItems=!0);break}case"format":{if(t.format&&t.format!==e.format){let s={type:e.type||"string",format:e.format},i={type:t.type||"string",format:t.format};delete e.format,e.oneOf=[s,i]}break}case"oneOf":{if(t.oneOf)for(let s of t.oneOf)e.oneOf.some(i=>JSON.stringify(i)===JSON.stringify(s))||e.oneOf.push(s);break}}}buildVariantSchema(e){let t={};return e.type&&(t.type=e.type),e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),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.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}stripConstraints(e){delete e.enum,delete e.pattern,delete e.format,delete e.minimum,delete e.maximum,delete e.exclusiveMinimum,delete e.exclusiveMaximum,delete e.multipleOf,delete e.minLength,delete e.maxLength,delete e.minItems,delete e.maxItems,delete e.uniqueItems,delete e.nullable}extractConstraints(e){let t={};return e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),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.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}widenType(e,t){if(!(!t.type||t.type===e.type))if(!e.type)e.type=t.type;else{let n=Ui(e.type,t.type);n&&(e.type=n)}}}});import*as cd from"yaml";var Gi,ld=E(()=>{"use strict";Gi=class{finalize(e,t,n,s){if(t.size>0)for(let[i,o]of t)e.components.securitySchemes[i]=o;else delete e.components.securitySchemes;return e.tags=[...n].map(i=>({name:i})),e.tags.length===0&&delete e.tags,this.deduplicateComponents(e),Object.keys(e.components.schemas).length===0&&delete e.components.schemas,Object.keys(e.components).length===0&&delete e.components,s.format==="yaml"?cd.stringify(e,{indent:2}):JSON.stringify(e,null,2)}deduplicateComponents(e){let t=new Map,n=new Map;if(e.paths)for(let[s,i]of Object.entries(e.paths))for(let[o,a]of Object.entries(i)){let c=a;if(c.responses){for(let[l,u]of Object.entries(c.responses))if(u.content)for(let d of Object.values(u.content))d.schema&&this.trackSchema(d.schema,`${o}${s}Response${l}`,t,n)}if(c.requestBody?.content)for(let l of Object.values(c.requestBody.content))l.schema&&this.trackSchema(l.schema,`${o}${s}Request`,t,n)}for(let[s,i]of t)if((n.get(s)||0)>=2){let a=this.sanitizeComponentName(i.name);e.components.schemas[a]=i.schema,this.replaceInlineSchema(e,i.schema,`#/components/schemas/${a}`)}}trackSchema(e,t,n,s){if(!e||e.type!=="object"||!e.properties)return;let i=JSON.stringify(e);n.has(i)||n.set(i,{name:t,schema:e}),s.set(i,(s.get(i)||0)+1)}replaceInlineSchema(e,t,n){let s=JSON.stringify(t);if(e.paths)for(let i of Object.values(e.paths))for(let o of Object.values(i)){if(o.responses){for(let a of Object.values(o.responses))if(a.content)for(let c of Object.values(a.content))c.schema&&JSON.stringify(c.schema)===s&&(c.schema={$ref:n})}if(o.requestBody?.content)for(let a of Object.values(o.requestBody.content))a.schema&&JSON.stringify(a.schema)===s&&(a.schema={$ref:n})}}sanitizeComponentName(e){return e.replace(/[^a-zA-Z0-9._-]/g,"").replace(/^[^a-zA-Z]/,"Schema")}}});var cn,Wi=E(()=>{"use strict";Vi();od();ad();ld();Os();cn=class{constructor(e,t,n){this.collectionService=e;this.envConfigService=t;this.inferenceService=n;let s=new an;this.merger=new Ji,this.operationBuilder=new zi(s),this.specWriter=new Gi}collectionService;envConfigService;inferenceService;merger;operationBuilder;specWriter;async export(e,t){let n=this.collectionService.getCollection(e);if(!n)throw new Error(`Collection ${e} not found`);let s={openapi:"3.0.3",info:this.buildInfo(n,t),servers:this.buildServers(t),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},i=new Map;if(n.auth&&n.auth.type!=="none"&&n.auth.type!=="inherit"){let c=this.operationBuilder.mapAuthToSecurityScheme(n.auth);if(c){let{schemeName:l,scheme:u,requirement:d}=c;i.set(l,u),s.security=[d]}}let o=new Set,a=new Set;return await this.processItems(n.items,s,i,o,a,void 0,n,t),this.augmentServersFromHostVars(a,s.servers,t),this.specWriter.finalize(s,i,o,t)}buildInfo(e,t){return{title:t.info?.title||e.name,description:t.info?.description||e.description||"",version:t.info?.version||e.version||"1.0.0"}}buildServers(e){let t=[],n=e.environments||[];if(n.length===0){let s=this.envConfigService.getSelectedEnvironment();if(s){let i=this.envConfigService.resolveVariables("{{baseUrl}}",s);i&&i!=="{{baseUrl}}"&&t.push({url:i,description:s})}}else{let s=new Set;for(let i of n){let o=this.envConfigService.resolveVariables("{{baseUrl}}",i);o&&o!=="{{baseUrl}}"&&!s.has(o)&&(s.add(o),t.push({url:o,description:i}))}}return t.length===0&&t.push({url:"http://localhost",description:"Default server"}),t}async processItems(e,t,n,s,i,o,a,c){for(let l of e)if(l.type==="folder"){let u=l,d=o||u.name;s.add(d),u.items&&await this.processItems(u.items,t,n,s,i,d,a,c)}else{let u=l;await this.processRequest(u,t,n,s,i,o,a,c)}}async processRequest(e,t,n,s,i,o,a,c){let{path:l,hostVar:u}=td(e.url);u&&i.add(u);let d=(e.method||"GET").toLowerCase();t.paths[l]||(t.paths[l]={});let p=await this.operationBuilder.buildOperation(e,d,l,t,n,s,o,a,c),m=t.paths[l][d];m?this.merger.mergeOperation(m,p,e.name):t.paths[l][d]=p}augmentServersFromHostVars(e,t,n){if(e.size===0)return;let s=new Set(t.map(o=>o.url)),i=n.environments?.length?n.environments:[this.envConfigService.getSelectedEnvironment()].filter(o=>!!o);for(let o of e){let a=`{{${o}}}`,c=!1;for(let l of i){let u=this.envConfigService.resolveVariables(a,l);u&&u!==a&&!s.has(u)&&(t.push({url:u,description:l}),s.add(u),c=!0)}if(!c){let l=`{${o}}`;s.has(l)||(t.push({url:l,variables:{[o]:{default:""}}}),s.add(l))}}}}});var fr,wc=E(()=>{"use strict";fr=class{generate(e,t){if(!e)return;let n=t||{};if(e.$ref){let s=this.resolveLocalRef(e.$ref,n.components);return s?this.generate(s,n):{}}if(e.nullable&&!e.type)return null;if(e.enum&&e.enum.length>0)return e.enum[0];if(e.default!==void 0)return e.default;if(e.example!==void 0)return e.example;if(e.allOf)return this.generateFromAllOf(e.allOf,e.discriminator,n);if(e.oneOf)return this.generateFromOneOfAnyOf(e.oneOf,e.discriminator,n);if(e.anyOf)return this.generateFromOneOfAnyOf(e.anyOf,e.discriminator,n);switch(e.type){case"string":return this.generateString(e);case"integer":return this.generateInteger(e);case"number":return this.generateNumber(e);case"boolean":return!1;case"array":return this.generateArray(e,n);case"object":return this.generateObject(e,n);default:return e.properties?this.generateObject(e,n):{}}}generateString(e){switch(e.format){case"email":return"user@example.com";case"date-time":return"2026-01-01T00:00:00Z";case"date":return"2026-01-01";case"time":return"00:00:00";case"uri":case"url":return"https://example.com";case"uuid":return"00000000-0000-0000-0000-000000000000";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"hostname":return"example.com";case"binary":return"";case"byte":return"c3RyaW5n";case"password":return"********";default:return"string"}}generateInteger(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+1:0}generateNumber(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+.1:0}generateArray(e,t){return e.items?[this.generate(e.items,t)]:[]}generateObject(e,t){let n={},s=e.properties||{};for(let[i,o]of Object.entries(s))t.omitReadOnly&&o.readOnly||(n[i]=this.generate(o,t));return n}generateFromAllOf(e,t,n){let s={type:"object",properties:{},required:[]};for(let o of e){let a=o.$ref?this.resolveLocalRef(o.$ref,n.components)||{}:o;a.properties&&Object.assign(s.properties,a.properties),a.required&&(s.required=[...s.required||[],...a.required])}let i=this.generateObject(s,n);return t?.propertyName&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}generateFromOneOfAnyOf(e,t,n){if(e.length===0)return{};let s=e[0].$ref&&this.resolveLocalRef(e[0].$ref,n.components)||e[0],i=this.generate(s,n);return t?.propertyName&&typeof i=="object"&&i!==null&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}guessDiscriminatorValue(e,t){if(e.length===0)return"unknown";let n=e[0];if(n.$ref){let s=n.$ref.split("/");return s[s.length-1]}return"variant1"}resolveLocalRef(e,t){if(!e||!t)return;let n=e.match(/^#\/components\/(?:schemas\/)?(.+)$/);if(n)return t[n[1]];let s=e.match(/^#\/components\/(.+)$/);if(s)return t[s[1]]}}});import Rc from"@apidevtools/json-schema-ref-parser";var mr,Cc=E(()=>{"use strict";mr=class{async resolve(e){try{return await Rc.dereference(e,{dereference:{circular:"ignore"}})}catch(t){return console.error("[RefResolver] Failed to fully resolve $ref pointers:",t),e}}async bundle(e){try{return await Rc.bundle(e)}catch(t){return console.error("[RefResolver] Failed to bundle $ref pointers:",t),e}}async resolveFile(e){try{return await Rc.dereference(e,{dereference:{circular:"ignore"}})}catch(t){throw console.error(`[RefResolver] Failed to resolve file ${e}:`,t),t}}}});import*as ud from"fs";import*as dd from"yaml";var $h,Dt,Ki=E(()=>{"use strict";Ge();wc();Cc();$h=["application/json","text/plain","text/html","multipart/form-data","application/x-www-form-urlencoded"],Dt=class{constructor(e,t){this.collectionService=e;this.envConfigService=t;this.exampleGenerator=new fr,this.refResolver=new mr}collectionService;envConfigService;exampleGenerator;refResolver;async import(e,t){let n=await ud.promises.readFile(e,"utf-8"),s=this.parseSpec(n,e);return this.importFromSpec(s,t)}async importFromUrl(e,t){let n=await fetch(e,{headers:{Accept:"application/json, application/yaml, text/yaml"}});if(!n.ok)throw new Error(`Failed to fetch OpenAPI spec from ${e}: HTTP ${n.status} ${n.statusText}`);let s=await n.text(),i=this.parseSpec(s,e);return this.importFromSpec(i,t)}async importFromString(e,t){let n=this.parseSpec(e,"spec");return this.importFromSpec(n,t)}parseSpec(e,t){let n=e.trim();if(!n)throw new Error(`OpenAPI spec is empty (${t})`);return n.startsWith("{")||n.startsWith("[")?JSON.parse(e):dd.parse(e)}async importFromSpec(e,t){let n=e;n=await this.refResolver.resolve(n);let s=n.components?.schemas||{},i=t?.collectionName||n.info?.title||"Imported API",a={id:se(i),name:i,description:n.info?.description||"",version:n.info?.version||"1.0.0",variables:{},items:[]};if(n.servers&&n.servers.length>0&&(a.variables.baseUrl=n.servers[0].url),n.security&&n.security.length>0&&n.components?.securitySchemes){let u=this.mapSecurityToAuth(n.security[0],n.components.securitySchemes);u&&(a.auth=u)}let c=new Map;if(n.tags)for(let u of n.tags){let d={type:"folder",id:se(u.name),name:u.name,description:u.description,items:[]};c.set(u.name,d),a.items.push(d)}if(n.paths)for(let[u,d]of Object.entries(n.paths))for(let p of["get","post","put","patch","delete","head","options","trace"]){let m=d[p];if(!m)continue;let f=this.processOperation(p,u,m,d,n,s),h=m.tags?.[0];if(h&&c.has(h))c.get(h).items.push(f);else if(h){let g={type:"folder",id:se(h),name:h,items:[f]};c.set(h,g),a.items.push(g)}else a.items.push(f)}await this.collectionService.saveCollection(a);let l;return t?.environmentName&&n.servers&&(l=await this.createEnvironmentFromServers(n.servers,t.environmentName)),{collection:a,environmentCreated:l}}processOperation(e,t,n,s,i,o){let a=se(n.operationId||`${e}-${t}`),c=`{{baseUrl}}${this.convertPathParams(t)}`,l=n.summary||n.operationId||`${e.toUpperCase()} ${t}`,u=n.deprecated===!0;u&&(l=`[DEPRECATED] ${l}`);let d={type:"request",id:a,name:l,method:e.toUpperCase(),url:c,description:n.description||"",deprecated:u};n.operationId&&(d.operationId=n.operationId),n.summary&&(d.summary=n.summary),n.tags?.length&&(d.tags=[...n.tags]);let p=[...s.parameters||[],...n.parameters||[]];if(this.processParameters(d,p,o),n.requestBody&&this.processRequestBody(d,n.requestBody,o),n.responses&&(d.responseSchema=this.processResponses(n.responses,o)),n.security!==void 0&&i.components?.securitySchemes){if(Array.isArray(n.security)&&n.security.length===0)d.auth={type:"none"};else if(n.security&&n.security.length>0){let m=this.mapSecurityToAuth(n.security[0],i.components.securitySchemes);m&&(d.auth=m)}}return d}convertPathParams(e){return e.replace(/\{(\w+)\}/g,":$1")}processParameters(e,t,n){let s=[],i=[],o={},a=[];for(let c of t){let l=c.name,u=c.in,d=c.schema||{},p=c.example!==void 0?String(c.example):this.generateExampleForParam(d,n),m=c.deprecated===!0;switch(u){case"path":{if(c.description||d.type||d.format||d.enum||m||d.pattern||d.minimum!==void 0||d.maximum!==void 0||d.minLength!==void 0||d.maxLength!==void 0||d.multipleOf!==void 0||d.minItems!==void 0||d.maxItems!==void 0||d.uniqueItems||d.nullable||d.oneOf){let h={value:p};d.oneOf?(h.oneOf=d.oneOf,this.applyOneOfHints(h,d.oneOf)):(d.type&&(h.type=d.type),d.format&&(h.format=d.format),d.enum&&(h.enum=d.enum.map(String)),d.pattern&&(h.pattern=d.pattern),d.minimum!==void 0&&(h.minimum=d.minimum),d.maximum!==void 0&&(h.maximum=d.maximum),d.exclusiveMinimum!==void 0&&(h.exclusiveMinimum=d.exclusiveMinimum),d.exclusiveMaximum!==void 0&&(h.exclusiveMaximum=d.exclusiveMaximum),d.multipleOf!==void 0&&(h.multipleOf=d.multipleOf),d.minLength!==void 0&&(h.minLength=d.minLength),d.maxLength!==void 0&&(h.maxLength=d.maxLength),d.minItems!==void 0&&(h.minItems=d.minItems),d.maxItems!==void 0&&(h.maxItems=d.maxItems),d.uniqueItems&&(h.uniqueItems=!0),d.nullable&&(h.nullable=!0)),c.description&&(h.description=c.description),m&&(h.deprecated=!0),o[l]=h}else o[l]=p;break}case"query":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),i.push(f);break}case"header":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),s.push(f);break}case"cookie":{a.push(`${l}={{${l}}}`);break}}}a.length>0&&s.push({key:"Cookie",value:a.join("; ")}),Object.keys(o).length>0&&(e.params=o),i.length>0&&(e.query=i),s.length>0&&(e.headers=s)}applySchemaConstraints(e,t,n,s){t.oneOf?(e.oneOf=t.oneOf,this.applyOneOfHints(e,t.oneOf)):(t.type&&(e.type=t.type),t.format&&(e.format=t.format),t.enum&&(e.enum=t.enum.map(String)),t.pattern&&(e.pattern=t.pattern),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.exclusiveMinimum!==void 0&&(e.exclusiveMinimum=t.exclusiveMinimum),t.exclusiveMaximum!==void 0&&(e.exclusiveMaximum=t.exclusiveMaximum),t.multipleOf!==void 0&&(e.multipleOf=t.multipleOf),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.minItems!==void 0&&(e.minItems=t.minItems),t.maxItems!==void 0&&(e.maxItems=t.maxItems),t.uniqueItems&&(e.uniqueItems=!0),t.nullable&&(e.nullable=!0)),n.required&&(e.required=!0),n.description&&(e.description=n.description),s&&(e.deprecated=!0)}applyOneOfHints(e,t){let n=[],s=new Set;for(let i of t)i.type&&s.add(i.type),i.enum&&n.push(...i.enum.map(String));s.size===1&&(e.type=[...s][0]),n.length>0&&(e.enum=[...new Set(n)])}generateExampleForParam(e,t){if(!e)return"";let n=this.exampleGenerator.generate(e,{components:t});return n==null?"":String(n)}processRequestBody(e,t,n){if(!t.content)return;let s=Object.keys(t.content);if(s.length===0)return;let i=this.selectPrimaryContentType(s),o=t.content[i],{bodyType:a,bodyFormat:c}=this.mapContentTypeToBodyType(i);if(e.body={type:a,...c&&{format:c},content:""},o){let u=this.generateBodyContent(o,i,n);u!==void 0&&(e.body.content=typeof u=="string"?u:JSON.stringify(u,null,2)),a==="form-data"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n)),a==="x-www-form-urlencoded"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n))}let l=this.buildBodySchema(t,i,n);l&&(e.bodySchema=l)}selectPrimaryContentType(e){for(let s of $h)if(e.includes(s))return s;let t=e.find(s=>s.includes("json"));if(t)return t;let n=e.find(s=>s.startsWith("text/"));return n||e[0]}mapContentTypeToBodyType(e){return e.includes("json")?{bodyType:"raw",bodyFormat:"json"}:e==="application/xml"||e==="text/xml"?{bodyType:"raw",bodyFormat:"xml"}:e==="text/html"?{bodyType:"raw",bodyFormat:"html"}:e.startsWith("text/")?{bodyType:"raw",bodyFormat:"text"}:e==="multipart/form-data"?{bodyType:"form-data"}:e==="application/x-www-form-urlencoded"?{bodyType:"x-www-form-urlencoded"}:e==="application/octet-stream"?{bodyType:"binary"}:{bodyType:"raw",bodyFormat:"text"}}generateBodyContent(e,t,n){if(e.example!==void 0)return e.example;if(e.examples){let s=Object.values(e.examples)[0];if(s?.value!==void 0)return s.value}if(e.schema)return this.exampleGenerator.generate(e.schema,{omitReadOnly:!0,components:n})}buildFormDataEntries(e,t){let n=[],s=e.properties||{},i=new Set(e.required||[]);for(let[o,a]of Object.entries(s)){let c=a,l=c.type==="string"&&c.format==="binary",u={key:o,value:l?"":String(this.exampleGenerator.generate(c,{components:t})||""),type:l?"file":"text",enabled:!0};n.push(u)}return n}buildBodySchema(e,t,n){let s=Object.keys(e.content),i=e.content[t];if(!i?.schema)return;let o={contentType:t,schema:i.schema};if(s.length>1){o.content={};for(let c of s){let l=e.content[c],u={};l.schema&&(u.schema=l.schema),l.examples&&(u.examples=l.examples),l.encoding&&(u.encoding=l.encoding),o.content[c]=u}}i.encoding&&(o.encoding=i.encoding);let a=this.extractUsedComponents(i.schema,n);return Object.keys(a).length>0&&(o.components=a),o}processResponses(e,t){let n={responses:{}},s={};for(let[i,o]of Object.entries(e)){let a=o,c={description:a.description||`Status ${i}`};if(a.content){let l=Object.keys(a.content);if(l.length===1){let u=l[0],d=a.content[u];c.contentType=u,d.schema&&(c.schema=d.schema),d.examples&&(c.examples=d.examples),d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}else{c.content={};for(let u of l){let d=a.content[u],p={};d.schema&&(p.schema=d.schema),d.examples&&(p.examples=d.examples),c.content[u]=p,d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}}}if(a.headers){c.headers={};for(let[l,u]of Object.entries(a.headers)){let d=u;c.headers[l]={...d.description&&{description:d.description},schema:d.schema||{type:"string"}}}}n.responses[i]=c}return Object.keys(s).length>0&&(n.components=s),n}mapSecurityToAuth(e,t){let n=Object.keys(e)[0];if(!n)return;let s=t[n];if(s)switch(s.type){case"http":if(s.scheme==="bearer")return{type:"bearer",bearerToken:""};if(s.scheme==="basic")return{type:"basic",basicAuth:{username:"",password:""}};break;case"apiKey":return{type:"apikey",apikey:{key:s.name||"X-Api-Key",value:"",in:s.in||"header"}};case"oauth2":{let i=s.flows||{},o=i.authorizationCode||i.clientCredentials||i.password||i.implicit||{},a="client_credentials";return i.authorizationCode?a="authorization_code":i.password?a="password":i.implicit&&(a="implicit"),{type:"oauth2",oauth2:{grantType:a,tokenUrl:o.tokenUrl||"",authUrl:o.authorizationUrl||"",clientId:"",clientSecret:"",scope:Object.keys(o.scopes||{}).join(" ")}}}}}async createEnvironmentFromServers(e,t){if(e.length>0){let n=e[0].url;this.envConfigService.setEnvironmentVariable("baseUrl",n)}return t}extractUsedComponents(e,t,n){let s=n||{};if(!e)return s;if(e.$ref){let i=this.extractRefName(e.$ref);i&&t[i]&&!s[i]&&(s[i]=t[i],this.extractUsedComponents(t[i],t,s))}if(e.properties)for(let i of Object.values(e.properties))this.extractUsedComponents(i,t,s);e.items&&this.extractUsedComponents(e.items,t,s);for(let i of["allOf","oneOf","anyOf"])if(e[i])for(let o of e[i])this.extractUsedComponents(o,t,s);return e.additionalProperties&&typeof e.additionalProperties=="object"&&this.extractUsedComponents(e.additionalProperties,t,s),s}extractRefName(e){return e.match(/^#\/components\/schemas\/(.+)$/)?.[1]}}});var ln,Qi=E(()=>{"use strict";ln=class{constructor(e,t,n){this.historyAnalyzer=e;this.scriptAnalyzer=t;this.inferrer=n}historyAnalyzer;scriptAnalyzer;inferrer;async infer(e,t,n,s){let i=await this.historyAnalyzer.analyze(e,t,{environment:s?.environment}),o;return s?.postResponseScript&&(o=this.scriptAnalyzer.analyze(s.postResponseScript)),this.mergeResponseSchemas(n,i,o)}async inferBodySchema(e,t,n,s,i){let o,a;if(t==="raw"&&n==="json"&&e){let c=e;if(typeof e=="string")try{c=JSON.parse(e)}catch{return}o=this.inferrer.inferFromValue(c),a="application/json"}else t==="form-data"&&s?(o=this.buildFormDataSchema(s),a="multipart/form-data"):t==="x-www-form-urlencoded"&&s?(o=this.buildFormDataSchema(s),a="application/x-www-form-urlencoded"):t==="raw"&&n==="xml"?(o={type:"string"},a="application/xml"):t==="raw"&&(n==="text"||n==="html")?(o={type:"string"},a=n==="html"?"text/html":"text/plain"):t==="binary"?(o={type:"string",format:"binary"},a="application/octet-stream"):t==="graphql"&&(o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a="application/json");if(o)return i?this.mergeBodySchemaWithExisting(o,i):{contentType:a,schema:o}}buildFormDataSchema(e){let t={type:"object",properties:{}},n=[];for(let s of e){if(!s.enabled&&s.enabled!==void 0)continue;let i={};s.type?i.type=s.type:i.type="string",s.description&&(i.description=s.description),s.format&&(i.format=s.format),s.enum&&(i.enum=s.enum),s.type==="file"&&(i.type="string",i.format="binary"),t.properties[s.key]=i,s.required&&n.push(s.key)}return n.length>0&&(t.required=n),t}mergeResponseSchemas(e,t,n){let s={responses:{}};for(let[i,o]of Object.entries(t.responses))s.responses[i]={...o};if(n&&this.applyScriptHints(s,n),e){for(let[i,o]of Object.entries(e.responses))s.responses[i]?s.responses[i]=this.mergeResponseDefinitions(s.responses[i],o):s.responses[i]={...o};e.components&&(s.components={...e.components})}return s}applyScriptHints(e,t){for(let n of t.expectedStatuses){let s=String(n);e.responses[s]||(e.responses[s]={description:`Status ${n}`})}for(let[,n]of Object.entries(e.responses))n.schema&&this.augmentSchemaWithHints(n.schema,t)}augmentSchemaWithHints(e,t){if(!(e.type!=="object"||!e.properties))for(let n of t.fieldPaths){let s=n.split(".");this.ensureFieldPath(e,s,t)}}ensureFieldPath(e,t,n,s=""){if(t.length===0||e.type!=="object")return;e.properties||(e.properties={});let i=t[0],o=i.endsWith("[]"),a=o?i.slice(0,-2):i,c=s?`${s}.${i}`:i,l=t.slice(1);if(!e.properties[a])if(o)e.properties[a]={type:"array",items:{type:"object"}};else if(l.length>0)e.properties[a]={type:"object",properties:{}};else{let u=n.typeHints[c];e.properties[a]={type:u||"string"};return}if(l.length>0){let u=o?e.properties[a].items:e.properties[a];u&&this.ensureFieldPath(u,l,n,c)}}mergeResponseDefinitions(e,t){let n={...e};return t.description&&(n.description=t.description),t.contentType&&(n.contentType=t.contentType),t.schema&&e.schema?n.schema=this.inferrer.mergeSchemas(e.schema,t.schema):t.schema&&(n.schema=t.schema),t.examples&&(n.examples={...e.examples||{},...t.examples}),t.content&&(n.content={...e.content||{},...t.content}),t.headers&&(n.headers={...e.headers||{},...t.headers}),n}mergeBodySchemaWithExisting(e,t){let n={...t};return t.schema?n.schema=this.inferrer.mergeSchemas(e,t.schema):n.schema=e,n}}});var pd,Zi,fd,md,hd,gd,yd,hr,Ec=E(()=>{"use strict";pd=/(?:jsonData|responseJson|data|json|body|response\.json\(\))\.([a-zA-Z_][\w.\[\]]*)/g,Zi="(?:pm|hf|ctx)",fd=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(?:a|an)\\(['"](\\w+)['"]\\)`,"g"),md=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.(?:equal|eql)\\((.+?)\\)`,"g"),hd=/(?:to\.have\.status|response\.code.*?equal)\((\d+)\)/g,gd=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(true|false)`,"g"),yd=new RegExp(`${Zi}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.have\\.(?:lengthOf|length\\.above|length\\.below)`,"g"),hr=class{analyze(e){let t={fieldPaths:[],typeHints:{},valueHints:{},expectedStatuses:[]};if(!e||e.trim().length===0)return t;let n=this.stripComments(e);return this.extractFieldPaths(n,t),this.extractTypeAssertions(n,t),this.extractEqualityAssertions(n,t),this.extractBooleanAssertions(n,t),this.extractLengthAssertions(n,t),this.extractStatusAssertions(n,t),t.fieldPaths=[...new Set(t.fieldPaths)],t.expectedStatuses=[...new Set(t.expectedStatuses)],t}stripComments(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"");return t=t.replace(/\/\/.*$/gm,""),t}extractFieldPaths(e,t){let n,s=new RegExp(pd.source,pd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&!this.isCommonMethodCall(i)&&t.fieldPaths.push(i)}}extractTypeAssertions(e,t){let n,s=new RegExp(fd.source,fd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].toLowerCase();i&&(t.typeHints[i]=this.mapAssertionType(o),t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractEqualityAssertions(e,t){let n,s=new RegExp(md.source,md.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].trim();if(i){let a=this.parseAssertionValue(o);a!==void 0&&(t.valueHints[i]=a,typeof a=="string"?t.typeHints[i]=t.typeHints[i]||"string":typeof a=="number"?t.typeHints[i]=t.typeHints[i]||(Number.isInteger(a)?"integer":"number"):typeof a=="boolean"&&(t.typeHints[i]=t.typeHints[i]||"boolean")),t.fieldPaths.includes(i)||t.fieldPaths.push(i)}}}extractBooleanAssertions(e,t){let n,s=new RegExp(gd.source,gd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]="boolean",t.valueHints[i]=n[2]==="true",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractLengthAssertions(e,t){let n,s=new RegExp(yd.source,yd.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]=t.typeHints[i]||"array",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractStatusAssertions(e,t){let n,s=new RegExp(hd.source,hd.flags);for(;(n=s.exec(e))!==null;){let i=parseInt(n[1],10);!isNaN(i)&&i>=100&&i<600&&t.expectedStatuses.push(i)}}normalizeFieldPath(e){let t=e.replace(/^\./,"");return t=t.replace(/\[\d+\]/g,"[]"),t}isCommonMethodCall(e){return new Set(["to","be","have","not","deep","any","all","that","is","has","include","includes","equal","eql","above","below","least","most","within","length","lengthOf","match","string","keys","key","property","ownProperty","status","header","json","text"]).has(e.split(".")[0])}mapAssertionType(e){return{string:"string",number:"number",object:"object",array:"array",boolean:"boolean",null:"null",undefined:"null",int:"integer",integer:"integer",float:"number",double:"number"}[e]||"string"}parseAssertionValue(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);let t=Number(e);return!isNaN(t)&&e.trim().length>0?t:e==="true"?!0:e==="false"?!1:e==="null"?null:e}}});var vd={};Tt(vd,{AwsSecretResolver:()=>Yi});var Yi,qc=E(()=>{"use strict";Yi=class{providerName="aws";region;moduleRequire;constructor(e,t){this.region=e.region??process.env.AWS_DEFAULT_REGION??process.env.AWS_REGION,this.moduleRequire=t??(n=>le(n))}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0;try{let{SecretsManagerClient:i,GetSecretValueCommand:o}=this.moduleRequire("@aws-sdk/client-secrets-manager"),c=await new i(this.region?{region:this.region}:{}).send(new o({SecretId:n})),l=c.SecretString??(c.SecretBinary?Buffer.from(c.SecretBinary).toString("utf-8"):void 0);if(l===void 0)return;if(s)try{let u=JSON.parse(l);return u[s]!==void 0?String(u[s]):void 0}catch{return}return l}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] AWS secret resolver requires @aws-sdk/client-secrets-manager. Install it in your project: npm install @aws-sdk/client-secrets-manager"):i}}}});var bd={};Tt(bd,{AzureKeyVaultResolver:()=>Xi});var Xi,Ac=E(()=>{"use strict";Xi=class{providerName="azure";vaultUrl;moduleRequire;constructor(e,t){let n=(e.vaultUrl||process.env.AZURE_KEYVAULT_URL)??"";this.vaultUrl=n.replace(/\/$/,""),this.moduleRequire=t??(s=>le(s))}async resolve(e){if(!this.vaultUrl)throw new Error("[HTTP Forge] Azure Key Vault resolver: no vault URL configured. Set secrets.providers.<alias>.vaultUrl or the AZURE_KEYVAULT_URL env var.");let t=e.split("/"),n=t[0],s=t[1];try{let{SecretClient:i}=this.moduleRequire("@azure/keyvault-secrets"),{DefaultAzureCredential:o}=this.moduleRequire("@azure/identity"),a=new o;return(await new i(this.vaultUrl,a).getSecret(n,s?{version:s}:{})).value}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] Azure Key Vault resolver requires @azure/keyvault-secrets and @azure/identity. Install them: npm install @azure/keyvault-secrets @azure/identity"):i}}}});var Sd={};Tt(Sd,{HashiCorpVaultResolver:()=>eo});var eo,Pc=E(()=>{"use strict";eo=class{providerName="vault";address;mountPath;namespace;constructor(e){this.address=(e.address??process.env.VAULT_ADDR??"http://127.0.0.1:8200").replace(/\/$/,""),this.mountPath=e.mountPath??"secret",this.namespace=e.namespace??process.env.VAULT_NAMESPACE}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0,i=process.env.VAULT_TOKEN;if(!i)throw new Error("[HTTP Forge] HashiCorp Vault resolver requires VAULT_TOKEN environment variable to be set.");let o=`${this.address}/v1/${this.mountPath}/data/${n}`,a={"X-Vault-Token":i};this.namespace&&(a["X-Vault-Namespace"]=this.namespace);let c;try{c=await fetch(o,{headers:a})}catch(p){throw new Error(`[HTTP Forge] Vault request failed: ${p?.message??p}`)}if(c.status===404)return;if(!c.ok)throw new Error(`[HTTP Forge] Vault returned HTTP ${c.status} for path: ${n}`);let u=(await c.json())?.data?.data;if(!u)return;if(s)return u[s]!==void 0?String(u[s]):void 0;if("value"in u)return String(u.value);let d=Object.keys(u);return d.length===1?String(u[d[0]]):void 0}}});var xd={};Tt(xd,{OnePasswordResolver:()=>to});import{execFile as Fh}from"child_process";import{promisify as Nh}from"util";var _h,to,kc=E(()=>{"use strict";_h=Nh(Fh),to=class{providerName="1password";defaultVault;constructor(e){this.defaultVault=e.vault}async resolve(e){let t=e.split("/"),n,s,i;if(this.defaultVault){if(t.length<2)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<item>/<field>" when vault is set in config.`);n=this.defaultVault,s=t.slice(0,t.length-1).join("/"),i=t[t.length-1]}else{if(t.length<3)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<vault>/<item>/<field>".`);n=t[0],s=t.slice(1,t.length-1).join("/"),i=t[t.length-1]}let o=await this.tryResolveSdk(n,s,i);return o!==null?o:this.resolveViaCli(n,s,i)}async tryResolveSdk(e,t,n){let s=process.env.OP_SERVICE_ACCOUNT_TOKEN;if(!s)return null;try{let{createClient:i}=le("@1password/sdk"),o=await i({auth:s,integrationName:"HTTP Forge",integrationVersion:"1.0.0"}),a=`op://${e}/${t}/${n}`;return await o.secrets.resolve(a)}catch(i){if(i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND")return null;throw new Error(`[HTTP Forge] 1Password SDK error for "${e}/${t}/${n}": ${i?.message??i}`)}}async resolveViaCli(e,t,n){try{let{stdout:s}=await _h("op",["item","get",t,"--vault",e,"--field",n,"--format","json"],{env:{...process.env},timeout:1e4}),i=JSON.parse(s.trim());return typeof i=="string"?i:i&&typeof i.value=="string"?i.value:void 0}catch(s){if(s?.code==="ENOENT")throw new Error("[HTTP Forge] 1Password resolver requires either the @1password/sdk npm package or the `op` CLI to be installed.\n Service Account: set OP_SERVICE_ACCOUNT_TOKEN and install @1password/sdk\n CLI: install 1Password CLI and run `op signin`");if(s?.stderr?.includes("not found")||s?.code===1)return;throw new Error(`[HTTP Forge] 1Password CLI error: ${s?.message??s}`)}}}});var wd={};Tt(wd,{GcpSecretResolver:()=>no});var no,Ic=E(()=>{"use strict";no=class{providerName="gcp";projectId;moduleRequire;constructor(e,t){this.projectId=e.projectId??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT??process.env.GCP_PROJECT,this.moduleRequire=t??(n=>le(n))}async resolve(e){let t=e.split("/"),n=t[0],s=t[1]==="versions"&&t[2]?t[2]:"latest";if(!this.projectId)throw new Error("[HTTP Forge] GCP secret resolver: no projectId configured and GOOGLE_CLOUD_PROJECT env var is not set.");try{let{SecretManagerServiceClient:i}=this.moduleRequire("@google-cloud/secret-manager"),o=new i,a=`projects/${this.projectId}/secrets/${n}/versions/${s}`,[c]=await o.accessSecretVersion({name:a}),l=c.payload?.data;return l?Buffer.isBuffer(l)?l.toString("utf-8"):Buffer.from(l).toString("utf-8"):void 0}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] GCP secret resolver requires @google-cloud/secret-manager. Install it: npm install @google-cloud/secret-manager"):i}}}});var Cd={};Tt(Cd,{DopplerResolver:()=>ro});import*as Rd from"https";var ro,Tc=E(()=>{"use strict";ro=class{providerName="doppler";token;constructor(e){this.token=e.serviceToken??process.env.DOPPLER_TOKEN}async resolve(e){let t=e.trim().toUpperCase(),n=this.token;if(!n)throw new Error("[HTTP Forge] Doppler secret resolver: no service token found. Set DOPPLER_TOKEN env var or add serviceToken to config.");let s=`https://api.doppler.com/v3/configs/config/secret?name=${encodeURIComponent(t)}`;return new Promise((i,o)=>{let a=Rd.request(s,{method:"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}},c=>{let l=[];c.on("data",u=>l.push(u)),c.on("end",()=>{let u=Buffer.concat(l).toString("utf-8");if(c.statusCode===404){i(void 0);return}if(c.statusCode!==200){o(new Error(`[HTTP Forge] Doppler API returned ${c.statusCode} for secret "${t}": ${u}`));return}try{let p=JSON.parse(u)?.value?.computed;i(p!=null?String(p):void 0)}catch{o(new Error(`[HTTP Forge] Doppler API returned non-JSON response for secret "${t}"`))}})});a.on("error",o),a.end()})}}});import*as so from"fs";import{createRequire as Mh}from"module";import*as Ed from"path";var $s,Oc=E(()=>{"use strict";$s=class{resolvers=new Map;moduleRequire;constructor(e){if(this.moduleRequire=this.buildModuleRequire(e),!e)return;let t;try{t=e.getConfig().secrets}catch{return}if(!(!t?.providers||typeof t.providers!="object"))for(let[n,s]of Object.entries(t.providers))try{let i=this.createResolver(s);i&&this.resolvers.set(n,i)}catch{}}async resolveSecretTokens(e,t){let n=t??new Map,s=new Set;if(this.collectTokens(e,s),s.size===0)return{};await Promise.all(Array.from(s).map(async o=>{if(n.has(o))return;let a=o.slice(7),c=a.indexOf("/");if(c<0)return;let l=a.slice(0,c),u=a.slice(c+1),d=this.resolvers.get(l);if(d)try{let p=await d.resolve(u);p!==void 0&&n.set(o,p)}catch(p){let m=p?.message??String(p);console.warn(`[HTTP Forge] {{${o}}} could not be resolved: ${m}`)}}));let i={};for(let[o,a]of n.entries())i[o]=a;return i}get hasProviders(){return this.resolvers.size>0}collectTokens(e,t){if(typeof e=="string"){let n=/\{\{(secret:[^}]+)\}\}/g,s;for(;(s=n.exec(e))!==null;)t.add(s[1])}else Array.isArray(e)?e.forEach(n=>this.collectTokens(n,t)):e!==null&&typeof e=="object"&&Object.values(e).forEach(n=>this.collectTokens(n,t))}createResolver(e){switch(e.provider){case"aws":{let{AwsSecretResolver:t}=(qc(),Yn(vd));return new t(e,this.moduleRequire)}case"azure":{let{AzureKeyVaultResolver:t}=(Ac(),Yn(bd));return new t(e,this.moduleRequire)}case"vault":{let{HashiCorpVaultResolver:t}=(Pc(),Yn(Sd));return new t(e)}case"1password":{let{OnePasswordResolver:t}=(kc(),Yn(xd));return new t(e)}case"gcp":{let{GcpSecretResolver:t}=(Ic(),Yn(wd));return new t(e,this.moduleRequire)}case"doppler":{let{DopplerResolver:t}=(Tc(),Yn(Cd));return new t(e)}default:return}}buildModuleRequire(e){let t=s=>le(s);if(!e)return t;let n=[];try{n=e.getModulePaths()??[]}catch{return t}for(let s of n)try{let i=Ed.resolve(s,"package.json");if(so.existsSync(i)){let o=so.realpathSync(i),a=Mh(o);return c=>{try{return a(c)}catch{return t(c)}}}}catch{}return t}}});function ke(r){return r.replace(/\//g,"%2F")}function Dh(r){return r.replace(/%2F/gi,"/")}function kt(r){return r?r.split("/").map(Dh).join(" / "):""}function gr(r){return r.includes(" / ")?r.split(" / ").map(e=>ke(e.trim())).join("/"):ke(r)}function Q(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="request")n.push({request:s,folderPath:t});else{let i=s,o=ke(i.name),a=t?`${t}/${o}`:o;n.push(...Q(r,i.items??[],a))}return n}function Ce(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="folder"){let i=s,o=ke(i.name),a=t?`${t}/${o}`:o;n.push({folderId:i.id,folderPath:a,requestCount:$c(i.items??[])}),n.push(...Ce(r,i.items??[],a))}return n}function $c(r){let e=0;for(let t of r)t.type==="request"?e++:e+=$c(t.items??[]);return e}var Ye=E(()=>{"use strict"});var jt,Fc=E(()=>{"use strict";jt={iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1}});import*as ie from"fs";import*as vt from"path";var Fs,Nc=E(()=>{"use strict";Ye();Ge();Fc();Fs=class{constructor(e,t,n){this.collectionService=e;this.configService=t;this.suitesDir=t.getSuitesPath(),this.onSuitesChanged=n?.onSuitesChanged,this.ensureSuitesDir(),this.loadSuites(),n?.watch!==!1&&this.setupFileWatcher()}collectionService;configService;suitesDir;suites=new Map;fileWatcher=null;debounceTimer=null;onSuitesChanged;ensureSuitesDir(){ie.existsSync(this.suitesDir)||ie.mkdirSync(this.suitesDir,{recursive:!0})}setupFileWatcher(){try{this.fileWatcher=ie.watch(this.suitesDir,(e,t)=>{t&&!t.endsWith(".suite.json")||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.loadSuites(),this.onSuitesChanged?.()},200))}),this.fileWatcher.on("error",()=>{})}catch{}}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.close(),this.fileWatcher=null}loadSuites(){if(this.suites.clear(),!ie.existsSync(this.suitesDir))return;let e=ie.readdirSync(this.suitesDir);for(let t of e)if(t.endsWith(".suite.json"))try{let n=vt.join(this.suitesDir,t),s=ie.readFileSync(n,"utf-8"),i=JSON.parse(s),o=Array.isArray(i.nodes)&&i.nodes.length>0?i.nodes:(Array.isArray(i.requests)?i.requests:[]).map(c=>({type:"request",name:c.description||c.name,request:c,enabled:c.enabled!==!1})),a={id:i.id,name:i.name,description:i.description,scripts:i.scripts,nodes:o,config:i.config??{...jt},isTemporary:i.isTemporary,ai_generated:i.ai_generated===!0,derived_from:Array.isArray(i.derived_from)?i.derived_from:void 0,createdAt:i.createdAt??Date.now(),updatedAt:i.updatedAt??Date.now()};a.id&&a.name&&this.suites.set(a.id,a)}catch(n){console.error(`[TestSuiteService] Failed to load ${t}:`,n)}}async getAllSuites(){return Array.from(this.suites.values())}async getSuite(e){return this.suites.get(e)}async createSuite(e){let t=Date.now(),n={id:se(e),name:e,nodes:[],config:{...jt},createdAt:t,updatedAt:t};return await this.saveSuiteToDisk(n),this.suites.set(n.id,n),n}async updateSuite(e){e.updatedAt=Date.now(),await this.saveSuiteToDisk(e),this.suites.set(e.id,e)}async duplicateSuite(e,t){let n=this.suites.get(e);if(!n)throw new Error(`Suite not found: ${e}`);let s=n.nodes||[],i=await this.createSuite(t);i.nodes=s.map(c=>({...c})),i.config={...n.config},i.description=n.description;let o=vt.join(this.suitesDir,e),a=vt.join(this.suitesDir,i.id);return ie.existsSync(o)&&this.copyDirRecursive(o,a),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}copyDirRecursive(e,t){ie.existsSync(t)||ie.mkdirSync(t,{recursive:!0});for(let n of ie.readdirSync(e,{withFileTypes:!0})){let s=vt.join(e,n.name),i=vt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):ie.copyFileSync(s,i)}}async deleteSuite(e){let t=this.suites.get(e);if(!t)return!1;let n=`${t.id}.suite.json`,s=vt.join(this.suitesDir,n),i=vt.join(this.suitesDir,t.id);try{return ie.existsSync(s)&&ie.unlinkSync(s),ie.existsSync(i)&&ie.rmSync(i,{recursive:!0,force:!0}),this.suites.delete(e),!0}catch(o){return console.error("[TestSuiteService] Failed to delete suite:",o),!1}}async createTempSuiteFromCollection(e){let t=this.collectionService.getCollection(e);if(!t){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let n=[];this.extractRequestsFromCollection(t,e,t.name,"",n);let s=n.map(a=>({type:"request",name:a.description||a.name,request:a,enabled:a.enabled!==!1})),i=Date.now();return{id:`temp-${e}`,name:t.name,nodes:s,config:{...jt},isTemporary:!0,createdAt:i,updatedAt:i}}async createTempSuiteFromFolder(e,t,n=!0){let s=this.collectionService.getCollection(e);if(!s){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let i=[];this.extractRequestsFromCollection(s,e,s.name,"",i);let o=t.replace(/\/+$/,""),a=i.filter(d=>n?d.folderPath===o||d.folderPath.startsWith(`${o}/`):d.folderPath===o);if(a.length===0){console.error(`[TestSuiteService] No requests under folder "${t}" in collection: ${e}`);return}let c=a.map(d=>({type:"request",name:d.description||d.name,request:d,enabled:d.enabled!==!1})),l=Date.now();return{id:`temp-${e}-${this.slugifyFolderPath(o)}`,name:`${s.name} / ${kt(o)}`,nodes:c,config:{...jt},isTemporary:!0,createdAt:l,updatedAt:l}}async createTempSuiteFromRequest(e,t){let n=this.collectionService.getCollection(e);if(!n){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let s=[];this.extractRequestsFromCollection(n,e,n.name,"",s);let i=s.find(u=>u.requestId===t);if(!i){console.error(`[TestSuiteService] Request not found: ${t} in collection: ${e}`);return}let a={type:"for",name:"Performance Loop (100 iterations)",init:'hf.variables.set("__i", 0)',loopCondition:'hf.variables.get("__i") < 100',update:'hf.variables.set("__i", hf.variables.get("__i") + 1)',maxIterations:100,nodes:[{type:"request",name:i.description||i.name,request:i,enabled:!0}],enabled:!0},c=Date.now();return{id:`temp-perf-${e}-${t}`,name:`${i.name} \u2014 Performance Test`,nodes:[a],config:{...jt},isTemporary:!0,createdAt:c,updatedAt:c}}slugifyFolderPath(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async saveTempSuite(e,t){let n=Date.now(),s=vt.join(this.suitesDir,e.id),i={...e,id:se(t),name:t,isTemporary:!1,createdAt:n,updatedAt:n},o=vt.join(this.suitesDir,i.id);return ie.existsSync(s)&&(ie.existsSync(o)&&ie.rmSync(o,{recursive:!0,force:!0}),ie.renameSync(s,o)),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}getAllAvailableRequests(){let e=[],t=this.collectionService.getAllCollections();for(let n of t)this.extractRequestsFromCollection(n,n.id,n.name,"",e);return e}extractRequestsFromCollection(e,t,n,s,i){if(e.requests)for(let o of e.requests)i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.items)for(let o of e.items)if(o.items||o.folders||o.requests){let a=s?`${s}/${ke(o.name)}`:ke(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}else i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.folders)for(let o of e.folders){let a=s?`${s}/${ke(o.name)}`:ke(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}}async saveSuiteToDisk(e){this.ensureSuitesDir();let t=`${e.id}.suite.json`,n=vt.join(this.suitesDir,t),s=`${n}.tmp-${process.pid}-${Date.now()}`,i={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/suite.schema.json",id:e.id,name:e.name,description:e.description,scripts:e.scripts,nodes:Array.isArray(e.nodes)?e.nodes:[],config:e.config??{...jt},isTemporary:e.isTemporary,ai_generated:e.ai_generated,derived_from:e.derived_from,createdAt:e.createdAt??Date.now(),updatedAt:e.updatedAt??Date.now()},o=JSON.stringify(i,null,2);ie.writeFileSync(s,o,"utf-8"),ie.renameSync(s,n)}}});var O,io=E(()=>{"use strict";O={Config:Symbol.for("IConfigService"),Console:Symbol.for("IConsoleService"),EnvironmentConfig:Symbol.for("IEnvironmentConfigService"),Collection:Symbol.for("ICollectionService"),HttpRequest:Symbol.for("IHttpRequestService"),HttpClient:Symbol.for("IHttpClient"),Cookie:Symbol.for("ICookieService"),RequestHistory:Symbol.for("IRequestHistoryService"),TestSuite:Symbol.for("ITestSuiteService"),UrlBuilder:Symbol.for("IUrlBuilder"),RequestPreprocessor:Symbol.for("IRequestPreprocessor"),RequestPreparer:Symbol.for("IRequestPreparer"),InterceptorChain:Symbol.for("IInterceptorChain"),ScriptExecutor:Symbol.for("IScriptExecutor"),DataFileParser:Symbol.for("IDataFileParser"),CollectionRequestExecutor:Symbol.for("ICollectionRequestExecutor"),WorkspaceFolder:Symbol.for("WorkspaceFolder"),PersistentCookieJar:Symbol.for("PersistentCookieJar"),OAuth2TokenManager:Symbol.for("IOAuth2TokenManager"),GraphQLSchemaService:Symbol.for("IGraphQLSchemaService"),SchemaInferrer:Symbol.for("SchemaInferrer"),HistoryAnalyzer:Symbol.for("HistoryAnalyzer"),ScriptAnalyzer:Symbol.for("ScriptAnalyzer"),SchemaInferenceService:Symbol.for("SchemaInferenceService"),OpenApiExporter:Symbol.for("OpenApiExporter"),OpenApiImporter:Symbol.for("OpenApiImporter"),SecretResolverRegistry:Symbol.for("SecretResolverRegistry")}});import*as qd from"path";function oo(r,e){let{workspaceFolder:t,fileWatcherFactory:n,notificationService:s,workspaceStore:i,globalStore:o,secretStore:a,browserService:c,applicationInfo:l,consoleService:u}=e;r.registerValue(O.WorkspaceFolder,t),r.registerSingleton(O.Config,()=>new rn(t,n,s)),r.registerSingleton(O.Console,()=>u??jh),r.registerSingleton(O.EnvironmentConfig,p=>new Cs(t,i,p.resolve(O.Config),n,a,e.persistOverrides??!0)),r.registerSingleton(O.Cookie,()=>new xs(o)),r.registerSingleton(O.Collection,p=>new Ss(p.resolve(O.Config),n)),r.registerSingleton(O.TestSuite,p=>new Fs(p.resolve(O.Collection),p.resolve(O.Config))),r.registerSingleton(O.HttpClient,p=>{let m=p.resolve(O.Config),f=p.resolve(O.EnvironmentConfig);return new An(()=>f.getResolvedConfig().request,t,()=>f.getResolvedConfig()?.proxy??null)}),r.registerSingleton(O.UrlBuilder,()=>new mt),r.registerSingleton(O.InterceptorChain,()=>new Ft),r.registerSingleton(O.HttpRequest,p=>new $t(p.resolve(O.UrlBuilder),p.resolve(O.InterceptorChain),p.resolve(O.HttpClient))),r.registerSingleton(O.RequestPreprocessor,()=>new Pn),r.registerSingleton(O.RequestHistory,p=>{let m=p.resolve(O.EnvironmentConfig);return new ks(m.getHistoriesPath(),qd.join(m.getRootPath(),"shared-histories"))}),a&&c&&r.registerSingleton(O.OAuth2TokenManager,p=>new ys(a,c,p.resolve(O.EnvironmentConfig),p.resolve(O.HttpRequest))),r.registerSingleton(O.GraphQLSchemaService,p=>new As(p.resolve(O.HttpClient))),r.registerSingleton(O.SecretResolverRegistry,p=>new $s(p.resolve(O.Config)));let d=l??{name:"HttpForge",version:"0.0.0"};r.registerSingleton(O.RequestPreparer,p=>new qs(p.resolve(O.EnvironmentConfig),p.resolve(O.HttpRequest),p.resolve(O.RequestPreprocessor),p.has(O.OAuth2TokenManager)?p.resolve(O.OAuth2TokenManager):void 0,d,p.resolve(O.SecretResolverRegistry))),r.registerSingleton(O.ScriptExecutor,p=>{let m=p.resolve(O.Config);return new Nt(p.resolve(O.HttpRequest),m.getModulePaths(),p.resolve(O.SecretResolverRegistry),m.getScriptScope(),m.getScriptTimeout())}),r.registerSingleton(O.DataFileParser,()=>new In),r.registerSingleton(O.CollectionRequestExecutor,p=>new _t(p.resolve(O.HttpRequest),p.resolve(O.ScriptExecutor),p.resolve(O.EnvironmentConfig),p.resolve(O.RequestPreparer),"")),r.registerSingleton(O.PersistentCookieJar,p=>new ws(p.resolve(O.Cookie))),r.registerSingleton(O.SchemaInferrer,()=>new an),r.registerSingleton(O.HistoryAnalyzer,p=>new pr(p.resolve(O.RequestHistory),p.resolve(O.SchemaInferrer))),r.registerSingleton(O.ScriptAnalyzer,()=>new hr),r.registerSingleton(O.SchemaInferenceService,p=>new ln(p.resolve(O.HistoryAnalyzer),p.resolve(O.ScriptAnalyzer),p.resolve(O.SchemaInferrer))),r.registerSingleton(O.OpenApiExporter,p=>new cn(p.resolve(O.Collection),p.resolve(O.EnvironmentConfig),p.resolve(O.SchemaInferenceService))),r.registerSingleton(O.OpenApiImporter,p=>new Dt(p.resolve(O.Collection),p.resolve(O.EnvironmentConfig)))}var jh,_c=E(()=>{"use strict";Qa();tc();Hi();rc();sc();ac();Es();cc();lc();hc();is();os();_i();Mi();er();gc();Wi();Ki();Qi();Vi();Ec();Di();ds();Oc();Nc();io();jh={log:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},logBatch:()=>{},logRawLines:()=>{},show:()=>{},clear:()=>{},dispose:()=>{}}});function Ad(){return Fn.instance}var Fn,Mc=E(()=>{"use strict";io();Fn=class r{static _instance;services=new Map;primitives=new Map;constructor(){}static get instance(){return r._instance||(r._instance=new r),r._instance}static createFresh(){return new r}static reset(){r._instance&&r._instance.clear(),r._instance=void 0}registerValue(e,t){return this.primitives.set(e,t),this}registerSingleton(e,t){return this.services.set(e,{factory:t,singleton:!0}),this}registerTransient(e,t){return this.services.set(e,{factory:t,singleton:!1}),this}registerInstance(e,t){return this.services.set(e,{factory:()=>t,singleton:!0,instance:t}),this}resolve(e){if(this.primitives.has(e))return this.primitives.get(e);let t=this.services.get(e);if(!t)throw new Error(`Service not registered: ${e.toString()}`);return t.singleton?(t.instance||(t.instance=t.factory(this)),t.instance):t.factory(this)}has(e){return this.services.has(e)||this.primitives.has(e)}dispose(){for(let e of this.services.values())if(e.singleton&&e.instance){let t=e.instance;if(typeof t.dispose=="function")try{t.dispose()}catch{}}this.clear()}clear(){this.services.clear(),this.primitives.clear()}get config(){return this.resolve(O.Config)}get console(){return this.resolve(O.Console)}get environmentConfig(){return this.resolve(O.EnvironmentConfig)}get collection(){return this.resolve(O.Collection)}get httpRequest(){return this.resolve(O.HttpRequest)}get httpClient(){return this.resolve(O.HttpClient)}get cookie(){return this.resolve(O.Cookie)}get requestHistory(){return this.resolve(O.RequestHistory)}get dataFileParser(){return this.resolve(O.DataFileParser)}get scriptExecutor(){return this.resolve(O.ScriptExecutor)}get requestPreparer(){return this.resolve(O.RequestPreparer)}get persistentCookieJar(){return this.resolve(O.PersistentCookieJar)}get oauth2TokenManager(){return this.has(O.OAuth2TokenManager)?this.resolve(O.OAuth2TokenManager):void 0}get graphqlSchemaService(){return this.resolve(O.GraphQLSchemaService)}get testSuite(){return this.resolve(O.TestSuite)}}});import*as _n from"fs";import*as yr from"path";function Lt(r){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Collection",body:kd(r),generatedAt:Date.now()}),freshness:()=>r.items.length>0?"fresh":"stale"}}function tt(r,e){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Request",body:Dc(r,e),generatedAt:Date.now()}),freshness:()=>Dc(r,e)?"fresh":"stale"}}function nt(r){return{kind:"workspace-knowledge",snapshot:()=>({kind:"workspace-knowledge",heading:"Business Knowledge",body:Ns(r),generatedAt:Date.now()}),freshness:()=>Ns(r)?"fresh":"stale"}}function co(r,e){return{kind:"run-results",snapshot:()=>({kind:"run-results",heading:"Test Results",body:Id(r,e),generatedAt:Date.now()}),freshness:()=>{if(!e||!r)return"stale";let t=r.get(e);return t?t.status==="running"?"stale":"fresh":"stale"}}}function Uh(r){lo.push(r)}function Vh(){lo.length=0}function zh(){return lo.slice()}function Dc(r,e){let t=[],n=e&&e!=="(root)"?`${e} / ${r.name}`:r.name;return r.description?.trim()&&t.push(`Description: ${Nn(r.description,400)}`),r.doc?.trim()&&t.push(`Docs (doc.md): ${Nn(r.doc,Lh)}`),r.operationId&&t.push(`OpenAPI operationId: ${r.operationId}`),r.summary?.trim()&&t.push(`OpenAPI summary: ${Nn(r.summary,200)}`),r.tags?.length&&t.push(`OpenAPI tags: ${r.tags.join(", ")}`),r.deprecated&&t.push("Deprecated: true"),r.responseSchema&&t.push(`Response schema: ${Nn(JSON.stringify(r.responseSchema),400)}`),r.bodySchema&&t.push(`Request body schema: ${Nn(JSON.stringify(r.bodySchema),300)}`),r.settings?.timeout!==void 0&&t.push(`Timeout: ${r.settings.timeout}ms`),t.length===0?"":`[${r.method??"GET"} ${r.url??""}] ${n}
|
|
287
287
|
${t.join(`
|
|
288
288
|
`)}`}function kd(r){let e=[];r.description?.trim()&&e.push(`Description: ${Nn(r.description,400)}`);let t=Object.keys(r.variables??{});t.length>0&&e.push(`Collection variables: ${t.join(", ")}`),r.auth?.type&&e.push(`Collection auth: ${r.auth.type}`);let n=[],s=(c,l)=>{for(let u of c)u.type==="request"?n.push({folderPath:l||"(root)",req:u}):u.type==="folder"&&u.items&&s(u.items,`${l}/${u.name}`.replace(/^\//,""))};if(s(r.items,""),n.length===0)return e.join(`
|
|
289
289
|
`);let i=new Set(n.map(c=>c.folderPath)),o=[...i].sort().map(c=>` ${c} (${n.filter(l=>l.folderPath===c).length} requests)`).join(`
|
|
@@ -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=V(r.collection,t),i=Be(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:[tt(i,Bd(s,i)).snapshot().body,nt(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=V(r.collection,e),n=Be(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:tt(n,Bd(t,n)).snapshot().body||void 0,body:i??null,headers:o,queryParams:a,placeholders:[...l],iterations:s}}}}]});function zd(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=zd(n.items??[],e);if(s)return s}}var Jd,Gd=E(()=>{"use strict";Fe();Ne();Ne();Jd=[{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=V(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=V(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=V(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=V(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=Ce(n);if(Q(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let d=Ce(n).find(p=>p.folderPath===r.parentFolder||p.folderPath.toLowerCase()===a);if(d){let p=n.items;i=zd(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=V(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw I('"folder" is required');let s=r.folder.toLowerCase(),i=Ce(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=Jc(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 Kc=E(()=>{"use strict"});var Wd=E(()=>{"use strict"});import*as St from"fs";import*as Sr from"path";var cg,lg,ug,xr,Ao=E(()=>{"use strict";cg=["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"],lg={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:[]},ug={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},xr=class{buildFingerprint(e){let t=[],n=Sr.join(e,"package.json"),s;for(let i of cg){let o=Sr.join(e,i);St.existsSync(o)&&t.push(o)}if(St.existsSync(n))try{let i=JSON.parse(St.readFileSync(n,"utf-8"));s={dependencies:i.dependencies,devDependencies:i.devDependencies,scripts:i.scripts}}catch{}return{projectRoot:e,packageJsonPath:St.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 St.existsSync(Sr.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=lg[t],i=ug[t],o=0,a=120;for(let c of n){let l=Sr.join(e.projectRoot,c);if(!St.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let d=u.shift(),p;try{p=St.readdirSync(d,{withFileTypes:!0})}catch{continue}for(let m of p){let f=Sr.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=St.readFileSync(f,"utf-8")}catch{continue}if(s.some(g=>h.includes(g)))return!0}}}return!1}}});import*as Kd from"fs";import*as Qd from"path";function ot(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Kd.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Qd.join(n,i.name);if(i.isDirectory()){dg.has(i.name)||t.push(o);continue}i.isFile()&&(pg.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var dg,pg,un=E(()=>{"use strict";dg=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),pg=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});import*as Zd from"fs";import*as Po from"path";function ko(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=Po.isAbsolute(t)?t:Po.join(r,t);if(!Zd.existsSync(n))return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader module not found: ${n}`}]};try{let s=ce(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 Io=E(()=>{"use strict"});function Xd(r,e){let t=r.projectName?.trim();if(t)return t;let n=Yd(r.source.filePath),s=fg(n);if(s)return s;let i;for(let a of e){let c=Yd(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 fg(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function Yd(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Qc=E(()=>{"use strict"});import*as _o from"fs";import*as Hn from"path";import*as x from"typescript";function dn(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function pn(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 $o(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,d=new Map,p=Ig(o),m=Pg(r,e,p),f=Fg(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=op(e),g=mg(e,t),y=kg(r,t,h,g,m,f),v=(R,A)=>{let F=l.find(_=>_.statusCode===R);return F||(F={statusCode:R},l.push(F)),A&&(F.body={type:A,schema:F.body?.schema}),F};x.isFunctionLike(r)&&qg(r,e,d,m,f,p);let w=(R,A)=>{let F=h.get(R);if(F){let W=`${t}:${R}`;if(s.visitedSymbols.has(W))return;s.visitedSymbols.add(W);let Z=y.get(W),ze=A?No(A,F,m,f):void 0,Kt=ip(Z,ze),qt=$o(F,e,t,n,s,Kt,o);Yc({parameters:a,requestBody:u,cookies:c,responses:l},qt),!u&&qt.requestBody&&(u=qt.requestBody);return}let _=g.get(R);if(!_||s.visitedSymbols.has(_.symbolKey))return;s.visitedSymbols.add(_.symbolKey);let D=y.get(_.symbolKey),B=A?No(A,_.node,m,f):void 0,T=ip(D,B),j=$o(_.node,_.sourceFile,_.filePath,n,s,T,o);Yc({parameters:a,requestBody:u,cookies:c,responses:l},j),!u&&j.requestBody&&(u=j.requestBody)},b=["POST","PUT","PATCH"].includes(n),C=R=>{x.isVariableDeclaration(R)&&Eg(R,e,d,m,f,p),x.isIdentifier(R)&&(x.isCallExpression(R.parent)&&R.parent.expression===R||w(R.text));let A=wr(R,e,"query",d,m,f,p);if(A){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:A.path,location:"query",type:Oo(R,e),detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}let F=wr(R,e,"params",d,m,f,p);if(F){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:F.path,location:"path",required:!0,type:Oo(R,e),detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}if(Cg(R,e,m)&&!u){let T=e.getLineAndCharacterOfPosition(R.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}}}let _=wr(R,e,"body",d,m,f,p);if(_){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:_.path,location:"body",type:Oo(R,e),detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let D=wr(R,e,"headers",d,m,f,p);if(D){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:D.path,location:"header",type:"string",detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}let B=wr(R,e,"cookies",d,m,f,p);if(B){let T=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:B.path,type:"request",detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}for(let T of p){let j=wr(R,e,T,d,m,f,p);if(!j)continue;let W=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:j.path,location:T,type:Oo(R,e),detectionLocation:{filePath:t,line:W.line+1,column:W.character+1,accessMode:"read"}})}if(x.isCallExpression(R)){let T=Tg(R,e,f);T&&v(T.statusCode,T.bodyType)}if(x.isCallExpression(R)){let T=Og(R,f);if(T){let j=v(T.statusCode);if(!j.headers?.some(W=>W.name===T.headerName)){let W=e.getLineAndCharacterOfPosition(R.getStart(e));j.headers=j.headers??[],j.headers.push({name:T.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:W.line+1,column:W.character+1,accessMode:"write"}})}}}if(x.isCallExpression(R)&&x.isPropertyAccessExpression(R.expression)&&Ng(R.expression.expression,f)&&R.expression.name.text==="cookie"&&R.arguments[0]&&x.isStringLiteral(R.arguments[0])){let T=R.arguments[0].text;if(T&&!c.some(j=>j.name===T&&j.type==="response")){let j=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:T,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:j.line+1,column:j.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 Vs(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=$o(o,e,t,n,void 0,void 0,s);Yc(i,a)}return i.parameters=fn(i.parameters),i.cookies=Rg(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 op(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 mg(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=gg(e,s);if(!o)return;let a=hg(o);if(!a)return;let c=yg(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 hg(r){let e="";try{e=_o.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 gg(r,e){let t=Hn.resolve(Hn.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,Hn.join(t,"index.ts"),Hn.join(t,"index.js")];for(let s of n)try{if(_o.statSync(s).isFile())return s}catch{continue}}function yg(r,e){let t=new Map,n=op(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(x.isFunctionDeclaration(i)&&i.name&&ep(i)){s(i.name.text,i),tp(i)&&s("default",i);continue}if(x.isVariableStatement(i)&&ep(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),tp(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=Zc(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=Zc(a,n);c&&s("default",c);continue}if(x.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=Zc(a,n);c&&s(o.name.text,c)}}return t}function Zc(r,e){if(x.isFunctionExpression(r)||x.isArrowFunction(r))return r;if(x.isIdentifier(r))return e.get(r.text)}function ep(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.ExportKeyword):!1}function tp(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.DefaultKeyword):!1}function Yc(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=fn([...s,...i])}}function fn(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:np([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=np(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=>vg(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=To(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=To(o)}}for(let i of s.values()){let o=To(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=To(o)}}return t}function np(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 vg(r){let e=xg([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=bg(e),n=e.filter(s=>!wg(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function bg(r){return[...r].sort(Sg)[0]}function Sg(r,e){let t=rp(r),n=rp(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 rp(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function xg(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 wg(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 Rg(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 Cg(r,e,t){return x.isPropertyAccessExpression(r)&&x.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function wr(r,e,t,n,s,i,o){return el(r,e,t,n,!1,s,i,o)}function el(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:Fo(h)}}if(!l||!x.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=Fo(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function Eg(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=el(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))&&Us(r.name,c,l,t)}}function qg(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){Ag(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let d of o){let p=el(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))&&Us(a.name,l,u,t)}}}function Ag(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=Xc(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))&&Us(s.name,o,"",e)}}function Pg(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=Ln(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=Ln(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 Us(r,e,t,n){if(x.isObjectBindingPattern(r)){for(let s of r.elements){let i=Xc(s);if(!i)continue;let o=sp(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))&&Us(s.name,e,o,n)}return}for(let s of r.elements){if(!x.isBindingElement(s))continue;let i=Xc(s)??"[]",o=sp(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))&&Us(s.name,e,o,n)}}function Xc(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 sp(r,e){return Fo(r?`${r}.${e}`.split("."):[e])}function Fo(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 To(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function kg(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=No(l,d,s,i);m&&a(`${e}:${u}`,m)}let p=n.get(u);if(p){let m=No(l,p.node,s,i);m&&a(p.symbolKey,m)}}x.forEachChild(l,c)};return c(r),o}function ip(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 Ig(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 No(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=Ln(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 Oo(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 Tg(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=ap(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":$g(r.arguments[0])}}function Og(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=ap(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function ap(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 $g(r){return r&&(x.isObjectLiteralExpression(r)||x.isArrayLiteralExpression(r))?"json":"text"}function Fg(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=Ln(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=Ln(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=Ln(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 Ng(r,e){let t=Ln(r);return t?e.has(t):!1}function Ln(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 Mo=E(()=>{"use strict"});import*as ae from"typescript";function Rr(r,e,t){let n={},s=o=>{if(ae.isVariableDeclaration(o)&&ae.isIdentifier(o.name)&&o.initializer){let a=mn(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}ae.forEachChild(o,s)};s(r);let i={...Mg(e),...t};return{variables:n,env:i}}function xt(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=mn(r,e,t);if(n!==void 0)return{pathExpression:n,resolvedPath:n,confidence:"high"};if(ae.isStringLiteral(r)||ae.isNoSubstitutionTemplateLiteral(r)){let s=r.text||"/";return{pathExpression:s,resolvedPath:s,confidence:"high"}}if(ae.isTemplateExpression(r)){let s=_g(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 ae.isIdentifier(r)?{pathExpression:r.getText(e),confidence:"low"}:{pathExpression:r.getText(e),confidence:"low"}}function Ut(r,e){let t=cp(r??""),n=cp(e??""),s=lp(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function cp(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function lp(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function mn(r,e,t){if(ae.isStringLiteral(r)||ae.isNoSubstitutionTemplateLiteral(r))return r.text;if(ae.isParenthesizedExpression(r))return mn(r.expression,e,t);if(ae.isIdentifier(r))return t?.variables?.[r.text];if(ae.isBinaryExpression(r)&&r.operatorToken.kind===ae.SyntaxKind.PlusToken){let n=mn(r.left,e,t),s=mn(r.right,e,t);if(n!==void 0&&s!==void 0)return`${n}${s}`}if(ae.isBinaryExpression(r)&&(r.operatorToken.kind===ae.SyntaxKind.BarBarToken||r.operatorToken.kind===ae.SyntaxKind.QuestionQuestionToken))return mn(r.left,e,t)??mn(r.right,e,t);if(ae.isPropertyAccessExpression(r)){let n=r.getText(e);if(n.startsWith("process.env.")){let s=n.substring(12);return t?.env?.[s]}}}function _g(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=mn(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?lp(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function Mg(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=ce("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 Do=E(()=>{"use strict"});import*as re from"typescript";function up(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function Dg(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 jg(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=Ut(u.pathExpression,a.prefix.pathExpression),p=dn(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 Lg(r){return re.isStringLiteral(r)||re.isNoSubstitutionTemplateLiteral(r)||re.isTemplateExpression(r)}function Hg(r){if(re.isStringLiteral(r)||re.isNoSubstitutionTemplateLiteral(r))return r.text}function Bg(r,e,t,n){let s=new Set(pn(n).map(a=>a.name));if(s.size===0)return[];let i=Ug(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 Ug(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 zs,dp=E(()=>{"use strict";Do();Mo();zs=class{async analyzeFile(e,t,n,s){let i=re.createSourceFile(e,t,re.ScriptTarget.Latest,!0,e.endsWith(".ts")?re.ScriptKind.TS:re.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,d=Rr(i,n.projectRoot,s.envOverrides),p=g=>{if(re.isVariableDeclaration(g)&&re.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)}re.forEachChild(g,p)};p(i);let m=g=>{if(re.isCallExpression(g)&&re.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&&re.isIdentifier(b)&&o.has(b.text)&&re.isIdentifier(b)){let R=xt(g.arguments[0],i,d);a.push({parent:y,child:b.text,prefix:R,middlewareNodes:g.arguments.slice(1,-1)})}else{let R=Lg(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=Hg(g.arguments[0]),C=g.arguments[1];if(b&&C&&re.isExpression(C)){let R=u.get(y)??[];R.push({paramName:b,node:C}),u.set(y,R)}}let w=up(v);if(w&&o.has(y)&&g.arguments.length>=1){let b=xt(g.arguments[0],i,d),C=Dg(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=xt(g.arguments[0],i,d),C=g.parent;if(re.isCallExpression(C)&&re.isPropertyAccessExpression(C.expression)){let R=up(C.expression.name.text);if(R){let A=C.arguments[0]??g.arguments[0],F=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:F.line+1,column:F.character+1,symbolName:A.getText(i)}})}}}}re.forEachChild(g,m)};m(i);let f=[],h=jg(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=Ut(w.pathExpression,g.pathExpression),C=dn(w.confidence,g.confidence),R=!!b.resolvedPath,A=pn(b.pathExpression),F=l.get(g.owner)??[],_=Bg(g.owner,a,u,b.pathExpression),D=[...w.middlewareNodes,...F,..._,...g.middlewareNodes,g.handlerNode],B=Vs(D,i,e,g.method,s.contextProperties);B.parameters.unshift(...A),B.parameters=fn(B.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:B.parameters.length>0?B.parameters:void 0,requestBody:B.requestBody,cookies:B.cookies.length>0?B.cookies:void 0,responses:B.responses})}}return f}}});import*as $ from"typescript";function Vg(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=zg(a,e,i),l=c?n.map(u=>{let d=Ut(u.pathExpression,c.pathExpression);return{pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?d.resolvedPath:void 0,confidence:dn(u.confidence,c.confidence)}}):n;if($.isArrowFunction(o)||$.isFunctionExpression(o)){let u=new Set(t),d=o.parameters[0];d&&$.isIdentifier(d.name)&&u.add(d.name.text),o.body&&$.forEachChild(o.body,p=>s(p,u,l))}}function zg(r,e,t){if(!r||!$.isObjectLiteralExpression(r))return;let n=qe(r,"prefix");if(!n)return;let s=xt(n,e,t);return{pathExpression:s.pathExpression,resolvedPath:s.resolvedPath,confidence:s.confidence}}function Jg(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function qe(r,e){for(let t of r.properties){if(!$.isPropertyAssignment(t))continue;if(($.isIdentifier(t.name)||$.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function Gg(r,e){return r?$.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:$.isArrayLiteralExpression(r)?r.elements.map(t=>$.isStringLiteral(t)||$.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function pp(r,e){return r?$.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function fp(r){return r?$.isArrayLiteralExpression(r)?r.elements.filter(e=>$.isExpression(e)):[r]:[]}function Wg(r){if(r&&($.isArrowFunction(r)||$.isFunctionExpression(r))&&r.parameters[0]&&$.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function Kg(r,e){if(!r||!$.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function Qg(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 Zg(r,e){return e?{parameters:fn([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function mp(r,e,t){if(!r||!$.isObjectLiteralExpression(r))return;let n=[],s=qe(r,"params");s&&n.push(...Js(s,"path",""));let i=qe(r,"querystring")??qe(r,"query");i&&n.push(...Js(i,"query",""));let o=qe(r,"headers");o&&n.push(...Js(o,"header",""));let a=qe(r,"body");a&&n.push(...Js(a,"body",""));let c=a?hp(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 hp(r,e){if($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if($.isNumericLiteral(r))return{type:"number"};if(!$.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!$.isPropertyAssignment(n))continue;let s=n.name,i=$.isIdentifier(s)||$.isStringLiteral(s)||$.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=gp(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function gp(r,e){if($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))return r.text;if($.isNumericLiteral(r))return Number(r.text);if(r.kind===$.SyntaxKind.TrueKeyword||r.kind===$.SyntaxKind.FalseKeyword)return r.kind===$.SyntaxKind.TrueKeyword;if(r.kind===$.SyntaxKind.NullKeyword)return null;if($.isArrayLiteralExpression(r)){let t=r.elements.map(n=>gp(n,e));return t.every(n=>n!==void 0)?t:void 0}if($.isObjectLiteralExpression(r))return hp(r,e)}function Js(r,e,t){if(!$.isObjectLiteralExpression(r))return[];let n=qe(r,"properties");if(!n||!$.isObjectLiteralExpression(n))return[];let s=qe(r,"required"),i=new Set;if(s&&$.isArrayLiteralExpression(s))for(let a of s.elements)($.isStringLiteral(a)||$.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!$.isPropertyAssignment(a))continue;let c=$.isIdentifier(a.name)||$.isStringLiteral(a.name)||$.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=Yg(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...Js(a.initializer,e,l))}return o}function Yg(r){if(!$.isObjectLiteralExpression(r))return;let e=qe(r,"type");if(e&&($.isStringLiteral(e)||$.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=qe(r,"properties");if(t&&$.isObjectLiteralExpression(t))return"object"}var Gs,yp=E(()=>{"use strict";Do();Mo();Gs=class{async analyzeFile(e,t,n,s){let i=$.createSourceFile(e,t,$.ScriptTarget.Latest,!0,e.endsWith(".ts")?$.ScriptKind.TS:$.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,d=Rr(i,n.projectRoot,s.envOverrides),p=(f,h,g)=>{if($.isVariableDeclaration(f)&&$.isIdentifier(f.name)&&f.initializer){let y=f.initializer.getText(i);(y.includes("fastify(")||y.includes("Fastify("))&&h.add(f.name.text)}if($.isCallExpression(f)&&$.isPropertyAccessExpression(f.expression)){let y=f.expression.expression.getText(i),v=f.expression.name.text;if(v==="register"){let b=Wg(f.arguments[0]);b&&u.set(b,y),Vg(f,i,h,g,p,d)}if(v==="addHook"&&h.has(y)&&f.arguments.length>=2&&Kg(f.arguments[0],i)){let b=l.get(y)??[];b.push(f.arguments[1]),l.set(y,b)}let w=Jg(v);if(w&&h.has(y)&&f.arguments[0]){let b=xt(f.arguments[0],i,d),C=f.arguments.length>=2&&$.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)),F=C?qe(C,"preHandler"):void 0,_=pp(F,i),D=fp(F),B=C?mp(qe(C,"schema"),i,w):void 0;for(let T of g){let j=Ut(T.pathExpression,b.pathExpression),W=dn(T.confidence,b.confidence),Z=!!j.resolvedPath;c.push({owner:y,method:w,pathExpression:j.pathExpression,resolvedPath:W==="high"&&Z?j.resolvedPath:void 0,confidence:W,handlerNode:R,middlewareNodes:D,schemaMetadata:B,source:{filePath:e,line:A.line+1,column:A.character+1,symbolName:R.getText(i)},middleware:_})}}if(v==="route"&&h.has(y)&&f.arguments[0]&&$.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],C=qe(b,"method"),R=qe(b,"url")??qe(b,"path"),A=qe(b,"handler"),F=qe(b,"preHandler"),_=qe(b,"schema"),D=xt(R,i,d),B=Gg(C,i),T=pp(F,i);for(let j of B){let W=A?i.getLineAndCharacterOfPosition(A.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let Z of g){let ze=Ut(Z.pathExpression,D.pathExpression),Kt=dn(Z.confidence,D.confidence),qt=!!ze.resolvedPath;c.push({owner:y,method:j,pathExpression:ze.pathExpression,resolvedPath:Kt==="high"&&qt?ze.resolvedPath:void 0,confidence:Kt,handlerNode:A??b,middlewareNodes:fp(F),schemaMetadata:mp(_,i,j),source:{filePath:e,line:W.line+1,column:W.character+1,symbolName:A?.getText(i)},middleware:T})}}}}$.forEachChild(f,y=>p(y,h,g))};p(i,o,a);let m=[];for(let f of c){let h=pn(f.pathExpression),y=[...Qg(f.owner,l,u),...f.middlewareNodes,f.handlerNode],v=Vs(y,i,e,f.method,s.contextProperties);v.parameters.unshift(...h),v.parameters=fn(v.parameters);let w=Zg(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}}});import*as M from"typescript";function Xg(r,e){M.forEachChild(r,t=>ey(t,r,e))}function ey(r,e,t){if(M.isExpressionStatement(r)&&M.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===M.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(M.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&jo(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=tl(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"&&jo(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=tl(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(M.isVariableStatement(r)&&vp(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!M.isIdentifier(n.name)||!n.initializer)&&jo(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=tl(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(M.isFunctionDeclaration(r)&&vp(r)&&r.name&&ty(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 jo(r,e){if(M.isArrowFunction(r)||M.isFunctionExpression(r))return ny(r);if(M.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(M.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return jo(r.expression.expression,e)}return M.isIdentifier(r)?/handler/i.test(r.text):!1}function ty(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function ny(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function vp(r){return(M.getCombinedModifierFlags(r)&M.ModifierFlags.Export)!==0}function tl(r,e){let t=[],n=r;for(;M.isCallExpression(n)&&M.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return M.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function ry(r,e,t){return r.map(n=>{let s=sy(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 sy(r,e){return M.isIdentifier(r)?r.text:M.isCallExpression(r)&&M.isIdentifier(r.expression)?r.expression.text:M.isCallExpression(r)&&M.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function oy(r,e,t){let n=ay(r);if(!n)return[];let s=new Map,i=o=>{if(M.isPropertyAccessExpression(o)||M.isElementAccessExpression(o)){let a=Ws(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=iy[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(M.isCallExpression(o)&&M.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Ws(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}})}}}M.forEachChild(o,i)};return i(r),Array.from(s.values())}function ay(r){if(M.isArrowFunction(r)||M.isFunctionExpression(r)||M.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&M.isIdentifier(e.name))return e.name.text}return M.isIdentifier(r),"event"}function Ws(r,e){return M.isIdentifier(r)?[r.text]:M.isPropertyAccessExpression(r)?[...Ws(r.expression,e),r.name.text]:r.kind===M.SyntaxKind.PropertyAccessExpression||M.isNonNullExpression(r)?Ws(r.expression,e):M.isElementAccessExpression(r)&&M.isStringLiteral(r.argumentExpression)?[...Ws(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var Ks,iy,nl=E(()=>{"use strict";Ks=class{async analyzeFile(e,t,n,s){let i=M.createSourceFile(e,t,M.ScriptTarget.Latest,!0,e.endsWith(".ts")?M.ScriptKind.TS:M.ScriptKind.JS),o=[];return Xg(i,o),o.length===0?[]:o.map(a=>{let c=oy(a.handlerNode,i,e),l=ry(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}})}};iy={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var Cr=E(()=>{"use strict";Mo();dp();yp();nl()});import*as Lo from"fs";function bp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function cy(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 Er,rl=E(()=>{"use strict";Cr();un();Er=class{id="provider.express";framework="express";analyzer=new zs;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(bp(t)===bp(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??ot(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=Lo.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=Lo.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=cy(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)}}});import*as Ho from"fs";function Sp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function ly(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 qr,sl=E(()=>{"use strict";Cr();un();qr=class{id="provider.fastify";framework="fastify";analyzer=new Gs;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(Sp(t)===Sp(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??ot(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=Ho.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=Ho.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=ly(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)}}});import*as Bo from"fs";import*as de from"typescript";function xp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function il(r,e){let t=r.expression;if(de.isCallExpression(t))return de.isIdentifier(t.expression)?t.expression.text:t.expression.getText(e);if(de.isIdentifier(t))return t.text}function wp(r){let e=r.expression;if(de.isCallExpression(e))return e.arguments[0]}function uy(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function Rp(r){return de.canHaveDecorators(r)?de.getDecorators(r)??[]:[]}function Cp(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=il(s,e);if(!i||!t.has(i))continue;let o=s.expression;if(!de.isCallExpression(o)){n.push({name:i});continue}for(let a of o.arguments)n.push({name:`${i}:${a.getText(e)}`})}return n}function dy(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var Ar,ol=E(()=>{"use strict";Do();un();Ar=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(xp(t)===xp(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??ot(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=Bo.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=Bo.readFileSync(a,"utf-8")}catch{continue}let d=[],p=[],m=de.createSourceFile(a,u,de.ScriptTarget.Latest,!0,a.endsWith(".ts")?de.ScriptKind.TS:de.ScriptKind.JS),f=Rr(m,t.projectRoot,e.envOverrides),h=g=>{if(de.isClassDeclaration(g)){let y=Rp(g),v=y.find(w=>il(w,m)==="Controller");if(v){let w=xt(wp(v),m,f),b=Cp(y,m);for(let C of g.members){if(!de.isMethodDeclaration(C))continue;let R=Rp(C),A=R.map(F=>({decorator:F,name:il(F,m)})).filter(F=>!!F.name);for(let F of A){let _=uy(F.name);if(!_)continue;let D=xt(wp(F.decorator),m,f),B=Ut(w.pathExpression,D.pathExpression),T=Cp(R,m),j=C.name?.getText(m),W=C.name??C,Z=m.getLineAndCharacterOfPosition(W.getStart(m)),ze=dy(w.confidence,D.confidence);p.push({id:"",method:_,framework:"nestjs",pathExpression:B.pathExpression,resolvedPath:ze==="high"?B.resolvedPath:void 0,confidence:ze,source:{filePath:a,line:Z.line+1,column:Z.character+1,symbolName:j},middleware:[...b,...T]}),ze!=="high"&&d.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${j??"unknown handler"} in ${a}`})}}}}de.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)}}});import*as _e from"fs";import*as at from"path";function py(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}=Ap(c,e),d=Pp(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=kp(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 Ep(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}=Ap(l,e),p=Pp(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=kp(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 Ap(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function Pp(r,e){let t=[at.join(e,`${r}.ts`),at.join(e,`${r}.js`),at.join(e,r,"index.ts"),at.join(e,r,"index.js")];for(let n of t)if(_e.existsSync(n))return n}function kp(r){return r.startsWith("/")?r:`/${r}`}function cl(r){let e=r.split(`
|
|
469
|
-
`);return Qs(e,0,-1).value}function Qs(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=fy(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=Qs(r,o+1,l),y={};y[h]=g.value,s.push(y),o=g.nextLine}else{let h=Qs(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=Qs(r,o+1,l);h[y]=w.value,s.push(h),o=w.nextLine}else h[y]=al(v),s.push(h),o++}else s.push(al(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=Qs(r,o+1,l);n[p]=f.value,o=f.nextLine}else n[p]=al(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function fy(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function al(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 my(r){return cl(r)}function qp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Pr,ll=E(()=>{"use strict";nl();un();Pr=class{id="provider.lambda";framework="lambda";analyzer=new Ks;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(qp(t)===qp(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=_e.existsSync(at.join(e.projectRoot,"serverless.yml"))||_e.existsSync(at.join(e.projectRoot,"serverless.yaml"))||_e.existsSync(at.join(e.projectRoot,"template.yaml"))||_e.existsSync(at.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=at.join(o,a);if(_e.existsSync(c)){try{let l=_e.readFileSync(c,"utf-8"),u=my(l),d=py(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=at.join(o,"template.yaml"),c=at.join(o,"template.json");if(_e.existsSync(c))try{let l=_e.readFileSync(c,"utf-8"),u=JSON.parse(l),d=Ep(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(_e.existsSync(a))try{let l=_e.readFileSync(a,"utf-8"),u=cl(l),d=Ep(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??ot(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=_e.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=_e.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)}}});import*as Uo from"fs";import*as Tp from"path";function gy(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=Uo.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=Tp.join(s,o.name);o.isDirectory()?hy.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function Zs(r){return gy(r,/\.java$/)}function Ys(r){return Uo.promises.readFile(r,"utf-8")}function ul(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function dl(r){return r.replace(/\\/g,"/").split("/").pop()||""}function Op(r,e){let t=Ip.get(e);if(t&&Date.now()-t.ts<yy)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=Zs(r).filter(i=>n.test(dl(i)));return Ip.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var hy,Ip,yy,Vo=E(()=>{"use strict";hy=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);Ip=new Map,yy=3e4});function vy(r){if(r.includes("/"))return r;if(Vt[r])return Vt[r];let e=`MediaType.${r}`;if(Vt[e])return Vt[e];for(let[s,i]of Object.entries(Vt))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(Vt[i])return Vt[i];let o=`MediaType.${s}_VALUE`;if(Vt[o])return Vt[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 Xs(r){return r.map(vy)}function zt(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 by.has(t)?zt(n.trim()):r}function kr(r){return/MultipartFile/.test(r)}var Vt,by,zo=E(()=>{"use strict";Vt={"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"};by=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var Bn,$p=E(()=>{"use strict";Vo();zo();Bn=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 Op(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await Ys(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 Ys(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=zt(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(T=>T.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 F=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");F&&i.maximum===void 0&&(i.maximum=Number(F));let _=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");_&&i.minimum===void 0&&(i.minimum=Number(_));let D=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");D&&i.maximum===void 0&&(i.maximum=Number(D)),/@Email\b/.test(s)&&(i.format=i.format||"email");let B=this.extractAttr(s,"Pattern","regexp");return B&&!i.pattern&&(i.pattern=B),/@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}}});import{BaseJavaCstVisitorWithDefaults as Sy}from"java-parser";function pl(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var Jo,Fp=E(()=>{"use strict";zo();Jo=class extends Sy{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=Xs(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Xs([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:pl(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,zt(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 zt(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(kr(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=zt(g));else if(b.name==="RequestPart"){o=!0;let C=this.getAnnotationStringValue(b)||p,R=kr(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 Np={};Tt(Np,{EndpointParser:()=>fl});import{parse as xy}from"java-parser";var fl,_p=E(()=>{"use strict";Vo();zo();Fp();fl=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>ul(n.trim()));for(let n of[...this.fileCache.keys()]){let s=ul(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=Zs(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(dl(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 Ys(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=xy(e),n=new Jo;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=[],F=b.args;if(F){R=this.extractPathFromArgs(F);let B=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(F);if(B){let T=B[1],j=[...T.matchAll(/["']([^"']+)["']/g)].map(Z=>Z[1]),W=[...T.matchAll(/MediaType\.([A-Z_]+)/g)].map(Z=>`MediaType.${Z[1]}`);A=Xs([...j,...W])}if(b.name==="RequestMapping"){let T=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(F);T&&(C=T[1])}}!C&&b.name==="RequestMapping"&&(C="GET");let _=R;a.basePath&&(_&&!_.startsWith("/")?_=a.basePath+"/"+_:_=a.basePath+_),_&&!_.startsWith("/")&&(_="/"+_);let D=this.extractParameterMetadataFromSig(v);a.endpoints.push({method:C,path:_,file:t,line:u+1,pathParams:pl(_),consumes:A,bodyType:D.bodyType,headers:D.headers,queryParams:D.queryParams,hasBody:D.hasBody,formParts:D.formParts.length>0?D.formParts:void 0,modelAttributeType:D.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(kr(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=zt(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=kr(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)})}}});import*as Go from"fs";import*as Mp from"path";function Cy(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 wy,Ry,Ir,ml=E(()=>{"use strict";Vo();$p();wy=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],Ry=/@(?:RestController|Controller)\b/,Ir=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of wy)if(Go.existsSync(Mp.join(e.projectRoot,s)))return{supported:!0,confidence:.95,reasons:[`${s} detected`]};let t=e.sourceFiles??Zs(e.projectRoot),n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=Go.readFileSync(s,"utf-8");if(Ry.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 Bn(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(()=>(_p(),Np))),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:Cy(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=Bn.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=Bn.javaTypeToParamType(e.schemaType);let n=Bn.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"}}}});import*as Ko from"fs";import*as Bp from"path";function hl(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Ko.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Bp.join(n,i.name);if(i.isDirectory()){Ey.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function Up(r){let e=hl(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let d="";try{d=Ko.readFileSync(u,"utf-8")}catch{continue}let p=Ay(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=jp(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=jp(d.imports,m.object),h=d.appNames.has(m.object)||d.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let y=Oy(m.method,m.args);if(y.length===0)continue;let v=$y(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?Ly(C,v):v,A=Hy(p.signature,jy(R)),F=g?a.get(f):void 0,D=Vp(m.args)??F;l.push({methods:y,path:R,file:u,line:m.line,functionName:p.functionName,statusCode:Fy(m.args),responseModel:Ny(m.args)??Iy(p.signature),tags:D,deprecated:_y(m.args),summary:My(m.args),params:A.params,security:Dy(m.args,p.signature),pathUnresolved:w})}}return{endpoints:l,models:t,warnings:i}}function jp(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function Jt(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 Jt(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return Jt(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:Jt(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:Jt(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=Jt(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 Ay(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=Vy(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}=Wo(i,a-1),w=Ty(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}=Wo(i,a-1),w=y.slice(y.indexOf("(")),b=ky(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}=Py(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}=Wo(i,a-1),v=y.slice(y.indexOf("("));n.routers.push({name:h[1],constructorPrefix:Hp(v)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:y}=Wo(i,a-1),v=y.slice(y.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:Hp(v),tags:Vp(v),line:l}),o=[];continue}o=[]}return n}function Py(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 Wo(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=V(r.collection,e),n=Be(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:tt(n,Bd(t,n)).snapshot().body||void 0,body:i??null,headers:o,queryParams:a,placeholders:[...l],iterations:s}}}}]});function zd(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=zd(n.items??[],e);if(s)return s}}var Jd,Gd=E(()=>{"use strict";Fe();Ne();Ne();Jd=[{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=V(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=V(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=V(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=V(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=Ce(n);if(Q(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let d=Ce(n).find(p=>p.folderPath===r.parentFolder||p.folderPath.toLowerCase()===a);if(d){let p=n.items;i=zd(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=V(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw I('"folder" is required');let s=r.folder.toLowerCase(),i=Ce(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=Jc(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 Kc=E(()=>{"use strict"});var Wd=E(()=>{"use strict"});import*as St from"fs";import*as Sr from"path";var cg,lg,ug,xr,Ao=E(()=>{"use strict";cg=["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"],lg={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:[]},ug={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},xr=class{buildFingerprint(e){let t=[],n=Sr.join(e,"package.json"),s;for(let i of cg){let o=Sr.join(e,i);St.existsSync(o)&&t.push(o)}if(St.existsSync(n))try{let i=JSON.parse(St.readFileSync(n,"utf-8"));s={dependencies:i.dependencies,devDependencies:i.devDependencies,scripts:i.scripts}}catch{}return{projectRoot:e,packageJsonPath:St.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 St.existsSync(Sr.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=lg[t],i=ug[t],o=0,a=120;for(let c of n){let l=Sr.join(e.projectRoot,c);if(!St.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let d=u.shift(),p;try{p=St.readdirSync(d,{withFileTypes:!0})}catch{continue}for(let m of p){let f=Sr.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=St.readFileSync(f,"utf-8")}catch{continue}if(s.some(g=>h.includes(g)))return!0}}}return!1}}});import*as Kd from"fs";import*as Qd from"path";function ot(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Kd.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Qd.join(n,i.name);if(i.isDirectory()){dg.has(i.name)||t.push(o);continue}i.isFile()&&(pg.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var dg,pg,un=E(()=>{"use strict";dg=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),pg=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});import*as Zd from"fs";import*as Po from"path";function ko(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=Po.isAbsolute(t)?t:Po.join(r,t);if(!Zd.existsSync(n))return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader module not found: ${n}`}]};try{let s=le(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 Io=E(()=>{"use strict"});function Xd(r,e){let t=r.projectName?.trim();if(t)return t;let n=Yd(r.source.filePath),s=fg(n);if(s)return s;let i;for(let a of e){let c=Yd(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 fg(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function Yd(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Qc=E(()=>{"use strict"});import*as _o from"fs";import*as Hn from"path";import*as x from"typescript";function dn(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function pn(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 $o(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,d=new Map,p=Ig(o),m=Pg(r,e,p),f=Fg(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=op(e),g=mg(e,t),y=kg(r,t,h,g,m,f),v=(R,A)=>{let F=l.find(_=>_.statusCode===R);return F||(F={statusCode:R},l.push(F)),A&&(F.body={type:A,schema:F.body?.schema}),F};x.isFunctionLike(r)&&qg(r,e,d,m,f,p);let w=(R,A)=>{let F=h.get(R);if(F){let W=`${t}:${R}`;if(s.visitedSymbols.has(W))return;s.visitedSymbols.add(W);let Z=y.get(W),ze=A?No(A,F,m,f):void 0,Kt=ip(Z,ze),qt=$o(F,e,t,n,s,Kt,o);Yc({parameters:a,requestBody:u,cookies:c,responses:l},qt),!u&&qt.requestBody&&(u=qt.requestBody);return}let _=g.get(R);if(!_||s.visitedSymbols.has(_.symbolKey))return;s.visitedSymbols.add(_.symbolKey);let D=y.get(_.symbolKey),B=A?No(A,_.node,m,f):void 0,T=ip(D,B),j=$o(_.node,_.sourceFile,_.filePath,n,s,T,o);Yc({parameters:a,requestBody:u,cookies:c,responses:l},j),!u&&j.requestBody&&(u=j.requestBody)},b=["POST","PUT","PATCH"].includes(n),C=R=>{x.isVariableDeclaration(R)&&Eg(R,e,d,m,f,p),x.isIdentifier(R)&&(x.isCallExpression(R.parent)&&R.parent.expression===R||w(R.text));let A=wr(R,e,"query",d,m,f,p);if(A){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:A.path,location:"query",type:Oo(R,e),detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}let F=wr(R,e,"params",d,m,f,p);if(F){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:F.path,location:"path",required:!0,type:Oo(R,e),detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}if(Cg(R,e,m)&&!u){let T=e.getLineAndCharacterOfPosition(R.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}}}let _=wr(R,e,"body",d,m,f,p);if(_){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:_.path,location:"body",type:Oo(R,e),detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let D=wr(R,e,"headers",d,m,f,p);if(D){let T=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:D.path,location:"header",type:"string",detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}let B=wr(R,e,"cookies",d,m,f,p);if(B){let T=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:B.path,type:"request",detectionLocation:{filePath:t,line:T.line+1,column:T.character+1,accessMode:"read"}})}for(let T of p){let j=wr(R,e,T,d,m,f,p);if(!j)continue;let W=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:j.path,location:T,type:Oo(R,e),detectionLocation:{filePath:t,line:W.line+1,column:W.character+1,accessMode:"read"}})}if(x.isCallExpression(R)){let T=Tg(R,e,f);T&&v(T.statusCode,T.bodyType)}if(x.isCallExpression(R)){let T=Og(R,f);if(T){let j=v(T.statusCode);if(!j.headers?.some(W=>W.name===T.headerName)){let W=e.getLineAndCharacterOfPosition(R.getStart(e));j.headers=j.headers??[],j.headers.push({name:T.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:W.line+1,column:W.character+1,accessMode:"write"}})}}}if(x.isCallExpression(R)&&x.isPropertyAccessExpression(R.expression)&&Ng(R.expression.expression,f)&&R.expression.name.text==="cookie"&&R.arguments[0]&&x.isStringLiteral(R.arguments[0])){let T=R.arguments[0].text;if(T&&!c.some(j=>j.name===T&&j.type==="response")){let j=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:T,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:j.line+1,column:j.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 Vs(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=$o(o,e,t,n,void 0,void 0,s);Yc(i,a)}return i.parameters=fn(i.parameters),i.cookies=Rg(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 op(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 mg(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=gg(e,s);if(!o)return;let a=hg(o);if(!a)return;let c=yg(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 hg(r){let e="";try{e=_o.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 gg(r,e){let t=Hn.resolve(Hn.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,Hn.join(t,"index.ts"),Hn.join(t,"index.js")];for(let s of n)try{if(_o.statSync(s).isFile())return s}catch{continue}}function yg(r,e){let t=new Map,n=op(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(x.isFunctionDeclaration(i)&&i.name&&ep(i)){s(i.name.text,i),tp(i)&&s("default",i);continue}if(x.isVariableStatement(i)&&ep(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),tp(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=Zc(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=Zc(a,n);c&&s("default",c);continue}if(x.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=Zc(a,n);c&&s(o.name.text,c)}}return t}function Zc(r,e){if(x.isFunctionExpression(r)||x.isArrowFunction(r))return r;if(x.isIdentifier(r))return e.get(r.text)}function ep(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.ExportKeyword):!1}function tp(r){return x.canHaveModifiers(r)?!!x.getModifiers(r)?.some(e=>e.kind===x.SyntaxKind.DefaultKeyword):!1}function Yc(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=fn([...s,...i])}}function fn(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:np([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=np(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=>vg(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=To(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=To(o)}}for(let i of s.values()){let o=To(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=To(o)}}return t}function np(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 vg(r){let e=xg([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=bg(e),n=e.filter(s=>!wg(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function bg(r){return[...r].sort(Sg)[0]}function Sg(r,e){let t=rp(r),n=rp(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 rp(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function xg(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 wg(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 Rg(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 Cg(r,e,t){return x.isPropertyAccessExpression(r)&&x.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function wr(r,e,t,n,s,i,o){return el(r,e,t,n,!1,s,i,o)}function el(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:Fo(h)}}if(!l||!x.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=Fo(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function Eg(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=el(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))&&Us(r.name,c,l,t)}}function qg(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){Ag(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let d of o){let p=el(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))&&Us(a.name,l,u,t)}}}function Ag(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=Xc(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))&&Us(s.name,o,"",e)}}function Pg(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=Ln(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=Ln(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 Us(r,e,t,n){if(x.isObjectBindingPattern(r)){for(let s of r.elements){let i=Xc(s);if(!i)continue;let o=sp(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))&&Us(s.name,e,o,n)}return}for(let s of r.elements){if(!x.isBindingElement(s))continue;let i=Xc(s)??"[]",o=sp(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))&&Us(s.name,e,o,n)}}function Xc(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 sp(r,e){return Fo(r?`${r}.${e}`.split("."):[e])}function Fo(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 To(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function kg(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=No(l,d,s,i);m&&a(`${e}:${u}`,m)}let p=n.get(u);if(p){let m=No(l,p.node,s,i);m&&a(p.symbolKey,m)}}x.forEachChild(l,c)};return c(r),o}function ip(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 Ig(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 No(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=Ln(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 Oo(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 Tg(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=ap(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":$g(r.arguments[0])}}function Og(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=ap(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function ap(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 $g(r){return r&&(x.isObjectLiteralExpression(r)||x.isArrayLiteralExpression(r))?"json":"text"}function Fg(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=Ln(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=Ln(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=Ln(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 Ng(r,e){let t=Ln(r);return t?e.has(t):!1}function Ln(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 Mo=E(()=>{"use strict"});import*as ce from"typescript";function Rr(r,e,t){let n={},s=o=>{if(ce.isVariableDeclaration(o)&&ce.isIdentifier(o.name)&&o.initializer){let a=mn(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}ce.forEachChild(o,s)};s(r);let i={...Mg(e),...t};return{variables:n,env:i}}function xt(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=mn(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=_g(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 Ut(r,e){let t=cp(r??""),n=cp(e??""),s=lp(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function cp(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function lp(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function mn(r,e,t){if(ce.isStringLiteral(r)||ce.isNoSubstitutionTemplateLiteral(r))return r.text;if(ce.isParenthesizedExpression(r))return mn(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=mn(r.left,e,t),s=mn(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 mn(r.left,e,t)??mn(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 _g(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=mn(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?lp(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function Mg(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=le("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 Do=E(()=>{"use strict"});import*as re from"typescript";function up(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function Dg(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 jg(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=Ut(u.pathExpression,a.prefix.pathExpression),p=dn(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 Lg(r){return re.isStringLiteral(r)||re.isNoSubstitutionTemplateLiteral(r)||re.isTemplateExpression(r)}function Hg(r){if(re.isStringLiteral(r)||re.isNoSubstitutionTemplateLiteral(r))return r.text}function Bg(r,e,t,n){let s=new Set(pn(n).map(a=>a.name));if(s.size===0)return[];let i=Ug(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 Ug(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 zs,dp=E(()=>{"use strict";Do();Mo();zs=class{async analyzeFile(e,t,n,s){let i=re.createSourceFile(e,t,re.ScriptTarget.Latest,!0,e.endsWith(".ts")?re.ScriptKind.TS:re.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,d=Rr(i,n.projectRoot,s.envOverrides),p=g=>{if(re.isVariableDeclaration(g)&&re.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)}re.forEachChild(g,p)};p(i);let m=g=>{if(re.isCallExpression(g)&&re.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&&re.isIdentifier(b)&&o.has(b.text)&&re.isIdentifier(b)){let R=xt(g.arguments[0],i,d);a.push({parent:y,child:b.text,prefix:R,middlewareNodes:g.arguments.slice(1,-1)})}else{let R=Lg(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=Hg(g.arguments[0]),C=g.arguments[1];if(b&&C&&re.isExpression(C)){let R=u.get(y)??[];R.push({paramName:b,node:C}),u.set(y,R)}}let w=up(v);if(w&&o.has(y)&&g.arguments.length>=1){let b=xt(g.arguments[0],i,d),C=Dg(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=xt(g.arguments[0],i,d),C=g.parent;if(re.isCallExpression(C)&&re.isPropertyAccessExpression(C.expression)){let R=up(C.expression.name.text);if(R){let A=C.arguments[0]??g.arguments[0],F=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:F.line+1,column:F.character+1,symbolName:A.getText(i)}})}}}}re.forEachChild(g,m)};m(i);let f=[],h=jg(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=Ut(w.pathExpression,g.pathExpression),C=dn(w.confidence,g.confidence),R=!!b.resolvedPath,A=pn(b.pathExpression),F=l.get(g.owner)??[],_=Bg(g.owner,a,u,b.pathExpression),D=[...w.middlewareNodes,...F,..._,...g.middlewareNodes,g.handlerNode],B=Vs(D,i,e,g.method,s.contextProperties);B.parameters.unshift(...A),B.parameters=fn(B.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:B.parameters.length>0?B.parameters:void 0,requestBody:B.requestBody,cookies:B.cookies.length>0?B.cookies:void 0,responses:B.responses})}}return f}}});import*as $ from"typescript";function Vg(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=zg(a,e,i),l=c?n.map(u=>{let d=Ut(u.pathExpression,c.pathExpression);return{pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?d.resolvedPath:void 0,confidence:dn(u.confidence,c.confidence)}}):n;if($.isArrowFunction(o)||$.isFunctionExpression(o)){let u=new Set(t),d=o.parameters[0];d&&$.isIdentifier(d.name)&&u.add(d.name.text),o.body&&$.forEachChild(o.body,p=>s(p,u,l))}}function zg(r,e,t){if(!r||!$.isObjectLiteralExpression(r))return;let n=qe(r,"prefix");if(!n)return;let s=xt(n,e,t);return{pathExpression:s.pathExpression,resolvedPath:s.resolvedPath,confidence:s.confidence}}function Jg(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function qe(r,e){for(let t of r.properties){if(!$.isPropertyAssignment(t))continue;if(($.isIdentifier(t.name)||$.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function Gg(r,e){return r?$.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:$.isArrayLiteralExpression(r)?r.elements.map(t=>$.isStringLiteral(t)||$.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function pp(r,e){return r?$.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function fp(r){return r?$.isArrayLiteralExpression(r)?r.elements.filter(e=>$.isExpression(e)):[r]:[]}function Wg(r){if(r&&($.isArrowFunction(r)||$.isFunctionExpression(r))&&r.parameters[0]&&$.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function Kg(r,e){if(!r||!$.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function Qg(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 Zg(r,e){return e?{parameters:fn([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function mp(r,e,t){if(!r||!$.isObjectLiteralExpression(r))return;let n=[],s=qe(r,"params");s&&n.push(...Js(s,"path",""));let i=qe(r,"querystring")??qe(r,"query");i&&n.push(...Js(i,"query",""));let o=qe(r,"headers");o&&n.push(...Js(o,"header",""));let a=qe(r,"body");a&&n.push(...Js(a,"body",""));let c=a?hp(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 hp(r,e){if($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if($.isNumericLiteral(r))return{type:"number"};if(!$.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!$.isPropertyAssignment(n))continue;let s=n.name,i=$.isIdentifier(s)||$.isStringLiteral(s)||$.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=gp(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function gp(r,e){if($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))return r.text;if($.isNumericLiteral(r))return Number(r.text);if(r.kind===$.SyntaxKind.TrueKeyword||r.kind===$.SyntaxKind.FalseKeyword)return r.kind===$.SyntaxKind.TrueKeyword;if(r.kind===$.SyntaxKind.NullKeyword)return null;if($.isArrayLiteralExpression(r)){let t=r.elements.map(n=>gp(n,e));return t.every(n=>n!==void 0)?t:void 0}if($.isObjectLiteralExpression(r))return hp(r,e)}function Js(r,e,t){if(!$.isObjectLiteralExpression(r))return[];let n=qe(r,"properties");if(!n||!$.isObjectLiteralExpression(n))return[];let s=qe(r,"required"),i=new Set;if(s&&$.isArrayLiteralExpression(s))for(let a of s.elements)($.isStringLiteral(a)||$.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!$.isPropertyAssignment(a))continue;let c=$.isIdentifier(a.name)||$.isStringLiteral(a.name)||$.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=Yg(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...Js(a.initializer,e,l))}return o}function Yg(r){if(!$.isObjectLiteralExpression(r))return;let e=qe(r,"type");if(e&&($.isStringLiteral(e)||$.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=qe(r,"properties");if(t&&$.isObjectLiteralExpression(t))return"object"}var Gs,yp=E(()=>{"use strict";Do();Mo();Gs=class{async analyzeFile(e,t,n,s){let i=$.createSourceFile(e,t,$.ScriptTarget.Latest,!0,e.endsWith(".ts")?$.ScriptKind.TS:$.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,d=Rr(i,n.projectRoot,s.envOverrides),p=(f,h,g)=>{if($.isVariableDeclaration(f)&&$.isIdentifier(f.name)&&f.initializer){let y=f.initializer.getText(i);(y.includes("fastify(")||y.includes("Fastify("))&&h.add(f.name.text)}if($.isCallExpression(f)&&$.isPropertyAccessExpression(f.expression)){let y=f.expression.expression.getText(i),v=f.expression.name.text;if(v==="register"){let b=Wg(f.arguments[0]);b&&u.set(b,y),Vg(f,i,h,g,p,d)}if(v==="addHook"&&h.has(y)&&f.arguments.length>=2&&Kg(f.arguments[0],i)){let b=l.get(y)??[];b.push(f.arguments[1]),l.set(y,b)}let w=Jg(v);if(w&&h.has(y)&&f.arguments[0]){let b=xt(f.arguments[0],i,d),C=f.arguments.length>=2&&$.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)),F=C?qe(C,"preHandler"):void 0,_=pp(F,i),D=fp(F),B=C?mp(qe(C,"schema"),i,w):void 0;for(let T of g){let j=Ut(T.pathExpression,b.pathExpression),W=dn(T.confidence,b.confidence),Z=!!j.resolvedPath;c.push({owner:y,method:w,pathExpression:j.pathExpression,resolvedPath:W==="high"&&Z?j.resolvedPath:void 0,confidence:W,handlerNode:R,middlewareNodes:D,schemaMetadata:B,source:{filePath:e,line:A.line+1,column:A.character+1,symbolName:R.getText(i)},middleware:_})}}if(v==="route"&&h.has(y)&&f.arguments[0]&&$.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],C=qe(b,"method"),R=qe(b,"url")??qe(b,"path"),A=qe(b,"handler"),F=qe(b,"preHandler"),_=qe(b,"schema"),D=xt(R,i,d),B=Gg(C,i),T=pp(F,i);for(let j of B){let W=A?i.getLineAndCharacterOfPosition(A.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let Z of g){let ze=Ut(Z.pathExpression,D.pathExpression),Kt=dn(Z.confidence,D.confidence),qt=!!ze.resolvedPath;c.push({owner:y,method:j,pathExpression:ze.pathExpression,resolvedPath:Kt==="high"&&qt?ze.resolvedPath:void 0,confidence:Kt,handlerNode:A??b,middlewareNodes:fp(F),schemaMetadata:mp(_,i,j),source:{filePath:e,line:W.line+1,column:W.character+1,symbolName:A?.getText(i)},middleware:T})}}}}$.forEachChild(f,y=>p(y,h,g))};p(i,o,a);let m=[];for(let f of c){let h=pn(f.pathExpression),y=[...Qg(f.owner,l,u),...f.middlewareNodes,f.handlerNode],v=Vs(y,i,e,f.method,s.contextProperties);v.parameters.unshift(...h),v.parameters=fn(v.parameters);let w=Zg(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}}});import*as M from"typescript";function Xg(r,e){M.forEachChild(r,t=>ey(t,r,e))}function ey(r,e,t){if(M.isExpressionStatement(r)&&M.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===M.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(M.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&jo(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=tl(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"&&jo(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=tl(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(M.isVariableStatement(r)&&vp(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!M.isIdentifier(n.name)||!n.initializer)&&jo(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=tl(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(M.isFunctionDeclaration(r)&&vp(r)&&r.name&&ty(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 jo(r,e){if(M.isArrowFunction(r)||M.isFunctionExpression(r))return ny(r);if(M.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(M.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return jo(r.expression.expression,e)}return M.isIdentifier(r)?/handler/i.test(r.text):!1}function ty(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function ny(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function vp(r){return(M.getCombinedModifierFlags(r)&M.ModifierFlags.Export)!==0}function tl(r,e){let t=[],n=r;for(;M.isCallExpression(n)&&M.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return M.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function ry(r,e,t){return r.map(n=>{let s=sy(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 sy(r,e){return M.isIdentifier(r)?r.text:M.isCallExpression(r)&&M.isIdentifier(r.expression)?r.expression.text:M.isCallExpression(r)&&M.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function oy(r,e,t){let n=ay(r);if(!n)return[];let s=new Map,i=o=>{if(M.isPropertyAccessExpression(o)||M.isElementAccessExpression(o)){let a=Ws(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=iy[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(M.isCallExpression(o)&&M.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Ws(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}})}}}M.forEachChild(o,i)};return i(r),Array.from(s.values())}function ay(r){if(M.isArrowFunction(r)||M.isFunctionExpression(r)||M.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&M.isIdentifier(e.name))return e.name.text}return M.isIdentifier(r),"event"}function Ws(r,e){return M.isIdentifier(r)?[r.text]:M.isPropertyAccessExpression(r)?[...Ws(r.expression,e),r.name.text]:r.kind===M.SyntaxKind.PropertyAccessExpression||M.isNonNullExpression(r)?Ws(r.expression,e):M.isElementAccessExpression(r)&&M.isStringLiteral(r.argumentExpression)?[...Ws(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var Ks,iy,nl=E(()=>{"use strict";Ks=class{async analyzeFile(e,t,n,s){let i=M.createSourceFile(e,t,M.ScriptTarget.Latest,!0,e.endsWith(".ts")?M.ScriptKind.TS:M.ScriptKind.JS),o=[];return Xg(i,o),o.length===0?[]:o.map(a=>{let c=oy(a.handlerNode,i,e),l=ry(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}})}};iy={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var Cr=E(()=>{"use strict";Mo();dp();yp();nl()});import*as Lo from"fs";function bp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function cy(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 Er,rl=E(()=>{"use strict";Cr();un();Er=class{id="provider.express";framework="express";analyzer=new zs;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(bp(t)===bp(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??ot(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=Lo.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=Lo.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=cy(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)}}});import*as Ho from"fs";function Sp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function ly(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 qr,sl=E(()=>{"use strict";Cr();un();qr=class{id="provider.fastify";framework="fastify";analyzer=new Gs;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(Sp(t)===Sp(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??ot(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=Ho.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=Ho.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=ly(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)}}});import*as Bo from"fs";import*as pe from"typescript";function xp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function il(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 wp(r){let e=r.expression;if(pe.isCallExpression(e))return e.arguments[0]}function uy(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function Rp(r){return pe.canHaveDecorators(r)?pe.getDecorators(r)??[]:[]}function Cp(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=il(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 dy(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var Ar,ol=E(()=>{"use strict";Do();un();Ar=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(xp(t)===xp(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??ot(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=Bo.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=Bo.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=Rr(m,t.projectRoot,e.envOverrides),h=g=>{if(pe.isClassDeclaration(g)){let y=Rp(g),v=y.find(w=>il(w,m)==="Controller");if(v){let w=xt(wp(v),m,f),b=Cp(y,m);for(let C of g.members){if(!pe.isMethodDeclaration(C))continue;let R=Rp(C),A=R.map(F=>({decorator:F,name:il(F,m)})).filter(F=>!!F.name);for(let F of A){let _=uy(F.name);if(!_)continue;let D=xt(wp(F.decorator),m,f),B=Ut(w.pathExpression,D.pathExpression),T=Cp(R,m),j=C.name?.getText(m),W=C.name??C,Z=m.getLineAndCharacterOfPosition(W.getStart(m)),ze=dy(w.confidence,D.confidence);p.push({id:"",method:_,framework:"nestjs",pathExpression:B.pathExpression,resolvedPath:ze==="high"?B.resolvedPath:void 0,confidence:ze,source:{filePath:a,line:Z.line+1,column:Z.character+1,symbolName:j},middleware:[...b,...T]}),ze!=="high"&&d.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${j??"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)}}});import*as _e from"fs";import*as at from"path";function py(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}=Ap(c,e),d=Pp(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=kp(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 Ep(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}=Ap(l,e),p=Pp(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=kp(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 Ap(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function Pp(r,e){let t=[at.join(e,`${r}.ts`),at.join(e,`${r}.js`),at.join(e,r,"index.ts"),at.join(e,r,"index.js")];for(let n of t)if(_e.existsSync(n))return n}function kp(r){return r.startsWith("/")?r:`/${r}`}function cl(r){let e=r.split(`
|
|
469
|
+
`);return Qs(e,0,-1).value}function Qs(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=fy(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=Qs(r,o+1,l),y={};y[h]=g.value,s.push(y),o=g.nextLine}else{let h=Qs(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=Qs(r,o+1,l);h[y]=w.value,s.push(h),o=w.nextLine}else h[y]=al(v),s.push(h),o++}else s.push(al(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=Qs(r,o+1,l);n[p]=f.value,o=f.nextLine}else n[p]=al(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function fy(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function al(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 my(r){return cl(r)}function qp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Pr,ll=E(()=>{"use strict";nl();un();Pr=class{id="provider.lambda";framework="lambda";analyzer=new Ks;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(qp(t)===qp(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=_e.existsSync(at.join(e.projectRoot,"serverless.yml"))||_e.existsSync(at.join(e.projectRoot,"serverless.yaml"))||_e.existsSync(at.join(e.projectRoot,"template.yaml"))||_e.existsSync(at.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=at.join(o,a);if(_e.existsSync(c)){try{let l=_e.readFileSync(c,"utf-8"),u=my(l),d=py(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=at.join(o,"template.yaml"),c=at.join(o,"template.json");if(_e.existsSync(c))try{let l=_e.readFileSync(c,"utf-8"),u=JSON.parse(l),d=Ep(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(_e.existsSync(a))try{let l=_e.readFileSync(a,"utf-8"),u=cl(l),d=Ep(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??ot(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=_e.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=_e.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)}}});import*as Uo from"fs";import*as Tp from"path";function gy(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=Uo.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=Tp.join(s,o.name);o.isDirectory()?hy.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function Zs(r){return gy(r,/\.java$/)}function Ys(r){return Uo.promises.readFile(r,"utf-8")}function ul(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function dl(r){return r.replace(/\\/g,"/").split("/").pop()||""}function Op(r,e){let t=Ip.get(e);if(t&&Date.now()-t.ts<yy)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=Zs(r).filter(i=>n.test(dl(i)));return Ip.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var hy,Ip,yy,Vo=E(()=>{"use strict";hy=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);Ip=new Map,yy=3e4});function vy(r){if(r.includes("/"))return r;if(Vt[r])return Vt[r];let e=`MediaType.${r}`;if(Vt[e])return Vt[e];for(let[s,i]of Object.entries(Vt))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(Vt[i])return Vt[i];let o=`MediaType.${s}_VALUE`;if(Vt[o])return Vt[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 Xs(r){return r.map(vy)}function zt(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 by.has(t)?zt(n.trim()):r}function kr(r){return/MultipartFile/.test(r)}var Vt,by,zo=E(()=>{"use strict";Vt={"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"};by=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var Bn,$p=E(()=>{"use strict";Vo();zo();Bn=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 Op(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await Ys(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 Ys(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=zt(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(T=>T.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 F=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");F&&i.maximum===void 0&&(i.maximum=Number(F));let _=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");_&&i.minimum===void 0&&(i.minimum=Number(_));let D=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");D&&i.maximum===void 0&&(i.maximum=Number(D)),/@Email\b/.test(s)&&(i.format=i.format||"email");let B=this.extractAttr(s,"Pattern","regexp");return B&&!i.pattern&&(i.pattern=B),/@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}}});import{BaseJavaCstVisitorWithDefaults as Sy}from"java-parser";function pl(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var Jo,Fp=E(()=>{"use strict";zo();Jo=class extends Sy{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=Xs(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Xs([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:pl(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,zt(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 zt(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(kr(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=zt(g));else if(b.name==="RequestPart"){o=!0;let C=this.getAnnotationStringValue(b)||p,R=kr(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 Np={};Tt(Np,{EndpointParser:()=>fl});import{parse as xy}from"java-parser";var fl,_p=E(()=>{"use strict";Vo();zo();Fp();fl=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>ul(n.trim()));for(let n of[...this.fileCache.keys()]){let s=ul(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=Zs(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(dl(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 Ys(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=xy(e),n=new Jo;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=[],F=b.args;if(F){R=this.extractPathFromArgs(F);let B=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(F);if(B){let T=B[1],j=[...T.matchAll(/["']([^"']+)["']/g)].map(Z=>Z[1]),W=[...T.matchAll(/MediaType\.([A-Z_]+)/g)].map(Z=>`MediaType.${Z[1]}`);A=Xs([...j,...W])}if(b.name==="RequestMapping"){let T=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(F);T&&(C=T[1])}}!C&&b.name==="RequestMapping"&&(C="GET");let _=R;a.basePath&&(_&&!_.startsWith("/")?_=a.basePath+"/"+_:_=a.basePath+_),_&&!_.startsWith("/")&&(_="/"+_);let D=this.extractParameterMetadataFromSig(v);a.endpoints.push({method:C,path:_,file:t,line:u+1,pathParams:pl(_),consumes:A,bodyType:D.bodyType,headers:D.headers,queryParams:D.queryParams,hasBody:D.hasBody,formParts:D.formParts.length>0?D.formParts:void 0,modelAttributeType:D.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(kr(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=zt(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=kr(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)})}}});import*as Go from"fs";import*as Mp from"path";function Cy(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 wy,Ry,Ir,ml=E(()=>{"use strict";Vo();$p();wy=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],Ry=/@(?:RestController|Controller)\b/,Ir=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of wy)if(Go.existsSync(Mp.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=Zs(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=Go.readFileSync(s,"utf-8");if(Ry.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 Bn(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(()=>(_p(),Np))),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:Cy(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=Bn.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=Bn.javaTypeToParamType(e.schemaType);let n=Bn.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"}}}});import*as Ko from"fs";import*as Bp from"path";function hl(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Ko.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Bp.join(n,i.name);if(i.isDirectory()){Ey.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function Up(r){let e=hl(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let d="";try{d=Ko.readFileSync(u,"utf-8")}catch{continue}let p=Ay(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=jp(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=jp(d.imports,m.object),h=d.appNames.has(m.object)||d.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let y=Oy(m.method,m.args);if(y.length===0)continue;let v=$y(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?Ly(C,v):v,A=Hy(p.signature,jy(R)),F=g?a.get(f):void 0,D=Vp(m.args)??F;l.push({methods:y,path:R,file:u,line:m.line,functionName:p.functionName,statusCode:Fy(m.args),responseModel:Ny(m.args)??Iy(p.signature),tags:D,deprecated:_y(m.args),summary:My(m.args),params:A.params,security:Dy(m.args,p.signature),pathUnresolved:w})}}return{endpoints:l,models:t,warnings:i}}function jp(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function Jt(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 Jt(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return Jt(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:Jt(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:Jt(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=Jt(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 Ay(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=Vy(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}=Wo(i,a-1),w=Ty(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}=Wo(i,a-1),w=y.slice(y.indexOf("(")),b=ky(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}=Py(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}=Wo(i,a-1),v=y.slice(y.indexOf("("));n.routers.push({name:h[1],constructorPrefix:Hp(v)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:y}=Wo(i,a-1),v=y.slice(y.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:Hp(v),tags:Vp(v),line:l}),o=[];continue}o=[]}return n}function Py(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 Wo(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 ky(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=Lp(i);if(c!==-1)return i.slice(0,c);for(;o+1<r.length;){o+=1;let l=r[o],u=Lp(l);if(u!==-1){i+=`
|
|
472
472
|
`+l.slice(0,u);break}i+=`
|
|
473
473
|
`+l}return i}function Lp(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 Iy(r){let e=/->\s*([^:\n]+?)\s*$/.exec(r.trim());return e?e[1].trim():void 0}function Ty(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 Oy(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=qy[r.toLowerCase()];return t?[t]:[]}function $y(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 Fy(r){let e=/status_code\s*=\s*(\d+)/.exec(r);return e?parseInt(e[1],10):void 0}function Ny(r){let e=/response_model\s*=\s*([^\s,]+)/.exec(r);return e?e[1]:void 0}function Vp(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 _y(r){return/deprecated\s*=\s*True/.test(r)?!0:void 0}function My(r){let e=/summary\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:void 0}function Dy(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 Hp(r){let e=/prefix\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:""}function jy(r){let e=[],t=/\{([^}:]+)(?::[^}]+)?\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}function Ly(r,e){return e?r?`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:e.startsWith("/")?e:"/"+e:r||"/"}function Hy(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=Uy(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(Dp.has(d))continue;let f=/^([A-Za-z_]\w*)/.exec(p)?.[1]??"";if(Dp.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=By(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 By(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 Uy(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 Vy(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 Ey,qy,Dp,zp=E(()=>{"use strict";Ey=new Set(["node_modules",".git",".venv","venv","env","__pycache__","site-packages",".mypy_cache",".pytest_cache",".tox","dist","build","out"]),qy={get:"GET",post:"POST",put:"PUT",patch:"PATCH",delete:"DELETE",options:"OPTIONS",head:"HEAD"},Dp=new Set(["Request","Response","WebSocket","BackgroundTasks","Depends","Header","Cookie"])});import*as Qo from"fs";import*as Jp from"path";function Wy(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 zy,Jy,Gy,Tr,gl=E(()=>{"use strict";zp();zy=["requirements.txt","pyproject.toml","poetry.lock","Pipfile","setup.py"],Jy=/^\s*from\s+fastapi\s+import|^\s*import\s+fastapi/m,Gy=/@[\w.]+\.(get|post|put|patch|delete|options|head|api_route)\(/,Tr=class{id="provider.fastapi";framework="fastapi";supports(e){for(let s of zy)if(Qo.existsSync(Jp.join(e.projectRoot,s)))return{supported:!0,confidence:.9,reasons:[`${s} detected`]};let t=e.sourceFiles??hl(e.projectRoot)
|
|
474
|
+
`)}var Ey,qy,Dp,zp=E(()=>{"use strict";Ey=new Set(["node_modules",".git",".venv","venv","env","__pycache__","site-packages",".mypy_cache",".pytest_cache",".tox","dist","build","out"]),qy={get:"GET",post:"POST",put:"PUT",patch:"PATCH",delete:"DELETE",options:"OPTIONS",head:"HEAD"},Dp=new Set(["Request","Response","WebSocket","BackgroundTasks","Depends","Header","Cookie"])});import*as Qo from"fs";import*as Jp from"path";function Wy(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 zy,Jy,Gy,Tr,gl=E(()=>{"use strict";zp();zy=["requirements.txt","pyproject.toml","poetry.lock","Pipfile","setup.py"],Jy=/^\s*from\s+fastapi\s+import|^\s*import\s+fastapi/m,Gy=/@[\w.]+\.(get|post|put|patch|delete|options|head|api_route)\(/,Tr=class{id="provider.fastapi";framework="fastapi";supports(e){for(let s of zy)if(Qo.existsSync(Jp.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=hl(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".py")){if(n>=60)break;n+=1;try{let i=Qo.readFileSync(s,"utf-8");if(Jy.test(i)&&Gy.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=Up(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=Wy(e.type),s=Jt(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=Jt(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=Jt(o,t);a&&(s.body={type:"json",schema:i?{type:"array",items:a}:a})}return[s]}}});import*as Zo from"fs";import*as Wp from"path";import{execSync as Ky}from"child_process";function ti(r){let e;try{let n=Ky("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=Zo.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){let c=Wp.join(i,a.name);if(a.isDirectory()){s.has(a.name)||n.push(c);continue}if(!(!a.isFile()||!Qy.some(l=>c.endsWith(l))))try{let l=Zo.statSync(c);l.mtimeMs>t&&(t=l.mtimeMs)}catch{}}}}catch{t=0}return{gitHash:e,maxSourceMtime:t}}function ni(r,e){let t=ti(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 Kp(r){let e=r.projects.map(t=>ni(t.projectRoot,t.freshness));return{projects:e,staleCount:e.filter(t=>t.status==="stale").length,checkedAt:new Date().toISOString()}}function ei(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 yl(r,e,t){let n=ei(r,e),s=ei(r,t),i=n.filter(o=>o.type!=="same").length;return{userChanges:n,regeneratedChanges:s,changed:t!==r,userEditedLineCount:i}}function vl(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">${H}</div>
|
|
763
|
-
</div>`,
|
|
763
|
+
</div>`,de=`
|
|
764
764
|
<div class="pane-section"><div class="pane-section-title">Overview</div>${Qt}</div>
|
|
765
765
|
<div class="pane-section"><div class="pane-section-title">Headers</div>${ut}</div>
|
|
766
766
|
${Aa?`<div class="pane-section"><div class="pane-section-title">Body</div>${mi}</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>${At}</div>
|
|
769
769
|
<div class="pane-section"><div class="pane-section-title">Cookies</div>${G}</div>
|
|
770
|
-
<div class="pane-section"><div class="pane-section-title">Body</div>${k}</div>`,N=
|
|
770
|
+
<div class="pane-section"><div class="pane-section-title">Body</div>${k}</div>`,N=de.length<=Te.length,je=N?oe:"",Le=N?"":oe,be=L?.consoleOutput?.length?`<div class="console-block"><pre class="code console-code">${L.consoleOutput.map(pt=>ee(typeof pt=="string"?pt:JSON.stringify(pt))).join(`
|
|
771
771
|
`)}</pre></div>`:"",Se=L?.error?`<div class="error-box">\u26A0 ${ee(L.error)}</div>`:"",vn=L?`<span class="${ua(L.status)} status-badge">${L.status} ${ee(L.statusText??"")}</span>`:"",fm=`<span class="dur-badge">${Xe(q.d)}</span>`,mm=e.config.iterations>1?`<span class="iter-badge">iter ${q.it}</span>`:"";o[`${q.i}-${q.it}`]={d:L??null,method:Ie,s:q.s,ap:q.ap,af:q.af,as:q.as??0,embed:dt};let hm=ee(`${q.n} ${L?.url??""}`.toLowerCase());return`
|
|
772
772
|
<details class="req-detail ${Ae?"req-pass":"req-fail"}" id="${Je}" data-key="${q.i}-${q.it}" data-search="${hm}" style="--border:${et}">
|
|
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 ui(r){return typeof r=="string"?r:""+JSON.stringify(r)}function zr(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function uu(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]=zr(n);return e}var du=E(()=>{"use strict"});var di,Kf=E(()=>{"use strict";la();Es();dr();oi();pa();es();du();nu();su();ca();di=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=Ur(t.variables),h=Vf(),g=ma(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(G=>typeof G=="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 G=s.environmentConfig.getResolvedEnvironment(i),H=uu(v.vars),Te={variables:{get:N=>zr(v.vars[N]),set:(N,je)=>{typeof N=="string"&&N.trim()&&(v.vars[N]=ui(je))},unset:N=>{typeof N=="string"&&N.trim()&&delete v.vars[N]},has:N=>Object.prototype.hasOwnProperty.call(v.vars,N),toObject:()=>({...H})},environment:{get:N=>zr(G?.variables?.[N]),set:(N,je)=>{typeof N=="string"&&N.trim()&&s.environmentConfig.setEnvironmentVariable(N,ui(je),i)},unset:N=>{typeof N=="string"&&N.trim()&&s.environmentConfig.deleteEnvironmentVariable(N,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:N=>zr(s.environmentConfig.getGlobalVariables()?.[N]),set:(N,je)=>{typeof N=="string"&&N.trim()&&s.environmentConfig.setGlobalVariable(N,ui(je))},unset:N=>{typeof N=="string"&&N.trim()&&s.environmentConfig.deleteGlobalVariable(N)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:H,lastResult:v.lastResult,iteration:k,node:P,pm:Te,ctx:Te,hf:Te}}function A(P,k,G){return typeof P!="string"||!P.trim()?!0:!!Pt(P,R(k,G))}function F(P){if(!P)return{};let k={};for(let[G,H]of Object.entries(P))k[G]=Array.isArray(H)?H.join("; "):String(H);return k}function _(P){return{executedRequest:P.executedRequest,status:P.response?.status??0,statusText:P.response?.statusText??"",headers:F(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 D(P,k,G,H,z){let oe=w(P);if(!oe||!oe.trim())return;let ue=s.environmentConfig.getResolvedEnvironment(i),Te=s.environmentConfig.getGlobalVariables(),je={request:{url:z?.request?.url??v.lastResult?.executedRequest?.url??"http://flow.local/node",method:z?.request?.method??v.lastResult?.executedRequest?.method??"GET",headers:F(z?.request?.headers),body:z?.request?.body??null,params:z?.request?.params??{},query:z?.request?.query??{}},variables:Ur(v.vars),environmentVariables:ue?.variables||{},globals:{...Te},environmentName:i,info:{eventName:H==="post"?"test":"prerequest",requestName:C(k),requestId:String(k?.id??C(k)),collectionName:e.name,iteration:G,iterationCount:o},onEnvironmentChange:(be,Se,vn)=>{be==="set"&&Se&&vn!==void 0?s.environmentConfig.setEnvironmentVariable(Se,vn,i):be==="unset"&&Se?s.environmentConfig.deleteEnvironmentVariable(Se,i):be==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(be,Se,vn)=>{be==="set"&&Se&&vn!==void 0?s.environmentConfig.setGlobalVariable(Se,vn):be==="unset"&&Se?s.environmentConfig.deleteGlobalVariable(Se):be==="clear"&&s.environmentConfig.clearGlobalVariables()}},Le=s.scriptExecutor.createRequestSession(je);try{if(H==="post"&&z?.response){let be=await Le.executePostResponse(oe,z.response),Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(v.vars={...Se})}else{let be=await Le.executePreRequest(oe);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 ${H}-script failed on node "${C(k)}": ${Se}`)}finally{Le.dispose?.()}}function B(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 T(P){return!P||typeof P!="object"?!1:P.type==="request"?!!B(P):!!(P.collectionId&&P.requestId&&P.name)}function j(P,k){for(let G of k){let H=P?.[G];if(Array.isArray(H))return H}return[]}async function W(P,k,G){if(me.signal.aborted||k.enabled===!1||u&&!u.some(Le=>k.name.toLowerCase().includes(Le.toLowerCase())))return;let H=s.collection.getCollection(k.collectionId);if(!H)return;let z=ci(H,k.requestId);if(!z)return;let oe=ba(z.request.auth,z.folderAuthChain,H.auth),ue=new _t(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,ut,H.scripts,z.folderScriptsChain,void 0,H.name,H.auth,P,o),Te=va(ya({...z.request,auth:oe}),{headers:t.headers,query:t.query,body:t.body,variables:{...v.vars,...t.variables}}),N=await ue.execute(Te,Ur(v.vars),me.signal);v.lastResult=N,N.modifiedVariables&&typeof N.modifiedVariables=="object"&&(v.vars={...N.modifiedVariables});let je=ii({collectionName:H.name,folderPath:k.folderPath??"",blockLabel:G});N.folderPath=k.folderPath??"",N.collectionName=H.name,N.groupPath=je.groupPath,N.groupType=je.groupType,await Y.saveResult(P,N),N.assertions?.length||et.add(k.name),N.passed?Je++:Ae++,d.includes("perRequest")&&L.push({name:k.name,iteration:P,status:N.response?.status,ok:(N.response?.status??0)>=200&&(N.response?.status??0)<300,duration:`${N.duration}ms`,allPassed:N.passed,...d.includes("consoleOutput")&&N.consoleOutput?.length?{consoleOutput:N.consoleOutput}:{}}),N.passed||(Ie.push({name:k.name,iteration:P,method:N.executedRequest?.method,url:N.executedRequest?.url,requestBody:li(N.executedRequest?.body?.content)??N.executedRequest?.body?.content??null,requestHeaders:yt(N.executedRequest?.headers??{}),status:N.response?.status,duration:`${N.duration}ms`,body:li(N.response?.body),headers:ha(N.response?.headers),cookies:ga(N.response?.cookies),failedTests:N.assertions?.filter(Le=>!Le.passed).map(Le=>({name:Le.name,...Le.message?{message:Le.message}:{}})),...N.error?{error:N.error}:{},...d.includes("consoleOutput")&&N.consoleOutput?.length?{consoleOutput:N.consoleOutput}:{}}),a&&me.abort()),c>0&&!me.signal.aborted&&await new Promise(Le=>setTimeout(Le,c))}async function Z(P,k,G){for(let H of k){if(me.signal.aborted)break;await ze(P,H,G)}}async function ze(P,k,G){if(!k||typeof k!="object"||k.enabled===!1||!A(k.condition,k,P))return;if(T(k)){let oe=B(k);oe&&await W(P,oe,G);return}let H=typeof k.type=="string"?k.type.toLowerCase():"",z=j(k,["then","nodes","body"]);if(H==="block"){let oe=typeof k.name=="string"?k.name.trim():"";await Z(P,z,oe||G);return}if(H==="script"){let oe=b(k),ue=k.phase==="post"?"post":"pre";await D(oe,k,P,ue);return}if(H==="if"){let oe=typeof k.if=="string"?k.if:k.condition;if(A(oe,k,P)){await Z(P,z,G);return}if(Array.isArray(k.elseif)){for(let ue of k.elseif)if(A(ue?.condition,ue,P)){await Z(P,j(ue,["then","nodes","body"]),G);return}}await Z(P,j(k,["else","elseNodes"]),G);return}if(H==="switch"){let oe=Pt(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===oe:A(ue?.condition,ue,P)){await Z(P,j(ue,["then","nodes","body"]),G);return}}await Z(P,j(k,["default","defaultNodes"]),G);return}if(H==="while"){let oe=typeof k.while=="string"?k.while:k.condition,ue=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),Te=0;for(;A(oe,k,P);){if(Te+=1,Te>ue)throw new Error(`Suite while loop exceeded maxIterations (${ue}) on node "${C(k)}"`);if(await Z(P,z,G),me.signal.aborted)break}return}if(H==="for"){let oe=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),ue=w(k.init),Te=w(k.update),N=typeof k.loopCondition=="string"&&k.loopCondition.trim()?k.loopCondition:typeof k.condition=="string"&&k.condition.trim()?k.condition:"true";ue&&await D(ue,k,P,"pre");let je=0;for(;A(N,k,P);){if(je+=1,je>oe)throw new Error(`Suite for loop exceeded maxIterations (${oe}) on node "${C(k)}"`);if(await Z(P,z,G),me.signal.aborted)break;Te&&await D(Te,k,P,"post")}return}z.length>0&&await Z(P,z,G)}function Kt(P){let k=0,G=[...P];for(;G.length>0;){let H=G.pop();if(!(!H||typeof H!="object"||H.enabled===!1)){if(T(H)){let z=B(H);z&&(!u||u.some(oe=>z.name.toLowerCase().includes(oe.toLowerCase())))&&(k+=1);continue}for(let z of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(H[z])&&G.push(...H[z]);if(Array.isArray(H.elseif))for(let z of H.elseif)Array.isArray(z?.nodes)&&G.push(...z.nodes),Array.isArray(z?.then)&&G.push(...z.then);if(Array.isArray(H.cases))for(let z of H.cases)Array.isArray(z?.nodes)&&G.push(...z.nodes),Array.isArray(z?.then)&&G.push(...z.then)}}return k}let qt=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(P=>({type:"request",request:P})):[],q=Kt(qt);if(h){let P=zf(),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 Y=new Jn(s.config),Re=await Y.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}),L=[],Ie=[],Je=0,Ae=0,et=new Set,me=new AbortController,ut=new Un;async function Qt(P){await Z(P,qt)}for(let P=1;P<=o&&!me.signal.aborted;P+=l){let k=Math.min(P+l-1,o),G=Array.from({length:k-P+1},(H,z)=>P+z);await Promise.all(G.map(Qt))}let ye=await Y.finalizeRun("completed",g),Wr=null;if(m)try{Wr=await new Gt(Y.getBasePath()).generate(e.id,Re)}catch(P){console.warn("[direct-execution] JUnit report generation failed:",P)}let Zn=n==="collection"?"collection":"suite",dt=Y.getCurrentStats()?.stats,mi=dt?{min:dt.minDuration,max:dt.maxDuration,avg:dt.avgDuration,p50:dt.p50??null,p95:dt.p95??null,p99:dt.p99??null}:null,At={[Zn]:e.name,environment:i,summary:{total:Je+Ae,passed:Je,failed:Ae,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:Ae===0,...mi?{durationMs:mi}:{}}};if((Ae>0||d.includes("failedOnly"))&&(At.failedRequests=Ie),d.includes("perRequest")&&(At.results=L),ye!==null&&(At.report={uri:`file://${ye}`,hint:"Click the URI to open the HTML report in your browser"}),Wr!==null&&(At.junitReport={path:Wr}),et.size>0){let P=Math.max(q,1),k=et.size,G=Array.from(et).slice(0,5);At.noAssertionExamples=G;let H=e.name;if(k/P>.5)At._suggestions=[`${k}/${P} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${H}") for a full coverage analysis and to identify assertion gaps.`];else{let z=G.map(oe=>`"${oe}"`).join(", ");At._suggestions=[`${k} request(s) have no pm.test() assertions: ${z}. Invoke the "suggest-assertions" prompt (collection="${H}") to generate test coverage for them.`]}}return At}}});var fi={};Tt(fi,{runCollection:()=>Wt,runFolder:()=>Jv,runRequest:()=>Ca,runSuite:()=>pi});function Qf(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}=ou(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 Zf(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=au(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function Ca(r){let e=lt(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=ma(t,n);try{let o=e.collection,a=Qf(o,r),c=Zf(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let C=cu(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=ci(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let d=ba(u.request.auth,u.folderAuthChain,a.auth),p=r.environment||e.environmentConfig.getSelectedEnvironment(),m=va(ya({...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 Un,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth).execute(m,Ur(r.variables)),g=ii({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 Jn(e.config),R=`request-${ru(a.id)}-${ru(l)}`,A=`Request: ${u.request.name}`,F=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 Gt(C.getBasePath()).generate(R,F)}catch(_){console.warn("[direct-execution] JUnit report generation failed:",_)}}let w=ha(h.response?.headers),b=ga(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:li(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{fa(e)}}async function Wt(r){let e=lt(r.workspaceFolder);try{let t=e.collection,n=Qf(t,r),s=Zf(n,r),i=tu(n),o=Hf(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}-${Bf(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 di(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{fa(e)}}async function Jv(r){return Wt({recursive:!0,...r})}async function pi(r){let e=lt(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new di(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{fa(e)}}var Jr=E(()=>{"use strict";la();Es();oi();pa();nu();su();Ra();lu();ca();Kf()});var tm={};Tt(tm,{createMcpRuntime:()=>ab});import*as em from"fs";import{createServer as Gv}from"http";import*as yn from"path";async function Ct(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 Gr(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function Qv(r,e){let t=mu.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=pu.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 Wl(a,c,i,r)})().then(i=>(mu.set(r,{tools:i,expiresAt:Date.now()+Kv}),i)).finally(()=>pu.delete(r));return pu.set(r,s),s}function Zv(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function Yv(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function Yf(r,e,t,n){Kn(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function Xv(r){return r.config.getMcpConfig().toolPageSize??200}async function eb(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 Qv(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=Xv(r.container);if(i<=0||t.length<=i)return{tools:t};let o=Gl(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=Jl(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 hu(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=Yv(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 G=s.environmentConfig.getResolvedEnvironment(i),H=uu(v.vars),Te={variables:{get:N=>zr(v.vars[N]),set:(N,je)=>{typeof N=="string"&&N.trim()&&(v.vars[N]=ui(je))},unset:N=>{typeof N=="string"&&N.trim()&&delete v.vars[N]},has:N=>Object.prototype.hasOwnProperty.call(v.vars,N),toObject:()=>({...H})},environment:{get:N=>zr(G?.variables?.[N]),set:(N,je)=>{typeof N=="string"&&N.trim()&&s.environmentConfig.setEnvironmentVariable(N,ui(je),i)},unset:N=>{typeof N=="string"&&N.trim()&&s.environmentConfig.deleteEnvironmentVariable(N,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:N=>zr(s.environmentConfig.getGlobalVariables()?.[N]),set:(N,je)=>{typeof N=="string"&&N.trim()&&s.environmentConfig.setGlobalVariable(N,ui(je))},unset:N=>{typeof N=="string"&&N.trim()&&s.environmentConfig.deleteGlobalVariable(N)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:H,lastResult:v.lastResult,iteration:k,node:P,pm:Te,ctx:Te,hf:Te}}function A(P,k,G){return typeof P!="string"||!P.trim()?!0:!!Pt(P,R(k,G))}function F(P){if(!P)return{};let k={};for(let[G,H]of Object.entries(P))k[G]=Array.isArray(H)?H.join("; "):String(H);return k}function _(P){return{executedRequest:P.executedRequest,status:P.response?.status??0,statusText:P.response?.statusText??"",headers:F(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 D(P,k,G,H,z){let oe=w(P);if(!oe||!oe.trim())return;let de=s.environmentConfig.getResolvedEnvironment(i),Te=s.environmentConfig.getGlobalVariables(),je={request:{url:z?.request?.url??v.lastResult?.executedRequest?.url??"http://flow.local/node",method:z?.request?.method??v.lastResult?.executedRequest?.method??"GET",headers:F(z?.request?.headers),body:z?.request?.body??null,params:z?.request?.params??{},query:z?.request?.query??{}},variables:Ur(v.vars),environmentVariables:de?.variables||{},globals:{...Te},environmentName:i,info:{eventName:H==="post"?"test":"prerequest",requestName:C(k),requestId:String(k?.id??C(k)),collectionName:e.name,iteration:G,iterationCount:o},onEnvironmentChange:(be,Se,vn)=>{be==="set"&&Se&&vn!==void 0?s.environmentConfig.setEnvironmentVariable(Se,vn,i):be==="unset"&&Se?s.environmentConfig.deleteEnvironmentVariable(Se,i):be==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(be,Se,vn)=>{be==="set"&&Se&&vn!==void 0?s.environmentConfig.setGlobalVariable(Se,vn):be==="unset"&&Se?s.environmentConfig.deleteGlobalVariable(Se):be==="clear"&&s.environmentConfig.clearGlobalVariables()}},Le=s.scriptExecutor.createRequestSession(je);try{if(H==="post"&&z?.response){let be=await Le.executePostResponse(oe,z.response),Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(v.vars={...Se})}else{let be=await Le.executePreRequest(oe);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 ${H}-script failed on node "${C(k)}": ${Se}`)}finally{Le.dispose?.()}}function B(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 T(P){return!P||typeof P!="object"?!1:P.type==="request"?!!B(P):!!(P.collectionId&&P.requestId&&P.name)}function j(P,k){for(let G of k){let H=P?.[G];if(Array.isArray(H))return H}return[]}async function W(P,k,G){if(me.signal.aborted||k.enabled===!1||u&&!u.some(Le=>k.name.toLowerCase().includes(Le.toLowerCase())))return;let H=s.collection.getCollection(k.collectionId);if(!H)return;let z=ci(H,k.requestId);if(!z)return;let oe=ba(z.request.auth,z.folderAuthChain,H.auth),de=new _t(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,ut,H.scripts,z.folderScriptsChain,void 0,H.name,H.auth,P,o),Te=va(ya({...z.request,auth:oe}),{headers:t.headers,query:t.query,body:t.body,variables:{...v.vars,...t.variables}}),N=await de.execute(Te,Ur(v.vars),me.signal);v.lastResult=N,N.modifiedVariables&&typeof N.modifiedVariables=="object"&&(v.vars={...N.modifiedVariables});let je=ii({collectionName:H.name,folderPath:k.folderPath??"",blockLabel:G});N.folderPath=k.folderPath??"",N.collectionName=H.name,N.groupPath=je.groupPath,N.groupType=je.groupType,await Y.saveResult(P,N),N.assertions?.length||et.add(k.name),N.passed?Je++:Ae++,d.includes("perRequest")&&L.push({name:k.name,iteration:P,status:N.response?.status,ok:(N.response?.status??0)>=200&&(N.response?.status??0)<300,duration:`${N.duration}ms`,allPassed:N.passed,...d.includes("consoleOutput")&&N.consoleOutput?.length?{consoleOutput:N.consoleOutput}:{}}),N.passed||(Ie.push({name:k.name,iteration:P,method:N.executedRequest?.method,url:N.executedRequest?.url,requestBody:li(N.executedRequest?.body?.content)??N.executedRequest?.body?.content??null,requestHeaders:yt(N.executedRequest?.headers??{}),status:N.response?.status,duration:`${N.duration}ms`,body:li(N.response?.body),headers:ha(N.response?.headers),cookies:ga(N.response?.cookies),failedTests:N.assertions?.filter(Le=>!Le.passed).map(Le=>({name:Le.name,...Le.message?{message:Le.message}:{}})),...N.error?{error:N.error}:{},...d.includes("consoleOutput")&&N.consoleOutput?.length?{consoleOutput:N.consoleOutput}:{}}),a&&me.abort()),c>0&&!me.signal.aborted&&await new Promise(Le=>setTimeout(Le,c))}async function Z(P,k,G){for(let H of k){if(me.signal.aborted)break;await ze(P,H,G)}}async function ze(P,k,G){if(!k||typeof k!="object"||k.enabled===!1||!A(k.condition,k,P))return;if(T(k)){let oe=B(k);oe&&await W(P,oe,G);return}let H=typeof k.type=="string"?k.type.toLowerCase():"",z=j(k,["then","nodes","body"]);if(H==="block"){let oe=typeof k.name=="string"?k.name.trim():"";await Z(P,z,oe||G);return}if(H==="script"){let oe=b(k),de=k.phase==="post"?"post":"pre";await D(oe,k,P,de);return}if(H==="if"){let oe=typeof k.if=="string"?k.if:k.condition;if(A(oe,k,P)){await Z(P,z,G);return}if(Array.isArray(k.elseif)){for(let de of k.elseif)if(A(de?.condition,de,P)){await Z(P,j(de,["then","nodes","body"]),G);return}}await Z(P,j(k,["else","elseNodes"]),G);return}if(H==="switch"){let oe=Pt(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===oe:A(de?.condition,de,P)){await Z(P,j(de,["then","nodes","body"]),G);return}}await Z(P,j(k,["default","defaultNodes"]),G);return}if(H==="while"){let oe=typeof k.while=="string"?k.while:k.condition,de=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),Te=0;for(;A(oe,k,P);){if(Te+=1,Te>de)throw new Error(`Suite while loop exceeded maxIterations (${de}) on node "${C(k)}"`);if(await Z(P,z,G),me.signal.aborted)break}return}if(H==="for"){let oe=Math.max(1,Math.min(1e4,Number(k.maxIterations??y))),de=w(k.init),Te=w(k.update),N=typeof k.loopCondition=="string"&&k.loopCondition.trim()?k.loopCondition:typeof k.condition=="string"&&k.condition.trim()?k.condition:"true";de&&await D(de,k,P,"pre");let je=0;for(;A(N,k,P);){if(je+=1,je>oe)throw new Error(`Suite for loop exceeded maxIterations (${oe}) on node "${C(k)}"`);if(await Z(P,z,G),me.signal.aborted)break;Te&&await D(Te,k,P,"post")}return}z.length>0&&await Z(P,z,G)}function Kt(P){let k=0,G=[...P];for(;G.length>0;){let H=G.pop();if(!(!H||typeof H!="object"||H.enabled===!1)){if(T(H)){let z=B(H);z&&(!u||u.some(oe=>z.name.toLowerCase().includes(oe.toLowerCase())))&&(k+=1);continue}for(let z of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(H[z])&&G.push(...H[z]);if(Array.isArray(H.elseif))for(let z of H.elseif)Array.isArray(z?.nodes)&&G.push(...z.nodes),Array.isArray(z?.then)&&G.push(...z.then);if(Array.isArray(H.cases))for(let z of H.cases)Array.isArray(z?.nodes)&&G.push(...z.nodes),Array.isArray(z?.then)&&G.push(...z.then)}}return k}let qt=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(P=>({type:"request",request:P})):[],q=Kt(qt);if(h){let P=zf(),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 Y=new Jn(s.config),Re=await Y.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}),L=[],Ie=[],Je=0,Ae=0,et=new Set,me=new AbortController,ut=new Un;async function Qt(P){await Z(P,qt)}for(let P=1;P<=o&&!me.signal.aborted;P+=l){let k=Math.min(P+l-1,o),G=Array.from({length:k-P+1},(H,z)=>P+z);await Promise.all(G.map(Qt))}let ye=await Y.finalizeRun("completed",g),Wr=null;if(m)try{Wr=await new Gt(Y.getBasePath()).generate(e.id,Re)}catch(P){console.warn("[direct-execution] JUnit report generation failed:",P)}let Zn=n==="collection"?"collection":"suite",dt=Y.getCurrentStats()?.stats,mi=dt?{min:dt.minDuration,max:dt.maxDuration,avg:dt.avgDuration,p50:dt.p50??null,p95:dt.p95??null,p99:dt.p99??null}:null,At={[Zn]:e.name,environment:i,summary:{total:Je+Ae,passed:Je,failed:Ae,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:Ae===0,...mi?{durationMs:mi}:{}}};if((Ae>0||d.includes("failedOnly"))&&(At.failedRequests=Ie),d.includes("perRequest")&&(At.results=L),ye!==null&&(At.report={uri:`file://${ye}`,hint:"Click the URI to open the HTML report in your browser"}),Wr!==null&&(At.junitReport={path:Wr}),et.size>0){let P=Math.max(q,1),k=et.size,G=Array.from(et).slice(0,5);At.noAssertionExamples=G;let H=e.name;if(k/P>.5)At._suggestions=[`${k}/${P} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${H}") for a full coverage analysis and to identify assertion gaps.`];else{let z=G.map(oe=>`"${oe}"`).join(", ");At._suggestions=[`${k} request(s) have no pm.test() assertions: ${z}. Invoke the "suggest-assertions" prompt (collection="${H}") to generate test coverage for them.`]}}return At}}});var fi={};Tt(fi,{runCollection:()=>Wt,runFolder:()=>Jv,runRequest:()=>Ca,runSuite:()=>pi});function Qf(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}=ou(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 Zf(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=au(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function Ca(r){let e=lt(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=ma(t,n);try{let o=e.collection,a=Qf(o,r),c=Zf(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let C=cu(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=ci(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let d=ba(u.request.auth,u.folderAuthChain,a.auth),p=r.environment||e.environmentConfig.getSelectedEnvironment(),m=va(ya({...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 Un,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth).execute(m,Ur(r.variables)),g=ii({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 Jn(e.config),R=`request-${ru(a.id)}-${ru(l)}`,A=`Request: ${u.request.name}`,F=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 Gt(C.getBasePath()).generate(R,F)}catch(_){console.warn("[direct-execution] JUnit report generation failed:",_)}}let w=ha(h.response?.headers),b=ga(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:li(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{fa(e)}}async function Wt(r){let e=lt(r.workspaceFolder);try{let t=e.collection,n=Qf(t,r),s=Zf(n,r),i=tu(n),o=Hf(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}-${Bf(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 di(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{fa(e)}}async function Jv(r){return Wt({recursive:!0,...r})}async function pi(r){let e=lt(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new di(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{fa(e)}}var Jr=E(()=>{"use strict";la();Es();oi();pa();nu();su();Ra();lu();ca();Kf()});var tm={};Tt(tm,{createMcpRuntime:()=>ab});import*as em from"fs";import{createServer as Gv}from"http";import*as yn from"path";async function Ct(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 Gr(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function Qv(r,e){let t=mu.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=pu.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 Wl(a,c,i,r)})().then(i=>(mu.set(r,{tools:i,expiresAt:Date.now()+Kv}),i)).finally(()=>pu.delete(r));return pu.set(r,s),s}function Zv(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function Yv(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function Yf(r,e,t,n){Kn(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function Xv(r){return r.config.getMcpConfig().toolPageSize??200}async function eb(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 Qv(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=Xv(r.container);if(i<=0||t.length<=i)return{tools:t};let o=Gl(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=Jl(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 hu(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=Yv(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:sa};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=lt(r.workspaceFolder);try{return await Al(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{Gr(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function tb(r,e,t){let n=!r.container,s=r.container??lt(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&Gr(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 nb(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=yn.resolve(s),o=r.container?.config.getResultsPath(),a=o?yn.dirname(o):yn.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+yn.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}em.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 fu(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 rb(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return Ct(()=>Ca({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=Q(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?fu(r.runStore,`${t.name} / ${kt(n)}`,i,()=>Ct(()=>Wt({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}))):Ct(()=>Wt({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=Q(t).length;return n.async===!0?fu(r.runStore,t.name,s,()=>Ct(()=>Wt({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):Ct(()=>Wt({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=lt(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{Gr(i)}return s.async===!0?fu(r.runStore,n,o,()=>Ct(()=>pi({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}))):Ct(()=>pi({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 hu(r,e,t={}){let n=r.workspaceFolder,s=Zv(r.container,e);if(Object.values(S).includes(s)){let a=lt(n),c=Bs();try{let l=await Ol(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,rb(r));return sb.has(s)&&mu.delete(n),l}finally{Gr(a)}}let i=jl(s),o=lt(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=Fr(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=Q(h).map(v=>v.request.id),y=Fr(f,g);if(!y)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return Ct(()=>Ca({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 Ct(()=>Wt({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=Q(h).map(w=>w.folderPath).filter((w,b,C)=>w&&C.indexOf(w)===b),v=Ll(f,y);if(!v)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return Ct(()=>Wt({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=Fr(u,d.map(m=>m.id));if(!p)throw new Error(`Test suite not found for tool: ${e}`);return Ct(()=>pi({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{Gr(o)}}function Kn(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function Xf(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 ib(r){return Gv(async(e,t)=>{try{if(tb(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){Kn(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){nb(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await Xf(e)}catch{Yf(t,null,-32700,"Parse error");return}try{let s=await eb(r,n);Kn(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){Yf(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await Xf(e);if(!n||typeof n.name!="string"||n.name.trim()===""){Kn(t,400,{error:'Field "name" is required'});return}let s=await hu(r,n.name,n.args??{});Kn(t,200,{result:s});return}Kn(t,405,{error:"Method not allowed"})}catch(n){Kn(t,500,{error:n.message})}})}function ob(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new rn(yn.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function ab(r){let e=ob(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new si};return Wv.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=lt(s.workspaceFolder));let i=ib(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&&(Gr(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 hu(s,i,o??{})}}}var Wv,Kv,mu,pu,sb,nm=E(()=>{"use strict";Hi();So();Jr();Ye();$l();ia();Fl();Kl();aa();Fe();Ra();Wv=new Map;Kv=3e3,mu=new Map,pu=new Map;sb=Tl});var Xn=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()}};bi();Yt();function Oa(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(Iu),source:{format:"folder",filePath:e,version:r.version}}}function Iu(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(Iu)};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 wm(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($a)}}function $a(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($a)}:{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 Qr=class{store;constructor(e){this.store=new Xt(e)}loadAll(){return this.store.loadAll().map(t=>Oa(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 Oa(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return Oa(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(wm(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,$a(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 Zr=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()}};bn();var Yr=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)}};wi();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})}};er();nr();var tn=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new Cn,this.urlBuilder=new mt}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)}};nr();is();os();er();ds();ls();var ir=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?[ce("path").join(i.forgeRoot,"modules")]:[],a=new $t(new mt,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:Ti(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=tn.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 ih(){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 ps=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=ih(),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 fs=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)}}};is();os();_i();Mi();er();var kn=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}}};Di();import*as Qe from"fs/promises";import*as or from"path";var gs=class{async readFile(e){return Qe.readFile(e,"utf-8")}async writeFile(e,t){let n=or.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=or.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=or.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)}};ds();var Ka=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 Cn,this.fileSystem=e.fileSystem||new gs,this.preprocessor=e.preprocessor||new Pn,this.dataFileParser=e.dataFileParser||new In,this.cookieJar=e.cookieJar||new Yr,e.enableHistory?this.requestHistory=e.requestHistory||new ps({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 An(i)}else this.httpClient=new fs;let t=e.forgeRoot?[ce("path").join(e.forgeRoot,"modules")]:[],n=new $t(new mt,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new Nt(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new Zr,this.parserRegistry.register("http-forge",new kn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=ce("path").join(e.forgeRoot,"collections");this.collectionLoader=new Qr(i)}else this.collectionLoader=new Xn(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new Ot(e.environmentConfig):Ot.fromVariables({}),this.forgeEnv=tn.fromResolver(this.environmentStore),this.requestExecutor=new ir(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 Xn)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=tn.fromResolver(this.environmentStore),this.requestExecutor=new ir(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=ce("path"),s=n.join(e,"environments"),i,o=Xr(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=ce("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})}};_c();Mc();io();Ye();$l();ia();Fl();Kl();aa();Fe();ca();async function cb(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(nm(),tm));return e(r)}async function lb(r){let{runRequest:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}async function ub(r){let{runCollection:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}async function db(r){let{runFolder:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}async function pb(r){let{runSuite:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}Ra();rc();bn();la();sc();is();os();_i();Mi();er();Ma();Ba();ds();as();ls();dr();Xa();tc();bi();Yt();Ya();fo();function fb(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 mb(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 hb(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 gb(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&&bt(c[2])?i(`${c[1].toUpperCase()}_TOKEN`,c[2]):bt(o.value)&&i("AUTH_TOKEN",o.value)}else uo.has(a)&&bt(o.value)&&i(Ht(o.key),o.value)}for(let o of e)po.has(o.key.toLowerCase())&&bt(o.value)&&i(Ht(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)&&!Ms(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function yb(r){let e=fb(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}=mb(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=gb(o,f,m||i);return{name:hb(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:y}}Dn();So();Mn();Dn();Mn();var Ea=10;async function vb(r,e,t,n){let s=rm(r.items);if(s.length===0)return;let i=Math.ceil(s.length/Ea);for(let o=0;o<s.length;o+=Ea){let a=s.slice(o,o+Ea),c=Math.floor(o/Ea)+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:wb(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 rt(()=>t.complete(bb(l,a))),d=Sb(u);xb(a,d)}catch{}}await e.saveCollection(r)}function bb(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:sa};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=lt(r.workspaceFolder);try{return await Al(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{Gr(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function tb(r,e,t){let n=!r.container,s=r.container??lt(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&Gr(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 nb(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=yn.resolve(s),o=r.container?.config.getResultsPath(),a=o?yn.dirname(o):yn.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+yn.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}em.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 fu(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 rb(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return Ct(()=>Ca({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=Q(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?fu(r.runStore,`${t.name} / ${kt(n)}`,i,()=>Ct(()=>Wt({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}))):Ct(()=>Wt({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=Q(t).length;return n.async===!0?fu(r.runStore,t.name,s,()=>Ct(()=>Wt({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):Ct(()=>Wt({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=lt(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{Gr(i)}return s.async===!0?fu(r.runStore,n,o,()=>Ct(()=>pi({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}))):Ct(()=>pi({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 hu(r,e,t={}){let n=r.workspaceFolder,s=Zv(r.container,e);if(Object.values(S).includes(s)){let a=lt(n),c=Bs();try{let l=await Ol(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,rb(r));return sb.has(s)&&mu.delete(n),l}finally{Gr(a)}}let i=jl(s),o=lt(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=Fr(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=Q(h).map(v=>v.request.id),y=Fr(f,g);if(!y)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return Ct(()=>Ca({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 Ct(()=>Wt({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=Q(h).map(w=>w.folderPath).filter((w,b,C)=>w&&C.indexOf(w)===b),v=Ll(f,y);if(!v)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return Ct(()=>Wt({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=Fr(u,d.map(m=>m.id));if(!p)throw new Error(`Test suite not found for tool: ${e}`);return Ct(()=>pi({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{Gr(o)}}function Kn(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function Xf(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 ib(r){return Gv(async(e,t)=>{try{if(tb(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){Kn(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){nb(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await Xf(e)}catch{Yf(t,null,-32700,"Parse error");return}try{let s=await eb(r,n);Kn(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){Yf(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await Xf(e);if(!n||typeof n.name!="string"||n.name.trim()===""){Kn(t,400,{error:'Field "name" is required'});return}let s=await hu(r,n.name,n.args??{});Kn(t,200,{result:s});return}Kn(t,405,{error:"Method not allowed"})}catch(n){Kn(t,500,{error:n.message})}})}function ob(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new rn(yn.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function ab(r){let e=ob(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new si};return Wv.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=lt(s.workspaceFolder));let i=ib(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&&(Gr(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 hu(s,i,o??{})}}}var Wv,Kv,mu,pu,sb,nm=E(()=>{"use strict";Hi();So();Jr();Ye();$l();ia();Fl();Kl();aa();Fe();Ra();Wv=new Map;Kv=3e3,mu=new Map,pu=new Map;sb=Tl});var Xn=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()}};bi();Yt();function Oa(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(Iu),source:{format:"folder",filePath:e,version:r.version}}}function Iu(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(Iu)};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 wm(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($a)}}function $a(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($a)}:{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 Qr=class{store;constructor(e){this.store=new Xt(e)}loadAll(){return this.store.loadAll().map(t=>Oa(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 Oa(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return Oa(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(wm(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,$a(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 Zr=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()}};bn();var Yr=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)}};wi();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})}};er();nr();var tn=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new Cn,this.urlBuilder=new mt}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)}};nr();is();os();er();ds();ls();var ir=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?[le("path").join(i.forgeRoot,"modules")]:[],a=new $t(new mt,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:Ti(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=tn.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 ih(){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 ps=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=ih(),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 fs=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)}}};is();os();_i();Mi();er();var kn=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}}};Di();import*as Qe from"fs/promises";import*as or from"path";var gs=class{async readFile(e){return Qe.readFile(e,"utf-8")}async writeFile(e,t){let n=or.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=or.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=or.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)}};ds();var Ka=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 Cn,this.fileSystem=e.fileSystem||new gs,this.preprocessor=e.preprocessor||new Pn,this.dataFileParser=e.dataFileParser||new In,this.cookieJar=e.cookieJar||new Yr,e.enableHistory?this.requestHistory=e.requestHistory||new ps({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 An(i)}else this.httpClient=new fs;let t=e.forgeRoot?[le("path").join(e.forgeRoot,"modules")]:[],n=new $t(new mt,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new Nt(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new Zr,this.parserRegistry.register("http-forge",new kn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=le("path").join(e.forgeRoot,"collections");this.collectionLoader=new Qr(i)}else this.collectionLoader=new Xn(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new Ot(e.environmentConfig):Ot.fromVariables({}),this.forgeEnv=tn.fromResolver(this.environmentStore),this.requestExecutor=new ir(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 Xn)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=tn.fromResolver(this.environmentStore),this.requestExecutor=new ir(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=le("path"),s=n.join(e,"environments"),i,o=Xr(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=le("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})}};_c();Mc();io();Ye();$l();ia();Fl();Kl();aa();Fe();ca();async function cb(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(nm(),tm));return e(r)}async function lb(r){let{runRequest:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}async function ub(r){let{runCollection:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}async function db(r){let{runFolder:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}async function pb(r){let{runSuite:e}=await Promise.resolve().then(()=>(Jr(),fi));return e(r)}Ra();rc();bn();la();sc();is();os();_i();Mi();er();Ma();Ba();ds();as();ls();dr();Xa();tc();bi();Yt();Ya();fo();function fb(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 mb(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 hb(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 gb(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&&bt(c[2])?i(`${c[1].toUpperCase()}_TOKEN`,c[2]):bt(o.value)&&i("AUTH_TOKEN",o.value)}else uo.has(a)&&bt(o.value)&&i(Ht(o.key),o.value)}for(let o of e)po.has(o.key.toLowerCase())&&bt(o.value)&&i(Ht(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)&&!Ms(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function yb(r){let e=fb(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}=mb(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=gb(o,f,m||i);return{name:hb(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:y}}Mn();Dn();So();Dn();Mn();var Ea=10;async function vb(r,e,t,n){let s=rm(r.items);if(s.length===0)return;let i=Math.ceil(s.length/Ea);for(let o=0;o<s.length;o+=Ea){let a=s.slice(o,o+Ea),c=Math.floor(o/Ea)+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:wb(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 rt(()=>t.complete(bb(l,a))),d=Sb(u);xb(a,d)}catch{}}await e.saveCollection(r)}function bb(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 kb(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 Ib(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 Tb(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 Ob(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 $b(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 om(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 Fb(r){return r.replace(/"""[\s\S]*?"""/g,'""').replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/#[^\n]*/g,"")}function yu(r,e,t){let n=0;for(let s of r)s===e?n++:s===t&&n--;return n}function sm(r){return yu(r,"(",")")>0}function Nb(r){if(yu(r,"(",")")<=0)return!1;let t=r.indexOf("{"),n=t>=0?r.slice(0,t):r;return/\$\w+\s*:\s*\w*$/.test(n)}function im(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 gu(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=_b(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 _b(r){let e=[],t=/([a-zA-Z_]\w*|[{}(),:=@!$\[\].]|\.\.\.|"[^"]*"|\d+)/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}lc();wc();gc();Cc();Vi();Ec();Qi();Wi();Ki();zc();Bc();Vc();
|
|
1463
|
+
}`),{label:r.name,kind:"field",detail:r.type,description:r.description,insertText:i,deprecated:r.isDeprecated,sortOrder:e}}function Fb(r){return r.replace(/"""[\s\S]*?"""/g,'""').replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/#[^\n]*/g,"")}function yu(r,e,t){let n=0;for(let s of r)s===e?n++:s===t&&n--;return n}function sm(r){return yu(r,"(",")")>0}function Nb(r){if(yu(r,"(",")")<=0)return!1;let t=r.indexOf("{"),n=t>=0?r.slice(0,t):r;return/\$\w+\s*:\s*\w*$/.test(n)}function im(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 gu(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=_b(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 _b(r){let e=[],t=/([a-zA-Z_]\w*|[{}(),:=@!$\[\].]|\.\.\.|"[^"]*"|\d+)/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}lc();wc();gc();Cc();Vi();Ec();Qi();Wi();Ki();zc();Bc();Vc();Cr();Sl();bl();gl();Ao();Qc();rl();sl();ll();ol();Io();un();ml();ho();Kc();vo();ql();import{execSync as am}from"child_process";var Mb=/^(feat|fix|perf|docs|refactor|test|build|chore)(?:\(([^)]*)\))?(!?):\s*(.+)$/i,cm=/BREAKING[- ]CHANGE:/i;function lm(r){let{projectRoot:e,from:t,to:n="HEAD"}=r,s=t?`${t}..${n}`:n,i=!0,o,a="";try{a=am(`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=am("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(Db).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 Db(r){let e=r.indexOf(" ");if(e<0)return null;let t=r.slice(0,e),n=r.slice(e+1),s=n.match(Mb);if(!s)return{type:"other",subject:n,hash:t,breaking:cm.test(n)};let[,i,o,a,c]=s;return{type:i.toLowerCase(),scope:o||void 0,subject:c,hash:t,breaking:a==="!"||cm.test(c)}}function um(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
|
-
`)}nc();Hi();eu();oi();Nr();pa();function qa(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,t)]}function vu(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 dm(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=qa(e,50),r.p90=qa(e,90),r.p95=qa(e,95),r.p99=qa(e,99)}var bu=class{summary;byRequest;overall;errors;startTime=0;constructor(){this.summary=this.createEmptySummary(),this.byRequest=new Map,this.overall=vu("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=vu("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,vu(e,t));let c=this.byRequest.get(e);if(c.name=t,c.count++,s?c.passed++:c.failed++,c.durations.push(n),dm(c),this.overall.count++,s?this.overall.passed++:this.overall.failed++,this.overall.durations.push(n),dm(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}}};Nc();Yt();import*as Et from"fs";import*as Qn from"path";var Su=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=Qn.join(this.suiteDir,e,"request.json");if(Et.existsSync(t))try{let n=JSON.parse(Et.readFileSync(t,"utf-8")),s=Qn.join(this.suiteDir,e,"scripts"),i=yi(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=Qn.join(this.suiteDir,e);Et.mkdirSync(n,{recursive:!0});let s=t.scripts,i={...t};delete i.scripts;let o=Qn.join(n,"request.json"),a=`${o}.tmp-${process.pid}-${Date.now()}`;if(Et.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),Et.renameSync(a,o),s){let c=Qn.join(n,"scripts");vi(c,{preRequest:s.preRequest||void 0,postResponse:s.postResponse||void 0})}}hasEmbeddedRequest(e){return!this.suiteDir||!e?!1:Et.existsSync(Qn.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=ft(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=ft(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)}};Ge();function xu(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(jb(a))}let o=Vb(i,e.collectionName??"Imported from HAR");return{requests:i,collection:o}}function pm(r,e={}){return xu(r,e).collection}function jb(r){let e=r.request,t=e.method||"GET",n=e.url||"",s=Ub(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=Lb(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 Lb(r,e){if(!r)return null;let t=typeof r.text=="string"?r.text:"",n=r.mimeType||Bb(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=Hb(t);if(s.length>0)return{type:"x-www-form-urlencoded",content:s}}return{type:"raw",format:"text",content:t}}function Hb(r){try{return[...new URLSearchParams(r).entries()].map(([t,n])=>({key:t,value:n,enabled:!0}))}catch{return[]}}function Bb(r){return r.find(t=>t.key.toLowerCase()==="content-type")?.value?.split(";")[0].trim()??""}function Ub(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 Vb(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:se(`har-${i}`),name:i,items:[]},t.set(i,o),n.push(o)),o.items.push(zb(s))}return{id:se("har-collection"),name:e,items:n,source:{format:"har",filePath:""},meta:{requestCount:r.length}}}function zb(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:se(`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}}oc();Li();Di();qc();Ac();Tc();Ic();Pc();kc();Oc();es();Ei();Ge();du();export{Hs as AnthropicProvider,Ls as ApiArchitectService,Or as ApiDiscoveryService,Yi as AwsSecretResolver,Xi as AzureKeyVaultResolver,Ru as BODY_FILE_MAP,Tl as CACHE_BUSTING_TOOLS,wo as COLLECTION_INPUT_SCHEMA,On as CONFIG_FILES,Xn as CollectionLoader,bs as CollectionLoaderFactory,_t as CollectionRequestExecutor,Ss as CollectionService,rn as ConfigService,Yr as CookieJar,xs as CookieService,ne as CookieUtils,pe as DEFAULT_CONFIG,Ja as DEFAULT_REQUEST_SETTINGS,In as DataFileParser,ro as DopplerResolver,Cs as EnvironmentConfigService,Ot as EnvironmentResolver,fr as ExampleGenerator,zs as ExpressComponentAnalyzer,Er as ExpressDiscoveryProvider,Ro as FOLDER_INPUT_SCHEMA,Tr as FastApiDiscoveryProvider,Gs as FastifyComponentAnalyzer,qr as FastifyDiscoveryProvider,fs as FetchHttpClient,Qr as FolderCollectionLoader,Xt as FolderCollectionStore,Ka as ForgeContainer,tn as ForgeEnv,xr as FrameworkDetector,S as GENERIC_TOOL_NAMES,no as GcpSecretResolver,As as GraphQLSchemaService,Ql as HTTP_METHOD_MAP,ct as HTTP_METHOD_REVERSE,eo as HashiCorpVaultResolver,pr as HistoryAnalyzer,Lr as HtmlReportGenerator,kn as HttpForgeParser,$t as HttpRequestService,Un as InMemoryCookieJar,Ft as InterceptorChain,Gt as JUnitReportGenerator,ur as JsonCollectionLoader,Ks as LambdaComponentAnalyzer,Pr as LambdaDiscoveryProvider,sa as MCP_PROMPTS,Me as METADATA_FILES,si as McpRunStore,qi as ModuleLoader,Ar as NestDiscoveryProvider,gs as NodeFileSystem,An as NodeHttpClient,ys as OAuth2TokenManager,to as OnePasswordResolver,bo as OpenAiProvider,cn as OpenApiExporter,Dt as OpenApiImporter,Zr as ParserRegistry,ws as PersistentCookieJar,xo as REQUEST_INPUT_SCHEMA,nn as ROOT_DIRECTORIES,mr as RefResolver,ir as RequestExecutor,ks as RequestHistoryService,ps as RequestHistoryStore,qs as RequestPreparer,Pn as RequestPreprocessor,us as RequestScriptSession,Jn as ResultStorageService,Kr as SCHEMA_FILES,Ke as SCRIPTS_DIR,gi as SCRIPT_FILES,Co as SUITE_INPUT_SCHEMA,ln as SchemaInferenceService,an as SchemaInferrer,hr as ScriptAnalyzer,Nt as ScriptExecutor,$s as SecretResolverRegistry,Fn as ServiceContainer,O as ServiceIdentifiers,Ir as SpringDiscoveryProvider,bu as StatisticsService,Fs as TestSuiteService,Su as TestSuiteStore,mt as UrlBuilder,Cn as VariableInterpolator,Rn as VariableResolver,Vs as analyzeComponentChainMetadata,$o as analyzeHandlerMetadata,jc as applyEnvSuggestionsToItems,xh as applyExtractionPlan,rs as applyFilterChain,Bt as applyMcpBodyTruncation,Xo as applyRegenerated,_s as assembleBusinessContext,Uc as buildArchitectPrompt,kd as buildCollectionBusinessContext,Bl as buildCollectionToolDescription,_l as buildCollectionToolName,Sh as buildExtractionPlan,Ul as buildFolderToolDescription,Ml as buildFolderToolName,Eo as buildGenericTools,Wl as buildMcpToolList,Al as buildPromptResult,Dc as buildRequestBusinessContext,Hl as buildRequestToolDescription,Nl as buildRequestToolName,Vn as buildResultFileName,Id as buildRunResultsContext,Vl as buildSuiteToolDescription,Dl as buildSuiteToolName,qu as cleanupOldBodyFiles,Vh as clearRegisteredKnowledgeSources,ot as collectSourceFiles,Lt as collectionKnowledgeSource,Hc as collectionToEndpoints,dn as combineConfidence,ti as computeProjectFreshness,Ii as concatenateScripts,$c as countRequests,Td as createDefaultKnowledgeSources,Bs as createEnvAiProvider,rr as createExpectChain,cb as createMcpRuntime,_a as createModuleLoader,Ai as createMomentShim,lt as createNodeContainer,ki as createResponseObject,ja as createTestFunction,Gl as decodeCursor,kt as decodeFolderPath,fn as dedupeDiscoveredApiParameters,Zt as deleteItemFromTree,uu as deserializeTypedRecord,zr as deserializeTypedValue,mo as detectEnvSuggestions,Kp as detectIndexDrift,ni as detectProjectDrift,ei as diffLines,jn as discoverWorkflows,Ol as dispatchGenericTool,Jl as encodeCursor,ke as encodeFolderName,vb as enhanceCollection,Ce as enumerateFolders,Pt as evaluateExpression,ah as exportCollectionToRestClient,It as extractJsonFromLlm,pn as extractPathParameters,we as findItemById,Q as flattenRequests,sr as formatConsoleOutput,Ns as gatherWorkspaceKnowledge,br as generateFlowFromEndpoints,se as generateId,lm as generateReleaseNotes,ft as generateSlug,vr as generateSuiteFromEndpoints,qb as getCompletions,zh as getRegisteredKnowledgeSources,Ad as getServiceContainer,pm as harToCollection,cs as hasChanged,wn as isExpression,xi as isSystemEnvironmentFile,Xr as loadEnvironmentsFromFolder,ko as loadHybridSeedEndpoints,gr as normalizeFolderInput,La as normalizeHeaders,yb as parseCurlCommand,ns as parseFilterChain,xu as parseHar,jl as parseMcpToolName,ic as parsePostmanEnvironment,Eb as parseQueryContext,Eu as prepareBodyForSave,Yo as proposeSuiteUpdates,Cu as readBodyFromDir,Au as readSchemaFile,yi as readScriptsFromDir,fc as redactFullResponse,mc as redactFullResultDetails,yt as redactHeaders,pc as redactHistoryEntry,oo as registerCoreServices,Uh as registerKnowledgeSource,Dd as renderArchitectDocs,um as renderReleaseNotesMarkdown,tt as requestKnowledgeSource,ou as resolveCollectionRef,au as resolveFolderRef,Ll as resolveFolderToken,Xd as resolveProjectName,vl as resolveRegenerated,cu as resolveRequestRef,ii as resolveResultGrouping,Fr as resolveToken,na as reviewSuiteRun,ub as runCollection,db as runFolder,lb as runRequest,co as runResultsKnowledgeSource,pb as runSuite,Rb as scanCollectionForEnvVarsWithAi,ka as searchForItemPath,Ia as searchForItemPathById,ui as serializeTypedValue,ku as sortItemsByOrder,js as suiteIdFromName,yl as threeWayDiff,ra as toReviewRequestResults,Md as validateDesignedSpec,rt as withAiRetry,nt as workspaceKnowledgeSource,lr as writeEnvFile,ji as writeFolderItems,Pu as writeSchemaFiles,vs as writeScriptFile,vi as writeScriptsToDir};
|
|
1465
|
+
`)}nc();Hi();eu();oi();Nr();pa();function qa(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,t)]}function vu(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 dm(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=qa(e,50),r.p90=qa(e,90),r.p95=qa(e,95),r.p99=qa(e,99)}var bu=class{summary;byRequest;overall;errors;startTime=0;constructor(){this.summary=this.createEmptySummary(),this.byRequest=new Map,this.overall=vu("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=vu("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,vu(e,t));let c=this.byRequest.get(e);if(c.name=t,c.count++,s?c.passed++:c.failed++,c.durations.push(n),dm(c),this.overall.count++,s?this.overall.passed++:this.overall.failed++,this.overall.durations.push(n),dm(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}}};Nc();Yt();import*as Et from"fs";import*as Qn from"path";var Su=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=Qn.join(this.suiteDir,e,"request.json");if(Et.existsSync(t))try{let n=JSON.parse(Et.readFileSync(t,"utf-8")),s=Qn.join(this.suiteDir,e,"scripts"),i=yi(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=Qn.join(this.suiteDir,e);Et.mkdirSync(n,{recursive:!0});let s=t.scripts,i={...t};delete i.scripts;let o=Qn.join(n,"request.json"),a=`${o}.tmp-${process.pid}-${Date.now()}`;if(Et.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),Et.renameSync(a,o),s){let c=Qn.join(n,"scripts");vi(c,{preRequest:s.preRequest||void 0,postResponse:s.postResponse||void 0})}}hasEmbeddedRequest(e){return!this.suiteDir||!e?!1:Et.existsSync(Qn.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=ft(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=ft(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)}};Ge();function xu(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(jb(a))}let o=Vb(i,e.collectionName??"Imported from HAR");return{requests:i,collection:o}}function pm(r,e={}){return xu(r,e).collection}function jb(r){let e=r.request,t=e.method||"GET",n=e.url||"",s=Ub(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=Lb(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 Lb(r,e){if(!r)return null;let t=typeof r.text=="string"?r.text:"",n=r.mimeType||Bb(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=Hb(t);if(s.length>0)return{type:"x-www-form-urlencoded",content:s}}return{type:"raw",format:"text",content:t}}function Hb(r){try{return[...new URLSearchParams(r).entries()].map(([t,n])=>({key:t,value:n,enabled:!0}))}catch{return[]}}function Bb(r){return r.find(t=>t.key.toLowerCase()==="content-type")?.value?.split(";")[0].trim()??""}function Ub(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 Vb(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:se(`har-${i}`),name:i,items:[]},t.set(i,o),n.push(o)),o.items.push(zb(s))}return{id:se("har-collection"),name:e,items:n,source:{format:"har",filePath:""},meta:{requestCount:r.length}}}function zb(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:se(`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}}oc();Li();Di();qc();Ac();Tc();Ic();Pc();kc();Oc();es();Ei();Ge();du();export{Hs as AnthropicProvider,Ls as ApiArchitectService,Or as ApiDiscoveryService,Yi as AwsSecretResolver,Xi as AzureKeyVaultResolver,Ru as BODY_FILE_MAP,Tl as CACHE_BUSTING_TOOLS,wo as COLLECTION_INPUT_SCHEMA,On as CONFIG_FILES,Xn as CollectionLoader,bs as CollectionLoaderFactory,_t as CollectionRequestExecutor,Ss as CollectionService,rn as ConfigService,Yr as CookieJar,xs as CookieService,ne as CookieUtils,ae as DEFAULT_CONFIG,Ja as DEFAULT_REQUEST_SETTINGS,In as DataFileParser,ro as DopplerResolver,Cs as EnvironmentConfigService,Ot as EnvironmentResolver,fr as ExampleGenerator,zs as ExpressComponentAnalyzer,Er as ExpressDiscoveryProvider,Ro as FOLDER_INPUT_SCHEMA,Tr as FastApiDiscoveryProvider,Gs as FastifyComponentAnalyzer,qr as FastifyDiscoveryProvider,fs as FetchHttpClient,Qr as FolderCollectionLoader,Xt as FolderCollectionStore,Ka as ForgeContainer,tn as ForgeEnv,xr as FrameworkDetector,S as GENERIC_TOOL_NAMES,no as GcpSecretResolver,As as GraphQLSchemaService,Ql as HTTP_METHOD_MAP,ct as HTTP_METHOD_REVERSE,eo as HashiCorpVaultResolver,pr as HistoryAnalyzer,Lr as HtmlReportGenerator,kn as HttpForgeParser,$t as HttpRequestService,Un as InMemoryCookieJar,Ft as InterceptorChain,Gt as JUnitReportGenerator,ur as JsonCollectionLoader,Ks as LambdaComponentAnalyzer,Pr as LambdaDiscoveryProvider,sa as MCP_PROMPTS,Me as METADATA_FILES,si as McpRunStore,qi as ModuleLoader,Ar as NestDiscoveryProvider,gs as NodeFileSystem,An as NodeHttpClient,ys as OAuth2TokenManager,to as OnePasswordResolver,bo as OpenAiProvider,cn as OpenApiExporter,Dt as OpenApiImporter,Zr as ParserRegistry,ws as PersistentCookieJar,xo as REQUEST_INPUT_SCHEMA,nn as ROOT_DIRECTORIES,mr as RefResolver,ir as RequestExecutor,ks as RequestHistoryService,ps as RequestHistoryStore,qs as RequestPreparer,Pn as RequestPreprocessor,us as RequestScriptSession,Jn as ResultStorageService,Kr as SCHEMA_FILES,Ke as SCRIPTS_DIR,gi as SCRIPT_FILES,Co as SUITE_INPUT_SCHEMA,ln as SchemaInferenceService,an as SchemaInferrer,hr as ScriptAnalyzer,Nt as ScriptExecutor,$s as SecretResolverRegistry,Fn as ServiceContainer,O as ServiceIdentifiers,Ir as SpringDiscoveryProvider,bu as StatisticsService,Fs as TestSuiteService,Su as TestSuiteStore,mt as UrlBuilder,Cn as VariableInterpolator,Rn as VariableResolver,Vs as analyzeComponentChainMetadata,$o as analyzeHandlerMetadata,jc as applyEnvSuggestionsToItems,xh as applyExtractionPlan,rs as applyFilterChain,Bt as applyMcpBodyTruncation,Xo as applyRegenerated,_s as assembleBusinessContext,Uc as buildArchitectPrompt,kd as buildCollectionBusinessContext,Bl as buildCollectionToolDescription,_l as buildCollectionToolName,Sh as buildExtractionPlan,Ul as buildFolderToolDescription,Ml as buildFolderToolName,Eo as buildGenericTools,Wl as buildMcpToolList,Al as buildPromptResult,Dc as buildRequestBusinessContext,Hl as buildRequestToolDescription,Nl as buildRequestToolName,Vn as buildResultFileName,Id as buildRunResultsContext,Vl as buildSuiteToolDescription,Dl as buildSuiteToolName,qu as cleanupOldBodyFiles,Vh as clearRegisteredKnowledgeSources,ot as collectSourceFiles,Lt as collectionKnowledgeSource,Hc as collectionToEndpoints,dn as combineConfidence,ti as computeProjectFreshness,Ii as concatenateScripts,$c as countRequests,Td as createDefaultKnowledgeSources,Bs as createEnvAiProvider,rr as createExpectChain,cb as createMcpRuntime,_a as createModuleLoader,Ai as createMomentShim,lt as createNodeContainer,ki as createResponseObject,ja as createTestFunction,Gl as decodeCursor,kt as decodeFolderPath,fn as dedupeDiscoveredApiParameters,Zt as deleteItemFromTree,uu as deserializeTypedRecord,zr as deserializeTypedValue,mo as detectEnvSuggestions,Kp as detectIndexDrift,ni as detectProjectDrift,ei as diffLines,jn as discoverWorkflows,Ol as dispatchGenericTool,Jl as encodeCursor,ke as encodeFolderName,vb as enhanceCollection,Ce as enumerateFolders,Pt as evaluateExpression,ah as exportCollectionToRestClient,It as extractJsonFromLlm,pn as extractPathParameters,we as findItemById,Q as flattenRequests,sr as formatConsoleOutput,Ns as gatherWorkspaceKnowledge,br as generateFlowFromEndpoints,se as generateId,lm as generateReleaseNotes,ft as generateSlug,vr as generateSuiteFromEndpoints,qb as getCompletions,zh as getRegisteredKnowledgeSources,Ad as getServiceContainer,pm as harToCollection,cs as hasChanged,wn as isExpression,xi as isSystemEnvironmentFile,Xr as loadEnvironmentsFromFolder,ko as loadHybridSeedEndpoints,gr as normalizeFolderInput,La as normalizeHeaders,yb as parseCurlCommand,ns as parseFilterChain,xu as parseHar,jl as parseMcpToolName,ic as parsePostmanEnvironment,Eb as parseQueryContext,Eu as prepareBodyForSave,Yo as proposeSuiteUpdates,Cu as readBodyFromDir,Au as readSchemaFile,yi as readScriptsFromDir,fc as redactFullResponse,mc as redactFullResultDetails,yt as redactHeaders,pc as redactHistoryEntry,oo as registerCoreServices,Uh as registerKnowledgeSource,Dd as renderArchitectDocs,um as renderReleaseNotesMarkdown,tt as requestKnowledgeSource,ou as resolveCollectionRef,au as resolveFolderRef,Ll as resolveFolderToken,Xd as resolveProjectName,vl as resolveRegenerated,cu as resolveRequestRef,ii as resolveResultGrouping,Fr as resolveToken,na as reviewSuiteRun,ub as runCollection,db as runFolder,lb as runRequest,co as runResultsKnowledgeSource,pb as runSuite,Rb as scanCollectionForEnvVarsWithAi,ka as searchForItemPath,Ia as searchForItemPathById,ui as serializeTypedValue,ku as sortItemsByOrder,js as suiteIdFromName,yl as threeWayDiff,ra as toReviewRequestResults,Md as validateDesignedSpec,rt as withAiRetry,nt as workspaceKnowledgeSource,lr as writeEnvFile,ji as writeFolderItems,Pu as writeSchemaFiles,vs as writeScriptFile,vi as writeScriptsToDir};
|