@ruiapp/rapid-core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/bootstrapApplicationConfig.d.ts +3 -0
  2. package/dist/core/eventManager.d.ts +7 -0
  3. package/dist/core/http-types.d.ts +3 -0
  4. package/dist/core/httpHandler.d.ts +18 -0
  5. package/dist/core/plugin.d.ts +6 -0
  6. package/dist/core/pluginManager.d.ts +27 -0
  7. package/dist/core/request.d.ts +15 -0
  8. package/dist/core/response.d.ts +17 -0
  9. package/dist/core/routeContext.d.ts +17 -0
  10. package/dist/core/routesBuilder.d.ts +4 -0
  11. package/dist/core/server.d.ts +83 -0
  12. package/dist/dataAccess/dataAccessor.d.ts +20 -0
  13. package/dist/dataAccess/entityManager.d.ts +6 -0
  14. package/dist/dataAccess/entityMapper.d.ts +3 -0
  15. package/dist/dataAccess/filterHelper.d.ts +2 -0
  16. package/dist/dataAccess/propertyMapper.d.ts +3 -0
  17. package/dist/deno-std/assert/assert.d.ts +2 -0
  18. package/dist/deno-std/assert/assertion_error.d.ts +4 -0
  19. package/dist/deno-std/datetime/to_imf.d.ts +17 -0
  20. package/dist/deno-std/http/cookie.d.ts +134 -0
  21. package/dist/helpers/entityHelpers.d.ts +1 -0
  22. package/dist/helpers/inputHelper.d.ts +1 -0
  23. package/dist/helpers/runCollectionEntityHttpHandler.d.ts +5 -0
  24. package/dist/index.d.ts +7 -0
  25. package/dist/index.js +3590 -0
  26. package/dist/plugins/authManager/httpHandlers/createSession.d.ts +8 -0
  27. package/dist/plugins/authManager/httpHandlers/deleteSession.d.ts +4 -0
  28. package/dist/plugins/authManager/httpHandlers/getMyProfile.d.ts +4 -0
  29. package/dist/plugins/authManager/httpHandlers/index.d.ts +5 -0
  30. package/dist/plugins/authManager/mod.d.ts +16 -0
  31. package/dist/plugins/authManager/models/AccessToken.d.ts +3 -0
  32. package/dist/plugins/authManager/models/index.d.ts +2 -0
  33. package/dist/plugins/authManager/routes/getMyProfile.d.ts +3 -0
  34. package/dist/plugins/authManager/routes/index.d.ts +2 -0
  35. package/dist/plugins/authManager/routes/signin.d.ts +3 -0
  36. package/dist/plugins/authManager/routes/signout.d.ts +3 -0
  37. package/dist/plugins/dataManager/httpHandlers/addEntityRelations.d.ts +4 -0
  38. package/dist/plugins/dataManager/httpHandlers/countCollectionEntities.d.ts +4 -0
  39. package/dist/plugins/dataManager/httpHandlers/createCollectionEntitiesBatch.d.ts +4 -0
  40. package/dist/plugins/dataManager/httpHandlers/createCollectionEntity.d.ts +4 -0
  41. package/dist/plugins/dataManager/httpHandlers/deleteCollectionEntityById.d.ts +4 -0
  42. package/dist/plugins/dataManager/httpHandlers/findCollectionEntities.d.ts +4 -0
  43. package/dist/plugins/dataManager/httpHandlers/findCollectionEntityById.d.ts +4 -0
  44. package/dist/plugins/dataManager/httpHandlers/queryDatabase.d.ts +4 -0
  45. package/dist/plugins/dataManager/httpHandlers/removeEntityRelations.d.ts +4 -0
  46. package/dist/plugins/dataManager/httpHandlers/updateCollectionEntityById.d.ts +4 -0
  47. package/dist/plugins/dataManager/mod.d.ts +16 -0
  48. package/dist/plugins/metaManager/httpHandlers/getMetaModelDetail.d.ts +4 -0
  49. package/dist/plugins/metaManager/httpHandlers/listMetaModels.d.ts +4 -0
  50. package/dist/plugins/metaManager/mod.d.ts +15 -0
  51. package/dist/plugins/routeManager/httpHandlers/httpProxy.d.ts +4 -0
  52. package/dist/plugins/routeManager/httpHandlers/listMetaRoutes.d.ts +4 -0
  53. package/dist/plugins/routeManager/mod.d.ts +15 -0
  54. package/dist/plugins/webhooks/mod.d.ts +24 -0
  55. package/dist/plugins/webhooks/pluginConfig.d.ts +48 -0
  56. package/dist/polyfill.d.ts +1 -0
  57. package/dist/proxy/mod.d.ts +13 -0
  58. package/dist/proxy/types.d.ts +17 -0
  59. package/dist/queryBuilder/index.d.ts +1 -0
  60. package/dist/queryBuilder/queryBuilder.d.ts +34 -0
  61. package/dist/server.d.ts +31 -0
  62. package/dist/types.d.ts +327 -0
  63. package/dist/utilities/httpUtility.d.ts +1 -0
  64. package/dist/utilities/jwtUtility.d.ts +8 -0
  65. package/dist/utilities/rapidUtility.d.ts +2 -0
  66. package/dist/utilities/typeUtility.d.ts +3 -0
  67. package/package.json +29 -0
  68. package/rollup.config.js +20 -0
  69. package/src/bootstrapApplicationConfig.ts +524 -0
  70. package/src/core/eventManager.ts +21 -0
  71. package/src/core/http-types.ts +4 -0
  72. package/src/core/httpHandler.ts +29 -0
  73. package/src/core/plugin.ts +13 -0
  74. package/src/core/pluginManager.ts +143 -0
  75. package/src/core/request.ts +23 -0
  76. package/src/core/response.ts +77 -0
  77. package/src/core/routeContext.ts +38 -0
  78. package/src/core/routesBuilder.ts +86 -0
  79. package/src/core/server.ts +144 -0
  80. package/src/dataAccess/dataAccessor.ts +110 -0
  81. package/src/dataAccess/entityManager.ts +651 -0
  82. package/src/dataAccess/entityMapper.ts +74 -0
  83. package/src/dataAccess/filterHelper.ts +47 -0
  84. package/src/dataAccess/propertyMapper.ts +27 -0
  85. package/src/deno-std/assert/assert.ts +9 -0
  86. package/src/deno-std/assert/assertion_error.ts +7 -0
  87. package/src/deno-std/datetime/to_imf.ts +47 -0
  88. package/src/deno-std/http/cookie.ts +398 -0
  89. package/src/helpers/entityHelpers.ts +24 -0
  90. package/src/helpers/inputHelper.ts +11 -0
  91. package/src/helpers/runCollectionEntityHttpHandler.ts +34 -0
  92. package/src/index.ts +12 -0
  93. package/src/plugins/authManager/httpHandlers/createSession.ts +57 -0
  94. package/src/plugins/authManager/httpHandlers/deleteSession.ts +22 -0
  95. package/src/plugins/authManager/httpHandlers/getMyProfile.ts +43 -0
  96. package/src/plugins/authManager/httpHandlers/index.ts +10 -0
  97. package/src/plugins/authManager/mod.ts +56 -0
  98. package/src/plugins/authManager/models/AccessToken.ts +56 -0
  99. package/src/plugins/authManager/models/index.ts +5 -0
  100. package/src/plugins/authManager/routes/getMyProfile.ts +15 -0
  101. package/src/plugins/authManager/routes/index.ts +9 -0
  102. package/src/plugins/authManager/routes/signin.ts +15 -0
  103. package/src/plugins/authManager/routes/signout.ts +15 -0
  104. package/src/plugins/dataManager/httpHandlers/addEntityRelations.ts +76 -0
  105. package/src/plugins/dataManager/httpHandlers/countCollectionEntities.ts +22 -0
  106. package/src/plugins/dataManager/httpHandlers/createCollectionEntitiesBatch.ts +57 -0
  107. package/src/plugins/dataManager/httpHandlers/createCollectionEntity.ts +43 -0
  108. package/src/plugins/dataManager/httpHandlers/deleteCollectionEntityById.ts +38 -0
  109. package/src/plugins/dataManager/httpHandlers/findCollectionEntities.ts +35 -0
  110. package/src/plugins/dataManager/httpHandlers/findCollectionEntityById.ts +30 -0
  111. package/src/plugins/dataManager/httpHandlers/queryDatabase.ts +29 -0
  112. package/src/plugins/dataManager/httpHandlers/removeEntityRelations.ts +72 -0
  113. package/src/plugins/dataManager/httpHandlers/updateCollectionEntityById.ts +53 -0
  114. package/src/plugins/dataManager/mod.ts +150 -0
  115. package/src/plugins/metaManager/httpHandlers/getMetaModelDetail.ts +14 -0
  116. package/src/plugins/metaManager/httpHandlers/listMetaModels.ts +13 -0
  117. package/src/plugins/metaManager/mod.ts +419 -0
  118. package/src/plugins/routeManager/httpHandlers/httpProxy.ts +15 -0
  119. package/src/plugins/routeManager/httpHandlers/listMetaRoutes.ts +13 -0
  120. package/src/plugins/routeManager/mod.ts +97 -0
  121. package/src/plugins/webhooks/mod.ts +144 -0
  122. package/src/plugins/webhooks/pluginConfig.ts +74 -0
  123. package/src/polyfill.ts +5 -0
  124. package/src/proxy/mod.ts +47 -0
  125. package/src/proxy/types.ts +21 -0
  126. package/src/queryBuilder/index.ts +1 -0
  127. package/src/queryBuilder/queryBuilder.ts +424 -0
  128. package/src/server.ts +192 -0
  129. package/src/types.ts +438 -0
  130. package/src/utilities/httpUtility.ts +23 -0
  131. package/src/utilities/jwtUtility.ts +16 -0
  132. package/src/utilities/rapidUtility.ts +5 -0
  133. package/src/utilities/typeUtility.ts +11 -0
  134. package/tsconfig.json +19 -0
