@stonyx/rest-server 0.2.1-beta.0 → 0.2.1-beta.2

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.
@@ -0,0 +1,44 @@
1
+ # Improvement Opportunities
2
+
3
+ ## 1. `new express()` in RestServer constructor
4
+
5
+ **File**: `src/main.js`, line 30
6
+
7
+ ```js
8
+ this.api = new express();
9
+ ```
10
+
11
+ Express 5 (which this project targets via `"express": "^5.1.0"`) documents calling `express()` as a plain function, not as a constructor with `new`. While `new express()` works in practice because the function returns a new object regardless, it is unconventional and may break if Express ever enforces non-constructor semantics. Consider changing to:
12
+
13
+ ```js
14
+ this.api = express();
15
+ ```
16
+
17
+ Note: The `Request` class in `src/request.js` line 26 already uses the correct pattern (`const api = express();` without `new`).
18
+
19
+ ## 2. `setupGlobalMiddleware` is `async` but contains no awaits
20
+
21
+ **File**: `src/main.js`, lines 63-70
22
+
23
+ ```js
24
+ async setupGlobalMiddleware() {
25
+ const { origin, methods } = config.restServer;
26
+
27
+ this.api.use([
28
+ cors({ origin, methods }),
29
+ express.json()
30
+ ]);
31
+ }
32
+ ```
33
+
34
+ The `async` keyword is unnecessary here since the method body contains no `await` expressions and `app.use()` is synchronous. The `async` keyword causes the method to return a `Promise` wrapping `undefined`, but the caller (`setupRouter`) does not `await` it either — it calls `this.setupGlobalMiddleware()` without `await` on line 52. Removing `async` would make the intent clearer.
35
+
36
+ ## 3. `logMethod` config option is not used in rest-server source
37
+
38
+ **File**: `config/environment.js`, line 16
39
+
40
+ ```js
41
+ logMethod: 'api'
42
+ ```
43
+
44
+ The `logMethod` property is defined in the default config but is never referenced anywhere in `src/main.js` or `src/request.js`. It is likely consumed by the Stonyx framework core (`stonyx/log`) for registering a named log method, but this should be verified. If it is indeed framework-level plumbing, consider documenting that it is a Stonyx convention rather than a rest-server feature. If it is unused, consider removing it to reduce config surface area.
@@ -0,0 +1,149 @@
1
+ # @stonyx/rest-server — Project Structure
2
+
3
+ ## Overview
4
+
5
+ REST server module for the Stonyx framework. Provides dynamic route registration from a file directory, built-in CORS/JSON middleware, per-route authorization hooks, and a structured `Request` base class for defining handlers.
6
+
7
+ - **Package**: `@stonyx/rest-server` (v0.2.1-beta.1)
8
+ - **License**: Apache-2.0
9
+ - **Entry point**: `src/main.js`
10
+ - **Module type**: ESM (`"type": "module"`)
11
+ - **Node version**: v24.13.0 (per `.nvmrc`)
12
+ - **Package manager**: pnpm
13
+
14
+ ## Architecture
15
+
16
+ ### RestServer (src/main.js)
17
+
18
+ Singleton class wrapping an Express 5 instance.
19
+
20
+ - **Constructor** — enforces singleton via `RestServer.instance`; creates the Express app with `new express()`
21
+ - **`init()`** — calls `setupRouter()`, then starts listening on the configured port
22
+ - **`setupRouter()`** — calls `setupGlobalMiddleware()`, then uses `forEachFileImport` (from `@stonyx/utils/file`) to dynamically import all files in the configured `dir` and mount each as a route via `mountRoute()`. Optionally registers a `/health` endpoint.
23
+ - **`setupGlobalMiddleware()`** — attaches `cors()` and `express.json()` middleware to the Express app
24
+ - **`mountRoute(routeClass, { name, options })`** — instantiates the imported Request subclass, wires up the `authorization` middleware if present, calls `registerCalls()`, and mounts the sub-app at `/<filename>`
25
+ - **`RestServer.close()`** — static method to close the server
26
+
27
+ ### Request (src/request.js)
28
+
29
+ Base class for route definitions. Each file in the requests directory exports a class extending `Request`.
30
+
31
+ - **Constructor** — creates a child Express instance with `x-powered-by` disabled
32
+ - **`handlers`** — instance property: object mapping HTTP methods (`get`, `post`, `put`, `delete`, `patch`) to route-path/handler pairs
33
+ - **`auth(req, state)`** — optional hook. Return an integer status code to reject the request; return nothing to allow it through.
34
+ - **`authorization(req, res, next)`** — wrapper that calls `auth()` and short-circuits with a status response if it returns a code
35
+ - **`registerCalls()`** — iterates `handlers`, registers each route on the child Express instance. Supports:
36
+ - Single handler function or array (last element is the main handler, preceding elements are middleware)
37
+ - Middleware functions are bound to the class instance and executed in order
38
+ - Integer return = status code response (via `sendStatusResponse`)
39
+ - Object return = JSON response
40
+ - `undefined` return = 200 OK
41
+ - Pipe support via `state.pipe` (sets headers and pipes a stream)
42
+ - **`Request.getState(req)`** — attaches/retrieves a `__stonyxState` object on the Express request
43
+ - **`Request.sendStatusResponse(res, status)`** — sends status with optional custom message from `config.restServer.statusMap`
44
+
45
+ Valid HTTP methods (enforced): `get`, `post`, `put`, `delete`, `patch`
46
+
47
+ ## Configuration Reference
48
+
49
+ From `config/environment.js`. All values are overridable via environment variables.
50
+
51
+ | Option | Type | Default | Env Var | Description |
52
+ |---------------------|-------------------|-------------------------------|----------------------------|-----------------------------------------------------------------|
53
+ | `enableHealthCheck` | **Boolean** | `true` | `REST_HEALTH_CHECK_DISABLE=true` to disable | Registers `GET /health` returning 200 |
54
+ | `origin` | **String** | `'*'` | `REST_CORS_ORIGIN` | CORS allowed origin(s) |
55
+ | `methods` | **String** | `'GET,POST,PATCH,PUT,DELETE'` | `REST_CORS_METHODS` | CORS allowed methods |
56
+ | `dir` | **String** | `'./requests'` | `REST_REQUEST_PATH` | Directory containing Request class files to mount as routes |
57
+ | `port` | **Number/String** | `2666` | `REST_PORT` | Port the REST server listens on |
58
+ | `logColor` | **String** | `'yellow'` | — | Console log color for this module (Stonyx logging integration) |
59
+ | `logMethod` | **String** | `'api'` | — | Log method name (Stonyx logging integration) |
60
+
61
+ Additional config used (not rest-server-specific):
62
+ - `config.debug` (top-level Stonyx config) — if truthy, logs errors during route setup
63
+ - `config.restServer.statusMap` (optional, no default in environment.js) — maps status codes to custom message strings
64
+ - `config.restServer.camelCaseRoutes` (optional, no default in environment.js) — when falsy, passes `rawName: true` to `forEachFileImport` so filenames are used as-is for route paths
65
+
66
+ ## Test Structure
67
+
68
+ Tests use **QUnit** and run via `stonyx test` (the `npm test` script).
69
+
70
+ ### test/config/environment.js
71
+ Overrides `restServer.dir` to `'./test/sample/requests'` so tests load sample request classes.
72
+
73
+ ### test/unit/request-test.js
74
+ Unit tests for `Request` static methods:
75
+ - `getState` — creates/returns state object on request
76
+ - `sendStatusResponse` — sends status with optional `statusMap` message
77
+
78
+ ### test/integration/rest-server-test.js
79
+ Integration tests that boot the full server and make HTTP requests:
80
+ - 404 for non-existent routes
81
+ - `/public` — JSON response, 200 OK default, URL params, middleware (success/failure), `this` binding for handlers and middleware
82
+ - `/private` — authenticated success, auth hook rejection (505)
83
+ - `/health` — health check endpoint returns 200
84
+
85
+ ### test/sample/requests/
86
+ Sample Request subclasses used by integration tests:
87
+ - `public.js` — `PublicRequest` with various GET handlers demonstrating middleware, params, binding
88
+ - `private.js` — `PrivateRequest` with `auth()` hook that rejects `/failure` with 505
89
+
90
+ ## CI/CD
91
+
92
+ ### .github/workflows/ci.yml
93
+ Runs on pull requests to `dev` and `main`. Delegates to shared workflow at `abofs/stonyx-workflows`.
94
+
95
+ ### .github/workflows/publish.yml
96
+ Publishes to NPM. Triggered by:
97
+ - `workflow_dispatch` with version-type selection (patch/minor/major) or custom version
98
+ - Pull requests to `main`/`dev`
99
+ - Pushes to `main`
100
+
101
+ Delegates to `abofs/stonyx-workflows/.github/workflows/npm-publish.yml@main`.
102
+
103
+ ## File Structure
104
+
105
+ ```
106
+ stonyx-rest-server/
107
+ ├── .claude/
108
+ │ ├── improvements.md
109
+ │ └── project-structure.md # this file
110
+ ├── .github/
111
+ │ └── workflows/
112
+ │ ├── ci.yml # PR CI — delegates to shared workflow
113
+ │ └── publish.yml # NPM publish — delegates to shared workflow
114
+ ├── config/
115
+ │ └── environment.js # Default config with env var overrides
116
+ ├── src/
117
+ │ ├── main.js # RestServer class (singleton, Express wrapper)
118
+ │ └── request.js # Request base class (handler registration, auth hook)
119
+ ├── test/
120
+ │ ├── config/
121
+ │ │ └── environment.js # Test config override (dir → test/sample/requests)
122
+ │ ├── integration/
123
+ │ │ └── rest-server-test.js # Integration tests (QUnit)
124
+ │ ├── sample/
125
+ │ │ └── requests/
126
+ │ │ ├── private.js # Sample private request with auth hook
127
+ │ │ └── public.js # Sample public request with middleware demos
128
+ │ └── unit/
129
+ │ └── request-test.js # Unit tests for Request statics (QUnit)
130
+ ├── .gitignore
131
+ ├── .npmignore
132
+ ├── .nvmrc # Node v24.13.0
133
+ ├── LICENSE.md # Apache 2.0
134
+ ├── package.json
135
+ ├── pnpm-lock.yaml
136
+ └── README.md
137
+ ```
138
+
139
+ ## Dependencies
140
+
141
+ ### Runtime
142
+ - `cors` ^2.8.5 — CORS middleware
143
+ - `express` ^5.1.0 — HTTP framework
144
+ - `stonyx` (local link) — Framework core (config, logging)
145
+
146
+ ### Dev
147
+ - `@stonyx/utils` (local link) — Utility functions (file import, object helpers)
148
+ - `qunit` ^2.24.1 — Test framework
149
+ - `sinon` ^21.0.0 — Test stubs/spies
@@ -1,6 +1,8 @@
1
1
  name: Publish to NPM
