@zero-server/sdk 0.9.1 → 0.9.3

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.
Files changed (128) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/body.d.ts +14 -0
  113. package/types/cli.d.ts +2 -0
  114. package/types/cluster.d.ts +75 -75
  115. package/types/env.d.ts +80 -80
  116. package/types/errors.d.ts +316 -316
  117. package/types/fetch.d.ts +43 -43
  118. package/types/grpc.d.ts +432 -432
  119. package/types/index.d.ts +384 -384
  120. package/types/lifecycle.d.ts +60 -60
  121. package/types/middleware.d.ts +320 -320
  122. package/types/observe.d.ts +304 -304
  123. package/types/orm.d.ts +1887 -1887
  124. package/types/request.d.ts +109 -109
  125. package/types/response.d.ts +157 -157
  126. package/types/router.d.ts +78 -78
  127. package/types/sse.d.ts +78 -78
  128. package/types/websocket.d.ts +126 -126
@@ -1,118 +1,118 @@
1
- /**
2
- * @module grpc/status
3
- * @description Standard gRPC status codes (as defined by the gRPC specification).
4
- * Each code has a numeric value, a name, and a human-readable description.
5
- * Used by both server and client to communicate call outcomes via trailers.
6
- *
7
- * @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html
8
- */
9
-
10
- const log = require('../debug')('zero:grpc');
11
-
12
- // -- Status Codes ------------------------------------------
13
-
14
- /**
15
- * gRPC status code enum. Mirrors the canonical codes from the gRPC spec.
16
- *
17
- * @enum {number}
18
- *
19
- * @example
20
- * const { GrpcStatus } = require('@zero-server/sdk');
21
- * call.sendError(GrpcStatus.NOT_FOUND, 'User not found');
22
- */
23
- const GrpcStatus = {
24
- /** The operation completed successfully. */
25
- OK: 0,
26
- /** The operation was cancelled (typically by the caller). */
27
- CANCELLED: 1,
28
- /** Unknown error — a catch-all for unexpected failures. */
29
- UNKNOWN: 2,
30
- /** The client specified an invalid argument. */
31
- INVALID_ARGUMENT: 3,
32
- /** The deadline expired before the operation could complete. */
33
- DEADLINE_EXCEEDED: 4,
34
- /** The requested entity was not found. */
35
- NOT_FOUND: 5,
36
- /** The entity that a client attempted to create already exists. */
37
- ALREADY_EXISTS: 6,
38
- /** The caller does not have permission to execute the operation. */
39
- PERMISSION_DENIED: 7,
40
- /** Some resource has been exhausted (e.g. quota, disk space). */
41
- RESOURCE_EXHAUSTED: 8,
42
- /** The operation was rejected because the system is not in a required state. */
43
- FAILED_PRECONDITION: 9,
44
- /** The operation was aborted, typically due to a concurrency conflict. */
45
- ABORTED: 10,
46
- /** The operation was attempted past the valid range. */
47
- OUT_OF_RANGE: 11,
48
- /** The operation is not implemented or not supported. */
49
- UNIMPLEMENTED: 12,
50
- /** Internal error — invariants expected by the server have been broken. */
51
- INTERNAL: 13,
52
- /** The service is currently unavailable, usually a transient condition. */
53
- UNAVAILABLE: 14,
54
- /** Unrecoverable data loss or corruption. */
55
- DATA_LOSS: 15,
56
- /** The request does not have valid authentication credentials. */
57
- UNAUTHENTICATED: 16,
58
- };
59
-
60
- /**
61
- * Reverse lookup: number → string name.
62
- * @type {Object<number, string>}
63
- */
64
- const STATUS_NAMES = {};
65
- for (const [name, code] of Object.entries(GrpcStatus))
66
- {
67
- STATUS_NAMES[code] = name;
68
- }
69
-
70
- /**
71
- * Map gRPC status code to the appropriate HTTP/2 status code for trailers-only responses.
72
- *
73
- * @param {number} grpcCode - gRPC status code.
74
- * @returns {number} Corresponding HTTP status code.
75
- */
76
- function grpcToHttp(grpcCode)
77
- {
78
- switch (grpcCode)
79
- {
80
- case GrpcStatus.OK: return 200;
81
- case GrpcStatus.INVALID_ARGUMENT: return 400;
82
- case GrpcStatus.FAILED_PRECONDITION: return 400;
83
- case GrpcStatus.OUT_OF_RANGE: return 400;
84
- case GrpcStatus.UNAUTHENTICATED: return 401;
85
- case GrpcStatus.PERMISSION_DENIED: return 403;
86
- case GrpcStatus.NOT_FOUND: return 404;
87
- case GrpcStatus.ALREADY_EXISTS: return 409;
88
- case GrpcStatus.ABORTED: return 409;
89
- case GrpcStatus.RESOURCE_EXHAUSTED: return 429;
90
- case GrpcStatus.CANCELLED: return 499;
91
- case GrpcStatus.UNIMPLEMENTED: return 501;
92
- case GrpcStatus.UNAVAILABLE: return 503;
93
- case GrpcStatus.DEADLINE_EXCEEDED: return 504;
94
- case GrpcStatus.UNKNOWN:
95
- case GrpcStatus.INTERNAL:
96
- case GrpcStatus.DATA_LOSS:
97
- default:
98
- return 500;
99
- }
100
- }
101
-
102
- /**
103
- * Get the human-readable name for a gRPC status code.
104
- *
105
- * @param {number} code - gRPC status code.
106
- * @returns {string} Status name or 'UNKNOWN'.
107
- */
108
- function statusName(code)
109
- {
110
- return STATUS_NAMES[code] || 'UNKNOWN';
111
- }
112
-
113
- module.exports = {
114
- GrpcStatus,
115
- STATUS_NAMES,
116
- grpcToHttp,
117
- statusName,
118
- };
1
+ /**
2
+ * @module grpc/status
3
+ * @description Standard gRPC status codes (as defined by the gRPC specification).
4
+ * Each code has a numeric value, a name, and a human-readable description.
5
+ * Used by both server and client to communicate call outcomes via trailers.
6
+ *
7
+ * @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html
8
+ */
9
+
10
+ const log = require('../debug')('zero:grpc');
11
+
12
+ // -- Status Codes ------------------------------------------
13
+
14
+ /**
15
+ * gRPC status code enum. Mirrors the canonical codes from the gRPC spec.
16
+ *
17
+ * @enum {number}
18
+ *
19
+ * @example
20
+ * const { GrpcStatus } = require('@zero-server/sdk');
21
+ * call.sendError(GrpcStatus.NOT_FOUND, 'User not found');
22
+ */
23
+ const GrpcStatus = {
24
+ /** The operation completed successfully. */
25
+ OK: 0,
26
+ /** The operation was cancelled (typically by the caller). */
27
+ CANCELLED: 1,
28
+ /** Unknown error — a catch-all for unexpected failures. */
29
+ UNKNOWN: 2,
30
+ /** The client specified an invalid argument. */
31
+ INVALID_ARGUMENT: 3,
32
+ /** The deadline expired before the operation could complete. */
33
+ DEADLINE_EXCEEDED: 4,
34
+ /** The requested entity was not found. */
35
+ NOT_FOUND: 5,
36
+ /** The entity that a client attempted to create already exists. */
37
+ ALREADY_EXISTS: 6,
38
+ /** The caller does not have permission to execute the operation. */
39
+ PERMISSION_DENIED: 7,
40
+ /** Some resource has been exhausted (e.g. quota, disk space). */
41
+ RESOURCE_EXHAUSTED: 8,
42
+ /** The operation was rejected because the system is not in a required state. */
43
+ FAILED_PRECONDITION: 9,
44
+ /** The operation was aborted, typically due to a concurrency conflict. */
45
+ ABORTED: 10,
46
+ /** The operation was attempted past the valid range. */
47
+ OUT_OF_RANGE: 11,
48
+ /** The operation is not implemented or not supported. */
49
+ UNIMPLEMENTED: 12,
50
+ /** Internal error — invariants expected by the server have been broken. */
51
+ INTERNAL: 13,
52
+ /** The service is currently unavailable, usually a transient condition. */
53
+ UNAVAILABLE: 14,
54
+ /** Unrecoverable data loss or corruption. */
55
+ DATA_LOSS: 15,
56
+ /** The request does not have valid authentication credentials. */
57
+ UNAUTHENTICATED: 16,
58
+ };
59
+
60
+ /**
61
+ * Reverse lookup: number → string name.
62
+ * @type {Object<number, string>}
63
+ */
64
+ const STATUS_NAMES = {};
65
+ for (const [name, code] of Object.entries(GrpcStatus))
66
+ {
67
+ STATUS_NAMES[code] = name;
68
+ }
69
+
70
+ /**
71
+ * Map gRPC status code to the appropriate HTTP/2 status code for trailers-only responses.
72
+ *
73
+ * @param {number} grpcCode - gRPC status code.
74
+ * @returns {number} Corresponding HTTP status code.
75
+ */
76
+ function grpcToHttp(grpcCode)
77
+ {
78
+ switch (grpcCode)
79
+ {
80
+ case GrpcStatus.OK: return 200;
81
+ case GrpcStatus.INVALID_ARGUMENT: return 400;
82
+ case GrpcStatus.FAILED_PRECONDITION: return 400;
83
+ case GrpcStatus.OUT_OF_RANGE: return 400;
84
+ case GrpcStatus.UNAUTHENTICATED: return 401;
85
+ case GrpcStatus.PERMISSION_DENIED: return 403;
86
+ case GrpcStatus.NOT_FOUND: return 404;
87
+ case GrpcStatus.ALREADY_EXISTS: return 409;
88
+ case GrpcStatus.ABORTED: return 409;
89
+ case GrpcStatus.RESOURCE_EXHAUSTED: return 429;
90
+ case GrpcStatus.CANCELLED: return 499;
91
+ case GrpcStatus.UNIMPLEMENTED: return 501;
92
+ case GrpcStatus.UNAVAILABLE: return 503;
93
+ case GrpcStatus.DEADLINE_EXCEEDED: return 504;
94
+ case GrpcStatus.UNKNOWN:
95
+ case GrpcStatus.INTERNAL:
96
+ case GrpcStatus.DATA_LOSS:
97
+ default:
98
+ return 500;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Get the human-readable name for a gRPC status code.
104
+ *
105
+ * @param {number} code - gRPC status code.
106
+ * @returns {string} Status name or 'UNKNOWN'.
107
+ */
108
+ function statusName(code)
109
+ {
110
+ return STATUS_NAMES[code] || 'UNKNOWN';
111
+ }
112
+
113
+ module.exports = {
114
+ GrpcStatus,
115
+ STATUS_NAMES,
116
+ grpcToHttp,
117
+ statusName,
118
+ };
package/lib/grpc/watch.js CHANGED
@@ -1,173 +1,173 @@
1
- /**
2
- * @module grpc/watch
3
- * @description Proto file hot-reload for development.
4
- * Watches `.proto` files for changes using `fs.watch()` and
5
- * re-parses/re-registers gRPC services automatically.
6
- *
7
- * **Dev-only** — disabled by default when `NODE_ENV=production`.
8
- *
9
- * @example
10
- * const { createApp, watchProto } = require('@zero-server/sdk');
11
- * const app = createApp();
12
- *
13
- * watchProto(app, './protos/greeter.proto', 'Greeter', handlers, {
14
- * onReload: (schema) => console.log('Reloaded!'),
15
- * });
16
- *
17
- * app.listen(50051, { http2: true });
18
- */
19
-
20
- const fs = require('fs');
21
- const path = require('path');
22
- const log = require('../debug')('zero:grpc:watch');
23
-
24
- // Lazy-load proto parser
25
- let _parseProtoFile = null;
26
- function _getParser()
27
- {
28
- if (!_parseProtoFile) _parseProtoFile = require('./proto').parseProtoFile;
29
- return _parseProtoFile;
30
- }
31
-
32
- // -- Constants ---------------------------------------------------
33
-
34
- const DEFAULT_DEBOUNCE = 300; // ms
35
-
36
- // -- watchProto --------------------------------------------------
37
-
38
- /**
39
- * Watch a `.proto` file and hot-reload the gRPC service on changes.
40
- * Parses the file, registers the service, then watches for modifications.
41
- *
42
- * Disabled in production unless `opts.production` is `true`.
43
- *
44
- * @param {object} app - The zero-server App instance.
45
- * @param {string} protoPath - Path to the `.proto` file.
46
- * @param {string} serviceName - Service name to register.
47
- * @param {Object<string, Function>} handlers - Method handlers map.
48
- * @param {object} [opts] - Options.
49
- * @param {Function[]} [opts.interceptors] - Per-service interceptors.
50
- * @param {number} [opts.maxMessageSize] - Max incoming message size.
51
- * @param {boolean} [opts.compress=false] - Compress outgoing messages.
52
- * @param {number} [opts.debounce=300] - Debounce interval in ms.
53
- * @param {boolean} [opts.production=false] - Allow in production.
54
- * @param {Function} [opts.onReload] - `(schema) => void` callback after reload.
55
- * @param {Function} [opts.onError] - `(err) => void` callback on parse/reload error.
56
- * @returns {{ stop: () => void, schema: object }} Controller with `stop()` and current schema.
57
- *
58
- * @example
59
- * const watcher = watchProto(app, './hello.proto', 'Greeter', {
60
- * SayHello(call) { return { message: 'Hello ' + call.request.name }; },
61
- * });
62
- * // Later: watcher.stop();
63
- */
64
- function watchProto(app, protoPath, serviceName, handlers, opts = {})
65
- {
66
- if (!opts.production && process.env.NODE_ENV === 'production')
67
- {
68
- log.warn('watchProto disabled in production (set { production: true } to override)');
69
- // Still do an initial load
70
- const parseProtoFile = _getParser();
71
- const schema = parseProtoFile(protoPath);
72
- app.grpc(schema, serviceName, handlers, opts);
73
- return { stop() {}, schema };
74
- }
75
-
76
- const debounceMs = opts.debounce || DEFAULT_DEBOUNCE;
77
- const resolvedPath = path.resolve(protoPath);
78
-
79
- const parseProtoFile = _getParser();
80
- let currentSchema = null;
81
-
82
- // Initial load
83
- try
84
- {
85
- currentSchema = parseProtoFile(resolvedPath);
86
- app.grpc(currentSchema, serviceName, handlers, opts);
87
- log.info('proto loaded: %s → %s', resolvedPath, serviceName);
88
- }
89
- catch (err)
90
- {
91
- log.error('initial proto parse failed: %s', err.message);
92
- if (typeof opts.onError === 'function') opts.onError(err);
93
- else throw err;
94
- }
95
-
96
- // Debounced reload
97
- let debounceTimer = null;
98
-
99
- function _reload()
100
- {
101
- try
102
- {
103
- const schema = parseProtoFile(resolvedPath);
104
-
105
- // Verify the service still exists in the schema
106
- if (!schema.services[serviceName])
107
- {
108
- const err = new Error(`Service "${serviceName}" not found after reload`);
109
- log.error(err.message);
110
- if (typeof opts.onError === 'function') opts.onError(err);
111
- return;
112
- }
113
-
114
- // Re-register: the grpc registry replaces the existing service entry
115
- if (app._grpcRegistry)
116
- {
117
- app._grpcRegistry.addService(schema, serviceName, handlers, opts);
118
- }
119
-
120
- currentSchema = schema;
121
- log.info('proto reloaded: %s', resolvedPath);
122
-
123
- if (typeof opts.onReload === 'function') opts.onReload(schema);
124
- }
125
- catch (err)
126
- {
127
- log.error('proto reload failed: %s', err.message);
128
- if (typeof opts.onError === 'function') opts.onError(err);
129
- }
130
- }
131
-
132
- // Watch the file
133
- let watcher;
134
- try
135
- {
136
- watcher = fs.watch(resolvedPath, (eventType) =>
137
- {
138
- if (eventType !== 'change') return;
139
-
140
- if (debounceTimer) clearTimeout(debounceTimer);
141
- debounceTimer = setTimeout(_reload, debounceMs);
142
- });
143
-
144
- watcher.on('error', (err) =>
145
- {
146
- log.error('fs.watch error: %s', err.message);
147
- if (typeof opts.onError === 'function') opts.onError(err);
148
- });
149
-
150
- log.info('watching proto file: %s', resolvedPath);
151
- }
152
- catch (err)
153
- {
154
- log.error('failed to watch proto file: %s', err.message);
155
- if (typeof opts.onError === 'function') opts.onError(err);
156
- }
157
-
158
- return {
159
- stop()
160
- {
161
- if (debounceTimer) clearTimeout(debounceTimer);
162
- if (watcher) watcher.close();
163
- log.info('stopped watching: %s', resolvedPath);
164
- },
165
- get schema() { return currentSchema; },
166
- };
167
- }
168
-
169
- // -- Exports -------------------------------------------------
170
-
171
- module.exports = {
172
- watchProto,
173
- };
1
+ /**
2
+ * @module grpc/watch
3
+ * @description Proto file hot-reload for development.
4
+ * Watches `.proto` files for changes using `fs.watch()` and
5
+ * re-parses/re-registers gRPC services automatically.
6
+ *
7
+ * **Dev-only** — disabled by default when `NODE_ENV=production`.
8
+ *
9
+ * @example
10
+ * const { createApp, watchProto } = require('@zero-server/sdk');
11
+ * const app = createApp();
12
+ *
13
+ * watchProto(app, './protos/greeter.proto', 'Greeter', handlers, {
14
+ * onReload: (schema) => console.log('Reloaded!'),
15
+ * });
16
+ *
17
+ * app.listen(50051, { http2: true });
18
+ */
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const log = require('../debug')('zero:grpc:watch');
23
+
24
+ // Lazy-load proto parser
25
+ let _parseProtoFile = null;
26
+ function _getParser()
27
+ {
28
+ if (!_parseProtoFile) _parseProtoFile = require('./proto').parseProtoFile;
29
+ return _parseProtoFile;
30
+ }
31
+
32
+ // -- Constants ---------------------------------------------------
33
+
34
+ const DEFAULT_DEBOUNCE = 300; // ms
35
+
36
+ // -- watchProto --------------------------------------------------
37
+
38
+ /**
39
+ * Watch a `.proto` file and hot-reload the gRPC service on changes.
40
+ * Parses the file, registers the service, then watches for modifications.
41
+ *
42
+ * Disabled in production unless `opts.production` is `true`.
43
+ *
44
+ * @param {object} app - The zero-server App instance.
45
+ * @param {string} protoPath - Path to the `.proto` file.
46
+ * @param {string} serviceName - Service name to register.
47
+ * @param {Object<string, Function>} handlers - Method handlers map.
48
+ * @param {object} [opts] - Options.
49
+ * @param {Function[]} [opts.interceptors] - Per-service interceptors.
50
+ * @param {number} [opts.maxMessageSize] - Max incoming message size.
51
+ * @param {boolean} [opts.compress=false] - Compress outgoing messages.
52
+ * @param {number} [opts.debounce=300] - Debounce interval in ms.
53
+ * @param {boolean} [opts.production=false] - Allow in production.
54
+ * @param {Function} [opts.onReload] - `(schema) => void` callback after reload.
55
+ * @param {Function} [opts.onError] - `(err) => void` callback on parse/reload error.
56
+ * @returns {{ stop: () => void, schema: object }} Controller with `stop()` and current schema.
57
+ *
58
+ * @example
59
+ * const watcher = watchProto(app, './hello.proto', 'Greeter', {
60
+ * SayHello(call) { return { message: 'Hello ' + call.request.name }; },
61
+ * });
62
+ * // Later: watcher.stop();
63
+ */
64
+ function watchProto(app, protoPath, serviceName, handlers, opts = {})
65
+ {
66
+ if (!opts.production && process.env.NODE_ENV === 'production')
67
+ {
68
+ log.warn('watchProto disabled in production (set { production: true } to override)');
69
+ // Still do an initial load
70
+ const parseProtoFile = _getParser();
71
+ const schema = parseProtoFile(protoPath);
72
+ app.grpc(schema, serviceName, handlers, opts);
73
+ return { stop() {}, schema };
74
+ }
75
+
76
+ const debounceMs = opts.debounce || DEFAULT_DEBOUNCE;
77
+ const resolvedPath = path.resolve(protoPath);
78
+
79
+ const parseProtoFile = _getParser();
80
+ let currentSchema = null;
81
+
82
+ // Initial load
83
+ try
84
+ {
85
+ currentSchema = parseProtoFile(resolvedPath);
86
+ app.grpc(currentSchema, serviceName, handlers, opts);
87
+ log.info('proto loaded: %s → %s', resolvedPath, serviceName);
88
+ }
89
+ catch (err)
90
+ {
91
+ log.error('initial proto parse failed: %s', err.message);
92
+ if (typeof opts.onError === 'function') opts.onError(err);
93
+ else throw err;
94
+ }
95
+
96
+ // Debounced reload
97
+ let debounceTimer = null;
98
+
99
+ function _reload()
100
+ {
101
+ try
102
+ {
103
+ const schema = parseProtoFile(resolvedPath);
104
+
105
+ // Verify the service still exists in the schema
106
+ if (!schema.services[serviceName])
107
+ {
108
+ const err = new Error(`Service "${serviceName}" not found after reload`);
109
+ log.error(err.message);
110
+ if (typeof opts.onError === 'function') opts.onError(err);
111
+ return;
112
+ }
113
+
114
+ // Re-register: the grpc registry replaces the existing service entry
115
+ if (app._grpcRegistry)
116
+ {
117
+ app._grpcRegistry.addService(schema, serviceName, handlers, opts);
118
+ }
119
+
120
+ currentSchema = schema;
121
+ log.info('proto reloaded: %s', resolvedPath);
122
+
123
+ if (typeof opts.onReload === 'function') opts.onReload(schema);
124
+ }
125
+ catch (err)
126
+ {
127
+ log.error('proto reload failed: %s', err.message);
128
+ if (typeof opts.onError === 'function') opts.onError(err);
129
+ }
130
+ }
131
+
132
+ // Watch the file
133
+ let watcher;
134
+ try
135
+ {
136
+ watcher = fs.watch(resolvedPath, (eventType) =>
137
+ {
138
+ if (eventType !== 'change') return;
139
+
140
+ if (debounceTimer) clearTimeout(debounceTimer);
141
+ debounceTimer = setTimeout(_reload, debounceMs);
142
+ });
143
+
144
+ watcher.on('error', (err) =>
145
+ {
146
+ log.error('fs.watch error: %s', err.message);
147
+ if (typeof opts.onError === 'function') opts.onError(err);
148
+ });
149
+
150
+ log.info('watching proto file: %s', resolvedPath);
151
+ }
152
+ catch (err)
153
+ {
154
+ log.error('failed to watch proto file: %s', err.message);
155
+ if (typeof opts.onError === 'function') opts.onError(err);
156
+ }
157
+
158
+ return {
159
+ stop()
160
+ {
161
+ if (debounceTimer) clearTimeout(debounceTimer);
162
+ if (watcher) watcher.close();
163
+ log.info('stopped watching: %s', resolvedPath);
164
+ },
165
+ get schema() { return currentSchema; },
166
+ };
167
+ }
168
+
169
+ // -- Exports -------------------------------------------------
170
+
171
+ module.exports = {
172
+ watchProto,
173
+ };
package/lib/http/index.js CHANGED
@@ -1,10 +1,10 @@
1
- /**
2
- * @module http
3
- * @description HTTP request/response wrappers for zero-server.
4
- * Exports Request and Response classes.
5
- */
6
- const Request = require('./request');
7
- const { compileTrust } = require('./request');
8
- const Response = require('./response');
9
-
10
- module.exports = { Request, Response, compileTrust };
1
+ /**
2
+ * @module http
3
+ * @description HTTP request/response wrappers for zero-server.
4
+ * Exports Request and Response classes.
5
+ */
6
+ const Request = require('./request');
7
+ const { compileTrust } = require('./request');
8
+ const Response = require('./response');
9
+
10
+ module.exports = { Request, Response, compileTrust };