@@ -0,0 +1,74 @@
1
+ import { RpdDataModel } from "~/types";
2
+ import { isRelationProperty } from "~/utilities/rapidUtility";
3
+
4
+ // TODO Generate mapper and cache it.
5
+
6
+ export function mapDbRowToEntity(model: RpdDataModel, row: any) {
7
+ if (!row) {
8
+ return null;
9
+ }
10
+
11
+ if (!model.properties || !model.properties.length) {
12
+ return row;
13
+ }
14
+
15
+ const result: Record<string, any> = {};
16
+ const columnNames = Object.keys(row);
17
+ columnNames.forEach(columnName => {
18
+ let isRelationProp = false;
19
+ let propertyName = columnName;
20
+ let property = model.properties.find(item => item.columnName === columnName);
21
+ if (property) {
22
+ propertyName = property.code;
23
+ } else {
24
+ property = model.properties.find(item => item.relation === "one" && item.targetIdColumnName === columnName);
25
+ if (property) {
26
+ isRelationProp = true;
27
+ propertyName = property.code;
28
+ }
29
+ }
30
+
31
+ if (isRelationProp) {
32
+ if (row[propertyName] && !result[propertyName]) {
33
+ result[propertyName] = row[propertyName];
34
+ }
35
+ } else {
36
+ if (!result[propertyName]) {
37
+ result[propertyName] = row[columnName];
38
+ }
39
+ }
40
+ });
41
+
42
+ return result;
43
+ }
44
+
45
+
46
+ export function mapEntityToDbRow(model: RpdDataModel, entity: any) {
47
+ if (!entity) {
48
+ return null;
49
+ }
50
+
51
+ if (!model.properties || !model.properties.length) {
52
+ return entity;
53
+ }
54
+
55
+ const result: Record<string, any> = {};
56
+ const propertyNames = Object.keys(entity);
57
+ propertyNames.forEach(propertyName => {
58
+ let columnName = propertyName;
59
+ const property = model.properties.find(item => item.code === propertyName);
60
+ if (property) {
61
+ if (!isRelationProperty(property)) {
62
+ columnName = property.columnName || property.code;
63
+ result[columnName] = entity[propertyName];
64
+ }
65
+ } else {
66
+ const oneRelationProperty = model.properties.find(item => item.relation === "one" && item.targetIdColumnName === propertyName);
67
+ if (oneRelationProperty) {
68
+ result[propertyName] = entity[propertyName];
69
+ }
70
+ }
71
+ })
72
+
73
+ return result;
74
+ }
@@ -0,0 +1,47 @@
1
+ import { EntityFilterOptions, FindEntityExistenceFilterOptions, FindEntityLogicalFilterOptions } from "~/types";
2
+ import { isNullOrUndefined } from "~/utilities/typeUtility";
3
+
4
+ export function removeFiltersWithNullValue(filters?: EntityFilterOptions[]) {
5
+ const result: EntityFilterOptions[] = [];
6
+ if (!filters) {
7
+ return result;
8
+ }
9
+
10
+ for (const filter of filters) {
11
+ const { operator } = filter;
12
+
13
+ switch (operator) {
14
+ case "null":
15
+ case "notNull":
16
+ result.push(filter);
17
+ break;
18
+ case "exists":
19
+ case "notExists":
20
+ case "and":
21
+ case "or":
22
+ const transformedFilter = transformFilterWithSubFilters(filter);
23
+ if (transformedFilter !== null) {
24
+ result.push(transformedFilter);
25
+ }
26
+ break;
27
+ default:
28
+ if (!isNullOrUndefined(filter.value)) {
29
+ result.push(filter);
30
+ }
31
+ }
32
+ }
33
+
34
+ return result;
35
+ }
36
+
37
+ function transformFilterWithSubFilters(
38
+ filter: FindEntityExistenceFilterOptions | FindEntityLogicalFilterOptions,
39
+ ): FindEntityExistenceFilterOptions | FindEntityLogicalFilterOptions | null {
40
+ const subFilters = removeFiltersWithNullValue(filter.filters);
41
+ if (!subFilters.length) {
42
+ return null;
43
+ }
44
+
45
+ filter.filters = subFilters;
46
+ return filter;
47
+ }
@@ -0,0 +1,27 @@
1
+ import { RpdDataModel } from "~/types";
2
+ import { isRelationProperty } from "~/utilities/rapidUtility";
3
+
4
+ export function mapPropertyNameToColumnName(model: RpdDataModel, propertyName: string) {
5
+ if (!model.properties) {
6
+ return propertyName;
7
+ }
8
+
9
+ const property = model.properties.find(item => item.code === propertyName);
10
+ if (!property) {
11
+ return propertyName;
12
+ }
13
+
14
+ if (isRelationProperty(property) && property.relation === "one") {
15
+ return property.targetIdColumnName!;
16
+ }
17
+
18
+ return property.columnName || property.code;
19
+ }
20
+
21
+ export function mapPropertyNamesToColumnNames(model: RpdDataModel, propertyNames: string[]) {
22
+ if (!propertyNames || !propertyNames.length) {
23
+ return [];
24
+ }
25
+
26
+ return propertyNames.map(fieldName => mapPropertyNameToColumnName(model, fieldName));
27
+ }
@@ -0,0 +1,9 @@
1
+ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
2
+ import { AssertionError } from "./assertion_error";
3
+
4
+ /** Make an assertion, error will be thrown if `expr` does not have truthy value. */
5
+ export function assert(expr: unknown, msg = ""): asserts expr {
6
+ if (!expr) {
7
+ throw new AssertionError(msg);
8
+ }
9
+ }
@@ -0,0 +1,7 @@
1
+ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
2
+ export class AssertionError extends Error {
3
+ override name = "AssertionError";
4
+ constructor(message: string) {
5
+ super(message);
6
+ }
7
+ }
@@ -0,0 +1,47 @@
1
+ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
2
+ // This module is browser compatible.
3
+
4
+ /**
5
+ * Formats the given date to IMF date time format. (Reference:
6
+ * https://tools.ietf.org/html/rfc7231#section-7.1.1.1).
7
+ * IMF is the time format to use when generating times in HTTP
8
+ * headers. The time being formatted must be in UTC for Format to
9
+ * generate the correct format.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { toIMF } from "https://deno.land/std@$STD_VERSION/datetime/to_imf.ts";
14
+ *
15
+ * toIMF(new Date(0)); // => returns "Thu, 01 Jan 1970 00:00:00 GMT"
16
+ * ```
17
+ * @param date Date to parse
18
+ * @return IMF date formatted string
19
+ */
20
+ export function toIMF(date: Date): string {
21
+ function dtPad(v: string, lPad = 2): string {
22
+ return v.padStart(lPad, "0");
23
+ }
24
+ const d = dtPad(date.getUTCDate().toString());
25
+ const h = dtPad(date.getUTCHours().toString());
26
+ const min = dtPad(date.getUTCMinutes().toString());
27
+ const s = dtPad(date.getUTCSeconds().toString());
28
+ const y = date.getUTCFullYear();
29
+ const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
30
+ const months = [
31
+ "Jan",
32
+ "Feb",
33
+ "Mar",
34
+ "Apr",
35
+ "May",
36
+ "Jun",
37
+ "Jul",
38
+ "Aug",
39
+ "Sep",
40
+ "Oct",
41
+ "Nov",
42
+ "Dec",
43
+ ];
44
+ return `${days[date.getUTCDay()]}, ${d} ${
45
+ months[date.getUTCMonth()]
46
+ } ${y} ${h}:${min}:${s} GMT`;
47
+ }
@@ -0,0 +1,398 @@
1
+ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
2
+ // Structured similarly to Go's cookie.go
3
+ // https://github.com/golang/go/blob/master/src/net/http/cookie.go
4
+ // This module is browser compatible.
5
+
6
+ import { assert } from "../assert/assert";
7
+ import { toIMF } from "../datetime/to_imf";
8
+
9
+ export interface Cookie {
10
+ /** Name of the cookie. */
11
+ name: string;
12
+ /** Value of the cookie. */
13
+ value: string;
14
+ /** The cookie's `Expires` attribute, either as an explicit date or UTC milliseconds.
15
+ * @example <caption>Explicit date:</caption>
16
+ *
17
+ * ```ts
18
+ * import { Cookie } from "https://deno.land/std@$STD_VERSION/http/cookie.ts";
19
+ * const cookie: Cookie = {
20
+ * name: 'name',
21
+ * value: 'value',
22
+ * // expires on Fri Dec 30 2022
23
+ * expires: new Date('2022-12-31')
24
+ * }
25
+ * ```
26
+ *
27
+ * @example <caption>UTC milliseconds</caption>
28
+ *
29
+ * ```ts
30
+ * import { Cookie } from "https://deno.land/std@$STD_VERSION/http/cookie.ts";
31
+ * const cookie: Cookie = {
32
+ * name: 'name',
33
+ * value: 'value',
34
+ * // expires 10 seconds from now
35
+ * expires: Date.now() + 10000
36
+ * }
37
+ * ```
38
+ */
39
+ expires?: Date | number;
40
+ /** The cookie's `Max-Age` attribute, in seconds. Must be a non-negative integer. A cookie with a `maxAge` of `0` expires immediately. */
41
+ maxAge?: number;
42
+ /** The cookie's `Domain` attribute. Specifies those hosts to which the cookie will be sent. */
43
+ domain?: string;
44
+ /** The cookie's `Path` attribute. A cookie with a path will only be included in the `Cookie` request header if the requested URL matches that path. */
45
+ path?: string;
46
+ /** The cookie's `Secure` attribute. If `true`, the cookie will only be included in the `Cookie` request header if the connection uses SSL and HTTPS. */
47
+ secure?: boolean;
48
+ /** The cookie's `HTTPOnly` attribute. If `true`, the cookie cannot be accessed via JavaScript. */
49
+ httpOnly?: boolean;
50
+ /**
51
+ * Allows servers to assert that a cookie ought not to
52
+ * be sent along with cross-site requests.
53
+ */
54
+ sameSite?: "Strict" | "Lax" | "None";
55
+ /** Additional key value pairs with the form "key=value" */
56
+ unparsed?: string[];
57
+ }
58
+
59
+ const FIELD_CONTENT_REGEXP = /^(?=[\x20-\x7E]*$)[^()@<>,;:\\"\[\]?={}\s]+$/;
60
+
61
+ function toString(cookie: Cookie): string {
62
+ if (!cookie.name) {
63
+ return "";
64
+ }
65
+ const out: string[] = [];
66
+ validateName(cookie.name);
67
+ validateValue(cookie.name, cookie.value);
68
+ out.push(`${cookie.name}=${cookie.value}`);
69
+
70
+ // Fallback for invalid Set-Cookie
71
+ // ref: https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
72
+ if (cookie.name.startsWith("__Secure")) {
73
+ cookie.secure = true;
74
+ }
75
+ if (cookie.name.startsWith("__Host")) {
76
+ cookie.path = "/";
77
+ cookie.secure = true;
78
+ delete cookie.domain;
79
+ }
80
+
81
+ if (cookie.secure) {
82
+ out.push("Secure");
83
+ }
84
+ if (cookie.httpOnly) {
85
+ out.push("HttpOnly");
86
+ }
87
+ if (typeof cookie.maxAge === "number" && Number.isInteger(cookie.maxAge)) {
88
+ assert(
89
+ cookie.maxAge >= 0,
90
+ "Max-Age must be an integer superior or equal to 0",
91
+ );
92
+ out.push(`Max-Age=${cookie.maxAge}`);
93
+ }
94
+ if (cookie.domain) {
95
+ validateDomain(cookie.domain);
96
+ out.push(`Domain=${cookie.domain}`);
97
+ }
98
+ if (cookie.sameSite) {
99
+ out.push(`SameSite=${cookie.sameSite}`);
100
+ }
101
+ if (cookie.path) {
102
+ validatePath(cookie.path);
103
+ out.push(`Path=${cookie.path}`);
104
+ }
105
+ if (cookie.expires) {
106
+ const { expires } = cookie;
107
+ const dateString = toIMF(
108
+ typeof expires === "number" ? new Date(expires) : expires,
109
+ );
110
+ out.push(`Expires=${dateString}`);
111
+ }
112
+ if (cookie.unparsed) {
113
+ out.push(cookie.unparsed.join("; "));
114
+ }
115
+ return out.join("; ");
116
+ }
117
+
118
+ /**
119
+ * Validate Cookie Name.
120
+ * @param name Cookie name.
121
+ */
122
+ function validateName(name: string | undefined | null) {
123
+ if (name && !FIELD_CONTENT_REGEXP.test(name)) {
124
+ throw new TypeError(`Invalid cookie name: "${name}".`);
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Validate Path Value.
130
+ * See {@link https://tools.ietf.org/html/rfc6265#section-4.1.2.4}.
131
+ * @param path Path value.
132
+ */
133
+ function validatePath(path: string | null) {
134
+ if (path == null) {
135
+ return;
136
+ }
137
+ for (let i = 0; i < path.length; i++) {
138
+ const c = path.charAt(i);
139
+ if (
140
+ c < String.fromCharCode(0x20) || c > String.fromCharCode(0x7E) || c == ";"
141
+ ) {
142
+ throw new Error(
143
+ path + ": Invalid cookie path char '" + c + "'",
144
+ );
145
+ }
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Validate Cookie Value.
151
+ * See {@link https://tools.ietf.org/html/rfc6265#section-4.1}.
152
+ * @param value Cookie value.
153
+ */
154
+ function validateValue(name: string, value: string | null) {
155
+ if (value == null || name == null) return;
156
+ for (let i = 0; i < value.length; i++) {
157
+ const c = value.charAt(i);
158
+ if (
159
+ c < String.fromCharCode(0x21) || c == String.fromCharCode(0x22) ||
160
+ c == String.fromCharCode(0x2c) || c == String.fromCharCode(0x3b) ||
161
+ c == String.fromCharCode(0x5c) || c == String.fromCharCode(0x7f)
162
+ ) {
163
+ throw new Error(
164
+ "RFC2616 cookie '" + name + "' cannot contain character '" + c + "'",
165
+ );
166
+ }
167
+ if (c > String.fromCharCode(0x80)) {
168
+ throw new Error(
169
+ "RFC2616 cookie '" + name + "' can only have US-ASCII chars as value" +
170
+ c.charCodeAt(0).toString(16),
171
+ );
172
+ }
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Validate Cookie Domain.
178
+ * See {@link https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.2.3}.
179
+ * @param domain Cookie domain.
180
+ */
181
+ function validateDomain(domain: string) {
182
+ if (domain == null) {
183
+ return;
184
+ }
185
+ const char1 = domain.charAt(0);
186
+ const charN = domain.charAt(domain.length - 1);
187
+ if (char1 == "-" || charN == "." || charN == "-") {
188
+ throw new Error(
189
+ "Invalid first/last char in cookie domain: " + domain,
190
+ );
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Parse cookies of a header
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * import { getCookies } from "https://deno.land/std@$STD_VERSION/http/cookie.ts";
200
+ *
201
+ * const headers = new Headers();
202
+ * headers.set("Cookie", "full=of; tasty=chocolate");
203
+ *
204
+ * const cookies = getCookies(headers);
205
+ * console.log(cookies); // { full: "of", tasty: "chocolate" }
206
+ * ```
207
+ *
208
+ * @param headers The headers instance to get cookies from
209
+ * @return Object with cookie names as keys
210
+ */
211
+ export function getCookies(headers: Headers): Record<string, string> {
212
+ const cookie = headers.get("Cookie");
213
+ if (cookie != null) {
214
+ const out: Record<string, string> = {};
215
+ const c = cookie.split(";");
216
+ for (const kv of c) {
217
+ const [cookieKey, ...cookieVal] = kv.split("=");
218
+ assert(cookieKey != null);
219
+ const key = cookieKey.trim();
220
+ out[key] = cookieVal.join("=");
221
+ }
222
+ return out;
223
+ }
224
+ return {};
225
+ }
226
+
227
+ /**
228
+ * Set the cookie header properly in the headers
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * import {
233
+ * Cookie,
234
+ * setCookie,
235
+ * } from "https://deno.land/std@$STD_VERSION/http/cookie.ts";
236
+ *
237
+ * const headers = new Headers();
238
+ * const cookie: Cookie = { name: "Space", value: "Cat" };
239
+ * setCookie(headers, cookie);
240
+ *
241
+ * const cookieHeader = headers.get("set-cookie");
242
+ * console.log(cookieHeader); // Space=Cat
243
+ * ```
244
+ *
245
+ * @param headers The headers instance to set the cookie to
246
+ * @param cookie Cookie to set
247
+ */
248
+ export function setCookie(headers: Headers, cookie: Cookie) {
249
+ // Parsing cookie headers to make consistent set-cookie header
250
+ // ref: https://tools.ietf.org/html/rfc6265#section-4.1.1
251
+ const v = toString(cookie);
252
+ if (v) {
253
+ headers.append("Set-Cookie", v);
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Set the cookie header with empty value in the headers to delete it
259
+ *
260
+ * > Note: Deleting a `Cookie` will set its expiration date before now. Forcing
261
+ * > the browser to delete it.
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * import { deleteCookie } from "https://deno.land/std@$STD_VERSION/http/cookie.ts";
266
+ *
267
+ * const headers = new Headers();
268
+ * deleteCookie(headers, "deno");
269
+ *
270
+ * const cookieHeader = headers.get("set-cookie");
271
+ * console.log(cookieHeader); // deno=; Expires=Thus, 01 Jan 1970 00:00:00 GMT
272
+ * ```
273
+ *
274
+ * @param headers The headers instance to delete the cookie from
275
+ * @param name Name of cookie
276
+ * @param attributes Additional cookie attributes
277
+ */
278
+ export function deleteCookie(
279
+ headers: Headers,
280
+ name: string,
281
+ attributes?: { path?: string; domain?: string },
282
+ ) {
283
+ setCookie(headers, {
284
+ name: name,
285
+ value: "",
286
+ expires: new Date(0),
287
+ ...attributes,
288
+ });
289
+ }
290
+
291
+ function parseSetCookie(value: string): Cookie | null {
292
+ const attrs = value
293
+ .split(";")
294
+ .map((attr) => {
295
+ const [key, ...values] = attr.trim().split("=");
296
+ return [key, values.join("=")];
297
+ });
298
+ const cookie: Cookie = {
299
+ name: attrs[0][0],
300
+ value: attrs[0][1],
301
+ };
302
+
303
+ for (const [key, value] of attrs.slice(1)) {
304
+ switch (key.toLocaleLowerCase()) {
305
+ case "expires":
306
+ cookie.expires = new Date(value);
307
+ break;
308
+ case "max-age":
309
+ cookie.maxAge = Number(value);
310
+ if (cookie.maxAge < 0) {
311
+ console.warn(
312
+ "Max-Age must be an integer superior or equal to 0. Cookie ignored.",
313
+ );
314
+ return null;
315
+ }
316
+ break;
317
+ case "domain":
318
+ cookie.domain = value;
319
+ break;
320
+ case "path":
321
+ cookie.path = value;
322
+ break;
323
+ case "secure":
324
+ cookie.secure = true;
325
+ break;
326
+ case "httponly":
327
+ cookie.httpOnly = true;
328
+ break;
329
+ case "samesite":
330
+ cookie.sameSite = value as Cookie["sameSite"];
331
+ break;
332
+ default:
333
+ if (!Array.isArray(cookie.unparsed)) {
334
+ cookie.unparsed = [];
335
+ }
336
+ cookie.unparsed.push([key, value].join("="));
337
+ }
338
+ }
339
+ if (cookie.name.startsWith("__Secure-")) {
340
+ /** This requirement is mentioned in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie but not the RFC. */
341
+ if (!cookie.secure) {
342
+ console.warn(
343
+ "Cookies with names starting with `__Secure-` must be set with the secure flag. Cookie ignored.",
344
+ );
345
+ return null;
346
+ }
347
+ }
348
+ if (cookie.name.startsWith("__Host-")) {
349
+ if (!cookie.secure) {
350
+ console.warn(
351
+ "Cookies with names starting with `__Host-` must be set with the secure flag. Cookie ignored.",
352
+ );
353
+ return null;
354
+ }
355
+ if (cookie.domain !== undefined) {
356
+ console.warn(
357
+ "Cookies with names starting with `__Host-` must not have a domain specified. Cookie ignored.",
358
+ );
359
+ return null;
360
+ }
361
+ if (cookie.path !== "/") {
362
+ console.warn(
363
+ "Cookies with names starting with `__Host-` must have path be `/`. Cookie has been ignored.",
364
+ );
365
+ return null;
366
+ }
367
+ }
368
+ return cookie;
369
+ }
370
+
371
+ /**
372
+ * Parse set-cookies of a header
373
+ *
374
+ * @example
375
+ * ```ts
376
+ * import { getSetCookies } from "https://deno.land/std@$STD_VERSION/http/cookie.ts";
377
+ *
378
+ * const headers = new Headers([
379
+ * ["Set-Cookie", "lulu=meow; Secure; Max-Age=3600"],
380
+ * ["Set-Cookie", "booya=kasha; HttpOnly; Path=/"],
381
+ * ]);
382
+ *
383
+ * const cookies = getSetCookies(headers);
384
+ * console.log(cookies); // [{ name: "lulu", value: "meow", secure: true, maxAge: 3600 }, { name: "booya", value: "kahsa", httpOnly: true, path: "/ }]
385
+ * ```
386
+ *
387
+ * @param headers The headers instance to get set-cookies from
388
+ * @return List of cookies
389
+ */
390
+ export function getSetCookies(headers: Headers): Cookie[] {
391
+ // TODO(lino-levan): remove this ts-ignore when Typescript 5.2 lands in Deno
392
+ // @ts-ignore Typescript's TS Dom types will be out of date until 5.2
393
+ return headers.getSetCookie()
394
+ /** Parse each `set-cookie` header separately */
395
+ .map(parseSetCookie)
396
+ /** Skip empty cookies */
397
+ .filter(Boolean) as Cookie[];
398
+ }
@@ -0,0 +1,24 @@
1
+ export function getEntityPartChanges(
2
+ before: any,
3
+ after: any,
4
+ ): Record<string, any> | null {
5
+ if (!before) {
6
+ throw new Error("Argument 'before' can not be null.");
7
+ }
8
+
9
+ if (!after) {
10
+ throw new Error("Argument 'after' can not be null.");
11
+ }
12
+
13
+ let changed = null;
14
+ for (const key in after) {
15
+ if (after[key] != before[key]) {
16
+ if (changed) {
17
+ changed[key] = after[key];
18
+ } else {
19
+ changed = { [key]: after[key] };
20
+ }
21
+ }
22
+ }
23
+ return changed;
24
+ }
@@ -0,0 +1,11 @@
1
+ import * as _ from "lodash";
2
+
3
+ export function mergeInput(defaultInput: any, input: any, fixedInput: any) {
4
+ return _.mergeWith({}, defaultInput, input, fixedInput, doNotMergeArray);
5
+ }
6
+
7
+ function doNotMergeArray(objValue: any, srcValue: any) {
8
+ if (_.isArray(srcValue)) {
9
+ return srcValue;
10
+ }
11
+ }
@@ -0,0 +1,34 @@
1
+ import * as _ from "lodash";
2
+ import { IRpdDataAccessor, RunEntityHttpHandlerOptions } from "~/types";
3
+ import { mergeInput } from "./inputHelper";
4
+ import { HttpHandlerContext } from "~/core/httpHandler";
5
+
6
+ type DataAccessHandler = (
7
+ dataAccessor: IRpdDataAccessor,
8
+ input: any,
9
+ ) => Promise<any>;
10
+
11
+ export default async function runCollectionEntityHttpHandler(
12
+ ctx: HttpHandlerContext,
13
+ options: RunEntityHttpHandlerOptions,
14
+ code: string,
15
+ handleDataAccess: DataAccessHandler,
16
+ ) {
17
+ const { server, input } = ctx;
18
+ const { defaultInput, fixedInput } = options;
19
+
20
+ console.debug(`Running ${code} handler...`);
21
+
22
+ console.debug(`defaultInput: ${JSON.stringify(defaultInput)}`);
23
+ const mergedInput = mergeInput(defaultInput, input, fixedInput);
24
+ console.debug(`fixedInput: ${JSON.stringify(fixedInput)}`);
25
+ console.debug(`mergedInput: ${JSON.stringify(mergedInput)}`);
26
+
27
+ const dataAccessor = server.getDataAccessor(options);
28
+ const result = handleDataAccess(dataAccessor, mergedInput);
29
+ if (result instanceof Promise) {
30
+ ctx.output = await result;
31
+ } else {
32
+ ctx.output = result;
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { fixBigIntJSONSerialize } from "./polyfill";
2
+ fixBigIntJSONSerialize();
3
+
4
+ export * from "./types";
5
+ export * as RpdServer from "./server";
6
+ export * from "./server";
7
+
8
+ export * from "./core/request";
9
+ export * from "./core/routeContext";
10
+ export * from "./core/server";
11
+
12
+ export * as bootstrapApplicationConfig from "./bootstrapApplicationConfig";