@nikhil-qeas/api-core 0.3.0 → 0.4.0

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 (3) hide show
  1. package/README.md +31 -86
  2. package/bin/qe-api.js +27 -0
  3. package/package.json +5 -2
package/README.md CHANGED
@@ -1,110 +1,55 @@
1
1
  # QE API Automation Core
2
2
 
3
- Shared **browserless** TypeScript API testing foundation consumed by Helios, EAB, Reflect, BaaS and other independent projects. `@qe-automation/api-core` has no runtime WebdriverIO or Mocha dependency: those belong in the **consuming** project's test runner. It can be called from Mocha API tests and from WDIO + Mocha/Healix UI flows. This separation avoids fake browser sessions in API pipelines.
3
+ A reusable TypeScript API test utility library and project initializer. Public npm package: `@nikhil-qeas/api-core`.
4
4
 
5
- ## What is included
5
+ ## Two ways to use this package
6
6
 
7
- - `ApiClient`: Node fetch, typed results, timeouts, exact-byte request signer hook, safe read-only retries, correlation and timing events.
8
- - `TokenManager`: refresh or reacquire, concurrent call deduplication, explicit invalidation.
9
- - `expectStatus`, `expectClientError`, `expectResponseTime`, `expectContract`: lightweight assertions (a consuming service can adapt AJV/OpenAPI validators).
10
- - `redact`: metadata redaction helper. **Not a guarantee that arbitrary unstructured text or bank responses are safe to log.** Do not attach raw bodies.
11
- - Environment validation and run IDs.
12
- - Node built-in unit tests, versioned npm package metadata, sample GitLab publish pipeline and consuming-project pipeline.
13
-
14
- ## Design boundaries
15
-
16
- **Shared core:** HTTP abstraction, auth provider interfaces, safe utilities, contract assertion interface, standard observability.
17
- **Project-specific:** Helios HMAC canonicalization, PKCE/RSA/login workflows, endpoints, payment/transfer safety gates, test user accounts, schemas, fixtures, Mocha specs, Allure adapters, WDIO/Healix setup, and GitLab deployment policy.
18
-
19
- ## First run
7
+ **Generate a complete new project:**
20
8
 
21
9
  ```bash
22
- npm install # initial local setup; generate and commit package-lock.json
10
+ npx --yes --package @nikhil-qeas/api-core@0.4.0 qe-api init my-api-project
11
+ cd my-api-project
12
+ npm install
23
13
  npm run check
24
- npm pack --dry-run
25
14
  ```
26
15
 
27
- If no lockfile is present, use `npm install` once and commit the generated `package-lock.json` before enabling CI.
28
-
29
- ## Private GitLab package publishing
30
-
31
- 1. Create an **internal/private GitLab repository** `QE-API-Automation-Core`, push this source and configure a GitLab runner.
32
- 2. Run `npm ci && npm run check`; protect release tags and require approval/review.
33
- 3. Tag a commit matching `package.json` version: `v0.1.0`. The publish job uses `CI_JOB_TOKEN` to push package to that GitLab project's npm registry.
34
- 4. In every consuming repo, configure `CORE_PROJECT_ID` and the npm scope registry. Ensure the core project permits the consumer CI job token in its allowlist (or use an appropriately scoped, masked registry token).
35
- 5. Install with `npm install --save-dev @qe-automation/api-core@0.1.0` and commit the resulting lockfile. Never commit secrets or a filled `.npmrc`.
36
- 6. Version and pin core releases; validate all adopter projects before promoting a breaking release. The GitLab file under `ci/` is a reference, not an immediately enforced enterprise deployment policy.
37
-
38
- ## Helios adoption strategy
39
-
40
- **Do not replace the working Helios-Plc-API repository.** First add this package as a dev dependency. Wrap the existing `ApiClient` and signing implementation through the `RequestSigner` interface; introduce module-level usage progressively. Maintain existing workflow logic and test titles. Preserve `HELIOS_ALLOW_MONEY_MOVEMENT` default-deny behavior. Run `npm run typecheck && npm run test:offline` before/after every extraction, then perform dedicated real-environment verification. The included `examples/helios-adoption/` shows a consumer wiring example, not a verified live Helios API integration.
41
-
42
- ## Current verification scope
43
-
44
- The unit suite covers safe retry classification, exact-body signing, bearer token deduplication, redaction, invalid config, response assertions and request path constraints. Real Helios, EAB, GitLab runners, npm package publication and browser/device runs require separate live verification. The framework contains no credentials or banking endpoint details.
45
-
46
- ## Security notes
47
-
48
- - Never retry POST/payment instructions just because a transport timeout occurred. `idempotent: true` is an explicit opt-in only after server-side idempotency is demonstrated and approved.
49
- - Default HTTP event metadata excludes headers and bodies. Avoid logging `ApiTransportError.cause`, which can contain native transport information.
50
- - Contract validation is provided through validator functions; use each product's existing Ajv schemas or OpenAPI tooling in its project.
51
- - No API calls should run against production without approved non-destructive data and an explicit gated execution policy.
52
-
53
- ## v0.3.0 enterprise candidate
16
+ This creates a project with TypeScript, Mocha, test folders, client/auth/contract/data/workflow folders, a local mock smoke test, and GitLab CI with JUnit output.
54
17
 
