@imqueue/rpc 3.2.2 → 3.3.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/AGENTS.md ADDED
@@ -0,0 +1,112 @@
1
+ # AGENTS.md — orientation for coding agents
2
+
3
+ This file is for AI coding agents (and humans who like density) working on
4
+ `@imqueue/rpc`. It captures how the codebase is built, tested and structured,
5
+ plus the invariants that are easy to get wrong. Read it before making changes.
6
+ For contribution *process/terms* see [CONTRIBUTING.md](./CONTRIBUTING.md); for
7
+ end-user docs see the [README](./README.md) and https://imqueue.org/.
8
+
9
+ ## What this is
10
+
11
+ `@imqueue/rpc` is the typed RPC layer of the @imqueue framework. It provides the
12
+ abstract base classes and decorators to build **self-describing services** and
13
+ the machinery to **generate strongly-typed clients** from them — all over the
14
+ Redis-backed message queue in [`@imqueue/core`](https://github.com/imqueue/core).
15
+ No service discovery, no load balancer, no hand-written HTTP layer: a service
16
+ describes itself and its client is generated from that description.
17
+
18
+ ## Toolchain & invariants (do not fight these)
19
+
20
+ - **ESM only**, `"type": "module"`. Use `import`, not `require()`. Import
21
+ sibling modules with the **`.js`** extension (NodeNext resolves it to the
22
+ `.ts` source).
23
+ - **TypeScript, `module`/`moduleResolution: nodenext`**, `target: es2024`,
24
+ `verbatimModuleSyntax: true`, `isolatedModules: true`, `strict: true`
25
+ (`strictPropertyInitialization: false`). Use `import type` for type-only
26
+ imports.
27
+ - **Standard (TC39) decorators** — `experimentalDecorators` is **false** and the
28
+ `esnext.decorators` lib is enabled. There is **no `emitDecoratorMetadata`**,
29
+ so there is **no runtime type reflection**.
30
+ - **Types are derived from JSDoc.** Because decorators carry no type metadata,
31
+ the RPC layer parses JSDoc `@param`/`@returns` tags (via `acorn`) to build a
32
+ service's description and its generated client's types. Consequences:
33
+ `removeComments` MUST stay **`false`**, and every exposed method MUST carry
34
+ accurate JSDoc — undocumented params fall back to `any` in generated clients.
35
+ - **Node ≥ 22.12.**
36
+ - Runtime deps: `@imqueue/core`, `acorn` (JSDoc/source parsing for client
37
+ generation), `typescript` (compiling generated clients on the fly).
38
+ - **Lint/format:** `oxlint` + `oxfmt`. Run `npm run format` before committing;
39
+ CI checks `npm run format:check`.
40
+ - Build **emits `.js`/`.d.ts`/`.js.map` next to sources**; **gitignored, not
41
+ committed**. `build` runs `build:deps` (builds `../core` if present) then
42
+ `clean-compiled` then `tsc`.
43
+
44
+ ## Commands
45
+
46
+ ```bash
47
+ npm install
48
+ npm run build # build ../core (if present) + clean + tsc
49
+ npm test # build + node:test over every test/**/*.spec.js
50
+ npm run lint # oxlint
51
+ npm run format # oxfmt (write) | npm run format:check (verify)
52
+ npm run test-coverage # tests + experimental coverage
53
+ ```
54
+
55
+ Tests use the native `node:test` runner with
56
+ `--experimental-test-module-mocks` and preload `./test/warmup.mjs`; timeout is
57
+ 15s. A local Redis on `localhost:6379` is expected for the integration-style
58
+ specs.
59
+
60
+ ## Layout
61
+
62
+ | Path | Role |
63
+ |---|---|
64
+ | `index.ts` | `export * from './src/index.js'` **and** `export * from '@imqueue/core'` — consumers get core's queue API re-exported. |
65
+ | `src/IMQService.ts` | `IMQService` abstract base — extend it and decorate methods with `@expose()`. |
66
+ | `src/IMQClient.ts` | `IMQClient` base + `IMQClient.create()` — generates/compiles/loads a client from a running service's description. |
67
+ | `src/decorators/expose.ts` | `@expose()` — marks a service method remotely callable. |
68
+ | `src/decorators/remote.ts` | `@remote()` — marks a hand-written client method. |
69
+ | `src/decorators/classType.ts`, `property.ts`, `indexed.ts` | Complex-type registration: `@classType()` on the class, `@property('type', optional?)` on fields. |
70
+ | `src/decorators/cache.ts`, `lock.ts`, `logged.ts`, `metadata.ts` | Cross-cutting method decorators. |
71
+ | `src/cache/` (`ICache`, `RedisCache`) | Caching layer for RPC results. |
72
+ | `src/helpers/signature.ts` | JSDoc/source signature extraction (acorn). |
73
+ | `src/IMQRPCDescription.ts`, `IMQRPCRequest.ts`, `IMQRPCResponse.ts`, `IMQRPCError.ts`, `IMQDelay.ts`, `IMQLock.ts`, `IMQMetadata.ts`, `IMQRequestContext.ts` | RPC wire types & context. |
74
+
75
+ ## Authoring rules (behavioural invariants that generated clients depend on)
76
+
77
+ - **Only `@expose()`-decorated methods are remotely callable.** Non-exposed
78
+ methods stay private to the service.
79
+ - **Arguments and return values must be JSON-serializable.**
80
+ - **No spread/rest params on exposed methods** — the generated client will not
81
+ compile. Pass an array instead: `foo(args: any[])`, not `foo(...args: any[])`.
82
+ - **Complex types need `@classType()` on the class** *and* `@property()` on each
83
+ field, or they will not appear in generated clients. `@indexed()` registers
84
+ `@property` fields too.
85
+ - **JSDoc is load-bearing**, not documentation-only (see toolchain note). Keep
86
+ `@param`/`@returns` types accurate.
87
+
88
+ ## Using this package correctly (for consumer-facing code an agent writes)
89
+
90
+ ```typescript
91
+ import { IMQService, expose } from '@imqueue/rpc';
92
+
93
+ export class UserService extends IMQService {
94
+ /**
95
+ * Returns a user by id
96
+ * @param {string} id - user identifier
97
+ * @return {Promise<{ id: string; name: string } | null>}
98
+ */
99
+ @expose()
100
+ public async get(id: string): Promise<{ id: string; name: string } | null> {
101
+ return { id, name: 'Jane Doe' };
102
+ }
103
+ }
104
+ ```
105
+
106
+ Generate the client with `@imqueue/cli` (`imq client generate UserService`) or
107
+ at runtime with `IMQClient.create('UserService')`, then
108
+ `const c = new UserServiceClient(); await c.start(); await c.get('42');`.
109
+
110
+ ## License
111
+
112
+ GPL-3.0. Commercial licensing for closed-source products: https://imqueue.com/.
package/CLAUDE.md ADDED
@@ -0,0 +1,3 @@
1
+ See [AGENTS.md](./AGENTS.md) for build, test, layout and the invariants to
2
+ respect when working on `@imqueue/rpc` (standard TC39 decorators, JSDoc-driven
3
+ types, `@expose()`/`@classType()` rules). End-user docs: https://imqueue.org/.
@@ -0,0 +1,58 @@
1
+ # Contributing to @imqueue
2
+
3
+ Thanks for your interest in improving @imqueue! Contributions of all kinds are
4
+ welcome — bug fixes, features, tests, and documentation.
5
+
6
+ ## Contribution terms — please read first
7
+
8
+ @imqueue is **dual-licensed**: it is free to everyone under **GPL-3.0**, and it is
9
+ also offered under **commercial licenses** for closed-source use. To make that
10
+ sustainable, contributions are accepted under the
11
+ **[@imqueue Contribution Terms](./CONTRIBUTION-TERMS.md)**.
12
+
13
+ **By opening a pull request — or otherwise contributing — you agree to those
14
+ terms.** In short:
15
+
16
+ - You **keep the copyright** in your contribution.
17
+ - Your contribution stays available to everyone under **GPL-3.0**.
18
+ - You grant the project owner the right to **also license your contribution
19
+ commercially**, royalty-free — you will not receive a fee for it.
20
+
21
+ **If you do not agree, please do not contribute.** Read the full text in
22
+ [CONTRIBUTION-TERMS.md](./CONTRIBUTION-TERMS.md).
23
+
24
+ ## How to contribute
25
+
26
+ 1. **Open an issue first** for anything non-trivial, so we can agree on the
27
+ approach before you invest time.
28
+ 2. **Fork** the repository and create a topic branch from `master`
29
+ (e.g. `fix/redis-reconnect` or `feat/lock-timeout`).
30
+ 3. **Make your change**, following the existing code style. Keep pull requests
31
+ focused — one logical change per PR.
32
+ 4. **Add or update tests** so the change is covered, and make sure the full suite
33
+ passes locally:
34
+ ```bash
35
+ npm ci
36
+ npm test
37
+ ```
38
+ 5. **Write clear commit messages** and a descriptive PR title and summary.
39
+ 6. **Open the pull request** against `master` and fill in the PR template,
40
+ including the contribution-terms checkbox.
41
+
42
+ ## Guidelines
43
+
44
+ - Match the existing TypeScript style and formatting already used in the file you
45
+ are editing.
46
+ - Keep public API changes documented (doc-blocks / README as appropriate).
47
+ - Be respectful and constructive in reviews and discussions.
48
+
49
+ ## Reporting security issues
50
+
51
+ Please **do not** open a public issue for security vulnerabilities. Report them
52
+ privately to the maintainers (see the repository's security policy or contact
53
+ address) so they can be addressed responsibly.
54
+
55
+ ---
56
+
57
+ Questions about the terms or a larger/corporate contribution? Reach out before you
58
+ start and we'll help.
@@ -0,0 +1,79 @@
1
+ # @imqueue Contribution Terms (v1.0)
2
+
3
+ These terms apply to every contribution to any repository of the **@imqueue**
4
+ project — the packages published under the `@imqueue` npm scope and any repository
5
+ in the imqueue GitHub organisation.
6
+
7
+ **By submitting a contribution — opening a pull request, pushing a commit, sending
8
+ a patch, or otherwise offering work for inclusion — you accept these terms in
9
+ full. If you do not agree with them, do not contribute.**
10
+
11
+ In these terms, **"Owner"** means Mykhailo Stadnyk, together with his successors,
12
+ assigns and any entity he controls (including VaryLogic s.r.o.), and
13
+ **"Contribution"** means any work of authorship — code, documentation or other
14
+ material — you submit to an @imqueue repository.
15
+
16
+ ## 1. What you grant
17
+
18
+ You grant the Owner a **perpetual, worldwide, irrevocable, royalty-free,
19
+ non-exclusive, transferable and sublicensable** license to use, reproduce,
20
+ modify, adapt, publish, distribute and otherwise exploit your Contribution and
21
+ derivative works of it, **and to license and sub-license it under any terms the
22
+ Owner chooses — including commercial and proprietary (closed-source) licenses,
23
+ without any obligation to release source code.**
24
+
25
+ In plain terms: the Owner may include your Contribution in @imqueue and **sell
26
+ commercial licenses that cover it**, alongside the open-source edition.
27
+
28
+ ## 2. No royalties, fees or compensation
29
+
30
+ The rights above are granted **free of charge**. You **waive** any right to
31
+ royalties, license fees, revenue share or any other compensation arising from the
32
+ Owner's use or licensing of your Contribution, including its commercial licensing,
33
+ and you agree not to seek any such payment now or in the future.
34
+
35
+ ## 3. You keep your copyright
36
+
37
+ You **retain ownership** of the copyright in your Contribution and may use it
38
+ elsewhere for your own purposes. You are granting the Owner the rights in Section
39
+ 1 — you are not required to transfer ownership. Your Contribution also remains
40
+ available to the public under the repository's open-source license (GPL-3.0).
41
+
42
+ ## 4. Patent license
43
+
44
+ You grant the Owner and all downstream recipients a perpetual, worldwide,
45
+ royalty-free, irrevocable (except as stated) patent license to make, use, sell,
46
+ offer to sell, import and transfer your Contribution, limited to the patent claims
47
+ you can license that are necessarily infringed by your Contribution alone or in
48
+ combination with the project. If you start patent litigation alleging the project
49
+ or your Contribution infringes your patents, the patent license you received
50
+ terminates.
51
+
52
+ ## 5. Your promises
53
+
54
+ You confirm that: (a) the Contribution is your own original work, or you have the
55
+ right to submit it and to grant these rights; (b) if your employer has any rights
56
+ in your work, you have their permission to contribute, or they have waived those
57
+ rights; and (c) you have identified any third-party material in your Contribution
58
+ and its license.
59
+
60
+ ## 6. Moral rights
61
+
62
+ To the maximum extent permitted by applicable law, you waive, or agree not to
63
+ exercise, any moral rights in your Contribution in a way that would prevent the
64
+ Owner from exercising the rights in Section 1. (Certain moral rights are
65
+ inalienable under Slovak/EU law; nothing here purports to transfer those.)
66
+
67
+ ## 7. No obligation; "as is"
68
+
69
+ The Owner is under no obligation to use your Contribution. It is provided **"as
70
+ is"**, without warranty of any kind.
71
+
72
+ ## 8. Governing law
73
+
74
+ These terms are governed by the laws of the Slovak Republic, without regard to its
75
+ conflict-of-laws rules.
76
+
77
+ ---
78
+
79
+ **If you do not agree to all of the above, do not contribute to @imqueue.**
package/README.md CHANGED
@@ -6,6 +6,16 @@ RPC-like client-service implementation over messaging queue. This module
6
6
  provides base set of abstract classes and decorators to build services and
7
7
  clients for them.
8
8
 
9
+ **Documentation:** full guides, tutorial and API reference at
10
+ [imqueue.org](https://imqueue.org/). Commercial licensing & support for
11
+ closed-source products at [imqueue.com](https://imqueue.com/). Related packages:
12
+ [@imqueue/core](https://github.com/imqueue/core) (the message queue this builds
13
+ on) and [@imqueue/cli](https://github.com/imqueue/cli) (scaffolding & client
14
+ generation).
15
+
16
+ **Using an AI assistant?** Point it at [imqueue.org/llms.txt](https://imqueue.org/llms.txt)
17
+ for a machine-readable index of the docs, or see [AGENTS.md](./AGENTS.md).
18
+
9
19
  ## Why?
10
20
 
11
21
  To provide fast and reliable way of communication between backend services.
package/SECURITY.md ADDED
@@ -0,0 +1,40 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ If you believe you have found a security vulnerability in **@imqueue/rpc** (or any
6
+ `@imqueue/*` package), please report it **privately** — do not open a public issue,
7
+ pull request, or discussion for it.
8
+
9
+ Two private channels:
10
+
11
+ - **GitHub** — use *Security → Report a vulnerability* on this repository to open a
12
+ private advisory (preferred; it keeps the report and the fix coordinated in one
13
+ place).
14
+ - **Email** — <support@imqueue.com> with the details below.
15
+
16
+ Please include:
17
+
18
+ - the affected package and version(s);
19
+ - a description of the issue and its impact;
20
+ - steps to reproduce, or a proof of concept, where possible.
21
+
22
+ ## What to expect
23
+
24
+ - We aim to acknowledge a report within a few business days.
25
+ - We'll confirm the issue, keep you updated on progress, and coordinate a fix and a
26
+ disclosure timeline with you.
27
+ - Once a fix is released we'll credit the reporter in the advisory unless you prefer
28
+ to remain anonymous.
29
+
30
+ ## Supported versions
31
+
32
+ Security fixes land on the latest published release line of each `@imqueue/*`
33
+ package on npm. Please make sure you can reproduce an issue against the current
34
+ release before reporting.
35
+
36
+ ## Scope
37
+
38
+ The `@imqueue` framework is open source under GPL-3.0. This policy covers the code
39
+ in the `@imqueue/*` packages. Vulnerabilities in third-party dependencies should be
40
+ reported to those projects, though we're glad to help coordinate an upgrade.
package/context7.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "https://context7.com/schema/context7.json",
3
+ "projectTitle": "@imqueue/rpc",
4
+ "description": "Type-safe RPC framework for Node.js & TypeScript microservices over a Redis message queue — self-describing services generate their own strongly-typed clients.",
5
+ "excludeFolders": ["src", "lib", "node_modules", "test", "tests", "coverage", "docs/api"],
6
+ "excludeFiles": ["CHANGELOG.md", "LICENSE"],
7
+ "rules": [
8
+ "Define a service as a class extending IMQService and mark callable methods with the @expose() decorator.",
9
+ "JSDoc on exposed methods is the type source — the client is generated from the running service, not hand-written.",
10
+ "Generate the typed client with the imq CLI: `imq client generate <ServiceName>`.",
11
+ "Correlation, timeouts, at-least-once delivery and serialization are handled by the library, not your service code.",
12
+ "@imqueue is GPL-3.0; a commercial license is available for closed-source use (see imqueue.com/license)."
13
+ ]
14
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@imqueue/rpc",
3
- "version": "3.2.2",
4
- "description": "RPC-like client-service implementation over messaging queue",
3
+ "version": "3.3.1",
4
+ "description": "Type-safe RPC framework for Node.js & TypeScript microservices over a Redis message queue — self-describing services generate their own strongly-typed clients (@imqueue framework)",
5
5
  "keywords": [
6
6
  "redis",
7
7
  "redis-queue",
@@ -10,7 +10,14 @@
10
10
  "service",
11
11
  "rpc-service",
12
12
  "rpc",
13
- "message-queue"
13
+ "message-queue",
14
+ "typescript",
15
+ "nodejs",
16
+ "microservices",
17
+ "typed-rpc",
18
+ "soa",
19
+ "inter-service-communication",
20
+ "imqueue"
14
21
  ],
15
22
  "scripts": {
16
23
  "clean-compiled": "npm run clean-js && npm run clean-typedefs && npm run clean-maps",
@@ -39,7 +46,8 @@
39
46
  "bugs": {
40
47
  "url": "https://github.com/imqueue/rpc/issues"
41
48
  },
42
- "homepage": "https://imqueue.com/",
49
+ "homepage": "https://imqueue.org/",
50
+ "funding": "https://imqueue.com/",
43
51
  "author": "imqueue.com <support@imqueue.com> (https://imqueue.com)",
44
52
  "license": "GPL-3.0-only",
45
53
  "dependencies": {
@@ -0,0 +1,3 @@
1
+ {
2
+ "signedContributors": []
3
+ }
package/src/IMQClient.js CHANGED
@@ -181,6 +181,13 @@ let IMQClient = (() => {
181
181
  if (!isFinite(delay) || isNaN(delay) || delay < 0) {
182
182
  delay = 0;
183
183
  }
184
+ // The metadata slot sits between the declared arguments and the
185
+ // delay, so callers who only need a delay may skip it with an
186
+ // explicit `undefined`. Drop it here, or it would travel on as a
187
+ // real call argument and break the service-side args count check.
188
+ if (args.length && args[args.length - 1] === undefined) {
189
+ args.pop();
190
+ }
184
191
  }
185
192
  if (args[args.length - 1] instanceof IMQMetadata) {
186
193
  metadata = args.pop();
@@ -537,8 +544,11 @@ export namespace ${namespaceName} {\n`;
537
544
  },
538
545
  ];
539
546
  let retType = ret.tsType.replace(/\r?\n/g, ' ').replace(/\s{2,}/g, ' ');
540
- for (let i = 1; i <= 2; i++) {
541
- const arg = args[args.length - i];
547
+ // drop framework args the service declared itself, so that they are not
548
+ // duplicated by the canonical pair appended below; the last element is
549
+ // re-read on every pass, as the array shrinks as they are removed
550
+ for (let i = 0; i < addArgs.length; i++) {
551
+ const arg = args[args.length - 1];
542
552
  if (arg && ~['IMQDelay', 'IMQMetadata'].indexOf(arg.type)) {
543
553
  args.pop(); // remove it
544
554
  }
@@ -46,6 +46,23 @@ export interface IMQBeforeCall<_T> {
46
46
  export interface IMQAfterCall<_T> {
47
47
  (req: IMQRPCRequest, res?: IMQRPCResponse): Promise<void>;
48
48
  }
49
+ /**
50
+ * Around hook wrapping the actual service method invocation. It receives the
51
+ * request/response and a `next` callback that runs the method and resolves to
52
+ * its return value; it MUST call `next()` (returning its resolved value) to
53
+ * produce the response data. Unlike `beforeCall`/`afterCall`, this lets a hook
54
+ * run the method inside its own scope — e.g. establishing an OpenTelemetry
55
+ * context so any spans the method (and its downstream calls) create nest under
56
+ * the request span. When unset, the method is invoked directly.
57
+ *
58
+ * @param {IMQRPCRequest} req - the incoming request
59
+ * @param {IMQRPCResponse} res - the response being prepared
60
+ * @param {() => Promise<any>} next - runs the method, resolves to its result
61
+ * @return {Promise<any>} - the value to use as the response data
62
+ */
63
+ export interface IMQWrapCall<_T> {
64
+ (req: IMQRPCRequest, res: IMQRPCResponse, next: () => Promise<any>): Promise<any>;
65
+ }
49
66
  /**
50
67
  * Options for the built-in metrics server.
51
68
  */
@@ -63,6 +80,7 @@ export interface IMQServiceOptions extends IMQOptions {
63
80
  metricsServer?: IMQMetricsServerOptions;
64
81
  beforeCall?: IMQBeforeCall<IMQService>;
65
82
  afterCall?: IMQAfterCall<IMQService>;
83
+ wrapCall?: IMQWrapCall<IMQService>;
66
84
  }
67
85
  /**
68
86
  * Options accepted by a generated IMQ client.
package/src/IMQService.js CHANGED
@@ -223,10 +223,19 @@ let IMQService = (() => {
223
223
  return await send(request, response, this);
224
224
  }
225
225
  try {
226
- response.data = this[method].apply(this, args);
227
- if (response.data && response.data.then) {
228
- response.data = await response.data;
229
- }
226
+ // Run the method through the optional `wrapCall` around-hook so a
227
+ // hook can execute it within its own scope (e.g. an OpenTelemetry
228
+ // context). Without a hook the method is invoked directly, exactly
229
+ // as before.
230
+ const invoke = async () => {
231
+ const result = this[method].apply(this, args);
232
+ return result && result.then ? await result : result;
233
+ };
234
+ const wrapCall = this.options.wrapCall;
235
+ response.data =
236
+ typeof wrapCall === 'function'
237
+ ? await wrapCall.call(this, request, response, invoke)
238
+ : await invoke();
230
239
  }
231
240
  catch (err) {
232
241
  response.error = IMQError(err.code || 'IMQ_RPC_CALL_ERROR', err.message, err.stack, method, args, err);