@http-forge/core 0.6.11 → 0.6.15

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/README.md CHANGED
@@ -1,82 +1,884 @@
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
- The headless API execution engine behind HTTP Forge.
11
+ **Standalone HTTP testing engine with Postman collection support and JavaScript-based automation.**
12
+
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)
17
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
18
+
19
+ ## 📦 What is @http-forge/core?
20
+
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.
22
+
23
+ **Core Features:**
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
+ | **OpenAPI and docs-ready workflows** | Request metadata stays aligned with API contracts and generated artifacts | Spec-driven API lifecycle and governance |
32
+ | **Extensible architecture** | Custom HTTP clients, interceptors, module loaders, and file-watching hooks | Internal platform tooling and custom runners |
33
+
34
+ **Ideal for:**
35
+ - CI/CD pipeline integration (GitHub Actions, GitLab CI, Jenkins)
36
+ - Headless API testing and contract validation
37
+ - Building custom API testing CLIs
38
+ - Load testing and performance monitoring
39
+ - Automated integration test suites
40
+
41
+ ## 🧭 Quick Navigation
42
+
43
+ - Pick the right entry point: [Start Here](#-start-here)
44
+ - AI/agent integrations: [AI and MCP Features](#-ai-and-mcp-features)
45
+ - First integration run: [Quick Start](#-quick-start)
46
+ - Common setup issues: [Troubleshooting](#-troubleshooting)
47
+ - Install: [Installation](#-installation)
48
+ - Core architecture and execution model: [Core Concepts](#-core-concepts)
49
+ - Advanced customization: [Advanced Features](#-advanced-features)
50
+ - Types and contracts: [API Reference](#-api-reference)
51
+ - End-to-end examples: [Use Cases](#-use-cases)
52
+ - Ecosystem links: [Links](#-links)
53
+
54
+ ## 🚦 Start Here
55
+
56
+ If you installed `@http-forge/core` from npm and do not have source access, this section is the fastest way to get productive.
57
+
58
+ ### 1. 30-Second Path: Pick The Right Entry Point
59
+
60
+ | Goal | Best Entry | Start Here |
61
+ |---|---|---|
62
+ | Visual authoring + debugging | HTTP Forge Extension | https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge |
63
+ | CI/CD automation + reports | HTTP Forge CLI | https://github.com/hsl1230/http-forge.cli#readme |
64
+ | Custom runtime/framework integration | `@http-forge/core` | Continue in this README |
65
+
66
+ Open-source implementation references:
67
+ - Extension source: https://github.com/hsl1230/http-forge
68
+ - CLI source: https://github.com/hsl1230/http-forge.cli
69
+
70
+ ### 2. Minimal Integration Template
71
+
72
+ Create a file such as `run-core.ts`:
73
+
74
+ ```typescript
75
+ import { ForgeContainer } from '@http-forge/core';
76
+
77
+ async function main() {
78
+ const forge = new ForgeContainer({
79
+ enableCookies: true,
80
+ requestTimeout: 15000,
81
+ });
82
+
83
+ // Load a collection (folder or file format)
84
+ const collection = await forge.loadCollection('./collections/my-api.forge.json');
85
+
86
+ // Optional: inject environment values used by {{variables}}
87
+ forge.setEnvironment({
88
+ baseUrl: 'https://api.example.com',
89
+ apiKey: process.env.API_KEY || ''
90
+ });
91
+
92
+ // Execute first request
93
+ const request = collection.items[0];
94
+ const result = await forge.execute(request, collection);
95
+
96
+ console.log('status:', result.response.status);
97
+ console.log('body:', result.response.body);
98
+ console.log('tests:', result.postResponseResult?.assertions || []);
99
+ }
4
100
 
5
- Run Postman-compatible collections, requests, suites, and OpenAPI-driven workflows in Node.js, CI/CD, and custom tooling.
101
+ main().catch((err) => {
102
+ console.error(err);
103
+ process.exit(1);
104
+ });
105
+ ```
106
+
107
+ Run it with your preferred TypeScript runtime or compile and execute with Node.
108
+
109
+ ### 3. Production Usage Checklist
110
+
111
+ - Set `requestTimeout` to match your environment/SLA.
112
+ - Enable cookies if your flow includes session-based auth.
113
+ - Feed secrets via environment variables, never hardcoded strings.
114
+ - Exit non-zero when assertions fail in CI pipelines.
115
+ - Keep collections/environments in source control for repeatability.
116
+
117
+ ### 4. Learn Faster From Real Products Built On Core
118
+
119
+ - HTTP Forge extension (UI-first workflow): https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge
120
+ - HTTP Forge CLI docs (automation workflow): https://github.com/hsl1230/http-forge.cli#readme
121
+
122
+ Both are powered by `@http-forge/core` patterns you can reuse.
123
+
124
+ ### 5. Postman Compatibility Matrix
125
+
126
+ | Capability | Compatibility |
127
+ |---|---|
128
+ | Postman collection import/export flows | Yes |
129
+ | Environment and variable interpolation (`{{var}}`) | Yes |
130
+ | `pm.test()` and assertions | Yes |
131
+ | `pm.variables`, `pm.environment`, `pm.collectionVariables`, `pm.globals` | Yes |
132
+ | `pm.execution.setNextRequest()` / `pm.setNextRequest()` | Yes |
133
+ | Cookie jar and persistence | Yes |
134
+ | Dynamic variables (`{{$timestamp}}`, `{{$uuid}}`, etc.) | Yes |
135
+ | Pre-request and post-response scripting | Yes |
136
+
137
+ ### 6. From Postman To HTTP Forge In 3 Steps
138
+
139
+ ```bash
140
+ # 1) Import Postman assets with HTTP Forge CLI
141
+ http-forge import collection --postman ./MyApi.postman_collection.json
142
+ http-forge import env --postman ./MyEnv.postman_environment.json --env staging --overwrite
6
143
 
7
- [![npm version](https://img.shields.io/npm/v/%40http-forge%2Fcore.svg)](https://www.npmjs.com/package/@http-forge/core)
8
- [![license](https://img.shields.io/npm/l/%40http-forge%2Fcore.svg)](LICENSE)
144
+ # 2) Run them in CI-ready mode
145
+ http-forge run collection "MyApi" --env staging --exit-code
9
146
 
10
- ## Why @http-forge/core
147
+ # 3) Embed the same collection with @http-forge/core (see Minimal Integration Template)
148
+ ```
149
+
150
+ ## 🤖 AI and MCP Features
151
+
152
+ `@http-forge/core` includes MCP runtime capabilities used by HTTP Forge agent workflows.
11
153
 
12
- - Run API tests headlessly in Node.js and CI/CD.
13
- - Execute Postman-style scripts with `pm.*` APIs.
14
- - Reuse the same HTTP Forge collections outside the UI.
15
- - Work with environments, cookies, dynamic variables, and OpenAPI flows.
16
- - Embed the runtime in your own CLI, automation, or agent workflows.
154
+ - Exposes MCP-compatible operations for collections, environments, and test execution.
155
+ - Enables AI agents to inspect, run, and update API testing resources programmatically.
156
+ - Powers HTTP Forge CLI/extension AI workflows through shared runtime behavior.
17
157
 
18
- ## What It Powers
158
+ Learn more:
159
+ - Runtime API (MCP runtime): [RUNTIME-API.md](RUNTIME-API.md)
160
+ - MCP management tools reference: [docs/MCP_MANAGEMENT_TOOLS.md](docs/MCP_MANAGEMENT_TOOLS.md)
19
161
 
20
- - HTTP Forge VS Code extension
21
- - HTTP Forge CLI
22
- - MCP server runtime
23
- - OpenAPI import/export and automation flows
24
- - Custom API testing tools built on top of the engine
162
+ ## 🎯 Installation
25
163
 
26
- ## 1-Minute Quickstart
164
+ Requires Node.js `20+`.
27
165
 
28
166
  ```bash
29
167
  npm install @http-forge/core
30
168
  ```
31
169
 
32
- ```ts
170
+ ## ⚡ Quick Start
171
+
172
+ ### Basic Usage
173
+
174
+ ```typescript
33
175
  import { ForgeContainer } from '@http-forge/core';
34
176
 
177
+ // Create a container with default settings
35
178
  const forge = new ForgeContainer();
179
+
180
+ // Load a collection
36
181
  const collection = await forge.loadCollection('./my-api.forge.json');
182
+
183
+ // Execute a request
37
184
  const result = await forge.execute(collection.items[0], collection);
38
185
 
39
- console.log(result.response.status);
40
- console.log(result.response.body);
186
+ console.log(result.response.status); // 200
187
+ console.log(result.response.body); // Response data
188
+ console.log(result.postResponseResult?.assertions); // Test results
189
+ ```
190
+
191
+ ### With Environment Variables
192
+
193
+ ```typescript
194
+ const forge = new ForgeContainer();
195
+
196
+ // Set environment variables
197
+ forge.setEnvironment({
198
+ baseUrl: 'https://api.example.com',
199
+ apiKey: 'your-api-key',
200
+ timeout: '5000'
201
+ });
202
+
203
+ // Variables are automatically interpolated in requests
204
+ // URL: {{baseUrl}}/users -> https://api.example.com/users
205
+ const result = await forge.execute(request, collection);
206
+ ```
207
+
208
+ ### With Custom Configuration
209
+
210
+ ```typescript
211
+ const forge = new ForgeContainer({
212
+ // Use native Node.js http/https instead of fetch
213
+ useNativeHttp: true,
214
+
215
+ // Enable automatic cookie management
216
+ enableCookies: true,
217
+
218
+ // Set request timeout
219
+ requestTimeout: 10000,
220
+
221
+ // Enable request history
222
+ enableHistory: true,
223
+ maxHistoryEntries: 50,
224
+
225
+ // Storage format
226
+ storageFormat: 'folder' // or 'file'
227
+ });
228
+ ```
229
+
230
+ ## 🧯 Troubleshooting
231
+
232
+ ### Collection Not Found
233
+
234
+ - Verify the path passed to `loadCollection()` points to an existing `.forge.json` file or collection folder.
235
+ - Use absolute paths in CI to avoid working-directory drift.
236
+
237
+ ### Variables Not Resolving (`{{baseUrl}}` remains literal)
238
+
239
+ - Ensure variables are set before `execute()` via `setEnvironment(...)` or environment config.
240
+ - Check for typos and case mismatches in variable names.
241
+
242
+ ### Script Timeout Or Stuck Script
243
+
244
+ - Increase `scriptTimeout` for heavy scripts.
245
+ - Remove long-running loops and external network calls from scripts.
246
+
247
+ ### Authentication/Cookie Flows Failing Across Requests
248
+
249
+ - Enable `enableCookies: true` in `ForgeContainer` options.
250
+ - Confirm login responses include `Set-Cookie` and that subsequent requests reuse the same container instance.
251
+
252
+ ### CI Does Not Fail On Test Assertion Errors
253
+
254
+ - Inspect `postResponseResult?.assertions` after each request and exit with non-zero code when failures exist.
255
+ - If using CLI, include `--exit-code`.
256
+
257
+ ## 📚 Core Concepts
258
+
259
+ ### ForgeContainer
260
+
261
+ The main entry point - a dependency injection container that wires up all components.
262
+
263
+ ```typescript
264
+ const forge = new ForgeContainer(options);
265
+
266
+ // Load collections
267
+ const collection = await forge.loadCollection(path);
268
+ const folderCollection = await forge.loadFolderCollection(path);
269
+
270
+ // Execute requests
271
+ const result = await forge.execute(request, collection, options);
272
+
273
+ // Manage environments
274
+ forge.setEnvironment(variables);
275
+ forge.setActiveEnvironment(name);
276
+ const resolved = forge.getResolvedEnvironment();
277
+
278
+ // Access services
279
+ const executor = forge.getRequestExecutor();
280
+ const loader = forge.getCollectionLoader();
281
+ ```
282
+
283
+ ### Request Execution
284
+
285
+ Execute requests with full control over the execution pipeline:
286
+
287
+ ```typescript
288
+ const result = await forge.execute(request, collection, {
289
+ environment: 'production',
290
+ overrides: {
291
+ url: 'https://override.com/api',
292
+ headers: { 'X-Custom': 'value' }
293
+ },
294
+ skipPreRequest: false,
295
+ skipPostResponse: false,
296
+ timeout: 5000
297
+ });
298
+
299
+ // Access results
300
+ console.log(result.response); // HTTP response
301
+ console.log(result.preRequestResult); // Pre-request script output
302
+ console.log(result.postResponseResult); // Test results
303
+ ```
304
+
305
+ ### Dynamic Variables
306
+
307
+ Automatic variable generation within request templates:
308
+
309
+ ```javascript
310
+ // URL with dynamic timestamp
311
+ https://api.example.com/events?timestamp={{$timestamp}}
312
+
313
+ // Headers with unique ID
314
+ X-Request-ID: {{$uuid}}
315
+
316
+ // Query parameters with random value
317
+ ?page=1&seed={{$randomInt:1:100}}
318
+ ```
319
+
320
+ **Supported dynamic variables:**
321
+ - `{{$randomInt}}` - Random integer (0-2147483647)
322
+ - `{{$randomInt:min:max}}` - Random integer in range
323
+ - `{{$timestamp}}` - Current Unix timestamp (seconds)
324
+ - `{{$uuid}}` - UUID v4
325
+ - `{{$guid}}` - GUID (alias for uuid)
326
+ - `{{$randomString}}` - 10-char alphanumeric string
327
+ - `{{$randomHexadecimal}}` - Random hex string
328
+ - `{{$isoTimestamp}}` - ISO 8601 timestamp
329
+
330
+ ### Script Execution
331
+
332
+ Run pre-request and post-response scripts with full Postman API compatibility:
333
+
334
+ **Pre-request script - Set variables & modify request:**
335
+ ```javascript
336
+ // Set variables across scopes
337
+ pm.variables.set('requestId', pm.variables.randomUUID());
338
+ pm.environment.set('token', 'abc-123');
339
+ pm.collectionVariables.set('counter', '1');
340
+
341
+ // Modify request headers
342
+ pm.request.headers.add({
343
+ name: 'X-Request-ID',
344
+ value: pm.variables.get('requestId')
345
+ });
346
+ pm.request.headers.update({
347
+ name: 'Authorization',
348
+ value: 'Bearer ' + pm.environment.get('token')
349
+ });
350
+
351
+ // Modify URL and body
352
+ pm.request.url = 'https://api.example.com' + pm.request.url;
353
+ pm.request.body.raw = JSON.stringify({ timestamp: Date.now() });
354
+
355
+ // Set cookies for next request
356
+ pm.cookies.set('sessionId', 'sess_abc123');
357
+ ```
358
+
359
+ **Post-response script - Test & extract data:**
360
+ ```javascript
361
+ // Run assertions
362
+ pm.test('Status is 200', () => {
363
+ pm.expect(pm.response.code).to.equal(200);
364
+ });
365
+ pm.test('Response time under 1s', () => {
366
+ pm.expect(pm.response.responseTime).to.be.below(1000);
367
+ });
368
+
369
+ // Extract data for next request
370
+ const data = pm.response.json();
371
+ pm.environment.set('userId', data.id);
372
+ pm.environment.set('authToken', data.token);
373
+
374
+ // Store non-string values (auto-serialized with type safety)
375
+ pm.environment.set('userList', data.users); // Array → stored with type marker
376
+ pm.environment.set('config', { retries: 3 }); // Object → stored with type marker
377
+ pm.environment.set('count', 42); // Number → stored with type marker
378
+
379
+ // get() auto-deserializes back to the original type
380
+ const users = pm.environment.get('userList'); // → Array
381
+ const config = pm.environment.get('config'); // → Object
382
+ const count = pm.environment.get('count'); // → 42 (number)
383
+
384
+ // Strings are never misinterpreted — "true" stays a string, true stays a boolean
385
+ pm.environment.set('flag', true); // boolean
386
+ pm.environment.set('label', 'true'); // string
387
+ pm.environment.get('flag'); // → true (boolean)
388
+ pm.environment.get('label'); // → "true" (string)
389
+
390
+ // Store cookies from response
391
+ if (pm.response.headers.has('Set-Cookie')) {
392
+ pm.cookies.set('authCookie', data.authCookie);
393
+ }
394
+ ```
395
+
396
+ ### Environment Management
397
+
398
+ ```typescript
399
+ // Define multiple environments
400
+ forge.setEnvironmentConfig({
401
+ dev: { baseUrl: 'https://dev.api.com', apiKey: 'dev-key' },
402
+ staging: { baseUrl: 'https://staging.api.com', apiKey: 'staging-key' },
403
+ prod: { baseUrl: 'https://api.com', apiKey: 'prod-key' }
404
+ });
405
+
406
+ // Switch environments
407
+ forge.setActiveEnvironment('prod');
408
+
409
+ // Get resolved variables (with inheritance and overrides)
410
+ const vars = forge.getResolvedEnvironment('prod');
411
+ ```
412
+
413
+ ## 🔧 Advanced Features
414
+
415
+ ### Custom HTTP Client
416
+
417
+ Implement your own HTTP client:
418
+
419
+ ```typescript
420
+ import { IHttpClient, HttpRequest, HttpResponse } from '@http-forge/core';
421
+
422
+ class CustomHttpClient implements IHttpClient {
423
+ async send(request: HttpRequest): Promise<HttpResponse> {
424
+ // Your custom HTTP logic
425
+ return {
426
+ status: 200,
427
+ statusText: 'OK',
428
+ headers: {},
429
+ body: {},
430
+ duration: 100,
431
+ size: 1024
432
+ };
433
+ }
434
+ }
435
+
436
+ const forge = new ForgeContainer({
437
+ httpClient: new CustomHttpClient()
438
+ });
439
+ ```
440
+
441
+ ### Request/Response Interceptors
442
+
443
+ Add custom interceptors to modify requests and responses:
444
+
445
+ ```typescript
446
+ import { IRequestInterceptor, IResponseInterceptor } from '@http-forge/core';
447
+
448
+ // Request interceptor
449
+ class AuthInterceptor implements IRequestInterceptor {
450
+ async intercept(request: HttpRequest): Promise<HttpRequest> {
451
+ request.headers['Authorization'] = `Bearer ${getToken()}`;
452
+ return request;
453
+ }
454
+ }
455
+
456
+ // Response interceptor
457
+ class LoggingInterceptor implements IResponseInterceptor {
458
+ async intercept(response: HttpResponse, request: HttpRequest): Promise<HttpResponse> {
459
+ console.log(`${request.method} ${request.url} -> ${response.status}`);
460
+ return response;
461
+ }
462
+ }
463
+
464
+ const forge = new ForgeContainer({
465
+ requestInterceptors: [new AuthInterceptor()],
466
+ responseInterceptors: [new LoggingInterceptor()]
467
+ });
468
+ ```
469
+
470
+ ### Cookie Management & Persistence
471
+
472
+ Automatic cookie storage and reuse across multi-request flows:
473
+
474
+ ```typescript
475
+ const forge = new ForgeContainer({
476
+ enableCookies: true // Cookies persist across requests in session
477
+ });
478
+
479
+ // Login - response sets Session-ID cookie
480
+ const loginResult = await forge.execute(loginRequest, collection);
481
+
482
+ // Subsequent requests automatically include Session-ID
483
+ // No need to manually extract and re-add cookies
484
+ const dataResult = await forge.execute(dataRequest, collection);
485
+ const updateResult = await forge.execute(updateRequest, collection);
486
+ ```
487
+
488
+ **Access cookies in scripts:**
489
+ ```javascript
490
+ // Pre-request script - read stored cookies
491
+ if (pm.cookies.has('sessionId')) {
492
+ const sid = pm.cookies.get('sessionId');
493
+ pm.request.headers.add({
494
+ name: 'Cookie',
495
+ value: 'sessionId=' + sid
496
+ });
497
+ }
498
+
499
+ // Post-response script - store new cookies
500
+ pm.response.cookies.forEach(cookie => {
501
+ pm.cookies.set(cookie.name, cookie.value);
502
+ });
503
+
504
+ // List all active cookies
505
+ const allCookies = pm.cookies.list(); // [{name, value}, ...]
506
+
507
+ // Clear cookies
508
+ pm.cookies.clear(); // When switching users/sessions
509
+ ```
510
+
511
+ Cookies are automatically extracted from `Set-Cookie` response headers and reused in subsequent `Cookie` request headers.
512
+
513
+ ### Request History
514
+
515
+ Track all executed requests:
516
+
517
+ ```typescript
518
+ const forge = new ForgeContainer({
519
+ enableHistory: true,
520
+ maxHistoryEntries: 100
521
+ });
522
+
523
+ // Execute requests
524
+ await forge.execute(request1, collection);
525
+ await forge.execute(request2, collection);
526
+
527
+ // Access history
528
+ const history = forge.getRequestHistory();
529
+ const entries = history.getAll(); // All requests
530
+ const byId = history.getByRequestId(id); // Specific request history
531
+ ```
532
+
533
+ ## 📖 API Reference
534
+
535
+ ### ForgeContainer
536
+
537
+ **Constructor Options:**
538
+ ```typescript
539
+ interface ForgeContainerOptions {
540
+ forgeRoot?: string; // Path to http-forge folder
541
+ storageFormat?: 'file' | 'folder'; // Collection storage format
542
+
543
+ // HTTP Settings
544
+ useNativeHttp?: boolean; // Use native http/https
545
+ httpClient?: IHttpClient; // Custom HTTP client
546
+ httpSettings?: RequestSettings; // Default HTTP settings
547
+ requestTimeout?: number; // Request timeout (ms)
548
+
549
+ // Cookie Settings
550
+ enableCookies?: boolean; // Enable cookie jar
551
+ cookieJar?: ICookieJar; // Custom cookie jar
552
+
553
+ // Interceptors
554
+ requestInterceptors?: IRequestInterceptor[];
555
+ responseInterceptors?: IResponseInterceptor[];
556
+ errorInterceptors?: IErrorInterceptor[];
557
+
558
+ // Script Settings
559
+ scriptRunner?: IScriptRunner; // Custom script runner
560
+ scriptTimeout?: number; // Script timeout (ms)
561
+
562
+ // History
563
+ enableHistory?: boolean; // Enable request history
564
+ maxHistoryEntries?: number; // Max history size
565
+
566
+ // File Watching
567
+ fileWatcherFactory?: IFileWatcherFactory; // Watch for collection/environment file changes
568
+ }
41
569
  ```
42
570
 
43
- ## Core Capabilities
571
+ **Methods:**
572
+ ```typescript
573
+ // Collection loading
574
+ loadCollection(path: string): Promise<UnifiedCollection>
575
+ loadFolderCollection(path: string): Promise<UnifiedCollection>
576
+
577
+ // Request execution
578
+ execute(
579
+ request: UnifiedRequest,
580
+ collection: UnifiedCollection,
581
+ options?: ExecuteOptions
582
+ ): Promise<ExecuteResult>
583
+
584
+ // Environment management
585
+ setEnvironment(variables: Record<string, string>): void
586
+ setEnvironmentConfig(config: EnvironmentConfig): void
587
+ setActiveEnvironment(name: string): void
588
+ getResolvedEnvironment(name?: string): Record<string, string>
589
+
590
+ // Service access
591
+ getRequestExecutor(): RequestExecutor
592
+ getCollectionLoader(): ICollectionLoader
593
+ getEnvironmentResolver(): EnvironmentResolver
594
+ getRequestHistory(): IRequestHistory
595
+ ```
44
596
 
45
- - Postman collection execution
46
- - JavaScript pre-request and post-response scripting
47
- - Dynamic variables and environment resolution
48
- - Cookie persistence and execution flow control
49
- - Secret resolution from AWS, Azure, Google Cloud, Vault, 1Password, and Doppler
50
- - AI and MCP runtime integration
51
- - Headless execution for CI/CD and custom runners
597
+ ### ExecuteResult
52
598
 
53
- ## Key APIs
599
+ ```typescript
600
+ interface ExecuteResult {
601
+ response: HttpResponse; // HTTP response
602
+ preRequestResult?: ScriptResult; // Pre-request script output
603
+ postResponseResult?: ScriptResult; // Test results
604
+ requestId: string; // Unique request ID
605
+ timestamp: number; // Execution timestamp
606
+ }
607
+ ```
608
+
609
+ ### HttpResponse
610
+
611
+ ```typescript
612
+ interface HttpResponse {
613
+ status: number; // HTTP status code
614
+ statusText: string; // Status text
615
+ headers: Record<string, string>; // Response headers
616
+ body: any; // Parsed response body
617
+ cookies?: Cookie[]; // Response cookies
618
+ duration: number; // Request duration (ms)
619
+ size: number; // Response size (bytes)
620
+ redirected?: boolean; // Whether redirected
621
+ }
622
+ ```
623
+
624
+ ### KeyValueEntry
625
+
626
+ Used for headers and query parameters in `CollectionRequest`. Supports OpenAPI metadata for generation and validation.
627
+
628
+ ```typescript
629
+ interface KeyValueEntry {
630
+ key: string;
631
+ value: string;
632
+ enabled?: boolean;
633
+ // OpenAPI metadata (all optional, backward-compatible)
634
+ type?: 'string' | 'integer' | 'number' | 'boolean' | 'array';
635
+ required?: boolean;
636
+ description?: string;
637
+ format?: string; // Semantic hint (e.g. "uuid", "date-time")
638
+ enum?: string[]; // Allowed values
639
+ deprecated?: boolean;
640
+ // Extended constraint fields for full OpenAPI round-trip
641
+ pattern?: string; // Regex validation pattern
642
+ minimum?: number;
643
+ maximum?: number;
644
+ exclusiveMinimum?: number;
645
+ exclusiveMaximum?: number;
646
+ minLength?: number;
647
+ maxLength?: number;
648
+ oneOf?: Array<Record<string, any>>; // Merged constraint variants
649
+ }
650
+ ```
651
+
652
+ ### PathParamEntry
653
+
654
+ Used for path parameters (`:param` in URLs). Same constraint fields as `KeyValueEntry` minus `key`/`enabled`.
655
+
656
+ ```typescript
657
+ interface PathParamEntry {
658
+ value: string;
659
+ type?: 'string' | 'integer' | 'number' | 'boolean';
660
+ description?: string;
661
+ format?: string;
662
+ enum?: string[];
663
+ deprecated?: boolean;
664
+ pattern?: string;
665
+ minimum?: number;
666
+ maximum?: number;
667
+ exclusiveMinimum?: number;
668
+ exclusiveMaximum?: number;
669
+ minLength?: number;
670
+ maxLength?: number;
671
+ oneOf?: Array<Record<string, any>>;
672
+ }
673
+ ```
674
+
675
+ ### OpenAPI Import / Export
676
+
677
+ The core library includes full OpenAPI 3.0.3 import and export with constraint preservation.
678
+
679
+ **Import** (`OpenApiImporter`):
680
+ - Parses OpenAPI 3.0 YAML/JSON specs into `UnifiedCollection`
681
+ - Extracts all parameter schema constraints (`pattern`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `minLength`, `maxLength`, `enum`, `format`)
682
+ - Preserves `oneOf` schemas from merged parameters, deriving combined enum hints for UI display
683
+
684
+ **Export** (`OpenApiExporter`):
685
+ - Generates OpenAPI 3.0.3 specs from collections
686
+ - **Collision-aware merging**: When multiple requests normalize to the same path + HTTP method, they are merged into a single operation:
687
+ - Descriptions are appended, tags are unioned
688
+ - Parameters with the **same constraint kind** (both enum, both pattern, etc.) are merged in-place (union enum values, widen numeric ranges, alternation-join patterns)
689
+ - Parameters with **different constraint kinds** are wrapped in `oneOf` — each variant keeps its self-consistent schema
690
+ - All constraint fields round-trip without data loss
691
+
692
+ ## 🛠️ Use Cases
693
+
694
+ ### CLI Tool
695
+
696
+ ```typescript
697
+ #!/usr/bin/env node
698
+ import { ForgeContainer } from '@http-forge/core';
699
+
700
+ async function runTests(collectionPath: string) {
701
+ const forge = new ForgeContainer();
702
+ const collection = await forge.loadCollection(collectionPath);
703
+
704
+ for (const request of collection.items) {
705
+ const result = await forge.execute(request, collection);
706
+ const tests = result.postResponseResult?.assertions || [];
707
+
708
+ console.log(`\n${request.name}: ${result.response.status}`);
709
+ tests.forEach(test => {
710
+ console.log(` ${test.passed ? '✓' : '✗'} ${test.name}`);
711
+ });
712
+ }
713
+ }
714
+
715
+ runTests(process.argv[2]);
716
+ ```
717
+
718
+ ### CI/CD Integration
719
+
720
+ ```typescript
721
+ import { ForgeContainer } from '@http-forge/core';
722
+
723
+ async function ciTest() {
724
+ const forge = new ForgeContainer({
725
+ enableCookies: true,
726
+ requestTimeout: 30000
727
+ });
728
+
729
+ forge.setEnvironment({
730
+ baseUrl: process.env.API_URL,
731
+ apiKey: process.env.API_KEY
732
+ });
733
+
734
+ const collection = await forge.loadCollection('./api-tests.forge.json');
735
+
736
+ let failedTests = 0;
737
+ for (const request of collection.items) {
738
+ const result = await forge.execute(request, collection);
739
+ const failed = result.postResponseResult?.assertions?.filter(t => !t.passed) || [];
740
+ failedTests += failed.length;
741
+ }
742
+
743
+ process.exit(failedTests > 0 ? 1 : 0);
744
+ }
745
+ ```
746
+
747
+ ### Custom Testing Framework
748
+
749
+ ```typescript
750
+ import { ForgeContainer } from '@http-forge/core';
751
+
752
+ class ApiTestRunner {
753
+ private forge: ForgeContainer;
754
+
755
+ constructor() {
756
+ this.forge = new ForgeContainer({
757
+ enableCookies: true,
758
+ enableHistory: true
759
+ });
760
+ }
761
+
762
+ async runSuite(suites: TestSuite[]) {
763
+ for (const suite of suites) {
764
+ await this.runTests(suite);
765
+ }
766
+ }
767
+
768
+ async runTests(suite: TestSuite) {
769
+ const collection = await this.forge.loadCollection(suite.collection);
770
+
771
+ for (const request of collection.items) {
772
+ const result = await this.forge.execute(request, collection);
773
+ suite.results.push(result);
774
+ }
775
+ }
776
+ }
777
+ ```
778
+
779
+ ### Multi-Request Workflows
780
+
781
+ Execute dependent request chains with automatic cookie and variable management:
782
+
783
+ ```typescript
784
+ import { ForgeContainer } from '@http-forge/core';
785
+
786
+ async function apiAuthWorkflow() {
787
+ const forge = new ForgeContainer({
788
+ enableCookies: true, // Cookies persist across requests
789
+ enableHistory: true
790
+ });
791
+
792
+ // Request 1: Login (sets session cookie)
793
+ const loginReq = {
794
+ name: 'Login',
795
+ method: 'POST',
796
+ url: 'https://api.example.com/auth/login',
797
+ body: { type: 'raw', content: JSON.stringify({
798
+ username: '{{email}}',
799
+ password: '{{password}}'
800
+ })},
801
+ scripts: {
802
+ postResponse: `
803
+ const { token, userId } = pm.response.json();
804
+ pm.environment.set('authToken', token);
805
+ pm.environment.set('userId', userId);
806
+ `
807
+ }
808
+ };
809
+
810
+ const loginResult = await forge.execute(loginReq, collection);
811
+ console.log('✓ Logged in, token:', forge.getResolvedEnvironment()['authToken']);
812
+
813
+ // Request 2: Fetch user profile (uses session cookie automatically)
814
+ const profileReq = {
815
+ name: 'Get Profile',
816
+ method: 'GET',
817
+ url: 'https://api.example.com/users/{{userId}}',
818
+ headers: {
819
+ 'Authorization': 'Bearer {{authToken}}' // Uses token from login
820
+ }
821
+ };
822
+
823
+ const profileResult = await forge.execute(profileReq, collection);
824
+ console.log('✓ Profile:', profileResult.response.body);
825
+
826
+ // Request 3: Update profile (session cookie still active)
827
+ const updateReq = {
828
+ name: 'Update Profile',
829
+ method: 'PATCH',
830
+ url: 'https://api.example.com/users/{{userId}}',
831
+ headers: {
832
+ 'Authorization': 'Bearer {{authToken}}'
833
+ },
834
+ body: { type: 'raw', content: JSON.stringify({ status: 'active' })}
835
+ };
836
+
837
+ const updateResult = await forge.execute(updateReq, collection);
838
+ console.log('✓ Updated profile');
839
+
840
+ // Session automatically logged out - cookies cleared
841
+ forge.getRequestHistory().clear();
842
+ }
843
+ ```
844
+
845
+ ## 📦 Storage Formats
846
+
847
+ ### File Format (Single JSON)
848
+ ```
849
+ my-api.forge.json
850
+ ```
851
+
852
+ ### Folder Format (Directory Structure)
853
+ ```
854
+ my-api/
855
+ collection.json
856
+ requests/
857
+ login/
858
+ request.json
859
+ doc.md # Optional request documentation (Markdown)
860
+ users/
861
+ get-users/
862
+ request.json
863
+ doc.md
864
+ create-user/
865
+ request.json
866
+ ```
54
867
 
55
- - `ForgeContainer`
56
- - `runRequest(options)`
57
- - `runCollection(options)`
58
- - `runSuite(options)`
59
- - `createMcpRuntime(options)`
60
- - `parseCurlCommand()`
61
- - `enhanceCollection()`
62
- - `detectEnvSuggestions()`
868
+ ## 🤝 Contributing
63
869
 
64
- ## Best For
870
+ Contributions are welcome! Please feel free to submit a Pull Request.
65
871
 
66
- - Headless API testing
67
- - CI/CD API validation
68
- - Postman-compatible automation
69
- - Custom API CLIs and runners
70
- - MCP and agent-driven API workflows
872
+ ## 📄 License
71
873
 
72
- ## Detailed Docs
874
+ MIT © Henry Huang
73
875
 
74
- - Full core reference: `docs/core-reference.md`
75
- - Runtime APIs: `RUNTIME-API.md`
76
- - Quick reference: `docs/QUICK_REFERENCE.md`
77
- - Architecture notes: `docs/ARCHITECTURE_IMPLEMENTATION.md`
78
- - Documentation inventory: `docs/README_DOCUMENTATION.md`
876
+ ## 🔗 Links
79
877
 
80
- ## License
878
+ - [HTTP Forge Extension](https://marketplace.visualstudio.com/items?itemName=henry-huang.http-forge)
879
+ - [HTTP Forge CLI](https://github.com/hsl1230/http-forge.cli#readme)
880
+ - [Core Reference Docs](docs/core-reference.md)
881
+ - [Changelog](CHANGELOG.md)
882
+ - [GitHub Repository](https://github.com/hsl1230/http-forge)
883
+ - [Issues](https://github.com/hsl1230/http-forge/issues)
81
884
 
82
- MIT