@http-forge/core 0.6.1 → 0.6.2-2.beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +223 -251
  2. package/dist/di/platform-adapters.d.ts +11 -4
  3. package/dist/index.d.ts +13 -2
  4. package/dist/index.js +497 -283
  5. package/dist/index.mjs +496 -282
  6. package/dist/infrastructure/ai/ai-provider.d.ts +16 -0
  7. package/dist/infrastructure/analysis/ai-env-suggester.d.ts +22 -0
  8. package/dist/infrastructure/analysis/collection-enhancer.d.ts +23 -0
  9. package/dist/infrastructure/analysis/env-suggester.d.ts +57 -0
  10. package/dist/infrastructure/collection/collection-store.d.ts +1 -1
  11. package/dist/infrastructure/config/config-service.d.ts +20 -1
  12. package/dist/infrastructure/config/config.interface.d.ts +26 -2
  13. package/dist/infrastructure/config/default-config.d.ts +4 -2
  14. package/dist/infrastructure/environment/environment-config-service.d.ts +2 -1
  15. package/dist/infrastructure/execution/collection-request-executor.d.ts +3 -2
  16. package/dist/infrastructure/execution/request-executor.d.ts +5 -0
  17. package/dist/infrastructure/execution/request-preparer.d.ts +1 -0
  18. package/dist/infrastructure/http/native-http-client.d.ts +6 -1
  19. package/dist/infrastructure/openapi/openapi-exporter.d.ts +5 -0
  20. package/dist/infrastructure/parsers/curl-parser.d.ts +61 -0
  21. package/dist/infrastructure/script/interfaces.d.ts +3 -0
  22. package/dist/infrastructure/script/module-loader.d.ts +1 -1
  23. package/dist/infrastructure/script/script-factories.d.ts +17 -0
  24. package/dist/infrastructure/test-suite/interfaces.d.ts +103 -6
  25. package/dist/infrastructure/test-suite/result-storage.d.ts +6 -0
  26. package/dist/infrastructure/test-suite/statistics-service.d.ts +1 -1
  27. package/dist/infrastructure/test-suite/test-suite-service.d.ts +2 -2
  28. package/dist/infrastructure/test-suite/test-suite-store.d.ts +27 -9
  29. package/dist/runtime/mcp-collection-utils.d.ts +29 -1
  30. package/dist/runtime/mcp-prompts.d.ts +39 -0
  31. package/dist/runtime/mcp-run-store.d.ts +11 -1
  32. package/dist/runtime/mcp-tool-builder.d.ts +6 -0
  33. package/dist/runtime/mcp-tool-name.d.ts +4 -5
  34. package/dist/runtime/mcp-tool-schemas.d.ts +45 -0
  35. package/dist/runtime/node-bootstrap.d.ts +9 -0
  36. package/dist/runtime/runtime-contracts.d.ts +14 -0
  37. package/dist/types/types.d.ts +67 -1
  38. package/dist/utils/typed-value.d.ts +14 -0
  39. package/package.json +20 -6
package/README.md CHANGED
@@ -1,8 +1,19 @@
1
+ <div align="center">
2
+
3
+ <a href="https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge">
4
+ <img src="https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/http-forge-icon.png" alt="HTTP Forge" width="120"/>
5
+ </a>
6
+
7
+ </div>
8
+
1
9
  # @http-forge/core
2
10
 
3
11
  **Standalone HTTP testing engine with Postman collection support and JavaScript-based automation.**
4
12
 
