@imqueue/rpc 3.2.1 → 3.3.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.
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/rpc",
3
- "version": "3.2.1",
3
+ "version": "3.3.0",
4
4
  "description": "RPC-like client-service implementation over messaging queue",
5
5
  "keywords": [
6
6
  "redis",
@@ -0,0 +1,3 @@
1
+ {
2
+ "signedContributors": []
3
+ }
@@ -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);
@@ -1,3 +1,21 @@
1
+ /**
2
+ * Extracts method JSDoc blocks from original source text of a given class.
3
+ *
4
+ * The text may be TypeScript (type annotations, generics, modifiers,
5
+ * decorators), which acorn cannot parse — so extraction is textual: the
6
+ * search is narrowed to the class region (from the class declaration to the
7
+ * next class declaration or EOF), and each doc block is attributed to the
8
+ * method whose declaration head immediately follows it. When several blocks
9
+ * precede a method, the closest one wins, matching the runtime parser.
10
+ *
11
+ * @param {string} src - source file text (TypeScript or JavaScript)
12
+ * @param {string} className - class to extract method docs for
13
+ * @return {{ [method: string]: string }} - map of method name to raw JSDoc
14
+ * block body (delimiters excluded, as acorn reports comment values)
15
+ */
16
+ export declare function parseSourceComments(src: string, className: string): {
17
+ [method: string]: string;
18
+ };
1
19
  /**
2
20
  * Expose decorator factory. Applied to a service method, it registers that
3
21
  * method in the RPC service description. (Complex argument/return types are
@@ -21,6 +21,8 @@
21
21
  * purchase a proprietary commercial license. Please contact us at
22
22
  * <support@imqueue.com> to get commercial licensing options.
23
23
  */
24
+ import { readFileSync } from 'fs';
25
+ import { fileURLToPath } from 'url';
24
26
  import { parse } from 'acorn';
25
27
  import { IMQRPCDescription, } from '../index.js';
26
28
  const descriptions = {};
@@ -29,10 +31,23 @@ const RX_COMMA_SPLIT = /\s*,\s*/;
29
31
  const RX_MULTILINE_CLEANUP = /\*?\n +\* ?/g;
30
32
  const RX_DESCRIPTION = /^([\s\S]*?)@/;
31
33
  const RX_TAG = /(@[^@]+)/g;
32
- const RX_TYPE = /\{([\s\S]+)\}/;
33
34
  const RX_LI_CLEANUP = /^\s*-\s*/;
34
35
  const RX_SPACE_SPLIT = / /;
35
36
  const RX_OPTIONAL = /^\[(.*?)\]$/;
