@vsaas/remoting 10.0.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.
Files changed (109) hide show
  1. package/LICENSE.md +202 -0
  2. package/README.md +78 -0
  3. package/dist/_virtual/_rolldown/runtime.js +32 -0
  4. package/dist/ext/meta.d.ts +1 -0
  5. package/dist/ext/meta.js +39 -0
  6. package/dist/ext/meta.js.map +1 -0
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.js +20 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/lib/context-base.d.ts +1 -0
  11. package/dist/lib/context-base.js +30 -0
  12. package/dist/lib/context-base.js.map +1 -0
  13. package/dist/lib/deprecate.d.ts +1 -0
  14. package/dist/lib/deprecate.js +34 -0
  15. package/dist/lib/deprecate.js.map +1 -0
  16. package/dist/lib/escape-regexp.d.ts +1 -0
  17. package/dist/lib/escape-regexp.js +12 -0
  18. package/dist/lib/escape-regexp.js.map +1 -0
  19. package/dist/lib/exports-helper.d.ts +1 -0
  20. package/dist/lib/exports-helper.js +101 -0
  21. package/dist/lib/exports-helper.js.map +1 -0
  22. package/dist/lib/http-context.d.ts +1 -0
  23. package/dist/lib/http-context.js +484 -0
  24. package/dist/lib/http-context.js.map +1 -0
  25. package/dist/lib/http-invocation.d.ts +1 -0
  26. package/dist/lib/http-invocation.js +254 -0
  27. package/dist/lib/http-invocation.js.map +1 -0
  28. package/dist/lib/jsonrpc-adapter.d.ts +1 -0
  29. package/dist/lib/jsonrpc-adapter.js +187 -0
  30. package/dist/lib/jsonrpc-adapter.js.map +1 -0
  31. package/dist/lib/looks-like-json.d.ts +1 -0
  32. package/dist/lib/looks-like-json.js +22 -0
  33. package/dist/lib/looks-like-json.js.map +1 -0
  34. package/dist/lib/messages.d.ts +1 -0
  35. package/dist/lib/messages.js +24 -0
  36. package/dist/lib/messages.js.map +1 -0
  37. package/dist/lib/number-checks.d.ts +1 -0
  38. package/dist/lib/number-checks.js +18 -0
  39. package/dist/lib/number-checks.js.map +1 -0
  40. package/dist/lib/phases/merge-phase-name-lists.d.ts +5 -0
  41. package/dist/lib/phases/merge-phase-name-lists.d.ts.map +1 -0
  42. package/dist/lib/phases/merge-phase-name-lists.js +39 -0
  43. package/dist/lib/phases/merge-phase-name-lists.js.map +1 -0
  44. package/dist/lib/phases/phase-list.d.ts +27 -0
  45. package/dist/lib/phases/phase-list.d.ts.map +1 -0
  46. package/dist/lib/phases/phase-list.js +154 -0
  47. package/dist/lib/phases/phase-list.js.map +1 -0
  48. package/dist/lib/phases/phase.d.ts +24 -0
  49. package/dist/lib/phases/phase.d.ts.map +1 -0
  50. package/dist/lib/phases/phase.js +144 -0
  51. package/dist/lib/phases/phase.js.map +1 -0
  52. package/dist/lib/remote-objects.d.ts +1 -0
  53. package/dist/lib/remote-objects.js +642 -0
  54. package/dist/lib/remote-objects.js.map +1 -0
  55. package/dist/lib/rest-adapter-browser.d.ts +1 -0
  56. package/dist/lib/rest-adapter-browser.js +302 -0
  57. package/dist/lib/rest-adapter-browser.js.map +1 -0
  58. package/dist/lib/rest-adapter.d.ts +1 -0
  59. package/dist/lib/rest-adapter.js +519 -0
  60. package/dist/lib/rest-adapter.js.map +1 -0
  61. package/dist/lib/server-sent-events.d.ts +1 -0
  62. package/dist/lib/server-sent-events.js +61 -0
  63. package/dist/lib/server-sent-events.js.map +1 -0
  64. package/dist/lib/shared-class.d.ts +1 -0
  65. package/dist/lib/shared-class.js +207 -0
  66. package/dist/lib/shared-class.js.map +1 -0
  67. package/dist/lib/shared-method.d.ts +1 -0
  68. package/dist/lib/shared-method.js +469 -0
  69. package/dist/lib/shared-method.js.map +1 -0
  70. package/dist/lib/socket-io-adapter.d.ts +1 -0
  71. package/dist/lib/socket-io-adapter.js +93 -0
  72. package/dist/lib/socket-io-adapter.js.map +1 -0
  73. package/dist/lib/socket-io-context.d.ts +1 -0
  74. package/dist/lib/socket-io-context.js +94 -0
  75. package/dist/lib/socket-io-context.js.map +1 -0
  76. package/dist/lib/type-registry.d.ts +1 -0
  77. package/dist/lib/type-registry.js +99 -0
  78. package/dist/lib/type-registry.js.map +1 -0
  79. package/dist/lib/types/any.d.ts +1 -0
  80. package/dist/lib/types/any.js +44 -0
  81. package/dist/lib/types/any.js.map +1 -0
  82. package/dist/lib/types/array.d.ts +1 -0
  83. package/dist/lib/types/array.js +99 -0
  84. package/dist/lib/types/array.js.map +1 -0
  85. package/dist/lib/types/boolean.d.ts +1 -0
  86. package/dist/lib/types/boolean.js +37 -0
  87. package/dist/lib/types/boolean.js.map +1 -0
  88. package/dist/lib/types/date.d.ts +1 -0
  89. package/dist/lib/types/date.js +37 -0
  90. package/dist/lib/types/date.js.map +1 -0
  91. package/dist/lib/types/geopoint.d.ts +1 -0
  92. package/dist/lib/types/geopoint.js +68 -0
  93. package/dist/lib/types/geopoint.js.map +1 -0
  94. package/dist/lib/types/integer.d.ts +1 -0
  95. package/dist/lib/types/integer.js +36 -0
  96. package/dist/lib/types/integer.js.map +1 -0
  97. package/dist/lib/types/number.d.ts +1 -0
  98. package/dist/lib/types/number.js +30 -0
  99. package/dist/lib/types/number.js.map +1 -0
  100. package/dist/lib/types/object.d.ts +1 -0
  101. package/dist/lib/types/object.js +57 -0
  102. package/dist/lib/types/object.js.map +1 -0
  103. package/dist/lib/types/string.d.ts +1 -0
  104. package/dist/lib/types/string.js +29 -0
  105. package/dist/lib/types/string.js.map +1 -0
  106. package/dist/phases.d.ts +4 -0
  107. package/dist/phases.js +35 -0
  108. package/dist/phases.js.map +1 -0
  109. package/package.json +96 -0