2
2
 
3
3
  on:
4
+ repository_dispatch:
5
+ types: [cascade-publish]
4
6
  workflow_dispatch:
5
7
  inputs:
6
8
  version-type:
@@ -17,10 +19,14 @@ on:
17
19
  type: string
18
20
  pull_request:
19
21
  types: [opened, synchronize, reopened]
20
- branches: [main, dev]
22
+ branches: [main]
21
23
  push:
22
24
  branches: [main]
23
25
 
26
+ concurrency:
27
+ group: ${{ github.event_name == 'repository_dispatch' && 'cascade-update' || format('publish-{0}', github.ref) }}
28
+ cancel-in-progress: false
29
+
24
30
  permissions:
25
31
  contents: write
26
32
  id-token: write
@@ -28,8 +34,18 @@ permissions:
28
34
 
29
35
  jobs:
30
36
  publish:
37
+ if: "!contains(github.event.head_commit.message, '[skip ci]')"
31
38
  uses: abofs/stonyx-workflows/.github/workflows/npm-publish.yml@main
32
39
  with:
33
40
  version-type: ${{ github.event.inputs.version-type }}
34
41
  custom-version: ${{ github.event.inputs.custom-version }}
42
+ cascade-source: ${{ github.event.client_payload.source_package || '' }}
43
+ secrets: inherit
44
+
45
+ cascade:
46
+ needs: publish
47
+ uses: abofs/stonyx-workflows/.github/workflows/cascade.yml@main
48
+ with:
49
+ package-name: ${{ needs.publish.outputs.package-name }}
50
+ published-version: ${{ needs.publish.outputs.published-version }}
35
51
  secrets: inherit