55
- Adds schema subset validation (`validateSchema`/`assertSchema`), synthetic test data with LIFO cleanup, scoped concurrency controls, runner-agnostic tag selection, JUnit metadata output, API metrics aggregation and environment configuration with non-destructive defaults. See `docs/ARCHITECTURE.md` and `docs/RELEASE.md`.
18
+ **Add utilities to an existing project:**
56
19
 
57
- **Important:** This is a framework component, not an end-to-end test platform. Full OpenAPI 3.x validation requires an application-approved Ajv/OpenAPI validator. WDIO, Mocha, Allure and GitLab policies live at the project or CI integration layer. Real banking endpoints and GitLab registry publish must be independently verified.
58
-
59
-
60
- ## Additional v0.3.0 capabilities
61
-
62
- - `OpenApiValidator(document, compiler)`: OpenAPI 3.0/3.1 response lookup with a supplied Ajv-compatible JSON Schema compiler; local schema refs supported. This is not a built-in full Ajv distribution.
63
- - `ExecutionContext`: per-run synthetic data, cleanup, bounded in-process account allocation, default-deny mutations.
64
- - `assertRequestPolicy` / `rejectUnsafeEnvironment`: explicit host and mutation controls (wire them into each project's clients).
65
- - `attachSafeMetadata`: allowlisted attachments for Allure integrations; no request/response bodies.
66
- - `MochaResultCollector`: collect test metadata in consuming Mocha hooks; `writeJunit` provides sanitized GitLab-compatible JUnit.
67
- - `CoverageRegistry`: registered scenario and endpoint execution coverage, not discovery of all real services.
68
- - `npm run test:ci`: generates JUnit test results for GitLab.
69
-
70
- ### Verification and limitations
71
-
72
- The 30 local tests cover existing HTTP/auth features and v0.3.0 adapters. Real bank API tests, complete OpenAPI/Ajv dialect behavior, concurrency across separate CI jobs, security penetration testing, package-registry publishing, and actual GitLab pipeline execution remain external integration gates. Do not represent them as completed based on offline unit tests.
73
-
74
- See `docs/ARCHITECTURE.md` and `docs/RELEASE.md`.
20
+ ```bash
21
+ npm install --save-dev @nikhil-qeas/api-core@0.4.0
22
+ ```
75
23
 
24
+ Installing the package does **not** modify your source tree: utilities live under `node_modules`. Run the generator explicitly when you want a new project. The CLI refuses to overwrite an existing directory.
76
25
 
77
- ## GitHub Packages release and installation
26
+ ## Core modules
78
27
 
79
- The published npm package is `@nikhil197610/api-core` (GitHub repository owner is `nikhil197610`). The shared TypeScript API remains unchanged.
28
+ - HTTP client with timeout handling, exact-body signing interface and safe GET retries
29
+ - Token provider and lifecycle manager
30
+ - OpenAPI response-contract adapter (supply a compatible JSON Schema validator)
31
+ - Synthetic test data and cleanup helpers
32
+ - In-process concurrency and execution context
33
+ - JUnit, runner-neutral Mocha result collection and metadata-only Allure adapter
34
+ - Safety policies, coverage registry, simple metrics and data redaction
80
35
 
81
- ### Maintainer: first release
36
+ The library does not bundle Mocha, WDIO, Ajv, OAuth providers, or real application-specific test cases. Configure those in each consuming application as appropriate.
82
37
 
83
- 1. Merge the GitHub Packages publishing pull request into `main`.
84
- 2. Run `npm ci && npm run check && npm run test:ci` from updated `main`.
85
- 3. Confirm repository Actions permissions permit workflows to write packages (the workflow requests `packages: write`).
86
- 4. Tag the verified main commit `v0.3.0` and push it. The tag triggers `.github/workflows/publish.yml`.
87
- 5. Verify the GitHub Actions workflow succeeded and the package appears under GitHub Packages.
38
+ ## Running the core test suite
88
39
 
89
40
  ```bash
90
- git pull origin main
91
- git tag v0.3.0
92
- git push origin v0.3.0
41
+ npm ci
42
+ npm run check
43
+ npm run test:ci
44
+ npm pack --dry-run
93
45
  ```
94
46
 
95
- Never tag an unmerged feature branch, and do not reuse an existing version tag. A failed workflow does not imply successful publication.
47
+ ## Limitations and security
96
48
 
97
- ### Team: install from GitHub Packages
49
+ The generated smoke test runs against a local isolated HTTP server. It does not connect to production systems. Source utilities do not automatically enforce all safety policies: integration code must wire authorization and environment gates before running write-capable requests. Use secret managers and secure runtime configuration; never commit tokens or response bodies to logs.
98
50
 
99
- Create a GitHub Personal Access Token (classic) with `read:packages` and access to this private package. Keep the token in the local environment or an approved secret manager; **never commit a filled .npmrc**.
100
-
101
- ```bash
102
- # In each consuming project:
103
- printf '@nikhil197610:registry=https://npm.pkg.github.com\\n' >> .npmrc
104
- printf '//npm.pkg.github.com/:_authToken=${GH_PACKAGES_TOKEN}\\n' >> .npmrc
105
- npm install --save-dev @nikhil197610/api-core@0.3.0
106
- ```
51
+ This is a public npm distribution. Review package contents and associated documentation before publishing. This version is suitable for a controlled integration pilot; domain-specific workflows and live-system compatibility are verified separately.
107
52
 
108
- The sample `.npmrc` must contain the literal environment placeholder, not an expanded token. Set `GH_PACKAGES_TOKEN` in the shell before installation. For GitLab CI, configure the token as a masked/protected CI variable. Ensure its account is authorized to read the private GitHub package. Use `npm ci` and the committed consumer lockfile for reproducible builds.
53
+ ## Distribution
109
54
 
110
- The GitLab pipelines can install this GitHub-hosted package, but GitLab's `CI_JOB_TOKEN` cannot authenticate directly to GitHub Packages.
55
+ Releases are published manually to public npmjs.org; GitHub Actions payment eligibility is not needed. See `docs/RELEASE.md` in the source repository for release verification and publication instructions.
package/bin/qe-api.js ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ import {existsSync,mkdirSync,writeFileSync} from 'node:fs';
3
+ import {resolve,join,dirname} from 'node:path';
4
+ const args=process.argv.slice(2);
5
+ if(!args.length||args.includes('--help')){console.log('Usage: qe-api init <project-name> [--dir <path>]');process.exit(0);}
6
+ const name=args[1],opt=args.indexOf('--dir');
7
+ if(args[0]!=='init'||!name||!/^[a-z][a-z0-9-]{1,62}$/.test(name)||name.endsWith('-')||name.includes('--')||(opt<0&&args.length!==2)||(opt>=0&&(args.length!==4||!args[opt+1]))){console.error('Invalid arguments. Try: qe-api init my-api');process.exit(2);}
8
+ const dest=resolve(opt<0?name:args[opt+1]);
9
+ if(existsSync(dest)){console.error('Target already exists: '+dest);process.exit(1);}
10
+ const packageJson={name,version:'0.1.0',private:true,type:'module',engines:{node:'>=22.12.0'},scripts:{typecheck:'tsc --noEmit',test:'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.mjs','test:smoke':'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.mjs --grep "@smoke"','test:ci':'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.mjs --reporter mocha-junit-reporter --reporter-options mochaFile=reports/junit/results.xml',check:'npm run typecheck && npm test'},devDependencies:{'@nikhil-qeas/api-core':'^0.4.0','@types/mocha':'^10.0.0','@types/node':'^22.0.0',mocha:'^11.0.0','mocha-junit-reporter':'^2.2.1',tsx:'^4.0.0',typescript:'^5.9.3'}};
11
+ const files={
12
+ 'package.json':JSON.stringify(packageJson,null,2)+'\n',
13
+ 'tsconfig.json':JSON.stringify({compilerOptions:{target:'ES2022',module:'NodeNext',moduleResolution:'NodeNext',strict:true,esModuleInterop:true,types:['node','mocha'],noEmit:true,skipLibCheck:true},include:['src/**/*.ts','tests/**/*.ts']},null,2)+'\n',
14
+ '.gitignore':'node_modules/\nreports/\n.env\n.env.*\n!.env.example\ndist/\n*.tgz\n',
15
+ '.env.example':'QE_ENV=local\nQE_ALLOW_MUTATIONS=false\n# API_BASE_URL=https://test.example.invalid\n',
16
+ 'config/mocha.config.mjs':"export default {extension:['ts'],spec:['tests/**/*.spec.ts'],timeout:30000,recursive:true,reporter:'spec'};\n",
17
+ 'config/environments/.gitkeep':'',
18
+ 'src/config/environment.ts':"export function targetBaseUrl(): string {\n const value=process.env.API_BASE_URL;\n if(!value)throw new Error('API_BASE_URL is required');\n const u=new URL(value);\n if(!['http:','https:'].includes(u.protocol))throw new Error('HTTP(S) required');\n return value;\n}\n",
19
+ 'src/clients/api.ts':"import {ApiClient} from '@nikhil-qeas/api-core';\nimport {targetBaseUrl} from '../config/environment.js';\n/** Add project auth and security approvals before connecting bank endpoints. */\nexport function createApiClient(){return new ApiClient({baseUrl:targetBaseUrl(),timeoutMs:15000,maxSafeRetries:1});}\n",
20
+ 'src/auth/.gitkeep':'','src/contracts/.gitkeep':'','src/data/.gitkeep':'','src/workflows/.gitkeep':'',
21
+ 'tests/fixtures/.gitkeep':'','tests/regression/.gitkeep':'','tests/contract/.gitkeep':'','tests/negative/.gitkeep':'','tests/security/.gitkeep':'','docs/.gitkeep':'','reports/.gitkeep':'',
22
+ 'tests/smoke/health.spec.ts':"import assert from 'node:assert/strict';\nimport {createServer} from 'node:http';\nimport {once} from 'node:events';\nimport {ApiClient,expectStatus} from '@nikhil-qeas/api-core';\ndescribe('@smoke local API core',()=>{it('tests an isolated mock server',async()=>{const server=createServer((_q,res)=>{res.setHeader('content-type','application/json');res.end(JSON.stringify({status:'ok'}));});server.listen(0,'127.0.0.1');try{await once(server,'listening');const addr=server.address();if(!addr||typeof addr==='string')throw Error('No port');const client=new ApiClient({baseUrl:'http://127.0.0.1:'+addr.port});const result=await client.request({method:'GET',path:'/health'});expectStatus(result,200);assert.deepEqual(result.body,{status:'ok'});}finally{server.close();}});});\n",
23
+ '.gitlab-ci.yml':"stages: [verify,test]\nimage: node:22-bookworm-slim\nverify:\n stage: verify\n script:\n - npm ci\n - npm run typecheck\nsmoke:\n stage: test\n script:\n - npm ci\n - npm run test:ci\n artifacts:\n when: always\n reports:\n junit: reports/junit/results.xml\n paths: [reports/junit/]\n",
24
+ 'README.md':'# '+name+'\n\nGenerated API automation project using @nikhil-qeas/api-core.\n\nRun npm install and npm run check. Sample smoke test uses a local mock HTTP server, not a banking environment.\n\nDirectories: src/clients, src/auth, src/contracts, src/data, src/workflows, tests/smoke, tests/regression, tests/contract, tests/negative, tests/security, config, reports, docs.\n\nStore credentials in approved environment secrets, not source control.\n'
25
+ };
26
+ for(const [path,data] of Object.entries(files)){const full=join(dest,path);mkdirSync(dirname(full),{recursive:true});writeFileSync(full,data,{flag:'wx'});}
27
+ console.log('Created '+dest+' ('+Object.keys(files).length+' files). Run npm install && npm run check.');
package/package.json CHANGED
@@ -1,7 +1,6 @@
1
-
2
1
  {
3
2
  "name": "@nikhil-qeas/api-core",
4
- "version": "0.3.0",
3
+ "version": "0.4.0",
5
4
  "description": "Reusable TypeScript API automation core with HTTP, auth, OpenAPI adapter, test isolation, reporting and CI",
6
5
  "private": false,
7
6
  "type": "module",
@@ -18,6 +17,7 @@
18
17
  },
19
18
  "files": [
20
19
  "dist",
20
+ "bin",
21
21
  "README.md"
22
22
  ],
23
23
  "scripts": {
@@ -41,5 +41,8 @@
41
41
  "publishConfig": {
42
42
  "registry": "https://registry.npmjs.org/",
43
43
  "access": "public"
44
+ },
45
+ "bin": {
46
+ "qe-api": "./bin/qe-api.js"
44
47
  }
45
48
  }