@@ -0,0 +1,519 @@
1
+ "use strict";
2
+ const require_runtime = require("../_virtual/_rolldown/runtime.js");
3
+ const require_lib_messages = require("./messages.js");
4
+ const require_lib_deprecate = require("./deprecate.js");
5
+ const require_lib_http_invocation = require("./http-invocation.js");
6
+ const require_lib_http_context = require("./http-context.js");
7
+ //#region src/lib/rest-adapter.ts
8
+ var require_rest_adapter = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
9
+ const g = require_lib_messages;
10
+ /*!
11
+ * Expose `RestAdapter`.
12
+ */
13
+ module.exports = RestAdapter;
14
+ RestAdapter.RestClass = RestClass;
15
+ RestAdapter.RestMethod = RestMethod;
16
+ /*!
17
+ * Module dependencies.
18
+ */
19
+ const deprecated = require_lib_deprecate("strong-remoting");
20
+ const EventEmitter = require("events").EventEmitter;
21
+ const debug = require("debug")("strong-remoting:rest-adapter");
22
+ const inherits = require("util").inherits;
23
+ const assert = require("assert");
24
+ const express = require("express");
25
+ const HttpInvocation = require_lib_http_invocation;
26
+ const HttpContext = require_lib_http_context;
27
+ const strongErrorHandler = require("@vsaas/error-handler");
28
+ const json = express.json;
29
+ const urlencoded = express.urlencoded;
30
+ /**
31
+ * Create a new `RestAdapter` with the given `options`.
32
+ *
33
+ * @param {Object} [options] REST options, default to `remotes.options.rest`.
34
+ * @return {RestAdapter}
35
+ */
36
+ function RestAdapter(remotes, options) {
37
+ EventEmitter.call(this);
38
+ this.remotes = remotes;
39
+ this.Context = HttpContext;
40
+ this.options = options || (remotes.options || {}).rest || {};
41
+ this.typeRegistry = remotes._typeRegistry;
42
+ }
43
+ /**
44
+ * Inherit from `EventEmitter`.
45
+ */
46
+ inherits(RestAdapter, EventEmitter);
47
+ /*!
48
+ * Simplified APIs
49
+ */
50
+ RestAdapter.create = RestAdapter.createRestAdapter = function(remotes) {
51
+ return new RestAdapter(remotes);
52
+ };
53
+ /**
54
+ * Get the path for the given method.
55
+ */
56
+ RestAdapter.prototype.getRoutes = function(obj) {
57
+ return getRoutes(obj, this.options);
58
+ };
59
+ function getRoutes(obj, options) {
60
+ let routes = obj.http;
61
+ if (routes && !Array.isArray(routes)) routes = [routes];
62
+ const classOptions = (obj.sharedClass || obj).options;
63
+ let normalize = classOptions && classOptions.normalizeHttpPath;
64
+ if (normalize === void 0 && options) normalize = options.normalizeHttpPath;
65
+ const toPath = normalize ? normalizeHttpPath : untransformedPath;
66
+ if (routes) routes.forEach(function(r) {
67
+ r.verb = String(r.verb || "all").toLowerCase();
68
+ r.path = toPath(r.path || "/" + obj.name);
69
+ });
70
+ else if (obj.name === "sharedCtor") routes = [{
71
+ verb: "all",
72
+ path: "/prototype"
73
+ }];
74
+ else routes = [{
75
+ verb: "all",
76
+ path: obj.name ? toPath("/" + obj.name) : ""
77
+ }];
78
+ return routes;
79
+ }
80
+ /**
81
+ * Normalize HTTP path.
82
+ */
83
+ function normalizeHttpPath(path) {
84
+ if (typeof path !== "string") return;
85
+ return path.replace(/[^\/]+/g, function(match) {
86
+ if (match.indexOf(":") > -1) return match;
87
+ return match.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase();
88
+ });
89
+ }
90
+ function untransformedPath(path) {
91
+ return path;
92
+ }
93
+ RestAdapter.prototype.connect = function(url) {
94
+ this.connection = url;
95
+ };
96
+ /**
97
+ *
98
+ * Get the authorization to use when invoking a remote method.
99
+ *
100
+ * @param {Object} invocationOptions The value of the "options" argument
101
+ * of the invoked method
102
+ * @private
103
+ */
104
+ RestAdapter.prototype._getInvocationAuth = function(invocationOptions) {
105
+ const auth = this.remotes.auth;
106
+ if (auth || !this.options.passAccessToken) return auth;
107
+ const accessToken = invocationOptions && invocationOptions.accessToken;
108
+ if (accessToken) return { accessToken };
109
+ };
110
+ RestAdapter.prototype.invoke = function(method, ctorArgs, args, callback) {
111
+ assert(this.connection, g.f("Cannot invoke method without a connection. See {{RemoteObjects#connect().}}"));
112
+ assert(typeof method === "string", g.f("method is required when calling {{invoke()}}"));
113
+ const lastArg = arguments[arguments.length - 1];
114
+ callback = typeof lastArg === "function" ? lastArg : void 0;
115
+ ctorArgs = Array.isArray(ctorArgs) ? ctorArgs : [];
116
+ if (!Array.isArray(args)) {
117
+ args = ctorArgs;
118
+ ctorArgs = [];
119
+ }
120
+ const remotes = this.remotes;
121
+ const restMethod = this.getRestMethodByName(method);
122
+ if (!restMethod) return callback(new Error(g.f("Cannot invoke unkown method: %s", method)));
123
+ const invokeOptions = restMethod.getArgByName("options", args);
124
+ const auth = this._getInvocationAuth(invokeOptions);
125
+ const invocation = new HttpInvocation(restMethod, ctorArgs, args, this.connection, auth, this.typeRegistry);
126
+ const ctx = invocation.context;
127
+ ctx.req = invocation.createRequest();
128
+ const scope = ctx.getScope();
129
+ remotes.execHooks("before", restMethod, scope, ctx, function(err) {
130
+ if (err) return callback(err);
131
+ invocation.invoke(function(err) {
132
+ if (err) return callback(err);
133
+ const args = Array.prototype.slice.call(arguments);
134
+ ctx.result = args.slice(1);
135
+ ctx.res = invocation.getResponse();
136
+ remotes.execHooks("after", restMethod, scope, ctx, function(err) {
137
+ if (err) return callback(err);
138
+ callback.apply(invocation, args);
139
+ });
140
+ });
141
+ });
142
+ };
143
+ /**
144
+ * creates the rest method by name cache map.
145
+ * @returns {Object} map of rest method name to rest method
146
+ */
147
+ RestAdapter.prototype._createRestMethodByNameCache = function() {
148
+ const restMethodByNameMap = {};
149
+ const classes = this.getClasses();
150
+ for (let i = 0; i < classes.length; i++) {
151
+ const restClass = classes[i];
152
+ for (let j = 0; j < restClass.methods.length; j++) {
153
+ const restMethod = restClass.methods[j];
154
+ restMethodByNameMap[restMethod.fullName] = restMethod;
155
+ }
156
+ }
157
+ return restMethodByNameMap;
158
+ };
159
+ RestAdapter.prototype.getRestMethodByName = function(name) {
160
+ let ret;
161
+ if (this._cachedRestMethodsByName) ret = this._cachedRestMethodsByName[name];
162
+ if (!ret) {
163
+ this._cachedRestMethodsByName = this._createRestMethodByNameCache();
164
+ ret = this._cachedRestMethodsByName[name];
165
+ }
166
+ if (ret && !ret.sharedMethod.sharedClass.isMethodEnabled(ret.sharedMethod)) ret = void 0;
167
+ return ret;
168
+ };
169
+ /*!
170
+ * Compare two routes
171
+ * @param {Object} r1 The first route {route: {verb: 'get', path: '/:id'}, method: ...}
172
+ * @param [Object} r2 The second route route: {verb: 'get', path: '/findOne'}, method: ...}
173
+ * @returns {number} 1: r1 comes after 2, -1: r1 comes before r2, 0: equal
174
+ */
175
+ function sortRoutes(r1, r2) {
176
+ const a = r1.route;
177
+ const b = r2.route;
178
+ let verb1 = a.verb.toLowerCase();
179
+ let verb2 = b.verb.toLowerCase();
180
+ if (verb1 === "del") verb1 = "delete";
181
+ if (verb2 === "del") verb2 = "delete";
182
+ if (verb1 > verb2) return -1;
183
+ else if (verb1 < verb2) return 1;
184
+ const p1 = a.path.split("/");
185
+ const p2 = b.path.split("/");
186
+ const len = Math.min(p1.length, p2.length);
187
+ for (let i = 0; i < len; i++) {
188
+ if (p1[i] === "" && p2[i] !== "") return 1;
189
+ else if (p1[i] !== "" && p2[i] === "") return -1;
190
+ if (p1[i][0] === ":" && p2[i][0] !== ":") return 1;
191
+ else if (p1[i][0] !== ":" && p2[i][0] === ":") return -1;
192
+ if (p1[i] > p2[i]) return 1;
193
+ else if (p1[i] < p2[i]) return -1;
194
+ }
195
+ return p2.length - p1.length;
196
+ }
197
+ RestAdapter.sortRoutes = sortRoutes;
198
+ RestAdapter.prototype.createHandler = function() {
199
+ const corsOptions = this.remotes.options.cors;
200
+ if (corsOptions !== void 0 && corsOptions !== false) throw new Error(g.f("The REST adapter no longer comes with a built-in CORS middleware, the config option %j is no longer available.See %s for more details.", "remoting.cors", "https://docs.strongloop.com/display/public/LB/Security+considerations"));
201
+ const root = express.Router();
202
+ const adapter = this;
203
+ const classes = this.getClasses();
204
+ root.use(function(req, res, next) {
205
+ if (requestIsJson(req)) {
206
+ if (getRequestHeader(req, "content-length") === "0") {
207
+ req._body = true;
208
+ req.body = {};
209
+ }
210
+ }
211
+ next();
212
+ });
213
+ debug("remoting options: %j", this.remotes.options);
214
+ const urlencodedOptions = this.remotes.options.urlencoded || { extended: true };
215
+ if (urlencodedOptions.extended === void 0) urlencodedOptions.extended = true;
216
+ const jsonOptions = this.remotes.options.json || { strict: false };
217
+ root.use(urlencoded(urlencodedOptions));
218
+ root.use(json(jsonOptions));
219
+ const handleUnknownPaths = this._shouldHandleUnknownPaths();
220
+ classes.forEach(function(restClass) {
221
+ const router = express.Router();
222
+ const className = restClass.sharedClass.name;
223
+ debug("registering REST handler for class %j", className);
224
+ const methods = [];
225
+ restClass.methods.forEach(function(restMethod) {
226
+ const sharedMethod = restMethod.sharedMethod;
227
+ debug(" method %s", sharedMethod.stringName);
228
+ restMethod.routes.forEach(function(route) {
229
+ methods.push({
230
+ route,
231
+ method: sharedMethod
232
+ });
233
+ });
234
+ });
235
+ methods.sort(sortRoutes);
236
+ methods.forEach(function(m) {
237
+ adapter._registerMethodRouteHandlers(router, m.method, m.route);
238
+ });
239
+ if (handleUnknownPaths) router.use(RestAdapter.remoteMethodNotFoundHandler(className));
240
+ restClass.routes.forEach(function(route) {
241
+ debug(" at %s", route.path);
242
+ root.use(route.path, router);
243
+ });
244
+ });
245
+ if (handleUnknownPaths) root.use(RestAdapter.urlNotFoundHandler());
246
+ if (this._shouldHandleErrors()) root.use(RestAdapter.errorHandler(this.remotes.options.errorHandler));
247
+ return root;
248
+ };
249
+ RestAdapter.prototype._shouldHandleUnknownPaths = function() {
250
+ return !(this.options && this.options.handleUnknownPaths === false);
251
+ };
252
+ RestAdapter.prototype._shouldHandleErrors = function() {
253
+ return !(this.options && this.options.handleErrors === false);
254
+ };
255
+ RestAdapter.remoteMethodNotFoundHandler = function(className) {
256
+ className = className || "(unknown)";
257
+ return function restRemoteMethodNotFound(req, res, next) {
258
+ const message = g.f("{{Shared class}} \"%s\" has no method handling %s %s", className, req.method, req.url);
259
+ const error = new Error(message);
260
+ error.statusCode = 404;
261
+ next(error);
262
+ };
263
+ };
264
+ RestAdapter.urlNotFoundHandler = function() {
265
+ return function restUrlNotFound(req, res, next) {
266
+ const message = g.f("There is no method to handle %s %s", req.method, req.url);
267
+ const error = new Error(message);
268
+ error.statusCode = 404;
269
+ next(error);
270
+ };
271
+ };
272
+ RestAdapter.errorHandler = function(options) {
273
+ options = options || {};
274
+ if (options.hasOwnProperty("disableStackTrace")) g.warn("{{strong-remoting}} no longer supports \"{{errorHandler.disableStackTrace}}\" option. Use the new option \"{{errorHandler.debug}}\" instead.");
275
+ const strongErrorHandlerInstance = strongErrorHandler(options);
276
+ return function restErrorHandler(err, req, res, next) {
277
+ if (typeof options.handler === "function") try {
278
+ options.handler(err, req, res, defaultHandler);
279
+ } catch (e) {
280
+ defaultHandler(e);
281
+ }
282
+ else return defaultHandler();
283
+ function defaultHandler(handlerError) {
284
+ if (handlerError) err = handlerError;
285
+ return strongErrorHandlerInstance(err, req, res, next);
286
+ }
287
+ };
288
+ };
289
+ RestAdapter.prototype._registerMethodRouteHandlers = function(router, sharedMethod, route) {
290
+ const handler = sharedMethod.isStatic ? this._createStaticMethodHandler(sharedMethod) : this._createPrototypeMethodHandler(sharedMethod);
291
+ debug(" %s %s %s", route.verb, route.path, handler.name);
292
+ let verb = route.verb;
293
+ if (verb === "del") verb = "delete";
294
+ router[verb](route.path, handler);
295
+ };
296
+ RestAdapter.prototype._createStaticMethodHandler = function(sharedMethod) {
297
+ const self = this;
298
+ const Context = this.Context;
299
+ return function restStaticMethodHandler(req, res, next) {
300
+ const ctx = new Context(req, res, sharedMethod, self.options, self.typeRegistry);
301
+ self._invokeMethod(ctx, sharedMethod, next);
302
+ };
303
+ };
304
+ RestAdapter.prototype._createPrototypeMethodHandler = function(sharedMethod) {
305
+ const self = this;
306
+ const Context = this.Context;
307
+ return function restPrototypeMethodHandler(req, res, next) {
308
+ const ctx = new Context(req, res, sharedMethod, self.options, self.typeRegistry);
309
+ ctx.invoke(sharedMethod.ctor, sharedMethod.sharedCtor, function(err, inst) {
310
+ if (err) ctx.sharedCtorError = err;
311
+ else ctx.instance = inst;
312
+ self._invokeMethod(ctx, sharedMethod, next);
313
+ }, true);
314
+ };
315
+ };
316
+ RestAdapter.prototype._invokeMethod = function(ctx, method, next) {
317
+ this.remotes;
318
+ const steps = [];
319
+ if (method.rest.before) steps.push(function invokeRestBefore(cb) {
320
+ debug("Invoking rest.before for " + ctx.methodString);
321
+ method.rest.before.call(ctx.getScope(), ctx, cb);
322
+ });
323
+ steps.push(this.remotes.invokeMethodInContext.bind(this.remotes, ctx));
324
+ if (method.rest.after) steps.push(function invokeRestAfter(cb) {
325
+ debug("Invoking rest.after for " + ctx.methodString);
326
+ method.rest.after.call(ctx.getScope(), ctx, cb);
327
+ });
328
+ runSeries(steps, function(err) {
329
+ if (err) return next(err);
330
+ ctx.done(function(err) {
331
+ if (err) return next(err);
332
+ });
333
+ });
334
+ };
335
+ RestAdapter.prototype.allRoutes = function() {
336
+ const routes = [];
337
+ const adapter = this;
338
+ const classes = this.remotes.classes(this.options);
339
+ let currentRoot = "";
340
+ classes.forEach(function(sc) {
341
+ adapter.getRoutes(sc).forEach(function(classRoute) {
342
+ currentRoot = classRoute.path;
343
+ sc.methods().forEach(function(method) {
344
+ adapter.getRoutes(method).forEach(function(route) {
345
+ if (method.isStatic) addRoute(route.verb, route.path, method);
346
+ else adapter.getRoutes(method.sharedCtor).forEach(function(sharedCtorRoute) {
347
+ addRoute(route.verb, sharedCtorRoute.path + route.path, method);
348
+ });
349
+ });
350
+ });
351
+ });
352
+ });
353
+ return routes;
354
+ function addRoute(verb, path, method) {
355
+ if (path === "/" || path === "//") path = currentRoot;
356
+ else path = currentRoot + path;
357
+ if (path[path.length - 1] === "/") path = path.substr(0, path.length - 1);
358
+ path = path.replace(/\/\//g, "/");
359
+ routes.push({
360
+ verb,
361
+ path,
362
+ description: method.description,
363
+ notes: method.notes,
364
+ documented: method.documented,
365
+ method: method.stringName,
366
+ accepts: method.accepts && method.accepts.length ? method.accepts : void 0,
367
+ returns: method.returns && method.returns.length ? method.returns : void 0,
368
+ errors: method.errors && method.errors.length ? method.errors : void 0,
369
+ http: method.http
370
+ });
371
+ }
372
+ };
373
+ RestAdapter.prototype.getClasses = function() {
374
+ return this.remotes.classes(this.options).map((c) => {
375
+ return new RestClass(c, this.options);
376
+ });
377
+ };
378
+ function RestClass(sharedClass, adapterOptions) {
379
+ nonEnumerableConstPropery(this, "sharedClass", sharedClass);
380
+ this.name = sharedClass.name;
381
+ this.options = adapterOptions;
382
+ this.routes = getRoutes(sharedClass, this.options);
383
+ this.ctor = sharedClass.sharedCtor && new RestMethod(this, sharedClass.sharedCtor);
384
+ this.methods = sharedClass.methods().filter(function(sm) {
385
+ return !sm.isSharedCtor;
386
+ }).map(function(sm) {
387
+ return new RestMethod(this, sm);
388
+ }.bind(this));
389
+ }
390
+ RestClass.prototype.getPath = function() {
391
+ return this.routes[0].path;
392
+ };
393
+ function RestMethod(restClass, sharedMethod) {
394
+ nonEnumerableConstPropery(this, "restClass", restClass);
395
+ nonEnumerableConstPropery(this, "sharedMethod", sharedMethod);
396
+ this.fullName = sharedMethod.stringName;
397
+ this.name = this.fullName.split(".").slice(1).join(".");
398
+ this.accepts = sharedMethod.accepts;
399
+ this.returns = sharedMethod.returns;
400
+ this.errors = sharedMethod.errors;
401
+ this.description = sharedMethod.description;
402
+ this.notes = sharedMethod.notes;
403
+ this.documented = sharedMethod.documented;
404
+ const methodRoutes = getRoutes(sharedMethod, restClass.options);
405
+ if (sharedMethod.isStatic || !restClass.ctor) this.routes = methodRoutes;
406
+ else {
407
+ const routes = this.routes = [];
408
+ methodRoutes.forEach(function(route) {
409
+ restClass.ctor.routes.forEach(function(ctorRoute) {
410
+ const fullRoute = Object.assign({}, route);
411
+ fullRoute.path = joinPaths(ctorRoute.path, route.path);
412
+ routes.push(fullRoute);
413
+ });
414
+ });
415
+ }
416
+ }
417
+ /**
418
+ * Get the argument from the invoked arg array by arg name.
419
+ * @param argName the name of the arg to lookup
420
+ * @param invokedArgs array
421
+ * @returns {*} the arg value or undefined if not found
422
+ */
423
+ RestMethod.prototype.getArgByName = function(argName, invokedArgs) {
424
+ let argValue;
425
+ if (!this.accepts || !this.accepts.length) return void 0;
426
+ this.accepts.some(function(argProperty, i) {
427
+ if (argProperty.arg && argProperty.arg.toLowerCase() === argName.toLowerCase()) {
428
+ argValue = invokedArgs[i];
429
+ return true;
430
+ }
431
+ return false;
432
+ });
433
+ return argValue;
434
+ };
435
+ RestMethod.prototype.isReturningArray = function() {
436
+ return this.returns.length == 1 && this.returns[0].root && getTypeString(this.returns[0].type) === "array" || false;
437
+ };
438
+ RestMethod.prototype.acceptsSingleBodyArgument = function() {
439
+ if (this.accepts.length != 1) return false;
440
+ const accepts = this.accepts[0];
441
+ return accepts.http && accepts.http.source == "body" && getTypeString(accepts.type) == "object" || false;
442
+ };
443
+ RestMethod.prototype.getEndpoints = function() {
444
+ const self = this;
445
+ return this.routes.map(function(route) {
446
+ let verbResult;
447
+ const verb = route.verb;
448
+ if (verb == "all") verbResult = "POST";
449
+ else if (verb == "del") verbResult = "DELETE";
450
+ else verbResult = verb.toUpperCase();
451
+ return {
452
+ verb: verbResult,
453
+ fullPath: joinPaths(self.restClass.getPath(), route.path)
454
+ };
455
+ });
456
+ };
457
+ RestMethod.prototype.getHttpMethod = function() {
458
+ deprecated("getHttpMethod() is deprecated, use getEndpoints()[0].verb instead.");
459
+ return this.getEndpoints()[0].verb;
460
+ };
461
+ RestMethod.prototype.getPath = function() {
462
+ return this.routes[0].path;
463
+ };
464
+ RestMethod.prototype.getFullPath = function() {
465
+ deprecated("getFullPath() is deprecated, use getEndpoints()[0].fullPath instead.");
466
+ return this.getEndpoints()[0].fullPath;
467
+ };
468
+ function getTypeString(ctorOrName) {
469
+ if (typeof ctorOrName === "function") ctorOrName = ctorOrName.name;
470
+ if (typeof ctorOrName === "string") return ctorOrName.toLowerCase();
471
+ else if (Array.isArray(ctorOrName)) return "array";
472
+ else {
473
+ debug("WARNING: unkown ctorOrName of type %s: %j", typeof ctorOrName, ctorOrName);
474
+ return "undefined";
475
+ }
476
+ }
477
+ function nonEnumerableConstPropery(object, name, value) {
478
+ Object.defineProperty(object, name, {
479
+ value,
480
+ enumerable: false,
481
+ writable: false,
482
+ configurable: false
483
+ });
484
+ }
485
+ function joinPaths(left, right) {
486
+ if (!left) return right;
487
+ if (!right || right == "/") return left;
488
+ const glue = left[left.length - 1] + right[0];
489
+ if (glue == "//") return left + right.slice(1);
490
+ else if (glue[0] == "/" || glue[1] == "/") return left + right;
491
+ else return left + "/" + right;
492
+ }
493
+ function runSeries(steps, callback) {
494
+ let index = 0;
495
+ function next(err) {
496
+ if (err || index === steps.length) {
497
+ callback(err);
498
+ return;
499
+ }
500
+ const step = steps[index];
501
+ index += 1;
502
+ step(next);
503
+ }
504
+ next();
505
+ }
506
+ function requestIsJson(req) {
507
+ if (typeof req.is === "function") return req.is("application/json");
508
+ const contentType = getRequestHeader(req, "content-type");
509
+ return /^application\/json\b/i.test(contentType || "");
510
+ }
511
+ function getRequestHeader(req, name) {
512
+ if (typeof req.get === "function") return req.get(name);
513
+ return req.headers && req.headers[name.toLowerCase()];
514
+ }
515
+ }));
516
+ //#endregion
517
+ module.exports = require_rest_adapter();
518
+
519
+ //# sourceMappingURL=rest-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rest-adapter.js","names":[],"sources":["../../src/lib/rest-adapter.ts"],"sourcesContent":["// Copyright IBM Corp. 2013,2018. All Rights Reserved.\n// Node module: strong-remoting\n// This file is licensed under the Artistic License 2.0.\n// License text available at https://opensource.org/licenses/Artistic-2.0\n\n// @ts-nocheck\n'use strict';\n\nconst g = require('./messages');\n/*!\n * Expose `RestAdapter`.\n */\nmodule.exports = RestAdapter;\n\nRestAdapter.RestClass = RestClass;\nRestAdapter.RestMethod = RestMethod;\n\n/*!\n * Module dependencies.\n */\n\nconst deprecated = require('./deprecate')('strong-remoting');\nconst EventEmitter = require('events').EventEmitter;\nconst debug = require('debug')('strong-remoting:rest-adapter');\nconst util = require('util');\nconst inherits = util.inherits;\nconst assert = require('assert');\nconst express = require('express');\nconst HttpInvocation = require('./http-invocation');\nconst HttpContext = require('./http-context');\nconst strongErrorHandler = require('@vsaas/error-handler');\n\nconst json = express.json;\nconst urlencoded = express.urlencoded;\n/**\n * Create a new `RestAdapter` with the given `options`.\n *\n * @param {Object} [options] REST options, default to `remotes.options.rest`.\n * @return {RestAdapter}\n */\n\nfunction RestAdapter(remotes, options) {\n EventEmitter.call(this);\n\n this.remotes = remotes;\n this.Context = HttpContext;\n this.options = options || (remotes.options || {}).rest || {};\n this.typeRegistry = remotes._typeRegistry;\n}\n\n/**\n * Inherit from `EventEmitter`.\n */\n\ninherits(RestAdapter, EventEmitter);\n\n/*!\n * Simplified APIs\n */\n\nRestAdapter.create = RestAdapter.createRestAdapter = function (remotes) {\n // add simplified construction / sugar here\n return new RestAdapter(remotes);\n};\n\n/**\n * Get the path for the given method.\n */\n\nRestAdapter.prototype.getRoutes = function (obj) {\n return getRoutes(obj, this.options);\n};\n\nfunction getRoutes(obj, options) {\n let routes = obj.http;\n if (routes && !Array.isArray(routes)) {\n routes = [routes];\n }\n\n // Options of obj (e.g. sharedClass) take precedence over options of adapter\n const sharedClass = obj.sharedClass || obj;\n const classOptions = sharedClass.options;\n let normalize = classOptions && classOptions.normalizeHttpPath;\n if (normalize === undefined && options) {\n normalize = options.normalizeHttpPath;\n }\n const toPath = normalize ? normalizeHttpPath : untransformedPath;\n\n // overridden\n if (routes) {\n // patch missing verbs / routes\n routes.forEach(function (r) {\n r.verb = String(r.verb || 'all').toLowerCase();\n r.path = toPath(r.path || '/' + obj.name);\n });\n } else {\n if (obj.name === 'sharedCtor') {\n routes = [\n {\n verb: 'all',\n path: '/prototype',\n },\n ];\n } else {\n // build default route\n routes = [\n {\n verb: 'all',\n path: obj.name ? toPath('/' + obj.name) : '',\n },\n ];\n }\n }\n\n return routes;\n}\n\n/**\n * Normalize HTTP path.\n */\nfunction normalizeHttpPath(path) {\n if (typeof path !== 'string') {\n return;\n }\n return path.replace(/[^\\/]+/g, function (match) {\n if (match.indexOf(':') > -1) {\n return match;\n }\n\n return match\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')\n .replace(/[_\\s]+/g, '-')\n .toLowerCase();\n });\n}\n\nfunction untransformedPath(path) {\n return path;\n}\n\nRestAdapter.prototype.connect = function (url) {\n this.connection = url;\n};\n\n/**\n *\n * Get the authorization to use when invoking a remote method.\n *\n * @param {Object} invocationOptions The value of the \"options\" argument\n * of the invoked method\n * @private\n */\nRestAdapter.prototype._getInvocationAuth = function (invocationOptions) {\n const auth = this.remotes.auth;\n if (auth || !this.options.passAccessToken) {\n // Use the globally-configured authentication credentials\n return auth;\n }\n\n // Check the `options` argument provided by the caller of the invoked method\n // It may have the access token that can be used\n const accessToken = invocationOptions && invocationOptions.accessToken;\n if (accessToken) {\n return { accessToken };\n }\n\n // No authentication credentials are configured.\n return undefined;\n};\n\nRestAdapter.prototype.invoke = function (method, ctorArgs, args, callback) {\n assert(\n this.connection,\n g.f('Cannot invoke method without a connection. See {{RemoteObjects#connect().}}'),\n );\n assert(typeof method === 'string', g.f('method is required when calling {{invoke()}}'));\n\n const lastArg = arguments[arguments.length - 1];\n callback = typeof lastArg === 'function' ? lastArg : undefined;\n\n ctorArgs = Array.isArray(ctorArgs) ? ctorArgs : [];\n if (!Array.isArray(args)) {\n args = ctorArgs;\n ctorArgs = [];\n }\n\n const remotes = this.remotes;\n const restMethod = this.getRestMethodByName(method);\n if (!restMethod) {\n return callback(new Error(g.f('Cannot invoke unkown method: %s', method)));\n }\n const invokeOptions = restMethod.getArgByName('options', args);\n const auth = this._getInvocationAuth(invokeOptions);\n\n const invocation = new HttpInvocation(\n restMethod,\n ctorArgs,\n args,\n this.connection,\n auth,\n this.typeRegistry,\n );\n const ctx = invocation.context;\n ctx.req = invocation.createRequest();\n const scope = ctx.getScope();\n remotes.execHooks('before', restMethod, scope, ctx, function (err) {\n if (err) {\n return callback(err);\n }\n invocation.invoke(function (err) {\n if (err) {\n return callback(err);\n }\n const args = Array.prototype.slice.call(arguments);\n\n ctx.result = args.slice(1);\n ctx.res = invocation.getResponse();\n remotes.execHooks('after', restMethod, scope, ctx, function (err) {\n if (err) {\n return callback(err);\n }\n callback.apply(invocation, args);\n });\n });\n });\n};\n\n/**\n * creates the rest method by name cache map.\n * @returns {Object} map of rest method name to rest method\n */\nRestAdapter.prototype._createRestMethodByNameCache = function () {\n const restMethodByNameMap = {};\n const classes = this.getClasses();\n for (let i = 0; i < classes.length; i++) {\n const restClass = classes[i];\n for (let j = 0; j < restClass.methods.length; j++) {\n const restMethod = restClass.methods[j];\n restMethodByNameMap[restMethod.fullName] = restMethod;\n }\n }\n return restMethodByNameMap;\n};\n\nRestAdapter.prototype.getRestMethodByName = function (name) {\n let ret;\n if (this._cachedRestMethodsByName) {\n ret = this._cachedRestMethodsByName[name];\n }\n\n if (!ret) {\n // Either the method was not found or the cache was not built yet\n // If the method was not found, then let's rebuild the cache\n // to see if there were any new methods added\n this._cachedRestMethodsByName = this._createRestMethodByNameCache();\n ret = this._cachedRestMethodsByName[name];\n }\n\n if (ret && !ret.sharedMethod.sharedClass.isMethodEnabled(ret.sharedMethod)) {\n // The method was disabled after our cache was built\n ret = undefined;\n }\n\n return ret;\n};\n\n/*!\n * Compare two routes\n * @param {Object} r1 The first route {route: {verb: 'get', path: '/:id'}, method: ...}\n * @param [Object} r2 The second route route: {verb: 'get', path: '/findOne'}, method: ...}\n * @returns {number} 1: r1 comes after 2, -1: r1 comes before r2, 0: equal\n */\nfunction sortRoutes(r1, r2) {\n const a = r1.route;\n const b = r2.route;\n\n // Normalize the verbs\n let verb1 = a.verb.toLowerCase();\n let verb2 = b.verb.toLowerCase();\n\n if (verb1 === 'del') {\n verb1 = 'delete';\n }\n if (verb2 === 'del') {\n verb2 = 'delete';\n }\n // First sort by verb\n if (verb1 > verb2) {\n return -1;\n } else if (verb1 < verb2) {\n return 1;\n }\n\n // Sort by path part by part using the / delimiter\n // For example '/:id' will become ['', ':id'], '/findOne' will become\n // ['', 'findOne']\n const p1 = a.path.split('/');\n const p2 = b.path.split('/');\n const len = Math.min(p1.length, p2.length);\n\n // Loop through the parts and decide which path should come first\n for (let i = 0; i < len; i++) {\n // Empty part has lower weight\n if (p1[i] === '' && p2[i] !== '') {\n return 1;\n } else if (p1[i] !== '' && p2[i] === '') {\n return -1;\n }\n // Wildcard has lower weight\n if (p1[i][0] === ':' && p2[i][0] !== ':') {\n return 1;\n } else if (p1[i][0] !== ':' && p2[i][0] === ':') {\n return -1;\n }\n // Now the regular string comparision\n if (p1[i] > p2[i]) {\n return 1;\n } else if (p1[i] < p2[i]) {\n return -1;\n }\n }\n // Both paths have the common parts. The longer one should come before the\n // shorter one\n return p2.length - p1.length;\n}\n\nRestAdapter.sortRoutes = sortRoutes; // For testing\n\nRestAdapter.prototype.createHandler = function () {\n const corsOptions = this.remotes.options.cors;\n if (corsOptions !== undefined && corsOptions !== false) {\n throw new Error(\n g.f(\n 'The REST adapter no longer comes with a built-in CORS middleware, ' +\n 'the config option %j is no longer available.' +\n 'See %s for more details.',\n 'remoting.cors',\n 'https://docs.strongloop.com/display/public/LB/Security+considerations',\n ),\n );\n }\n\n const root = express.Router();\n const adapter = this;\n const classes = this.getClasses();\n\n // Add a handler to tolerate empty json as connect's json middleware throws an error\n root.use(function (req, res, next) {\n if (requestIsJson(req)) {\n if (getRequestHeader(req, 'content-length') === '0') {\n // This doesn't cover the transfer-encoding: chunked\n req._body = true; // Mark it as parsed\n req.body = {};\n }\n }\n next();\n });\n\n // Set strict to be `false` so that anything `JSON.parse()` accepts will be parsed\n debug('remoting options: %j', this.remotes.options);\n const urlencodedOptions = this.remotes.options.urlencoded || { extended: true };\n if (urlencodedOptions.extended === undefined) {\n urlencodedOptions.extended = true;\n }\n const jsonOptions = this.remotes.options.json || { strict: false };\n\n root.use(urlencoded(urlencodedOptions));\n root.use(json(jsonOptions));\n\n const handleUnknownPaths = this._shouldHandleUnknownPaths();\n\n classes.forEach(function (restClass) {\n const router = express.Router();\n const className = restClass.sharedClass.name;\n\n debug('registering REST handler for class %j', className);\n\n const methods = [];\n // Register handlers for all shared methods of this class sharedClass\n restClass.methods.forEach(function (restMethod) {\n const sharedMethod = restMethod.sharedMethod;\n debug(' method %s', sharedMethod.stringName);\n restMethod.routes.forEach(function (route) {\n methods.push({ route: route, method: sharedMethod });\n });\n });\n\n // Sort all methods based on the route path\n methods.sort(sortRoutes);\n\n methods.forEach(function (m) {\n adapter._registerMethodRouteHandlers(router, m.method, m.route);\n });\n\n if (handleUnknownPaths) {\n // Convert requests for unknown methods of this sharedClass into 404.\n // Do not allow other middleware to invade our URL space.\n router.use(RestAdapter.remoteMethodNotFoundHandler(className));\n }\n\n // Mount the remoteClass router on all class routes.\n restClass.routes.forEach(function (route) {\n debug(' at %s', route.path);\n root.use(route.path, router);\n });\n });\n\n if (handleUnknownPaths) {\n // Convert requests for unknown URLs into 404.\n // Do not allow other middleware to invade our URL space.\n root.use(RestAdapter.urlNotFoundHandler());\n }\n\n if (this._shouldHandleErrors()) {\n // Use our own error handler to make sure the error response has\n // always the format expected by remoting clients.\n root.use(RestAdapter.errorHandler(this.remotes.options.errorHandler));\n }\n\n return root;\n};\n\nRestAdapter.prototype._shouldHandleUnknownPaths = function () {\n return !(this.options && this.options.handleUnknownPaths === false);\n};\n\nRestAdapter.prototype._shouldHandleErrors = function () {\n return !(this.options && this.options.handleErrors === false);\n};\n\nRestAdapter.remoteMethodNotFoundHandler = function (className) {\n className = className || '(unknown)';\n return function restRemoteMethodNotFound(req, res, next) {\n const message = g.f(\n '{{Shared class}} \\\"%s\\\" has no method handling %s %s',\n className,\n req.method,\n req.url,\n );\n const error = new Error(message);\n error.statusCode = 404;\n next(error);\n };\n};\n\nRestAdapter.urlNotFoundHandler = function () {\n return function restUrlNotFound(req, res, next) {\n const message = g.f('There is no method to handle %s %s', req.method, req.url);\n const error = new Error(message);\n error.statusCode = 404;\n next(error);\n };\n};\n\nRestAdapter.errorHandler = function (options) {\n options = options || {};\n if (options.hasOwnProperty('disableStackTrace')) {\n g.warn(\n '{{strong-remoting}} no longer supports ' +\n '\"{{errorHandler.disableStackTrace}}\" option. ' +\n 'Use the new option \"{{errorHandler.debug}}\" instead.',\n );\n }\n\n const strongErrorHandlerInstance = strongErrorHandler(options);\n\n return function restErrorHandler(err, req, res, next) {\n if (typeof options.handler === 'function') {\n try {\n options.handler(err, req, res, defaultHandler);\n } catch (e) {\n defaultHandler(e);\n }\n } else {\n return defaultHandler();\n }\n\n function defaultHandler(handlerError) {\n if (handlerError) {\n // ensure errors that occurred during\n // the handler are reported\n err = handlerError;\n }\n return strongErrorHandlerInstance(err, req, res, next);\n }\n };\n};\n\nRestAdapter.prototype._registerMethodRouteHandlers = function (router, sharedMethod, route) {\n const handler = sharedMethod.isStatic\n ? this._createStaticMethodHandler(sharedMethod)\n : this._createPrototypeMethodHandler(sharedMethod);\n\n debug(' %s %s %s', route.verb, route.path, handler.name);\n let verb = route.verb;\n if (verb === 'del') {\n // Express 4.x only supports delete\n verb = 'delete';\n }\n router[verb](route.path, handler);\n};\n\nRestAdapter.prototype._createStaticMethodHandler = function (sharedMethod) {\n const self = this;\n const Context = this.Context;\n\n return function restStaticMethodHandler(req, res, next) {\n const ctx = new Context(req, res, sharedMethod, self.options, self.typeRegistry);\n self._invokeMethod(ctx, sharedMethod, next);\n };\n};\n\nRestAdapter.prototype._createPrototypeMethodHandler = function (sharedMethod) {\n const self = this;\n const Context = this.Context;\n\n return function restPrototypeMethodHandler(req, res, next) {\n const ctx = new Context(req, res, sharedMethod, self.options, self.typeRegistry);\n\n // invoke the shared constructor to get an instance\n ctx.invoke(\n sharedMethod.ctor,\n sharedMethod.sharedCtor,\n function (err, inst) {\n if (err) {\n // Defer handling of this error until the request is authorized.\n // The error handler is in RemotObjects.prototype._setupPhase\n // TODO(bajtos) refactor this code so that sharedCtor is invoked\n // from \"invokeMethodInContext\" too, see #315\n ctx.sharedCtorError = err;\n } else {\n ctx.instance = inst;\n }\n self._invokeMethod(ctx, sharedMethod, next);\n },\n true,\n );\n };\n};\n\nRestAdapter.prototype._invokeMethod = function (ctx, method, next) {\n const remotes = this.remotes;\n const steps = [];\n\n if (method.rest.before) {\n steps.push(function invokeRestBefore(cb) {\n debug('Invoking rest.before for ' + ctx.methodString);\n method.rest.before.call(ctx.getScope(), ctx, cb);\n });\n }\n\n steps.push(this.remotes.invokeMethodInContext.bind(this.remotes, ctx));\n\n if (method.rest.after) {\n steps.push(function invokeRestAfter(cb) {\n debug('Invoking rest.after for ' + ctx.methodString);\n method.rest.after.call(ctx.getScope(), ctx, cb);\n });\n }\n\n runSeries(steps, function (err) {\n if (err) {\n return next(err);\n }\n\n ctx.done(function (err) {\n if (err) {\n return next(err);\n }\n // otherwise do not call next middleware\n // the request is handled\n });\n });\n};\n\nRestAdapter.prototype.allRoutes = function () {\n const routes = [];\n const adapter = this;\n const classes = this.remotes.classes(this.options);\n let currentRoot = '';\n\n classes.forEach(function (sc) {\n adapter.getRoutes(sc).forEach(function (classRoute) {\n currentRoot = classRoute.path;\n const methods = sc.methods();\n\n methods.forEach(function (method) {\n adapter.getRoutes(method).forEach(function (route) {\n if (method.isStatic) {\n addRoute(route.verb, route.path, method);\n } else {\n adapter.getRoutes(method.sharedCtor).forEach(function (sharedCtorRoute) {\n addRoute(route.verb, sharedCtorRoute.path + route.path, method);\n });\n }\n });\n });\n });\n });\n\n return routes;\n\n function addRoute(verb, path, method) {\n if (path === '/' || path === '//') {\n path = currentRoot;\n } else {\n path = currentRoot + path;\n }\n\n if (path[path.length - 1] === '/') {\n path = path.substr(0, path.length - 1);\n }\n\n // TODO this could be cleaner\n path = path.replace(/\\/\\//g, '/');\n\n routes.push({\n verb: verb,\n path: path,\n description: method.description,\n notes: method.notes,\n documented: method.documented,\n method: method.stringName,\n accepts: method.accepts && method.accepts.length ? method.accepts : undefined,\n returns: method.returns && method.returns.length ? method.returns : undefined,\n errors: method.errors && method.errors.length ? method.errors : undefined,\n http: method.http,\n });\n }\n};\n\nRestAdapter.prototype.getClasses = function () {\n return this.remotes.classes(this.options).map((c) => {\n return new RestClass(c, this.options);\n });\n};\n\nfunction RestClass(sharedClass, adapterOptions) {\n nonEnumerableConstPropery(this, 'sharedClass', sharedClass);\n\n this.name = sharedClass.name;\n this.options = adapterOptions;\n this.routes = getRoutes(sharedClass, this.options);\n\n this.ctor = sharedClass.sharedCtor && new RestMethod(this, sharedClass.sharedCtor);\n\n this.methods = sharedClass\n .methods()\n .filter(function (sm) {\n return !sm.isSharedCtor;\n })\n .map(\n function (sm) {\n return new RestMethod(this, sm);\n }.bind(this),\n );\n}\n\nRestClass.prototype.getPath = function () {\n return this.routes[0].path;\n};\n\nfunction RestMethod(restClass, sharedMethod) {\n nonEnumerableConstPropery(this, 'restClass', restClass);\n nonEnumerableConstPropery(this, 'sharedMethod', sharedMethod);\n\n // The full name is ClassName.methodName or ClassName.prototype.methodName\n this.fullName = sharedMethod.stringName;\n this.name = this.fullName.split('.').slice(1).join('.');\n\n this.accepts = sharedMethod.accepts;\n this.returns = sharedMethod.returns;\n this.errors = sharedMethod.errors;\n this.description = sharedMethod.description;\n this.notes = sharedMethod.notes;\n this.documented = sharedMethod.documented;\n\n const methodRoutes = getRoutes(sharedMethod, restClass.options);\n if (sharedMethod.isStatic || !restClass.ctor) {\n this.routes = methodRoutes;\n } else {\n const routes = (this.routes = []);\n methodRoutes.forEach(function (route) {\n restClass.ctor.routes.forEach(function (ctorRoute) {\n const fullRoute = Object.assign({}, route);\n fullRoute.path = joinPaths(ctorRoute.path, route.path);\n routes.push(fullRoute);\n });\n });\n }\n}\n\n/**\n * Get the argument from the invoked arg array by arg name.\n * @param argName the name of the arg to lookup\n * @param invokedArgs array\n * @returns {*} the arg value or undefined if not found\n */\nRestMethod.prototype.getArgByName = function (argName, invokedArgs) {\n let argValue;\n if (!this.accepts || !this.accepts.length) return undefined;\n this.accepts.some(function (argProperty, i) {\n if (argProperty.arg && argProperty.arg.toLowerCase() === argName.toLowerCase()) {\n argValue = invokedArgs[i];\n return true;\n }\n return false;\n });\n return argValue;\n};\n\nRestMethod.prototype.isReturningArray = function () {\n return (\n (this.returns.length == 1 &&\n this.returns[0].root &&\n getTypeString(this.returns[0].type) === 'array') ||\n false\n );\n};\n\nRestMethod.prototype.acceptsSingleBodyArgument = function () {\n if (this.accepts.length != 1) return false;\n const accepts = this.accepts[0];\n\n return (\n (accepts.http && accepts.http.source == 'body' && getTypeString(accepts.type) == 'object') ||\n false\n );\n};\n\nRestMethod.prototype.getEndpoints = function () {\n const self = this;\n return this.routes.map(function (route) {\n let verbResult;\n const verb = route.verb;\n if (verb == 'all') {\n verbResult = 'POST';\n } else if (verb == 'del') {\n verbResult = 'DELETE';\n } else {\n verbResult = verb.toUpperCase();\n }\n return {\n verb: verbResult,\n fullPath: joinPaths(self.restClass.getPath(), route.path),\n };\n });\n};\n\nRestMethod.prototype.getHttpMethod = function () {\n // deprecate message to let the users know what they were using\n // was retuning just the first route's verb\n deprecated('getHttpMethod() is deprecated, use getEndpoints()[0].verb instead.');\n return this.getEndpoints()[0].verb;\n};\n\nRestMethod.prototype.getPath = function () {\n return this.routes[0].path;\n};\n\nRestMethod.prototype.getFullPath = function () {\n // deprecate message to let the users know what they were using\n // was retuning just the first route's path\n deprecated('getFullPath() is deprecated, use getEndpoints()[0].fullPath instead.');\n return this.getEndpoints()[0].fullPath;\n};\n\nfunction getTypeString(ctorOrName) {\n if (typeof ctorOrName === 'function') ctorOrName = ctorOrName.name;\n if (typeof ctorOrName === 'string') {\n return ctorOrName.toLowerCase();\n } else if (Array.isArray(ctorOrName)) {\n return 'array';\n } else {\n debug('WARNING: unkown ctorOrName of type %s: %j', typeof ctorOrName, ctorOrName);\n return typeof undefined;\n }\n}\n\nfunction nonEnumerableConstPropery(object, name, value) {\n Object.defineProperty(object, name, {\n value: value,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n}\n\nfunction joinPaths(left, right) {\n if (!left) return right;\n if (!right || right == '/') return left;\n\n const glue = left[left.length - 1] + right[0];\n if (glue == '//') return left + right.slice(1);\n else if (glue[0] == '/' || glue[1] == '/') return left + right;\n else return left + '/' + right;\n}\n\nfunction runSeries(steps, callback) {\n let index = 0;\n\n function next(err) {\n if (err || index === steps.length) {\n callback(err);\n return;\n }\n\n const step = steps[index];\n index += 1;\n step(next);\n }\n\n next();\n}\n\nfunction requestIsJson(req) {\n if (typeof req.is === 'function') {\n return req.is('application/json');\n }\n\n const contentType = getRequestHeader(req, 'content-type');\n return /^application\\/json\\b/i.test(contentType || '');\n}\n\nfunction getRequestHeader(req, name) {\n if (typeof req.get === 'function') {\n return req.get(name);\n }\n\n return req.headers && req.headers[name.toLowerCase()];\n}\n"],"mappings":";;;;;;;;CAQA,MAAM,IAAA;;;;AAIN,QAAO,UAAU;AAEjB,aAAY,YAAY;AACxB,aAAY,aAAa;;;;CAMzB,MAAM,aAAA,sBAAoC,kBAAkB;CAC5D,MAAM,eAAe,QAAQ,SAAS,CAAC;CACvC,MAAM,QAAQ,QAAQ,QAAQ,CAAC,+BAA+B;CAE9D,MAAM,WADO,QAAQ,OAAO,CACN;CACtB,MAAM,SAAS,QAAQ,SAAS;CAChC,MAAM,UAAU,QAAQ,UAAU;CAClC,MAAM,iBAAA;CACN,MAAM,cAAA;CACN,MAAM,qBAAqB,QAAQ,uBAAuB;CAE1D,MAAM,OAAO,QAAQ;CACrB,MAAM,aAAa,QAAQ;;;;;;;CAQ3B,SAAS,YAAY,SAAS,SAAS;AACrC,eAAa,KAAK,KAAK;AAEvB,OAAK,UAAU;AACf,OAAK,UAAU;AACf,OAAK,UAAU,YAAY,QAAQ,WAAW,EAAE,EAAE,QAAQ,EAAE;AAC5D,OAAK,eAAe,QAAQ;;;;;AAO9B,UAAS,aAAa,aAAa;;;;AAMnC,aAAY,SAAS,YAAY,oBAAoB,SAAU,SAAS;AAEtE,SAAO,IAAI,YAAY,QAAQ;;;;;AAOjC,aAAY,UAAU,YAAY,SAAU,KAAK;AAC/C,SAAO,UAAU,KAAK,KAAK,QAAQ;;CAGrC,SAAS,UAAU,KAAK,SAAS;EAC/B,IAAI,SAAS,IAAI;AACjB,MAAI,UAAU,CAAC,MAAM,QAAQ,OAAO,CAClC,UAAS,CAAC,OAAO;EAKnB,MAAM,gBADc,IA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AK,eAAe,GAAG;;CAGxD,SAAS,iBAAiB,KAAK,MAAM;AACnC,MAAI,OAAO,IAAI,QAAQ,WACrB,QAAO,IAAI,IAAI,KAAK;AAGtB,SAAO,IAAI,WAAW,IAAI,QAAQ,KAAK,aAAa"}
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ //#region src/lib/server-sent-events.ts
3
+ var require_server_sent_events = /* @__PURE__ */ require("../_virtual/_rolldown/runtime.js").__commonJSMin(((exports, module) => {
4
+ module.exports = ServerSentEvents;
5
+ const EventEmitter = require("events").EventEmitter;
6
+ const inherits = require("util").inherits;
7
+ function ServerSentEvents(req, res) {
8
+ EventEmitter.call(this);
9
+ this.req = req;
10
+ this.res = res;
11
+ this.initialized = false;
12
+ this.closed = false;
13
+ const emitClose = this._emitClose.bind(this);
14
+ if (req && typeof req.on === "function") req.on("close", emitClose);
15
+ if (res && typeof res.on === "function") res.on("close", emitClose);
16
+ }
17
+ inherits(ServerSentEvents, EventEmitter);
18
+ ServerSentEvents.prototype.initialize = function() {
19
+ if (this.initialized) return;
20
+ const res = this.res;
21
+ if (!res.getHeader("Content-Type")) res.setHeader("Content-Type", "text/event-stream");
22
+ if (!res.getHeader("Cache-Control")) res.setHeader("Cache-Control", "no-cache, no-transform");
23
+ if (!res.getHeader("Connection")) res.setHeader("Connection", "keep-alive");
24
+ if (typeof res.flushHeaders === "function") res.flushHeaders();
25
+ res.write("\n");
26
+ this.initialized = true;
27
+ };
28
+ ServerSentEvents.prototype.send = function(eventOrMessage, data) {
29
+ const message = normalizeMessage(eventOrMessage, data);
30
+ this.res.write(serializeMessage(message));
31
+ if (typeof this.res.flush === "function") this.res.flush();
32
+ };
33
+ ServerSentEvents.prototype._emitClose = function() {
34
+ if (this.closed) return;
35
+ this.closed = true;
36
+ this.emit("close");
37
+ };
38
+ function normalizeMessage(eventOrMessage, data) {
39
+ if (eventOrMessage && typeof eventOrMessage === "object") return eventOrMessage;
40
+ return {
41
+ event: eventOrMessage,
42
+ data
43
+ };
44
+ }
45
+ function serializeMessage(message) {
46
+ let output = "";
47
+ if (message.id !== void 0) output += serializeField("id", message.id);
48
+ if (message.event !== void 0) output += serializeField("event", message.event);
49
+ if (message.retry !== void 0) output += serializeField("retry", message.retry);
50
+ if (message.data === void 0) output += "data:\n";
51
+ else output += serializeField("data", message.data);
52
+ return output + "\n";
53
+ }
54
+ function serializeField(name, value) {
55
+ return String(value).split(/\r?\n/u).map((line) => name + ": " + line + "\n").join("");
56
+ }
57
+ }));
58
+ //#endregion
59
+ module.exports = require_server_sent_events();
60
+
61
+ //# sourceMappingURL=server-sent-events.js.map