package/README.md CHANGED
@@ -41,16 +41,13 @@ export default {
41
41
  };
42
42
  ```
43
43
 
44
- Then initialize the Stonyx framework, which auto-initializes all of its modules, including `@stonyx/rest-server`:
44
+ Then run the application via the Stonyx CLI, which auto-initializes all modules including the REST server:
45
45
 
46
- ```js
47
- import Stonyx from 'stonyx';
48
- import config from './config/environment.js';
49
-
50
- new Stonyx(config);
46
+ ```bash
47
+ stonyx serve
51
48
  ```
52
49
 
53
- For further framework initialization instructions, see the [Stonyx repository](https://github.com/abofs/stonyx).
50
+ For further framework instructions, see the [Stonyx repository](https://github.com/abofs/stonyx).
54
51
 
55
52
  ### Optional Direct Usage
56
53
 
@@ -72,12 +69,13 @@ Configuration is read from `stonyx/config` under `restServer`:
72
69
 
73
70
  | Option | Type | Default | Description |
74
71
  | :---------------: | :-----------------: | :---------- | :--------------------------------------------------------- |
75
- | `dir` | **String** | `undefined` | Directory containing request classes to mount as routes |
72
+ | `dir` | **String** | `'./requests'` | Directory containing request classes to mount as routes |
76
73
  | `camelCaseRoutes` | **Boolean** | `true` | Convert filenames to camelCase when generating route paths |
77
- | `port` | **Number** | `3000` | Port to listen on |
74
+ | `port` | **Number** | `2666` | Port to listen on |
78
75
  | `origin` | **String \| Array** | `'*'` | CORS origin(s) allowed |
76
+ | `methods` | **String** | `'GET,POST,PATCH,PUT,DELETE'` | CORS allowed methods |
77
+ | `enableHealthCheck` | **Boolean** | `true` | Register `GET /health` endpoint (disable via `REST_HEALTH_CHECK_DISABLE=true`) |
79
78
  | `statusMap` | **Object** | `{}` | Optional mapping of HTTP status codes to custom messages |
80
- | `debug` | **Boolean** | `false` | Enable debug logging during route setup |
81
79
 
82
80
  ## Request Class
83
81
 
@@ -135,10 +133,6 @@ project-root/
135
133
 
136
134
  The `RestServer` will automatically mount these routes using the filenames as paths (`/public` and `/private` by default, or camelCased if configured).
137
135
 
138
- Perfect! Here’s a self-contained **“Example Requests”** section with sample `curl` calls:
139
-
140
- ---
141
-
142
136
  ### Example Requests
143
137
 
144
138
  Assuming you have `public.js` and `private.js` routes mounted, you can test them like this:
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "stonyx-async",
5
5
  "stonyx-module"
6
6
  ],
7
- "version": "0.2.1-beta.0",
7
+ "version": "0.2.1-beta.2",
8
8
  "description": "Rest Server Module for Stonyx Framework",
9
9
  "repository": {
10
10
  "type": "git",
@@ -27,14 +27,14 @@
27
27
  "dependencies": {
28
28
  "cors": "^2.8.5",
29
29
  "express": "^5.1.0",
30
- "stonyx": "^0.2.2"
30
+ "stonyx": "0.2.3-beta.1"
31
31
  },
32
32
  "devDependencies": {
33
- "@stonyx/utils": "^0.2.2",
33
+ "@stonyx/utils": "0.2.3-beta.2",
34
34
  "qunit": "^2.24.1",
35
35
  "sinon": "^21.0.0"
36
36
  },
37
37
  "scripts": {
38
- "test": "qunit --require ./stonyx-bootstrap.cjs"
38
+ "test": "stonyx test"
39
39
  }
40
40
  }
@@ -1,12 +0,0 @@
1
- /**
2
- * commonJS Bootstrap loading - Stonyx must be loaded first, prior to the rest of the application
3
- */
4
- const { default:Stonyx } = require('stonyx');
5
- const { default:config } = require('./config/environment.js');
6
-
7
- // Override dir for tests
8
- config.dir = './test/sample/requests';
9
-
10
- new Stonyx(config, __dirname);
11
-
12
- module.exports = Stonyx;