5
13
  [![npm version](https://img.shields.io/npm/v/@http-forge/core.svg)](https://www.npmjs.com/package/@http-forge/core)
14
+ [![npm downloads](https://img.shields.io/npm/dm/%40http-forge%2Fcore)](https://www.npmjs.com/package/@http-forge/core)
15
+ [![node](https://img.shields.io/node/v/%40http-forge%2Fcore)](https://www.npmjs.com/package/@http-forge/core)
16
+ [![VS Code Marketplace](https://img.shields.io/visual-studio-marketplace/v/henry-huang.http-forge?label=VS%20Code%20Marketplace)](https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge)
6
17
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
18
 
8
19
  ## 📦 What is @http-forge/core?
@@ -10,18 +21,16 @@
10
21
  `@http-forge/core` is a headless, framework-agnostic HTTP execution engine with **full Postman collection compatibility**. Execute complex API workflows, test suites, and automated flows without the overhead of a UI.
11
22
 
12
23
  **Core Features:**
13
- - 🚀 **Postman Collections** - Load and execute `.postman_collection.json` and `.forge.json` files
14
- - 📝 **JavaScript Scripting** - Pre-request and post-response scripts with full `pm.*` API (variables, assertions, execution flow, visualizer)
15
- - 🔄 **Dynamic Variables** - Built-in generators: `{{$randomInt}}`, `{{$timestamp}}`, `{{$uuid}}`, `{{$guid}}`, etc.
16
- - 🌍 **Environments** - Full variable scoping (globals, collection, environment, session, iterationData)
17
- - � **Cloud Secret Resolvers** - Resolve `{{secret:alias/path}}` from AWS Secrets Manager, Azure Key Vault, Google Secret Manager, HashiCorp Vault, 1Password, and Doppler; credentials read from the ambient environment, never from config
18
- - �👁️ **File Watching** - Automatic reload on collection/environment file changes with notification callbacks
19
- - 🍪 **Cookie Persistence** - Automatic cookie storage and reuse, `pm.cookies.jar()` and `.toObject()`
20
- - 📊 **Test Assertions** - BDD-style testing with `pm.test()` (sync/async), `pm.test.skip()` / `.fail()` / `.index()`, full Chai `expect()` chains (incl. `.contain()`), and JSON Schema validation via `pm.response.to.have.jsonSchema()`
21
- - 🔐 **CryptoJS** - Full crypto library: hash, HMAC, AES/DES/TripleDES, PBKDF2, encoding helpers
22
- - 🎯 **Execution Flow** - `pm.setNextRequest()`, `pm.execution.skipRequest()` for suite runner flow control
23
- - 📈 **Visualizer** - `pm.visualizer.set(template, data)` for custom Handlebars-based HTML output
24
- - 🔌 **Extensible** - Custom interceptors, HTTP clients, and module loaders
24
+ | Capability | What you get | Typical use case |
25
+ |---|---|---|
26
+ | **Postman-compatible execution** | Run `.postman_collection.json` and `.forge.json` with high `pm.*` API compatibility | Migrate existing Postman suites without rewriting tests |
27
+ | **AI and MCP automation** | Agent-ready MCP runtime and tools for listing, running, and managing API workflows | Copilot/agent integrations and autonomous API operations |
28
+ | **Built-in scripting and assertions** | Pre-request and post-response scripts with `pm.test()` and Chai `expect()` | API contract checks in CI/CD |
29
+ | **Variables and environments** | `{{variables}}` resolution across global, collection, environment, and runtime scopes; dynamic values like `{{$timestamp}}` and `{{$uuid}}` | Multi-environment testing (dev/staging/prod) |
30
+ | **Stateful request flows** | Automatic cookie persistence and flow control with `pm.setNextRequest()` / `pm.execution.skipRequest()` | Auth/login chains and dependent request sequences |
31
+ | **Suite flow nodes** | Conditional/loop/script orchestration via `suite.nodes` with reusable `scriptRef` library entries | Advanced API scenarios without creating script-only HTTP requests |
32
+ | **OpenAPI and docs-ready workflows** | Request metadata stays aligned with API contracts and generated artifacts | Spec-driven API lifecycle and governance |
33
+ | **Extensible architecture** | Custom HTTP clients, interceptors, module loaders, and file-watching hooks | Internal platform tooling and custom runners |
25
34
 
26
35
  **Ideal for:**
27
36
  - CI/CD pipeline integration (GitHub Actions, GitLab CI, Jenkins)
@@ -30,28 +39,184 @@
30
39
  - Load testing and performance monitoring
31
40
  - Automated integration test suites
32
41
 
33
- ## 🎯 Installation
42
+ ## 🧭 Quick Navigation
34
43
 
35
- Requires Node.js `20+`.
44
+ - Pick the right entry point: [Start Here](#-start-here)
45
+ - AI/agent integrations: [AI and MCP Features](#-ai-and-mcp-features)
46
+ - First integration run: [Quick Start](#-quick-start)
47
+ - Common setup issues: [Troubleshooting](#-troubleshooting)
48
+ - Install: [Installation](#-installation)
49
+ - Core architecture and execution model: [Core Concepts](#-core-concepts)
50
+ - Advanced customization: [Advanced Features](#-advanced-features)
51
+ - Types and contracts: [API Reference](#-api-reference)
52
+ - End-to-end examples: [Use Cases](#-use-cases)
53
+ - Ecosystem links: [Links](#-links)
36
54
 
37
- ```bash
38
- npm install @http-forge/core
55
+ ## 🚦 Start Here
56
+
57
+ If you installed `@http-forge/core` from npm and do not have source access, this section is the fastest way to get productive.
58
+
59
+ ### 1. 30-Second Path: Pick The Right Entry Point
60
+
61
+ | Goal | Best Entry | Start Here |
62
+ |---|---|---|
63
+ | Visual authoring + debugging | HTTP Forge Extension | https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge |
64
+ | CI/CD automation + reports | HTTP Forge CLI | https://github.com/hsl1230/http-forge.cli#readme |
65
+ | Custom runtime/framework integration | `@http-forge/core` | Continue in this README |
66
+
67
+ Open-source implementation references:
68
+ - Extension source: https://github.com/hsl1230/http-forge
69
+ - CLI source: https://github.com/hsl1230/http-forge.cli
70
+
71
+ ### 2. Minimal Integration Template
72
+
73
+ Create a file such as `run-core.ts`:
74
+
75
+ ```typescript
76
+ import { ForgeContainer } from '@http-forge/core';
77
+
78
+ async function main() {
79
+ const forge = new ForgeContainer({
80
+ enableCookies: true,
81
+ requestTimeout: 15000,
82
+ });
83
+
84
+ // Load a collection (folder or file format)
85
+ const collection = await forge.loadCollection('./collections/my-api.forge.json');
86
+
87
+ // Optional: inject environment values used by {{variables}}
88
+ forge.setEnvironment({
89
+ baseUrl: 'https://api.example.com',
90
+ apiKey: process.env.API_KEY || ''
91
+ });
92
+
93
+ // Execute first request
94
+ const request = collection.items[0];
95
+ const result = await forge.execute(request, collection);
96
+
97
+ console.log('status:', result.response.status);
98
+ console.log('body:', result.response.body);
99
+ console.log('tests:', result.postResponseResult?.assertions || []);
100
+ }
101
+
102
+ main().catch((err) => {
103
+ console.error(err);
104
+ process.exit(1);
105
+ });
39
106
  ```
40
107
 
41
- Or using the tarball:
108
+ Run it with your preferred TypeScript runtime or compile and execute with Node.
109
+
110
+ ### 3. Production Usage Checklist
111
+
112
+ - Set `requestTimeout` to match your environment/SLA.
113
+ - Enable cookies if your flow includes session-based auth.
114
+ - Feed secrets via environment variables, never hardcoded strings.
115
+ - Exit non-zero when assertions fail in CI pipelines.
116
+ - Keep collections/environments in source control for repeatability.
117
+
118
+ ### 4. Learn Faster From Real Products Built On Core
119
+
120
+ - HTTP Forge extension (UI-first workflow): https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge
121
+ - HTTP Forge CLI docs (automation workflow): https://github.com/hsl1230/http-forge.cli#readme
122
+
123
+ Both are powered by `@http-forge/core` patterns you can reuse.
124
+
125
+ ### 5. Postman Compatibility Matrix
126
+
127
+ | Capability | Compatibility |
128
+ |---|---|
129
+ | Postman collection import/export flows | Yes |
130
+ | Environment and variable interpolation (`{{var}}`) | Yes |
131
+ | `pm.test()` and assertions | Yes |
132
+ | `pm.variables`, `pm.environment`, `pm.collectionVariables`, `pm.globals` | Yes |
133
+ | `pm.execution.setNextRequest()` / `pm.setNextRequest()` | Yes |
134
+ | Cookie jar and persistence | Yes |
135
+ | Dynamic variables (`{{$timestamp}}`, `{{$uuid}}`, etc.) | Yes |
136
+ | Pre-request and post-response scripting | Yes |
137
+
138
+ ### 6. From Postman To HTTP Forge In 3 Steps
139
+
42
140
  ```bash
43
- npm install ./http-forge-core-0.1.0.tgz
141
+ # 1) Import Postman assets with HTTP Forge CLI
142
+ http-forge import collection --postman ./MyApi.postman_collection.json
143
+ http-forge import env --postman ./MyEnv.postman_environment.json --env staging --overwrite
144
+
145
+ # 2) Run them in CI-ready mode
146
+ http-forge run collection "MyApi" --env staging --exit-code
147
+
148
+ # 3) Embed the same collection with @http-forge/core (see Minimal Integration Template)
149
+ ```
150
+
151
+ ## 🤖 AI and MCP Features
152
+
153
+ `@http-forge/core` includes MCP runtime capabilities used by HTTP Forge agent workflows.
154
+
155
+ - Exposes MCP-compatible operations for collections, environments, and test execution.
156
+ - Enables AI agents to inspect, run, and update API testing resources programmatically.
157
+ - Powers HTTP Forge CLI/extension AI workflows through shared runtime behavior.
158
+
159
+ Learn more:
160
+ - Runtime API (MCP runtime): [RUNTIME-API.md](RUNTIME-API.md)
161
+ - MCP management tools reference: [docs/MCP_MANAGEMENT_TOOLS.md](docs/MCP_MANAGEMENT_TOOLS.md)
162
+
163
+ ## 🔀 Suite Flow Nodes
164
+
165
+ `@http-forge/core` now supports graph-style suite execution through optional `nodes` on a suite definition.
166
+
167
+ What you can use:
168
+ - `request` nodes for normal HTTP steps
169
+ - `script` nodes for script-only orchestration steps
170
+ - `if`, `switch`, `for`, `while`, and `block` for flow control
171
+ - `scripts` library on the suite plus `scriptRef` on script nodes for reuse
172
+
173
+ Behavior notes:
174
+ - `if` nodes support `then`, optional `elseif[]`, and optional `else` branches.
175
+ - `switch` nodes support `cases[]` and optional `default`.
176
+ - `for` nodes prefer `loopCondition` for loop evaluation (legacy `condition` remains backward compatible).
177
+
178
+ Flow scripts run through the same script session runtime as request scripts, so you can use `pm.variables.set/get`, `pm.environment`, and `pm.globals` consistently.
179
+
180
+ ```json
181
+ {
182
+ "id": "smoke-with-flow",
183
+ "name": "Smoke With Flow",
184
+ "requests": [],
185
+ "scripts": {
186
+ "setRole": "pm.variables.set('role', 'admin');"
187
+ },
188
+ "nodes": [
189
+ { "type": "script", "scriptRef": "setRole" },
190
+ {
191
+ "type": "if",
192
+ "if": "pm.variables.get('role') === 'admin'",
193
+ "then": [
194
+ {
195
+ "type": "request",
196
+ "request": {
197
+ "collectionId": "my-api_abc123",
198
+ "requestId": "get-users_def456",
199
+ "name": "Get Users"
200
+ }
201
+ }
202
+ ]
203
+ }
204
+ ],
205
+ "config": { "iterations": 1 }
206
+ }
44
207
  ```
45
208
 
46
- ## Runtime APIs (Headless + MCP)
209
+ For the full runtime behavior and limits, see:
210
+ - [RUNTIME-API.md](RUNTIME-API.md)
211
+ - [docs/SUITE_FLOW_SCRIPT_SANDBOX_SOLUTION.md](docs/SUITE_FLOW_SCRIPT_SANDBOX_SOLUTION.md)
47
212
 
48
- For current programmatic runtime APIs, see [RUNTIME-API.md](RUNTIME-API.md):
49
- - `runRequest(options)`
50
- - `runCollection(options)`
51
- - `runSuite(options)`
52
- - `createMcpRuntime(options)`
213
+ ## 🎯 Installation
53
214
 
54
- This covers direct execution, embeddable MCP runtime lifecycle, response include options, and report behavior.
215
+ Requires Node.js `20+`.
216
+
217
+ ```bash
218
+ npm install @http-forge/core
219
+ ```
55
220
 
56
221
  ## ⚡ Quick Start
57
222
 
@@ -113,6 +278,33 @@ const forge = new ForgeContainer({
113
278
  });
114
279
  ```
115
280
 
281
+ ## 🧯 Troubleshooting
282
+
283
+ ### Collection Not Found
284
+
285
+ - Verify the path passed to `loadCollection()` points to an existing `.forge.json` file or collection folder.
286
+ - Use absolute paths in CI to avoid working-directory drift.
287
+
288
+ ### Variables Not Resolving (`{{baseUrl}}` remains literal)
289
+
290
+ - Ensure variables are set before `execute()` via `setEnvironment(...)` or environment config.
291
+ - Check for typos and case mismatches in variable names.
292
+
293
+ ### Script Timeout Or Stuck Script
294
+
295
+ - Increase `scriptTimeout` for heavy scripts.
296
+ - Remove long-running loops and external network calls from scripts.
297
+
298
+ ### Authentication/Cookie Flows Failing Across Requests
299
+
300
+ - Enable `enableCookies: true` in `ForgeContainer` options.
301
+ - Confirm login responses include `Set-Cookie` and that subsequent requests reuse the same container instance.
302
+
303
+ ### CI Does Not Fail On Test Assertion Errors
304
+
305
+ - Inspect `postResponseResult?.assertions` after each request and exit with non-zero code when failures exist.
306
+ - If using CLI, include `--exit-code`.
307
+
116
308
  ## 📚 Core Concepts
117
309
 
118
310
  ### ForgeContainer
@@ -252,75 +444,6 @@ if (pm.response.headers.has('Set-Cookie')) {
252
444
  }
253
445
  ```
254
446
 
255
- #### Response Body Type
256
-
257
- Like Postman, `pm.response.body` is the **raw response string** — it is not eagerly parsed. Parse JSON on demand:
258
-
259
- ```javascript
260
- const data = pm.response.json(); // parsed object (null if not JSON)
261
- const text = pm.response.text(); // raw string
262
- const obj = JSON.parse(pm.response.body); // body is a string
263
- ```
264
-
265
- `json()` tolerates an already-parsed object body for backward compatibility, but new code should treat `pm.response.body` as a string.
266
-
267
- #### Legacy Postman Globals
268
-
269
- Older Postman scripts and many Newman-exported collections rely on bare globals from the pre-`pm.*` sandbox. The core injects these so legacy scripts run unchanged.
270
-
271
- Available in **both** pre-request and test scripts: `request` (`{ id, name, description, url, method, headers, data }`), `environment` (read snapshot), `globals` (read snapshot), `data` (iteration row), `iteration` (index), and `tv4` (`tv4.validate(data, schema)` — when the optional `tv4` module is installed).
272
-
273
- Available in **test** scripts only: `responseBody` (raw string), `responseCode` (`{ code, name, detail }`), `responseHeaders`, `responseTime`, `responseCookies` (cookie objects with `name`, `value`, `domain`, `path`, `expires`, `maxAge`, `httpOnly`, `secure`, `sameSite`), `tests` (`tests['name'] = boolean`), plus `postman.getResponseHeader(name)` and `postman.getResponseCookie(name)` (case-insensitive; `getResponseCookie` returns the full cookie object, both return `null` if absent).
274
-
275
- ```javascript
276
- // Legacy-style test script — runs unmodified
277
- tests['status 200'] = responseCode.code === 200;
278
- tests['has token'] = JSON.parse(responseBody).token !== undefined;
279
- tests['is json'] = /application\/json/.test(postman.getResponseHeader('Content-Type'));
280
- ```
281
-
282
- > `environment` and `globals` are read snapshots — direct assignment was never persisted in legacy Postman either. Use `postman.setEnvironmentVariable()` / `postman.setGlobalVariable()` (or the modern `pm.environment.set()` / `pm.globals.set()`) to persist changes.
283
-
284
- #### Script Scope
285
-
286
- Control how script levels (collection → folder → request) and the pre-request/post-response phases share a JavaScript scope via `scripts.scope` in `http-forge.config.json` (or the `scriptScope` SDK option):
287
-
288
- | Mode | Behavior |
289
- |------|----------|
290
- | `'shared'` *(default)* | All levels and both phases run in one scope. `var`/`function` and global assignments leak across them; lowest overhead. Top-level `let`/`const` are scoped to a single phase. |
291
- | `'isolated'` | Each level runs in its own scope, matching Postman. Declarations cannot collide or leak; pass state through `pm.variables` / `pm.environment` / `pm.globals`. |
292
-
293
- ```typescript
294
- const forge = ForgeContainer.create({ scriptScope: 'isolated' });
295
- ```
296
-
297
- Use `'isolated'` when importing Postman collections whose scripts re-declare the same identifiers at multiple levels, which would otherwise throw `Identifier already declared` in shared mode.
298
-
299
- #### Async Script Execution (Event-Loop Draining)
300
-
301
- Like Postman, scripts do **not** end when their synchronous code returns. After the sync body completes, the core keeps the sandbox alive and drains pending timers (`setTimeout`/`setInterval`) and microtasks (un-awaited `Promise`s), then commits variable scopes — so deferred `pm.globals` / `pm.environment` / `pm.variables` writes are visible to the next request **without** `await`.
302
-
303
- ```typescript
304
- // Post-response script — committed for the next request, no await required
305
- setTimeout(() => pm.globals.set('authToken', generateToken()), 1500);
306
- ```
307
-
308
- The drain is bounded by `scripts.timeout` (the `scriptTimeout` SDK option), default **5000 ms**, which caps **both** synchronous CPU time and the async-drain window:
309
-
310
- ```typescript
311
- const forge = ForgeContainer.create({ scriptTimeout: 10000 });
312
- ```
313
-
314
- | Behavior | Notes |
315
- |----------|-------|
316
- | Sandbox kept alive after sync return | Pending timers/microtasks drained before the request advances |
317
- | Deferred `pm.*` writes committed | Visible to the next request without `await` |
318
- | Errors in timer/Promise callbacks | Reported as a console error, **non-fatal** — the request/test is not failed |
319
- | Runaway timers | A never-clearing `setInterval` or infinite timer loop is force-cancelled at the timeout, with a warning |
320
- | No async work | Returns immediately; draining adds no measurable latency |
321
-
322
- **Divergences from Postman:** uses real Node timers with a poll-based wall-clock drain (no exact pending-promise count, so pathological microtask recursion is bounded by the budget rather than a precise idle signal); a single `scripts.timeout` bounds both CPU time and the async window.
323
-
324
447
  ### Environment Management
325
448
 
326
449
  ```typescript
@@ -429,11 +552,6 @@ pm.response.cookies.forEach(cookie => {
429
552
  pm.cookies.set(cookie.name, cookie.value);
430
553
  });
431
554
 
432
- // Read a response cookie (Postman-compatible CookieList)
433
- const sid = pm.response.cookies.get('sessionId'); // value string
434
- const sidCookie = pm.response.cookies.one('sessionId'); // full object
435
- if (sidCookie?.secure && sidCookie.maxAge > 0) { /* ... */ }
436
-
437
555
  // List all active cookies
438
556
  const allCookies = pm.cookies.list(); // [{name, value}, ...]
439
557
 
@@ -490,7 +608,7 @@ interface ForgeContainerOptions {
490
608
 
491
609
  // Script Settings
492
610
  scriptRunner?: IScriptRunner; // Custom script runner
493
- scriptTimeout?: number; // Script budget (ms); caps CPU time + async-drain window. Default 5000
611
+ scriptTimeout?: number; // Script timeout (ms)
494
612
 
495
613
  // History
496
614
  enableHistory?: boolean; // Enable request history
@@ -605,46 +723,6 @@ interface PathParamEntry {
605
723
  }
606
724
  ```
607
725
 
608
- ### Postman Collection Import / Export
609
-
610
- `CollectionService` can import and export Postman Collection v2.1 JSON files, preserving all request body types, auth, scripts, and folder structure.
611
-
612
- **Import** (`importCollection(filePath)`):
613
-
614
- Detects Postman format by `info._postman_id` and converts all five body modes:
615
-
616
- | Postman `mode` | HTTP Forge `type` | Notes |
617
- |---|---|---|
618
- | `raw` | `raw` | `format` inferred from `options.raw.language` (json/xml/html/javascript/text) |
619
- | `urlencoded` | `x-www-form-urlencoded` | Fields mapped to `[{key, value, enabled}]` |
620
- | `formdata` | `form-data` | Fields mapped to `[{key, value, type, enabled}]` |
621
- | `graphql` | `graphql` | `variables` JSON string parsed to object |
622
- | `binary` | `binary` | File path not portable; imported with empty content |
623
-
624
- Auth types `bearer`, `basic`, and `apikey` are converted. Pre-request and test scripts (`prerequest`/`test` events) are imported as `scripts.preRequest`/`scripts.postResponse`. Folder hierarchy and item order are preserved.
625
-
626
- The whole collection is built in memory and persisted with a single `saveCollection()`
627
- call. `FolderCollectionStore.save()` writes sibling items and each request's
628
- independent files (body, docs, scripts, schemas) in parallel and writes each
629
- metadata file once; fresh imports skip stale-body cleanup and schema-existence
630
- probes. Loaders read JSON via a `readJsonFileSafe` helper that silently skips
631
- empty or half-written files, so a watcher reloading mid-import never throws
632
- `Unexpected end of JSON input`.
633
-
634
- **Export** (`exportCollection(collectionId, filePath)`):
635
-
636
- Converts back to Postman v2.1 JSON. All body types round-trip correctly: `x-www-form-urlencoded` exports as `mode: "urlencoded"`, `form-data` as `mode: "formdata"`, `graphql` as `mode: "graphql"`, and `binary` as `mode: "binary"`.
637
-
638
- ```typescript
639
- const service = container.getCollectionService();
640
-
641
- // Import
642
- const collection = await service.importCollection('./my-api.postman_collection.json');
643
-
644
- // Export
645
- await service.exportCollection(collection.id, './exported.postman_collection.json');
646
- ```
647
-
648
726
  ### OpenAPI Import / Export
649
727
 
650
728
  The core library includes full OpenAPI 3.0.3 import and export with constraint preservation.
@@ -656,59 +734,13 @@ The core library includes full OpenAPI 3.0.3 import and export with constraint p
656
734
 
657
735
  **Export** (`OpenApiExporter`):
658
736
  - Generates OpenAPI 3.0.3 specs from collections
659
- - **Host-variable server resolution** — Any `{{varName}}` that prefixes a request URL (e.g. `{{dcqHost}}/api/...`) is stripped from the path and resolved to a server URL entry. If the variable resolves in the active environment(s), a concrete `url` is added to `servers`. If unresolvable, an OAS server-variable entry is emitted: `url: '{varName}', variables: { varName: { default: '' } }`. This handles arbitrary host variables beyond `{{baseUrl}}`.
660
- - **Environment variable placeholder sanitization** — `{{varName}}` tokens in parameter examples (path, query, header) and request body examples are replaced with `<varName>` so the exported spec contains readable human placeholders rather than raw template syntax.
661
737
  - **Collision-aware merging**: When multiple requests normalize to the same path + HTTP method, they are merged into a single operation:
662
738
  - Descriptions are appended, tags are unioned
663
739
  - Parameters with the **same constraint kind** (both enum, both pattern, etc.) are merged in-place (union enum values, widen numeric ranges, alternation-join patterns)
664
740
  - Parameters with **different constraint kinds** are wrapped in `oneOf` — each variant keeps its self-consistent schema
665
741
  - All constraint fields round-trip without data loss
666
742
 
667
- ## � Exported Types
668
-
669
- ### Configuration
670
-
671
- `HttpForgeConfig` is the shape of `http-forge.config.json`. Key sub-interfaces:
672
-
673
- | Interface | Description |
674
- |---|---|
675
- | `StorageConfig` | Root/history/results paths |
676
- | `RequestConfig` | Timeout, redirects, SSL |
677
- | `ScriptsConfig` | Module search paths |
678
- | `RunnerConfig` | Retention, index page size |
679
- | `EnvironmentsConfig` | Default environment |
680
- | `RestClientExportConfig` | REST Client export path/merge settings |
681
- | `McpConfig` | MCP server project-level settings (see below) |
682
- | `ProxyConfig` | HTTP/HTTPS proxy URLs |
683
-
684
- **`McpConfig`** — controls what the HTTP Forge MCP server exposes to AI agents. All fields are optional; the service fills defaults automatically via `IConfigService.getMcpConfig()`.
685
-
686
- ```typescript
687
- interface McpConfig {
688
- excludedCollections: string[]; // IDs or names to hide (default: [] = expose all)
689
- excludedSuites: string[]; // IDs or names to hide (default: [] = expose all)
690
- toolPrefix: string; // Prefix for every tool name (default: "")
691
- maxRequestsPerCall: number; // Safety cap per collection/suite call (default: 500; min 1, max 10000)
692
- toolMode: 'flat' | 'drilldown' | 'auto'; // How tools are exposed (default: 'auto')
693
- drilldownThreshold: number; // 'auto' switches to drill-down above this request-tool count (default: 100; min 10, max 500)
694
- toolPageSize: number; // Max tools per tools/list page (default: 200; 0 = no pagination; min 10, max 1000)
695
- cors: {
696
- allowedOrigins: string[]; // CORS origins (default: ["http://localhost","http://127.0.0.1"])
697
- };
698
- }
699
- ```
700
-
701
- **`toolMode`** controls how collections/requests are surfaced as MCP tools:
702
-
703
- - `auto` (**default**) — uses `flat` below `drilldownThreshold` (100 requests), then switches to `drilldown`. Adapts automatically as the workspace grows.
704
- - `drilldown` — a small fixed set of generic tools (`list_collections`, `list_requests`, `run_request`, `run_folder`, `run_collection`, `run_suite`) whose arguments select the target. Keeps the tool list tiny regardless of scale.
705
- - `flat` — one tool per request, folder, collection, and suite. Only suitable for small, stable collections (<100 requests). **Avoid for large workspaces** — the tool list bloats the AI context window and degrades tool-selection accuracy.
706
-
707
- Use `IConfigService.getMcpConfig()` to read the resolved config with all defaults applied.
708
-
709
- ---
710
-
711
- ## �🛠️ Use Cases
743
+ ## 🛠️ Use Cases
712
744
 
713
745
  ### CLI Tool
714
746
 
@@ -894,70 +926,10 @@ MIT © Henry Huang
894
926
 
895
927
  ## 🔗 Links
896
928
 
897
- - [HTTP Forge Extension](https://marketplace.visualstudio.com/items?itemName=your-publisher.http-forge)
929
+ - [HTTP Forge Extension](https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge)
930
+ - [HTTP Forge CLI](https://github.com/hsl1230/http-forge.cli#readme)
931
+ - [Core Reference Docs](docs/core-reference.md)
932
+ - [Changelog](CHANGELOG.md)
898
933
  - [GitHub Repository](https://github.com/hsl1230/http-forge)
899
934
  - [Issues](https://github.com/hsl1230/http-forge/issues)
900
935
 
901
- ## 📝 Changelog
902
-
903
- ### 0.2.16 (Duplicate Collection & Folder)
904
-
905
- - ✅ **`duplicateCollection(sourceId, newName)`** — Duplicates a collection including all nested folders, requests, scripts, and schemas
906
- - ✅ **`duplicateFolder(collectionId, folderId, newName)`** — Duplicates a folder within a collection, preserving all nested request content
907
- - ✅ **`getItemPath(collectionId, itemId)`** — Resolves the disk path of a folder or request within a collection
908
-
909
- ### 0.2.6 (OpenAPI Export — Environment Variable Handling)
910
-
911
- - ✅ **Host-variable URL stripping** — Any leading `{{varName}}` in a request URL (e.g. `{{dcqHost}}/DCQ/templates/GetEpg`) is now correctly stripped from the path. The variable name is resolved via `envConfigService.resolveVariables()` and the resulting URL is added to `servers`. When the variable cannot be resolved, an OAS server-variable entry (`url: '{varName}', variables: { varName: { default: '' } }`) is emitted instead. Previously, unknown host variables were converted to `/{varName}/...` path segments.
912
- - ✅ **Example sanitization** — `{{varName}}` placeholders in parameter examples (path, query, header) and request body examples are replaced with `<varName>` so they render as readable human placeholders instead of raw template syntax in the exported spec.
913
-
914
- ### 0.2.5 (OpenAPI Constraint Round-Trip & Collision Merging)
915
-
916
- - ✅ **Full parameter constraint round-trip** — OpenAPI import/export now preserves all schema constraint fields: `pattern`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `minLength`, `maxLength`, and `oneOf` on both `KeyValueEntry` and `PathParamEntry`
917
- - ✅ **Collision-aware OpenAPI export** — When multiple requests normalize to the same path + HTTP method, the exporter merges them into a single operation with intelligent parameter schema merging (same-kind merge in-place, different-kind wraps in `oneOf`)
918
- - ✅ **`oneOf` import with UI hints** — `applyOneOfHints()` derives combined enum arrays and type hints from `oneOf` variants for downstream UI rendering (combobox vs strict dropdown)
919
- - ✅ **`format` vs `pattern` separation** — `format` is a semantic hint (e.g. `"uuid"`), `pattern` is an enforced regex. Both stored and round-tripped independently
920
-
921
- ### 0.2.4 (File Watching & Request Documentation)
922
-
923
- - ✅ **File watching for CollectionService** - Automatic reload and `onCollectionsChanged` callback when collection files change on disk
924
- - ✅ **File watching for EnvironmentConfigService** - Automatic reload and `onEnvironmentsChanged` callback when environment JSON files change on disk
925
- - ✅ **Request documentation (`doc.md`)** - Persist per-request Markdown documentation as `doc.md` alongside `request.json`
926
- - ✅ **`doc` field on UnifiedRequest / CollectionRequest** - Optional `doc?: string` field for request documentation content
927
- - ✅ **`fileWatcherFactory` bootstrap option** - Pass `IFileWatcherFactory` to enable file watching in both collection and environment services
928
-
929
- ### 0.2.0 (Postman API Parity)
930
-
931
- - ✅ **Async `pm.test()` support** - Tests with async callbacks are properly awaited
932
- - ✅ **Expect chain assertions** - `.a(type)`, `.an(type)`, `.deep.equal()`, `.lengthOf()`, `.exist`, `.members()`, `.keys()`, `.string()`
933
- - ✅ **`pm.iterationData`** scope - Data-driven testing with iteration variables
934
- - ✅ **Response status getters** - `response.to.be.ok`, `.error`, `.clientError`, `.serverError` work as getters and functions
935
- - ✅ **Response headers HeaderList** - `.get()`, `.has()`, `.toObject()`, `.each()` on `pm.response.headers`
936
- - ✅ **`pm.cookies.toObject()`** - Flat `{name: value}` cookie map
937
- - ✅ **`replaceIn()` on all scopes** - Available on `pm.variables`, `pm.environment`, `pm.collectionVariables`, `pm.globals`
938
- - ✅ **Sandbox globals** - `xml2Json()`, `jsonStringify()`, `jsonParse()` available in scripts
939
- - ✅ **Request headers API** - `.toObject()`, `.each()` on `pm.request.headers`
940
- - ✅ **`pm.execution.setNextRequest()`** - Runner flow control (jump to named request or stop with `null`)
941
- - ✅ **`pm.execution.skipRequest()`** - Skip HTTP call from pre-request scripts
942
- - ✅ **`pm.setNextRequest()`** - Top-level alias for flow control
943
- - ✅ **`pm.visualizer.set(template, data)`** - Custom HTML visualization with Handlebars templates
944
- - ✅ **`pm.request.url` as Url object** - Postman SDK-compatible Url with `getHost()`, `getPath()`, `getQueryString()`, `protocol`, `host`, `port`, `path`, `query`, `hash`
945
- - ✅ **Full CryptoJS** - AES/DES/TripleDES encrypt/decrypt, PBKDF2, all hash algorithms (SHA1/256/384/512/SHA3/MD5/RIPEMD160), HMAC, encoding helpers (Hex/Base64/Utf8/Latin1/Utf16)
946
-
947
- ### 0.1.0 (Initial Release)
948
-
949
- - ✅ **Core request execution** with Postman collection support
950
- - ✅ **Dynamic variables** - 7 generators for on-the-fly value generation
951
- - ✅ **Postman-compatible scripting** - `pm.*` API with full feature parity
952
- - ✅ **Variable scoping** - globals, collection, environment, session, flow-level
953
- - ✅ **Cookie persistence** - automatic storage and reuse across request chains
954
- - ✅ **Pre-request & post-response scripts** with shared VM context
955
- - ✅ **Test assertions** with BDD-style `pm.test()` and expect chains
956
- - ✅ **Environment management** with variable substitution
957
- - ✅ **Cookie jar** with domain-aware matching
958
- - ✅ **Request/response interceptors** for customization
959
- - ✅ **Request history** tracking
960
- - ✅ **File and folder collection formats** (Postman-compatible)
961
- - ✅ **Full TypeScript support** with comprehensive types
962
- - ✅ **Dependency injection** for extensibility
963
- - ✅ **Comprehensive test coverage**
@@ -7,11 +7,11 @@
7
7
  * The core bootstrap uses these adapters to wire up services
8
8
  * without depending on any specific platform.
9
9
  */
10
- import type { IConsoleService } from '../types/console-service';
11
- import type { IApplicationInfo, IExternalBrowserService, IFileSystem, IFileWatcherFactory, IHttpClient, IKeyValueStore, INotificationService, ISecretStore } from '../types/platform';
12
10
  import type { IHttpExecutor } from '../ports/executors/http-executor.interface';
13
11
  import type { IScriptExecutor } from '../ports/executors/script-executor.interface';
14
12
  import type { ILogger } from '../ports/external/logger.interface';
13
+ import type { IConsoleService } from '../types/console-service';
14
+ import type { IApplicationInfo, IExternalBrowserService, IFileSystem, IFileWatcherFactory, IHttpClient, IKeyValueStore, INotificationService, ISecretStore } from '../types/platform';
15
15
  /**
16
16
  * Platform adapters required by core service bootstrap.
17
17
  *
@@ -41,8 +41,8 @@ export interface PlatformAdapters {
41
41
  fileWatcherFactory: IFileWatcherFactory;
42
42
  /** Notification service — shows info/warning/error messages (ConfigService) */
43
43
  notificationService: INotificationService;
44
- /** Per-workspace key-value store (EnvironmentConfigService) */
45
- workspaceStore: IKeyValueStore;
44
+ /** Per-workspace key-value store (EnvironmentConfigService). Optional — CLI/Node runs without it. */
45
+ workspaceStore?: IKeyValueStore;
46
46
  /** Global key-value store (CookieService) */
47
47
  globalStore: IKeyValueStore;
48
48
  /** Secret storage for tokens (OAuth2TokenManager). Optional — OAuth2 disabled if absent. */
@@ -53,6 +53,13 @@ export interface PlatformAdapters {
53
53
  applicationInfo?: IApplicationInfo;
54
54
  /** Structured logging service. Optional — a no-op console is used if absent. */
55
55
  consoleService?: IConsoleService;
56
+ /**
57
+ * Whether script-written environment overrides (pm.environment.set) should be
58
+ * persisted to the workspace store between runs.
59
+ * - `true` (default) — VS Code extension: Current Values survive restarts.
60
+ * - `false` — CLI/Node: overrides are in-memory only, runs are stateless.
61
+ */
62
+ persistOverrides?: boolean;
56
63
  /** File system adapter */
57
64
  fileSystem?: IFileSystem;
58
65
  /** Logger adapter */
package/dist/index.d.ts CHANGED
@@ -20,10 +20,12 @@ export { ForgeContainer } from './container';
20
20
  export type { ForgeContainerOptions, StorageFormat } from './container';
21
21
  export { getServiceContainer, registerCoreServices, ServiceContainer, ServiceIdentifiers } from './di';
22
22
  export type { PlatformAdapters, ServiceIdentifier } from './di';
23
- export { countRequests, enumerateFolders, flattenRequests } from './runtime/mcp-collection-utils';
23
+ export { countRequests, decodeFolderName, decodeFolderPath, encodeFolderName, enumerateFolders, flattenRequests, normalizeFolderInput } from './runtime/mcp-collection-utils';
24
24
  export type { FlatRequest } from './runtime/mcp-collection-utils';
25
25
  export { CACHE_BUSTING_TOOLS, dispatchGenericTool } from './runtime/mcp-dispatcher';
26
26
  export type { McpDispatchServices, McpRunCallbacks } from './runtime/mcp-dispatcher';
27
+ export { buildPromptResult, MCP_PROMPTS } from './runtime/mcp-prompts';
28
+ export type { McpPromptArg, McpPromptDef, PromptResult } from './runtime/mcp-prompts';
27
29
  export { McpRunStore } from './runtime/mcp-run-store';
28
30
  export type { McpRunRecord } from './runtime/mcp-run-store';
29
31
  export { buildMcpToolList, decodeCursor, dedupeToolsByName, encodeCursor } from './runtime/mcp-tool-builder';
@@ -79,6 +81,14 @@ export { generateSlug } from './infrastructure/collection/folder-io';
79
81
  export { ParserRegistry } from './infrastructure/collection/parser-registry';
80
82
  export { JsonCollectionLoader } from './infrastructure/collection/json-collection-loader';
81
83
  export type { Collection, CollectionFolderItem, CollectionItem, CollectionRequestItem, ICollectionService } from './types/collection';
84
+ export { parseCurlCommand } from './infrastructure/parsers/curl-parser';
85
+ export type { ParsedCurlRequest } from './infrastructure/parsers/curl-parser';
86
+ export type { IAiProvider } from './infrastructure/ai/ai-provider';
87
+ export { enhanceCollection } from './infrastructure/analysis/collection-enhancer';
88
+ export type { EnhanceProgressCallback } from './infrastructure/analysis/collection-enhancer';
89
+ export { scanCollectionForEnvVarsWithAi } from './infrastructure/analysis/ai-env-suggester';
90
+ export { applyEnvSuggestionsToItems, detectEnvSuggestions } from './infrastructure/analysis/env-suggester';
91
+ export type { EnvSuggestion } from './infrastructure/analysis/env-suggester';
82
92
  export { AmbiguousRefError, resolveCollectionRef, resolveFolderRef, resolveRequestRef } from './runtime/ref-resolver';
83
93
  export type { RefCandidate, RefKind, RefTier, ResolutionInfo } from './runtime/ref-resolver';
84
94
  export { EnvironmentConfigService } from './infrastructure/environment/environment-config-service';
@@ -114,7 +124,7 @@ export { CONFIG_FILES, ConfigService, DEFAULT_CONFIG, ROOT_DIRECTORIES } from '.
114
124
  export type { EnvironmentsConfig, HttpForgeConfig, IConfigService, McpConfig, McpCorsConfig, McpToolMode, ProxyConfig, RequestConfig, RestClientExportConfig, RunnerConfig, ScriptsConfig, StorageConfig } from './infrastructure/config';
115
125
  export { HtmlReportGenerator } from './infrastructure/test-suite/html-report-generator';
116
126
  export { DEFAULT_SUITE_CONFIG } from './infrastructure/test-suite/interfaces';
117
- export type { ErrorSummary, IStatisticsService, ITestSuiteService, RequestStatistics, RunStatistics, RunSummary, SuiteConfig, SuiteRequest, TestSuite } from './infrastructure/test-suite/interfaces';
127
+ export type { ErrorSummary, IStatisticsService, ITestSuiteService, RequestStatistics, RunStatistics, RunSummary, SuiteBlockNode, SuiteConfig, SuiteElseIfBranch, SuiteFlowNode, SuiteFlowNodeBase, SuiteForNode, SuiteIfNode, SuiteRequest, SuiteRequestNode, SuiteScriptNode, SuiteSwitchCase, SuiteSwitchNode, SuiteWhileNode, TestSuite } from './infrastructure/test-suite/interfaces';
118
128
  export { JUnitReportGenerator } from './infrastructure/test-suite/junit-report-generator';
119
129
  export { buildResultFileName, expandSummary, HTTP_METHOD_MAP, HTTP_METHOD_REVERSE } from './infrastructure/test-suite/result-storage';
120
130
  export type { FullResultDetails, IndexPage, IResultStorageService, RecentError, RequestStats, ResultSummary, RunConfig, RunManifest, RunStats } from './infrastructure/test-suite/result-storage';
@@ -143,3 +153,4 @@ export { augmentWithDynamicVars, DYNAMIC_VARIABLES, resolveDynamicVariable, reso
143
153
  export { evaluateExpression, isExpression } from './utils/expression-evaluator';
144
154
  export { applyFilterChain, parseFilterChain } from './utils/filter-engine';
145
155
  export { deepClone, formatBytes, formatDuration, generateId, generateUUID, isPlainObject, mergeHeadersCaseInsensitive, safeJsonParse, sanitizeName } from './utils/helpers';
156
+ export { deserializeTypedRecord, deserializeTypedValue, serializeTypedValue } from './utils/typed-value';