{"_id":"@acenecti/naas","name":"@acenecti/naas","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@acenecti/naas","version":"1.0.0","description":"No as a Service - A configurable Express.js middleware that randomly returns errors","main":"index.js","scripts":{"lint":"eslint .","start":"node example/server.js"},"keywords":["express","middleware","naas","saas","no-as-a-service"],"author":{"name":"Acenecti"},"license":"MIT","dependencies":{"@eslint/js":"^9.28.0","express":"^4.18.2"},"devDependencies":{"eslint":"^8.57.1"},"engines":{"node":">=14.0.0"},"repository":{"type":"git","url":"git+https://github.com/acenecti/NaaS.git"},"bugs":{"url":"https://github.com/acenecti/NaaS/issues"},"homepage":"https://github.com/acenecti/NaaS#readme","_id":"@acenecti/naas@1.0.0","gitHead":"05ba42dfdf111ed7738419eb0fcc915b811b18a5","_nodeVersion":"20.12.2","_npmVersion":"9.8.1","dist":{"integrity":"sha512-6mx58S80aPrRh0H6of8PLK7GcDxvLUcs3wZ89g0D2y3iZIYrochL27FqygeNWuRU1uxfyIog7qOVSGY3C4BEdg==","shasum":"38721ec0163d7a7e180b80248820029dcca060c8","tarball":"https://registry.npmjs.org/@acenecti/naas/-/naas-1.0.0.tgz","fileCount":4,"unpackedSize":21214,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCAZwVQqQz5Iy3MEMCyoa4quZNpb7XzeZd328AGkI1bngIgG9yBH2Zu14t3S0O85nBhFx6R4pIfWo98xYUlveLJovg="}]},"_npmUser":{"name":"acenecti","email":"pearlmasam@gmail.com"},"directories":{},"maintainers":[{"name":"acenecti","email":"pearlmasam@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/naas_1.0.0_1748643377709_0.4593638364166994"},"_hasShrinkwrap":false}},"time":{"created":"2025-05-30T22:16:17.641Z","1.0.0":"2025-05-30T22:16:17.947Z","modified":"2025-05-30T22:16:18.211Z"},"maintainers":[{"name":"acenecti","email":"pearlmasam@gmail.com"}],"description":"No as a Service - A configurable Express.js middleware that randomly returns errors","homepage":"https://github.com/acenecti/NaaS#readme","keywords":["express","middleware","naas","saas","no-as-a-service"],"repository":{"type":"git","url":"git+https://github.com/acenecti/NaaS.git"},"author":{"name":"Acenecti"},"bugs":{"url":"https://github.com/acenecti/NaaS/issues"},"license":"MIT","readme":"# NaaS: Express.js Middleware for Chaos Engineering\r\n\r\n[![NPM Version](https://img.shields.io/npm/v/naas.svg)](https://www.npmjs.com/package/naas)\r\n[![Build Status](https://img.shields.io/travis/com/[yourusername]/naas.svg)](https://travis-ci.com/[yourusername]/naas)\r\n[![Coverage Status](https://img.shields.io/coveralls/github/[yourusername]/naas.svg)](https://coveralls.io/github/[yourusername]/naas)\r\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\r\n\r\n**NaaS** is a configurable Express.js middleware developed for chaos engineering practices.\r\n\r\n---\r\n\r\n## Installation\r\n\r\nInstall the package using npm or yarn:\r\n\r\n```bash\r\nnpm install naas\r\n```\r\n\r\nor\r\n\r\n```bash\r\nyarn add naas\r\n```\r\n\r\n---\r\n\r\n## Usage Guide\r\n\r\n### Basic Integration\r\n\r\nThe `createNaaS` factory function provides a straightforward method for integrating the middleware.\r\n\r\n```javascript\r\nconst express = require(\"express\");\r\nconst createNaaS = require(\"naas\"); // or: import { createNaaS } from 'naas';\r\n\r\nconst app = express();\r\n\r\n// Initialize NaaS middleware (default: 10% fault rate)\r\nconst naasMiddleware = createNaaS();\r\n\r\n// Apply middleware globally\r\napp.use(naasMiddleware);\r\n\r\n// Example route\r\napp.get(\"/api/resource\", (req, res) => {\r\n  res.json({ data: \"Resource data, subject to potential fault injection.\" });\r\n});\r\n\r\nconst PORT = process.env.PORT || 3000;\r\napp.listen(PORT, () => {\r\n  console.log(\r\n    `Application server running on port ${PORT}. NaaS middleware active.`\r\n  );\r\n});\r\n```\r\n\r\n### Advanced Integration using the `NaaS` Class\r\n\r\nFor fine-grained control, such as runtime configuration updates, instantiate the `NaaS` class directly.\r\n\r\n```javascript\r\nconst express = require(\"express\");\r\nconst { NaaS } = require(\"naas\"); // or: import { NaaS } from 'naas';\r\n\r\nconst app = express();\r\n\r\nconst naasInstance = new NaaS({\r\n  errorRate: 15, // 15% of targeted requests will experience a fault\r\n  targetRoutes: [\"/api/critical/*\"], // Apply only to routes under /api/critical/\r\n  delays: {\r\n    enabled: true,\r\n    min: 200, // milliseconds\r\n    max: 1500, // milliseconds\r\n    probability: 40, // 40% chance of delay if request is selected for fault\r\n  },\r\n});\r\n\r\n// Apply the middleware instance\r\napp.use(naasInstance.middleware);\r\n\r\napp.get(\"/api/critical/data\", (req, res) => {\r\n  res.json({ status: \"Data retrieved successfully.\" });\r\n});\r\n\r\n// Example: Dynamically updating configuration\r\n// This could be triggered via an internal API or monitoring system\r\nsetTimeout(() => {\r\n  naasInstance.updateConfig({ errorRate: 5 });\r\n  console.log(\"NaaS fault rate adjusted to 5%.\");\r\n}, 120000); // Adjust after 2 minutes\r\n\r\nconst PORT = process.env.PORT || 3000;\r\napp.listen(PORT, () => {\r\n  console.log(\r\n    `Application server with advanced NaaS configuration running on port ${PORT}.`\r\n  );\r\n});\r\n```\r\n\r\n---\r\n\r\n## Configuration Options\r\n\r\nThe middleware is configured by passing an options object to `createNaaS(options)` or `new NaaS(options)`.\r\n\r\n| Option           | Type                      | Default Value                                                                                 | Description                                                                                                                                                           |\r\n| ---------------- | ------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\r\n| `errorRate`      | `number`                  | `10`                                                                                          | The probability (0-100) that a targeted request will result in a fault.                                                                                               |\r\n| `targetRoutes`   | `Array<string \\| RegExp>` | `[]`                                                                                          | Routes to which faults will be applied. Supports string patterns (exact/prefix match) or regular expressions. If empty, applies to all routes not in `excludeRoutes`. |\r\n| `excludeRoutes`  | `Array<string \\| RegExp>` | `[]`                                                                                          | Routes to be exempted from fault injection.                                                                                                                           |\r\n| `targetMethods`  | `Array<string>`           | `[\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"]`                                                   | HTTP methods eligible for fault injection.                                                                                                                            |\r\n| `errors`         | `Array<ErrorObject>`      | See [Default Errors](https://www.google.com/search?q=%23default-errors-configuration)         | A list of error definitions, each with an HTTP status code, message, and selection weight.                                                                            |\r\n| `delays`         | `Object`                  | See [Delay Configuration](https://www.google.com/search?q=%23delay-configuration-details)     | Parameters for injecting latency.                                                                                                                                     |\r\n| `responseFormat` | `string`                  | `\"json\"`                                                                                      | Format for error responses: `\"json\"`, `\"xml\"`, or `\"plain\"`.                                                                                                          |\r\n| `customHeaders`  | `Object`                  | `{}`                                                                                          | Custom HTTP headers to include in error responses.                                                                                                                    |\r\n| `logging`        | `Object`                  | See [Logging Configuration](https://www.google.com/search?q=%23logging-configuration-details) | Settings for the internal logger.                                                                                                                                     |\r\n| `environments`   | `Array<string>`           | `[\"development\", \"testing\", \"production\"]`                                                    | Node.js environments (`process.env.NODE_ENV`) in which the middleware will be active.                                                                                 |\r\n| `customChaos`    | `Array<AsyncFunction>`    | `[]`                                                                                          | Array of user-defined asynchronous functions `(req, res) => Promise<boolean \\| void>` for custom fault logic. A return of `false` halts NaaS processing for the request. |\r\n\r\n### Default `errors` Configuration\r\n\r\n```javascript\r\n[\r\n  { code: 500, message: \"Internal Server Error\", weight: 30 },\r\n  { code: 503, message: \"Service Unavailable\", weight: 25 },\r\n  { code: 502, message: \"Bad Gateway\", weight: 20 },\r\n  { code: 504, message: \"Gateway Timeout\", weight: 10 },\r\n  { code: 429, message: \"Too Many Requests\", weight: 10 },\r\n  { code: 404, message: \"Not Found\", weight: 3 },\r\n  { code: 403, message: \"Forbidden\", weight: 2 },\r\n];\r\n```\r\n\r\n- `code`: HTTP status code.\r\n- `message`: Error message text.\r\n- `weight`: Relative probability influencing the selection of this error.\r\n\r\n### `delays` Configuration Details\r\n\r\n- `enabled` (`boolean`): If `true`, latency injection is active. Default: `true`.\r\n- `min` (`number`): Minimum delay in milliseconds. Default: `100`.\r\n- `max` (`number`): Maximum delay in milliseconds. Default: `5000`.\r\n- `probability` (`number`): Probability (0-100) of applying a delay if the request is selected for a fault and delays are enabled. Default: `30`.\r\n\r\n### `logging` Configuration Details\r\n\r\n- `enabled` (`boolean`): If `true`, NaaS will log its actions. Default: `true`.\r\n- `level` (`string`): Default log level (e.g., \"info\", \"error\"). Default: `\"info\"`.\r\n- `logger` (`Object`): A logger instance (e.g., `console`, Winston) with methods like `.log()`, `.info()`, `.error()`. Default: `console`.\r\n\r\n---\r\n\r\n## API Reference\r\n\r\n### `createNaaS(options?: NaaSConfig): ExpressMiddleware`\r\n\r\nFactory function that instantiates and returns a NaaS middleware configured with the provided options.\r\n\r\n### `NaaS` Class Methods\r\n\r\nAn instance of the `NaaS` class provides the following methods:\r\n\r\n#### `constructor(options?: NaaSConfig)`\r\n\r\nInitializes a new `NaaS` instance with the specified configuration.\r\n\r\n#### `naasInstance.middleware(req, res, next): Promise<void>`\r\n\r\nThe Express.js middleware function to be integrated into the application's request pipeline.\r\n\r\n#### `naasInstance.updateConfig(newConfig: Partial<NaaSConfig>): void`\r\n\r\nDynamically updates the instance's configuration. Unspecified options in `newConfig` retain their current values. The configuration is re-validated after updates.\r\n\r\n#### `naasInstance.getStats(): object`\r\n\r\nReturns an object detailing the current configuration, active `NODE_ENV`, and NaaS version.\r\n\r\n```javascript\r\n{\r\n  config: { /* Current NaaS configuration object */ },\r\n  environment: 'development', // Example value\r\n  version: '1.0.0'\r\n}\r\n```\r\n\r\n#### `naasInstance.disable(): void`\r\n\r\nTemporarily deactivates fault injection by setting `errorRate` to `0`. The original `errorRate` is preserved for potential re-activation.\r\n\r\n#### `naasInstance.enable(): void`\r\n\r\nRestores the `errorRate` to its value prior to `disable()` being called, effectively re-activating fault injection.\r\n\r\n---\r\n\r\n## Example Server Execution\r\n\r\nThe `package.json` includes a script to run an example Express server, typically located at `example/server.js`.\r\n\r\n```bash\r\nnpm start\r\n```\r\n\r\nEnsure `example/server.js` is present and configured to use the NaaS middleware.\r\n\r\n---\r\n\r\n## Development and Testing\r\n\r\n### System Prerequisites\r\n\r\n- Node.js version \\>= 14.0.0\r\n\r\n### Available Scripts\r\n\r\n- **Code Linting:**\r\n  ```bash\r\n  npm run lint\r\n  ```\r\n- **Automated Tests:**\r\n  ```bash\r\n  npm test              # Execute tests\r\n  npm run test:watch    # Execute tests in watch mode for continuous development\r\n  ```\r\n\r\n---\r\n\r\n## Contribution Guidelines\r\n\r\nContributions aimed at improving the functionality and reliability of this tool are welcome. Please adhere to the following process:\r\n\r\n1.  Fork the repository.\r\n2.  Create a new branch for your feature or bug fix (`git checkout -b feature/my-enhancement` or `bugfix/issue-fix`).\r\n3.  Implement your changes and include appropriate tests.\r\n4.  Ensure all tests pass (`npm test`) and linting checks are clean (`npm run lint`).\r\n5.  Commit your changes with clear, descriptive messages.\r\n6.  Push your branch to your fork (`git push origin feature/my-enhancement`).\r\n7.  Submit a pull request to the main repository for review.\r\n\r\n---\r\n\r\n## License\r\n\r\nThis project is licensed under the MIT License. Consult the `LICENSE` file for detailed information.\r\n(Ensure a `LICENSE` file containing the MIT License text is present in your repository.)\r\n\r\n---\r\n\r\n## Issue Reporting and Support\r\n\r\nTo report issues, request features, or seek support, please open an issue on the GitHub repository:\r\n[https://github.com/[yourusername]/naas/issues](https://www.google.com/search?q=https://github.com/%5Byourusername%5D/naas/issues)\r\n","readmeFilename":"README.md","_rev":"1-49e129dc6cb1aa1d47d4b734053ca028"}