37
+ // member head that may follow a doc block in original (possibly TypeScript)
38
+ // source: optional decorators and modifiers, then the method name right
39
+ // before its (possibly generic) argument list
40
+ const RX_SOURCE_METHOD = /^\s*(?:@[\w$.]+(?:\([^)]*\))?\s*)*(?:(?:public|protected|private|static|override|abstract|async)\s+)*([\w$]+)\s*(?:<[^>]*>)?\s*\(/;
41
+ const RX_JSDOC_BLOCK = /\/\*\*([\s\S]*?)\*\//g;
42
+ // path of this very module — used to skip own frames during caller capture
43
+ const OWN_PATH = (() => {
44
+ try {
45
+ return fileURLToPath(import.meta.url);
46
+ }
47
+ catch {
48
+ return '';
49
+ }
50
+ })();
36
51
  /**
37
52
  * Lookup and returns a list of argument names for a given function
38
53
  *
@@ -47,6 +62,37 @@ function argumentNames(fn) {
47
62
  .map(arg => arg.trim().replace(RX_ARG_NAMES, '$1'))
48
63
  .filter(arg => arg);
49
64
  }
65
+ /**
66
+ * Extracts a leading JSDoc `{type}` from a tag definition. Braces are matched
67
+ * by depth, so object-literal types (e.g. `{{ x: number }}`) are captured whole
68
+ * and a later `}` in the description cannot extend the captured type. The type,
69
+ * if present, must be the leading token of the definition.
70
+ *
71
+ * @param {string} tagDef - tag definition text following the tag name
72
+ * @return {{ tsType: string, rest: string } | null} - captured type and the
73
+ * remaining definition (name + description), or null when there is no type
74
+ */
75
+ function extractType(tagDef) {
76
+ const start = tagDef.indexOf('{');
77
+ // a type is only a type when it leads the definition; a `{` preceded by
78
+ // any non-whitespace belongs to the description, not to a type
79
+ if (start === -1 || tagDef.slice(0, start).trim() !== '') {
80
+ return null;
81
+ }
82
+ let depth = 0;
83
+ for (let i = start; i < tagDef.length; i++) {
84
+ if (tagDef[i] === '{') {
85
+ depth++;
86
+ }
87
+ else if (tagDef[i] === '}' && --depth === 0) {
88
+ return {
89
+ tsType: tagDef.slice(start + 1, i),
90
+ rest: tagDef.slice(i + 1).trim(),
91
+ };
92
+ }
93
+ }
94
+ return null; // unbalanced braces — treat as having no parseable type
95
+ }
50
96
  /**
51
97
  * Parses given multi-line comment block
52
98
  *
@@ -73,13 +119,12 @@ function parseComment(src) {
73
119
  let parts = tag.split(RX_SPACE_SPLIT);
74
120
  let tagName = parts.shift();
75
121
  let tagDef = parts.join(' ');
76
- let typeMatch = tagDef.match(RX_TYPE);
122
+ let typeInfo = extractType(tagDef);
77
123
  let tsType = '', name = '', description = '', type = '';
78
124
  let isOptional = false;
79
- if (typeMatch) {
80
- tsType = typeMatch[1];
81
- tagDef = tagDef.replace(RX_TYPE, '').trim();
82
- parts = tagDef.split(/ /);
125
+ if (typeInfo) {
126
+ tsType = typeInfo.tsType;
127
+ parts = typeInfo.rest.split(/ /);
83
128
  }
84
129
  name = (parts.shift() || '').replace(RX_LI_CLEANUP, '');
85
130
  description = parts.join(' ').replace(RX_LI_CLEANUP, '');
@@ -188,6 +233,124 @@ function parseDescriptions(name, src) {
188
233
  }
189
234
  }
190
235
  }
236
+ /**
237
+ * Extracts method JSDoc blocks from original source text of a given class.
238
+ *
239
+ * The text may be TypeScript (type annotations, generics, modifiers,
240
+ * decorators), which acorn cannot parse — so extraction is textual: the
241
+ * search is narrowed to the class region (from the class declaration to the
242
+ * next class declaration or EOF), and each doc block is attributed to the
243
+ * method whose declaration head immediately follows it. When several blocks
244
+ * precede a method, the closest one wins, matching the runtime parser.
245
+ *
246
+ * @param {string} src - source file text (TypeScript or JavaScript)
247
+ * @param {string} className - class to extract method docs for
248
+ * @return {{ [method: string]: string }} - map of method name to raw JSDoc
249
+ * block body (delimiters excluded, as acorn reports comment values)
250
+ */
251
+ export function parseSourceComments(src, className) {
252
+ const comments = {};
253
+ const classRx = new RegExp(`\\bclass\\s+${className}\\b`);
254
+ const classMatch = classRx.exec(src);
255
+ if (!classMatch) {
256
+ return comments;
257
+ }
258
+ const start = classMatch.index + classMatch[0].length;
259
+ const nextClass = /\bclass\s+[\w$]+/g;
260
+ nextClass.lastIndex = start;
261
+ const next = nextClass.exec(src);
262
+ const region = src.slice(start, next ? next.index : src.length);
263
+ let match;
264
+ RX_JSDOC_BLOCK.lastIndex = 0;
265
+ while ((match = RX_JSDOC_BLOCK.exec(region))) {
266
+ const head = region
267
+ .slice(match.index + match[0].length)
268
+ .match(RX_SOURCE_METHOD);
269
+ if (head && head[1] !== 'constructor') {
270
+ comments[head[1]] = match[1];
271
+ }
272
+ }
273
+ return comments;
274
+ }
275
+ // per-path cache of source file reads used by the dev-mode fallback;
276
+ // null marks an unreadable path so it is only attempted once
277
+ const sourceFileCache = {};
278
+ /**
279
+ * Reads and caches a source file, returning null when unreadable.
280
+ *
281
+ * @param {string} path - absolute source file path
282
+ * @return {string | null}
283
+ */
284
+ function readSourceFile(path) {
285
+ if (!(path in sourceFileCache)) {
286
+ try {
287
+ sourceFileCache[path] = readFileSync(path, 'utf8');
288
+ }
289
+ catch {
290
+ sourceFileCache[path] = null;
291
+ }
292
+ }
293
+ return sourceFileCache[path];
294
+ }
295
+ /**
296
+ * Captures the file path of the code that invoked the expose() factory —
297
+ * physically the module defining the decorated class. Own and internal
298
+ * frames are skipped. Returns an empty string when no frame is usable
299
+ * (e.g. bundled builds without source maps).
300
+ *
301
+ * @return {string}
302
+ */
303
+ function captureCallerPath() {
304
+ const stack = new Error().stack || '';
305
+ for (const line of stack.split('\n').slice(1)) {
306
+ const match = line.match(/\(?((?:file:\/\/)?[^()\s]+?\.[cm]?[jt]sx?)(?::\d+){0,2}\)?$/);
307
+ if (!match) {
308
+ continue;
309
+ }
310
+ let path = match[1];
311
+ if (path.startsWith('file://')) {
312
+ try {
313
+ path = fileURLToPath(path);
314
+ }
315
+ catch {
316
+ continue;
317
+ }
318
+ }
319
+ if (path === OWN_PATH ||
320
+ path.startsWith('node:') ||
321
+ path.includes('node_modules')) {
322
+ continue;
323
+ }
324
+ return path;
325
+ }
326
+ return '';
327
+ }
328
+ /**
329
+ * Dev-mode fallback: when the runtime class source yields no JSDoc (a
330
+ * comment-stripping transpiler like tsx/esbuild), re-extract method docs
331
+ * from the defining source file on disk. Runtime source always wins when
332
+ * it carries any JSDoc; extraction misses leave methods at their current
333
+ * (untyped) state, so behavior never degrades below the status quo.
334
+ *
335
+ * @param {string} className - class to describe
336
+ * @param {string} sourcePath - captured defining file path
337
+ */
338
+ function applySourceFallback(className, sourcePath) {
339
+ const hasJsdoc = Object.keys(descriptions[className] || {}).some(key => key !== 'inherits');
340
+ if (hasJsdoc || !sourcePath) {
341
+ return;
342
+ }
343
+ const src = readSourceFile(sourcePath);
344
+ if (!src) {
345
+ return;
346
+ }
347
+ const comments = parseSourceComments(src, className);
348
+ for (const method of Object.keys(comments)) {
349
+ descriptions[className][method] = {
350
+ comment: parseComment(comments[method]),
351
+ };
352
+ }
353
+ }
191
354
  /**
192
355
  * Helper function to make easy descriptions parts extractions
193
356
  *
@@ -217,12 +380,18 @@ function get(prop, className, method, defaults) {
217
380
  * @param {Function} ctor - class that declares the method
218
381
  * @param {string} methodName - exposed method name
219
382
  * @param {(...args: any[]) => any} fn - the method implementation
383
+ * @param {string} [sourcePath] - defining file path captured at decoration
220
384
  */
221
- function buildMethodDescription(ctor, methodName, fn) {
385
+ function buildMethodDescription(ctor, methodName, fn, sourcePath) {
222
386
  const className = ctor.name;
223
387
  const argNames = argumentNames(fn);
224
388
  if (!descriptions[className]) {
225
389
  parseDescriptions(className, ctor.toString());
390
+ // dev-mode: a comment-stripping transpiler leaves no JSDoc in the
391
+ // runtime source — recover method docs from the file on disk
392
+ if (sourcePath) {
393
+ applySourceFallback(className, sourcePath);
394
+ }
226
395
  }
227
396
  const args = get('params', className, methodName, []);
228
397
  const ret = get('returns', className, methodName, {
@@ -275,6 +444,10 @@ function buildMethodDescription(ctor, methodName, fn) {
275
444
  * @return {(value: any, context: ClassMethodDecoratorContext) => void}
276
445
  */
277
446
  export function expose() {
447
+ // the factory executes at class-definition time inside the defining
448
+ // module, so the caller frame points at the service source file — used
449
+ // as the dev-mode fallback when runtime comments are stripped
450
+ const sourcePath = captureCallerPath();
278
451
  // Dual-mode: standard (TC39) invocations pass a context object with a
279
452
  // `kind` property; legacy ones pass (target, propertyKey, descriptor).
280
453
  return function exposeDecorator(target, context, descriptor) {
@@ -295,13 +468,13 @@ export function expose() {
295
468
  const ctor = proto
296
469
  ? proto.constructor
297
470
  : this.constructor;
298
- buildMethodDescription(ctor, methodName, value);
471
+ buildMethodDescription(ctor, methodName, value, sourcePath);
299
472
  });
300
473
  return;
301
474
  }
302
475
  // legacy: `target` is the prototype, so its constructor is the class
303
476
  // that declares the method — available immediately at decoration time
304
- buildMethodDescription(target.constructor, String(context), descriptor.value);
477
+ buildMethodDescription(target.constructor, String(context), descriptor.value, sourcePath);
305
478
  return descriptor;
306
479
  };
307
480
  }