@nikhil-qeas/api-core 0.3.0 → 0.4.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.
- package/README.md +34 -85
- package/bin/qe-api.js +27 -0
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -1,110 +1,59 @@
|
|
|
1
1
|
# QE API Automation Core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A reusable TypeScript API test utility library and project initializer. Public npm package: `@nikhil-qeas/api-core`.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Two ways to use this package
|
|
6
6
|
|
|
7
|
-
|
|
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
|
-
|
|
10
|
+
npx --yes --package @nikhil-qeas/api-core@0.4.1 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
|
-
|
|
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
|
-
|
|
18
|
+
**Add utilities to an existing project:**
|
|
56
19
|
|
|
57
|
-
|
|
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.1
|
|
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
|
-
##
|
|
26
|
+
## Core modules
|
|
78
27
|
|
|
79
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
91
|
-
|
|
92
|
-
|
|
41
|
+
npm ci
|
|
42
|
+
npm run check
|
|
43
|
+
npm run test:ci
|
|
44
|
+
npm pack --dry-run
|
|
93
45
|
```
|
|
94
46
|
|
|
95
|
-
|
|
47
|
+
## Limitations and security
|
|
96
48
|
|
|
97
|
-
|
|
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
|
-
|
|
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.
|
|
100
52
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
printf '//npm.pkg.github.com/:_authToken=${GH_PACKAGES_TOKEN}\\n' >> .npmrc
|
|
105
|
-
npm install --save-dev @nikhil197610/api-core@0.3.0
|
|
106
|
-
```
|
|
53
|
+
## Distribution
|
|
54
|
+
|
|
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.
|
|
107
56
|
|
|
108
|
-
|
|
57
|
+
## v0.4.1 consumer fix
|
|
109
58
|
|
|
110
|
-
The
|
|
59
|
+
The v0.4.0 generator accidentally supplied an ES module `.mjs` file as a JSON Mocha configuration. v0.4.1 generates `config/mocha.config.json` and points all Mocha scripts to that file. Existing v0.4.0 projects should replace the file and script references or regenerate in a fresh directory. The dependency audit must be checked in each generated project before enterprise use.
|
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.json','test:smoke':'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.json --grep "@smoke"','test:ci':'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.json --reporter mocha-junit-reporter --reporter-options mochaFile=reports/junit/results.xml',check:'npm run typecheck && npm test'},devDependencies:{'@nikhil-qeas/api-core':'^0.4.1','@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.json':JSON.stringify({extension:['ts'],spec:['tests/**/*.spec.ts'],timeout:30000,recursive:true,reporter:'spec'},null,2)+'\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
|
+
"version": "0.4.1",
|
|
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
|
}
|