@celljs/core 3.9.0 → 4.1.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 (219) hide show
  1. package/README.md +0 -6
  2. package/cell.remote.yml +8 -0
  3. package/cell.yml +0 -3
  4. package/esm/common/application/application-entry.js +21 -3
  5. package/esm/common/application/application-entry.js.map +1 -1
  6. package/esm/common/application/application-host.d.ts +38 -0
  7. package/esm/common/application/application-host.js +17 -0
  8. package/esm/common/application/application-host.js.map +1 -0
  9. package/esm/common/application/application-protocol.js +1 -1
  10. package/esm/common/application/application-protocol.js.map +1 -1
  11. package/esm/common/application/index.d.ts +1 -0
  12. package/esm/common/application/index.js +1 -0
  13. package/esm/common/application/index.js.map +1 -1
  14. package/esm/common/config/config-provider.js +2 -1
  15. package/esm/common/config/config-provider.js.map +1 -1
  16. package/esm/common/config/env-config-util.d.ts +48 -0
  17. package/esm/common/config/env-config-util.js +185 -0
  18. package/esm/common/config/env-config-util.js.map +1 -0
  19. package/esm/common/config/index.d.ts +1 -0
  20. package/esm/common/config/index.js +1 -0
  21. package/esm/common/config/index.js.map +1 -1
  22. package/esm/common/container/auto-bind.js +26 -12
  23. package/esm/common/container/auto-bind.js.map +1 -1
  24. package/esm/common/el/expression-compiler.d.ts +4 -15
  25. package/esm/common/el/expression-compiler.js +6 -163
  26. package/esm/common/el/expression-compiler.js.map +1 -1
  27. package/esm/common/el/expression-handler.d.ts +7 -2
  28. package/esm/common/el/expression-handler.js +14 -53
  29. package/esm/common/el/expression-handler.js.map +1 -1
  30. package/esm/common/el/expression-util.d.ts +68 -0
  31. package/esm/common/el/expression-util.js +347 -0
  32. package/esm/common/el/expression-util.js.map +1 -0
  33. package/esm/common/el/index.d.ts +1 -0
  34. package/esm/common/el/index.js +1 -0
  35. package/esm/common/el/index.js.map +1 -1
  36. package/esm/common/logger/abstract-logger.d.ts +4 -2
  37. package/esm/common/logger/abstract-logger.js +11 -6
  38. package/esm/common/logger/abstract-logger.js.map +1 -1
  39. package/esm/common/logger/logger-protocol.d.ts +4 -0
  40. package/esm/common/logger/logger-protocol.js +2 -0
  41. package/esm/common/logger/logger-protocol.js.map +1 -1
  42. package/esm/common/logger/logger.js +7 -7
  43. package/esm/common/logger/logger.js.map +1 -1
  44. package/esm/common/test/mock-logger.d.ts +1 -0
  45. package/esm/common/test/mock-logger.js +3 -0
  46. package/esm/common/test/mock-logger.js.map +1 -1
  47. package/esm/common/utils/emitter.d.ts +1 -10
  48. package/esm/common/utils/emitter.js +0 -56
  49. package/esm/common/utils/emitter.js.map +1 -1
  50. package/esm/common/utils/mime-type-util.js +1 -1
  51. package/esm/common/utils/mime-type-util.js.map +1 -1
  52. package/esm/common/utils/mime-type.js +1 -1
  53. package/esm/common/utils/mime-type.js.map +1 -1
  54. package/esm/node/context/context.d.ts +11 -2
  55. package/esm/node/context/context.js +36 -12
  56. package/esm/node/context/context.js.map +1 -1
  57. package/esm/node/index.d.ts +0 -1
  58. package/esm/node/index.js +0 -1
  59. package/esm/node/index.js.map +1 -1
  60. package/lib/common/aop/aop.spec.d.ts +2 -0
  61. package/lib/common/aop/aop.spec.d.ts.map +1 -0
  62. package/lib/common/aop/aop.spec.js +170 -0
  63. package/lib/common/aop/aop.spec.js.map +1 -0
  64. package/lib/common/application/application-entry.d.ts.map +1 -1
  65. package/lib/common/application/application-entry.js +21 -3
  66. package/lib/common/application/application-entry.js.map +1 -1
  67. package/lib/common/application/application-host.d.ts +39 -0
  68. package/lib/common/application/application-host.d.ts.map +1 -0
  69. package/lib/common/application/application-host.js +20 -0
  70. package/lib/common/application/application-host.js.map +1 -0
  71. package/lib/common/application/application-protocol.js +1 -1
  72. package/lib/common/application/application-protocol.js.map +1 -1
  73. package/lib/common/application/index.d.ts +1 -0
  74. package/lib/common/application/index.d.ts.map +1 -1
  75. package/lib/common/application/index.js +1 -0
  76. package/lib/common/application/index.js.map +1 -1
  77. package/lib/common/application/lifecycle.spec.d.ts +2 -0
  78. package/lib/common/application/lifecycle.spec.d.ts.map +1 -0
  79. package/lib/common/application/lifecycle.spec.js +155 -0
  80. package/lib/common/application/lifecycle.spec.js.map +1 -0
  81. package/lib/common/config/config-provider.js +2 -1
  82. package/lib/common/config/config-provider.js.map +1 -1
  83. package/lib/common/config/env-config-util.d.ts +49 -0
  84. package/lib/common/config/env-config-util.d.ts.map +1 -0
  85. package/lib/common/config/env-config-util.js +188 -0
  86. package/lib/common/config/env-config-util.js.map +1 -0
  87. package/lib/common/config/env-config-util.spec.d.ts +2 -0
  88. package/lib/common/config/env-config-util.spec.d.ts.map +1 -0
  89. package/lib/common/config/env-config-util.spec.js +314 -0
  90. package/lib/common/config/env-config-util.spec.js.map +1 -0
  91. package/lib/common/config/index.d.ts +1 -0
  92. package/lib/common/config/index.d.ts.map +1 -1
  93. package/lib/common/config/index.js +1 -0
  94. package/lib/common/config/index.js.map +1 -1
  95. package/lib/common/container/assembly.spec.d.ts +2 -0
  96. package/lib/common/container/assembly.spec.d.ts.map +1 -0
  97. package/lib/common/container/assembly.spec.js +464 -0
  98. package/lib/common/container/assembly.spec.js.map +1 -0
  99. package/lib/common/container/auto-bind.js +26 -12
  100. package/lib/common/container/auto-bind.js.map +1 -1
  101. package/lib/common/el/expression-compiler.d.ts +4 -15
  102. package/lib/common/el/expression-compiler.d.ts.map +1 -1
  103. package/lib/common/el/expression-compiler.js +6 -163
  104. package/lib/common/el/expression-compiler.js.map +1 -1
  105. package/lib/common/el/expression-handler.d.ts +7 -2
  106. package/lib/common/el/expression-handler.d.ts.map +1 -1
  107. package/lib/common/el/expression-handler.js +14 -56
  108. package/lib/common/el/expression-handler.js.map +1 -1
  109. package/lib/common/el/expression-handler.spec.d.ts +2 -0
  110. package/lib/common/el/expression-handler.spec.d.ts.map +1 -0
  111. package/lib/common/el/expression-handler.spec.js +99 -0
  112. package/lib/common/el/expression-handler.spec.js.map +1 -0
  113. package/lib/common/el/expression-util.d.ts +69 -0
  114. package/lib/common/el/expression-util.d.ts.map +1 -0
  115. package/lib/common/el/expression-util.js +352 -0
  116. package/lib/common/el/expression-util.js.map +1 -0
  117. package/lib/common/el/expression-util.spec.d.ts +2 -0
  118. package/lib/common/el/expression-util.spec.d.ts.map +1 -0
  119. package/lib/common/el/expression-util.spec.js +45 -0
  120. package/lib/common/el/expression-util.spec.js.map +1 -0
  121. package/lib/common/el/index.d.ts +1 -0
  122. package/lib/common/el/index.d.ts.map +1 -1
  123. package/lib/common/el/index.js +1 -0
  124. package/lib/common/el/index.js.map +1 -1
  125. package/lib/common/el/value-and-el.spec.d.ts +2 -0
  126. package/lib/common/el/value-and-el.spec.d.ts.map +1 -0
  127. package/lib/common/el/value-and-el.spec.js +216 -0
  128. package/lib/common/el/value-and-el.spec.js.map +1 -0
  129. package/lib/common/logger/abstract-logger.d.ts +4 -2
  130. package/lib/common/logger/abstract-logger.d.ts.map +1 -1
  131. package/lib/common/logger/abstract-logger.js +10 -5
  132. package/lib/common/logger/abstract-logger.js.map +1 -1
  133. package/lib/common/logger/logger-protocol.d.ts +4 -0
  134. package/lib/common/logger/logger-protocol.d.ts.map +1 -1
  135. package/lib/common/logger/logger-protocol.js +3 -1
  136. package/lib/common/logger/logger-protocol.js.map +1 -1
  137. package/lib/common/logger/logger.js +7 -7
  138. package/lib/common/logger/logger.js.map +1 -1
  139. package/lib/common/logger/logger.spec.d.ts +2 -0
  140. package/lib/common/logger/logger.spec.d.ts.map +1 -0
  141. package/lib/common/logger/logger.spec.js +57 -0
  142. package/lib/common/logger/logger.spec.js.map +1 -0
  143. package/lib/common/test/mock-logger.d.ts +1 -0
  144. package/lib/common/test/mock-logger.d.ts.map +1 -1
  145. package/lib/common/test/mock-logger.js +3 -0
  146. package/lib/common/test/mock-logger.js.map +1 -1
  147. package/lib/common/utils/emitter.d.ts +1 -10
  148. package/lib/common/utils/emitter.d.ts.map +1 -1
  149. package/lib/common/utils/emitter.js +1 -58
  150. package/lib/common/utils/emitter.js.map +1 -1
  151. package/lib/common/utils/mime-type-util.js +1 -1
  152. package/lib/common/utils/mime-type-util.js.map +1 -1
  153. package/lib/common/utils/mime-type.js +1 -1
  154. package/lib/common/utils/mime-type.js.map +1 -1
  155. package/lib/common/utils/utils-behavior.spec.d.ts +2 -0
  156. package/lib/common/utils/utils-behavior.spec.d.ts.map +1 -0
  157. package/lib/common/utils/utils-behavior.spec.js +232 -0
  158. package/lib/common/utils/utils-behavior.spec.js.map +1 -0
  159. package/lib/node/context/context.d.ts +11 -2
  160. package/lib/node/context/context.d.ts.map +1 -1
  161. package/lib/node/context/context.js +36 -10
  162. package/lib/node/context/context.js.map +1 -1
  163. package/lib/node/context/context.spec.d.ts +2 -0
  164. package/lib/node/context/context.spec.d.ts.map +1 -0
  165. package/lib/node/context/context.spec.js +202 -0
  166. package/lib/node/context/context.spec.js.map +1 -0
  167. package/lib/node/index.d.ts +0 -1
  168. package/lib/node/index.d.ts.map +1 -1
  169. package/lib/node/index.js +0 -1
  170. package/lib/node/index.js.map +1 -1
  171. package/package.json +20 -41
  172. package/src/common/aop/aop.spec.ts +145 -0
  173. package/src/common/application/application-entry.ts +20 -4
  174. package/src/common/application/application-host.ts +46 -0
  175. package/src/common/application/application-protocol.ts +1 -1
  176. package/src/common/application/index.ts +1 -0
  177. package/src/common/application/lifecycle.spec.ts +148 -0
  178. package/src/common/config/config-provider.ts +1 -1
  179. package/src/common/config/env-config-util.spec.ts +341 -0
  180. package/src/common/config/env-config-util.ts +225 -0
  181. package/src/common/config/index.ts +1 -0
  182. package/src/common/container/assembly.spec.ts +293 -0
  183. package/src/common/container/auto-bind.ts +23 -10
  184. package/src/common/el/expression-compiler.ts +6 -166
  185. package/src/common/el/expression-handler.spec.ts +110 -0
  186. package/src/common/el/expression-handler.ts +14 -51
  187. package/src/common/el/expression-util.spec.ts +45 -0
  188. package/src/common/el/expression-util.ts +363 -0
  189. package/src/common/el/index.ts +2 -1
  190. package/src/common/el/value-and-el.spec.ts +186 -0
  191. package/src/common/logger/abstract-logger.ts +12 -6
  192. package/src/common/logger/logger-protocol.ts +5 -0
  193. package/src/common/logger/logger.spec.ts +61 -0
  194. package/src/common/logger/logger.ts +7 -7
  195. package/src/common/test/mock-logger.ts +3 -0
  196. package/src/common/utils/emitter.ts +1 -63
  197. package/src/common/utils/mime-type-util.ts +1 -1
  198. package/src/common/utils/mime-type.ts +1 -1
  199. package/src/common/utils/utils-behavior.spec.ts +259 -0
  200. package/src/node/context/context.spec.ts +219 -0
  201. package/src/node/context/context.ts +35 -10
  202. package/src/node/index.ts +0 -1
  203. package/cell-remote.yml +0 -3
  204. package/esm/node/utils/crc.d.ts +0 -1
  205. package/esm/node/utils/crc.js +0 -7
  206. package/esm/node/utils/crc.js.map +0 -1
  207. package/esm/node/utils/index.d.ts +0 -1
  208. package/esm/node/utils/index.js +0 -2
  209. package/esm/node/utils/index.js.map +0 -1
  210. package/lib/node/utils/crc.d.ts +0 -2
  211. package/lib/node/utils/crc.d.ts.map +0 -1
  212. package/lib/node/utils/crc.js +0 -10
  213. package/lib/node/utils/crc.js.map +0 -1
  214. package/lib/node/utils/index.d.ts +0 -2
  215. package/lib/node/utils/index.d.ts.map +0 -1
  216. package/lib/node/utils/index.js +0 -18
  217. package/lib/node/utils/index.js.map +0 -1
  218. package/src/node/utils/crc.ts +0 -7
  219. package/src/node/utils/index.ts +0 -1
@@ -0,0 +1,225 @@
1
+ /** An environment variable that was applied to the configuration. */
2
+ export interface EnvOverride {
3
+ variable: string;
4
+ /** Dotted path of the overridden key, e.g. `cell.server.port`. */
5
+ path: string;
6
+ /**
7
+ * Set when the first key also exists under `cell`: the top-level key wins, and this is the path
8
+ * under `cell` that the variable does not set (reach it with `CELL_<TARGET>__CELL__...`).
9
+ */
10
+ shadows?: string;
11
+ }
12
+
13
+ /** An environment variable with the override prefix that could not be applied. */
14
+ export interface EnvOverrideProblem {
15
+ variable: string;
16
+ message: string;
17
+ }
18
+
19
+ export interface EnvOverrideResult {
20
+ applied: EnvOverride[];
21
+ problems: EnvOverrideProblem[];
22
+ }
23
+
24
+ /**
25
+ * Overrides configuration keys from environment variables: `CELL_BACKEND__SERVER__PORT=8080` sets
26
+ * `cell.server.port` of the backend. Segments are separated by `__` and matched against existing
27
+ * keys ignoring case, `_` and `-` (`ORM_CONFIG` matches `ormConfig`, `SERVE_STATIC` matches
28
+ * `serve-static`); array items are addressed by canonical index. The first key is looked up at the
29
+ * top level, then under `cell`, so `SERVER__PORT` is short for `CELL__SERVER__PORT` unless the
30
+ * project has a top-level `server` of its own; `CELL__...` always means `cell`.
31
+ *
32
+ * Only existing keys can be overridden, so a misspelled variable is reported instead of silently
33
+ * ignored. Each key is set by one variable at most: variables that set the same key, or a key and
34
+ * one inside it, are all reported and none applies, whatever their order. The value is converted to
35
+ * the type of the value it replaces (a finite number in JSON syntax, `true` / `false`, JSON for
36
+ * objects and arrays, JSON or text where cell.yml has `null`, text for strings); a value that is one
37
+ * `${...}` expression is kept and evaluated like cell.yml. Overrides land before `${...}`
38
+ * expressions are evaluated, so references such as `${cell.server.port}` see the new value. The
39
+ * backend applies its variables at startup; the frontend applies them when it is built.
40
+ */
41
+ export namespace EnvConfigUtil {
42
+
43
+ export const PREFIXES = { backend: 'CELL_BACKEND__', frontend: 'CELL_FRONTEND__' } as const;
44
+
45
+ export type Target = keyof typeof PREFIXES;
46
+
47
+ interface Resolved {
48
+ variable: string;
49
+ value: string;
50
+ /** Keys from the root, as written in the configuration. */
51
+ keys: string[];
52
+ shadows?: string;
53
+ }
54
+
55
+ /** Applies the variables of `target` in `env` to `config` in place. */
56
+ export function apply(config: Record<string, any>, env: Record<string, string | undefined>, target: Target): EnvOverrideResult {
57
+ const result: EnvOverrideResult = { applied: [], problems: [] };
58
+ const prefix = PREFIXES[target];
59
+ const resolved: Resolved[] = [];
60
+ for (const variable of Object.keys(env).filter(name => name.startsWith(prefix)).sort()) {
61
+ const value = env[variable];
62
+ if (value === undefined) {
63
+ continue;
64
+ }
65
+ try {
66
+ resolved.push({ variable, value, ...resolve(config, variable.slice(prefix.length).split('__')) });
67
+ } catch (error) {
68
+ result.problems.push({ variable, message: (error as Error).message });
69
+ }
70
+ }
71
+ // Paths are resolved against cell.yml before anything changes, so the outcome never depends on the order of the variables.
72
+ for (const entry of resolved) {
73
+ const path = entry.keys.join('.');
74
+ const others = resolved.filter(other => other !== entry && overlaps(entry.keys, other.keys));
75
+ if (others.length > 0) {
76
+ const list = others.map(other => `${other.variable} (${other.keys.join('.')})`).join(', ');
77
+ result.problems.push({ variable: entry.variable, message: `sets ${path}, which ${list} also set${others.length === 1 ? 's' : ''}. Set each key with one variable; to change items of an object or array you replace, write them into its JSON.` });
78
+ continue;
79
+ }
80
+ try {
81
+ assign(config, entry.keys, entry.value);
82
+ result.applied.push({ variable: entry.variable, path, ...(entry.shadows ? { shadows: entry.shadows } : {}) });
83
+ } catch (error) {
84
+ result.problems.push({ variable: entry.variable, message: (error as Error).message });
85
+ }
86
+ }
87
+ result.problems.sort((x, y) => (x.variable < y.variable ? -1 : x.variable > y.variable ? 1 : 0));
88
+ return result;
89
+ }
90
+
91
+ /** Applies the backend variables of `process.env` and warns about the ones that do not apply. */
92
+ export function applyProcessEnv(config: Record<string, any>): EnvOverrideResult {
93
+ const result = apply(config, process.env, 'backend');
94
+ for (const problem of result.problems) {
95
+ console.warn(`[cell] ${problem.variable} is ignored: ${problem.message}`);
96
+ }
97
+ return result;
98
+ }
99
+
100
+ /** The same key, or one inside the other. */
101
+ function overlaps(a: string[], b: string[]): boolean {
102
+ const length = Math.min(a.length, b.length);
103
+ return a.slice(0, length).every((key, i) => key === b[i]);
104
+ }
105
+
106
+ function resolve(config: Record<string, any>, segments: string[]): Pick<Resolved, 'keys' | 'shadows'> {
107
+ if (segments.some(segment => !segment)) {
108
+ throw new Error('empty segment; separate keys with exactly two underscores.');
109
+ }
110
+ const cell = config.cell && typeof config.cell === 'object' ? config.cell : undefined;
111
+ const top = find(config, segments[0]);
112
+ const inCell = cell ? find(cell, segments[0]) : undefined;
113
+ if (top === undefined && inCell === undefined) {
114
+ const cellKeys = cell ? ` or under cell (keys: ${Object.keys(cell).join(', ') || '(none)'})` : '';
115
+ throw new Error(
116
+ `no key '${segments[0]}' at the top level (keys: ${Object.keys(config).join(', ') || '(none)'})${cellKeys}. Only keys present in cell.yml can be overridden.`,
117
+ );
118
+ }
119
+ const keys: string[] = top === undefined ? ['cell'] : [];
120
+ const shadows = top !== undefined && inCell !== undefined && top !== 'cell' ? `cell.${inCell}` : undefined;
121
+ let node: any = top === undefined ? cell : config;
122
+ for (let i = 0; i < segments.length; i++) {
123
+ const key = find(node, segments[i]);
124
+ if (key === undefined) {
125
+ const where = keys.length > 0 ? keys.join('.') : 'the top level';
126
+ const available = Array.isArray(node) ? `indexes 0-${node.length - 1}` : `keys: ${Object.keys(node).join(', ') || '(none)'}`;
127
+ throw new Error(`no key '${segments[i]}' under ${where} (${available}). Only keys present in cell.yml can be overridden.`);
128
+ }
129
+ keys.push(key);
130
+ if (i < segments.length - 1) {
131
+ if (!node[key] || typeof node[key] !== 'object') {
132
+ throw new Error(`${keys.join('.')} is not an object, so it has no key '${segments[i + 1]}'.`);
133
+ }
134
+ node = node[key];
135
+ }
136
+ }
137
+ return { keys, ...(shadows ? { shadows } : {}) };
138
+ }
139
+
140
+ function assign(config: Record<string, any>, keys: string[], value: string): void {
141
+ const parent = keys.slice(0, -1).reduce((node, key) => node[key], config);
142
+ const last = keys[keys.length - 1];
143
+ parent[last] = convert(parent[last], value, keys.join('.'));
144
+ }
145
+
146
+ function find(node: any, segment: string): string | undefined {
147
+ if (Array.isArray(node)) {
148
+ // Canonical indexes only: '08' would set a property named '08', not item 8.
149
+ return /^(0|[1-9]\d*)$/.test(segment) && Number(segment) < node.length ? segment : undefined;
150
+ }
151
+ const wanted = normalize(segment);
152
+ const keys = Object.keys(node);
153
+ return keys.find(key => key === segment) ?? keys.find(key => normalize(key) === wanted);
154
+ }
155
+
156
+ function normalize(key: string): string {
157
+ return key.replace(/[-_]/g, '').toLowerCase();
158
+ }
159
+
160
+ /** JSON number syntax: `Number()` would also take '', 'Infinity', '0x10' and ' 8 '. */
161
+ const NUMBER = /^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$/;
162
+
163
+ /** A value that is one `${...}` expression and nothing else. */
164
+ function isExpression(value: string): boolean {
165
+ return value.startsWith('${') && value.endsWith('}') && value.indexOf('${', 2) === -1;
166
+ }
167
+
168
+ /**
169
+ * Converts `value` to the type of `current`, the value in cell.yml. A value that is one `${...}`
170
+ * expression is kept for evaluation, as if written in cell.yml, so its result decides the type:
171
+ * `CELL_BACKEND__SERVER__PORT='${env.PORT}'` works although the port is a number.
172
+ */
173
+ function convert(current: unknown, value: string, path: string): unknown {
174
+ if (isExpression(value)) {
175
+ return value;
176
+ }
177
+ switch (typeof current) {
178
+ case 'number':
179
+ return number(value, path);
180
+ case 'boolean':
181
+ if (!/^(true|false)$/i.test(value)) {
182
+ throw new Error(`${path} is a boolean, got '${value}'. Use true or false.`);
183
+ }
184
+ return value.toLowerCase() === 'true';
185
+ case 'object':
186
+ if (current === null) {
187
+ // No type to follow: JSON when it is JSON (null, 5, true, "x", [], {}), else the text.
188
+ const parsed = parse(value);
189
+ return parsed ? parsed.value : value;
190
+ }
191
+ return json(current, value, path);
192
+ default:
193
+ return value;
194
+ }
195
+ }
196
+
197
+ function number(value: string, path: string): number {
198
+ const result = NUMBER.test(value) ? Number(value) : NaN;
199
+ if (!Number.isFinite(result)) {
200
+ throw new Error(`${path} is a number, got '${value}'. Use a decimal number such as 8080, -1 or 0.5.`);
201
+ }
202
+ // An integer literal past 2^53 would silently become a different number.
203
+ if (/^-?\d+$/.test(value) && !Number.isSafeInteger(result)) {
204
+ throw new Error(`${path} is a number, got '${value}', which is too large to keep exactly. Use a string in cell.yml for such values.`);
205
+ }
206
+ return result;
207
+ }
208
+
209
+ function json(current: object, value: string, path: string): unknown {
210
+ const kind = Array.isArray(current) ? 'an array' : 'an object';
211
+ const parsed = parse(value)?.value;
212
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed) !== Array.isArray(current)) {
213
+ throw new Error(`${path} is ${kind}; pass it as JSON, or override its keys one by one.`);
214
+ }
215
+ return parsed;
216
+ }
217
+
218
+ function parse(value: string): { value: unknown } | undefined {
219
+ try {
220
+ return { value: JSON.parse(value) };
221
+ } catch {
222
+ return undefined;
223
+ }
224
+ }
225
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './config-protocol';
2
2
  export * from './config-provider';
3
3
  export * from './config-util';
4
+ export * from './env-config-util';
@@ -0,0 +1,293 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { ApplicationFactory } from '../application/application-factory';
4
+ import {
5
+ Component, Autowired, Optional, Constant, AutowiredProvider, PostConstruct, Named, Tagged
6
+ } from '../annotation';
7
+ import { ContainerUtil } from './container-util';
8
+ import { ContainerProvider } from './container-provider';
9
+ import { Scope } from './scope';
10
+ import { Provider } from '../provider';
11
+ import { ConfigProvider } from '../config/config-protocol';
12
+ import { autoBind } from './auto-bind';
13
+
14
+ /**
15
+ * 组件装配的约定(阶段 1.E 行为测试):只用公开的注解、ApplicationFactory 和 ContainerUtil 断言,
16
+ * 不碰 inversify 的 API,这样阶段 2 换容器时这些用例可以原样复用。
17
+ *
18
+ * 注意:组件元数据是全局登记的,ApplicationFactory.create() 里的 autoBind() 会把登记过的全部取走。
19
+ * 所以每个用例都在自己的函数里定义类,然后马上 create,用例之间互不影响。
20
+ */
21
+ async function boot(props: Record<string, any> = {}) {
22
+ return ApplicationFactory.create(props);
23
+ }
24
+
25
+ describe('core 组件装配', () => {
26
+
27
+ it('@Component 不带参数时以类本身为 id,默认单例', async () => {
28
+ @Component()
29
+ class Plain { }
30
+ await boot();
31
+ const a = ContainerUtil.get(Plain);
32
+ expect(a).to.be.instanceOf(Plain);
33
+ expect(ContainerUtil.get(Plain)).to.equal(a);
34
+ });
35
+
36
+ it('@Component(id) 同时可以按类和按 id 取到,且是同一个实例', async () => {
37
+ const Greeter = Symbol('Greeter');
38
+ @Component(Greeter)
39
+ class GreeterImpl { hello() { return 'hi'; } }
40
+ await boot();
41
+ const byId = ContainerUtil.get<GreeterImpl>(Greeter);
42
+ expect(byId.hello()).to.equal('hi');
43
+ expect(ContainerUtil.get(GreeterImpl)).to.equal(byId);
44
+ });
45
+
46
+ it('一个组件可以登记多个 id,都指向同一个实例', async () => {
47
+ const A = Symbol('A');
48
+ const B = Symbol('B');
49
+ @Component({ id: [A, B] })
50
+ class Both { }
51
+ await boot();
52
+ expect(ContainerUtil.get(A)).to.be.instanceOf(Both);
53
+ expect(ContainerUtil.get(A)).to.equal(ContainerUtil.get(B));
54
+ expect(ContainerUtil.get(Both)).to.equal(ContainerUtil.get(A));
55
+ });
56
+
57
+ it('Scope.Transient 每次取都是新实例', async () => {
58
+ @Component({ scope: Scope.Transient })
59
+ class Fresh { }
60
+ await boot();
61
+ expect(ContainerUtil.get(Fresh)).not.to.equal(ContainerUtil.get(Fresh));
62
+ });
63
+
64
+ it('@Autowired 属性注入:按声明的类型,也可以显式给 id', async () => {
65
+ const Repo = Symbol('Repo');
66
+ @Component(Repo)
67
+ class RepoImpl { find() { return 'row'; } }
68
+ @Component()
69
+ class Dep { }
70
+ @Component()
71
+ class Service {
72
+ @Autowired(Repo)
73
+ readonly repo: RepoImpl;
74
+ @Autowired()
75
+ readonly dep: Dep;
76
+ }
77
+ await boot();
78
+ const s = ContainerUtil.get(Service);
79
+ expect(s.repo.find()).to.equal('row');
80
+ expect(s.dep).to.equal(ContainerUtil.get(Dep));
81
+ });
82
+
83
+ it('@Autowired 构造器参数注入', async () => {
84
+ const Clock = Symbol('Clock');
85
+ @Component(Clock)
86
+ class FixedClock { now() { return 42; } }
87
+ @Component()
88
+ class UsesClock {
89
+ constructor(@Autowired(Clock) readonly clock: FixedClock) { }
90
+ }
91
+ await boot();
92
+ expect(ContainerUtil.get(UsesClock).clock.now()).to.equal(42);
93
+ });
94
+
95
+ it('同一 id 有多个实现时,数组类型的 @Autowired 拿到全部', async () => {
96
+ const Plugin = Symbol('Plugin');
97
+ @Component(Plugin)
98
+ class P1 { readonly name = 'p1'; }
99
+ @Component(Plugin)
100
+ class P2 { readonly name = 'p2'; }
101
+ @Component()
102
+ class Host {
103
+ @Autowired(Plugin)
104
+ readonly plugins: { name: string }[];
105
+ }
106
+ await boot();
107
+ expect(ContainerUtil.get(Host).plugins.map(p => p.name).sort()).to.deep.equal(['p1', 'p2']);
108
+ expect(ContainerUtil.getAll(Plugin)).to.have.length(2);
109
+ expect([P1, P2]).to.have.length(2);
110
+ });
111
+
112
+ it('@Optional:没有实现时单值为 undefined,数组为 []', async () => {
113
+ const Missing = Symbol('Missing');
114
+ const MissingMany = Symbol('MissingMany');
115
+ @Component()
116
+ class Tolerant {
117
+ @Autowired(Missing) @Optional()
118
+ readonly one?: unknown;
119
+ @Autowired(MissingMany) @Optional()
120
+ readonly many: unknown[];
121
+ }
122
+ await boot();
123
+ const t = ContainerUtil.get(Tolerant);
124
+ expect(t.one).to.equal(undefined);
125
+ expect(t.many).to.deep.equal([]);
126
+ });
127
+
128
+ it('没有实现又不是 @Optional 时,取的时候报错,错误信息里有缺的 id', async () => {
129
+ const Absent = Symbol('AbsentService');
130
+ @Component()
131
+ class Needy {
132
+ @Autowired(Absent)
133
+ readonly absent: unknown;
134
+ }
135
+ await boot();
136
+ expect(() => ContainerUtil.get(Needy)).to.throw(/AbsentService/);
137
+ });
138
+
139
+ it('@Component({ id, name / tag / default }) 按名字、标签或默认选实现,类本身仍可直接取(F1)', async () => {
140
+ const Store = Symbol('Store');
141
+ @Component({ id: Store, name: 'redis' })
142
+ class RedisStore { readonly kind = 'redis'; }
143
+ @Component({ id: Store, tag: { tag: 'region', value: 'eu' } })
144
+ class EuStore { readonly kind = 'eu'; }
145
+ @Component({ id: Store, default: true })
146
+ class MemoryStore { readonly kind = 'memory'; }
147
+ @Component()
148
+ class Consumer {
149
+ @Autowired(Store) @Named('redis')
150
+ readonly redis: { kind: string };
151
+ @Autowired(Store) @Tagged('region', 'eu')
152
+ readonly eu: { kind: string };
153
+ @Autowired(Store)
154
+ readonly fallback: { kind: string };
155
+ }
156
+ await boot();
157
+ const c = ContainerUtil.get(Consumer);
158
+ expect([c.redis.kind, c.eu.kind, c.fallback.kind]).to.deep.equal(['redis', 'eu', 'memory']);
159
+ expect(ContainerUtil.getNamed<{ kind: string }>(Store, 'redis')).to.equal(ContainerUtil.get(RedisStore));
160
+ expect(ContainerUtil.getTagged<{ kind: string }>(Store, 'region', 'eu')).to.equal(ContainerUtil.get(EuStore));
161
+ expect(ContainerUtil.get(Store)).to.equal(ContainerUtil.get(MemoryStore));
162
+ });
163
+
164
+ it('rebind: true 替换先加载的模块里的实现(应用覆盖框架或其他包的组件)', async () => {
165
+ const Mailer = Symbol('Mailer');
166
+ @Component(Mailer)
167
+ class DefaultMailer { readonly who = 'default'; }
168
+ const base = autoBind();
169
+ @Component({ id: Mailer, rebind: true })
170
+ class CustomMailer { readonly who = 'custom'; }
171
+ const overrides = autoBind();
172
+ await ApplicationFactory.create({}, base, overrides);
173
+ expect(ContainerUtil.getAll<{ who: string }>(Mailer).map(m => m.who)).to.deep.equal(['custom']);
174
+ expect([DefaultMailer, CustomMailer]).to.have.length(2);
175
+ });
176
+
177
+ it('现状:同一批 autoBind 里 rebind 本批先定义的组件会失败(按定义的逆序登记,rebind 先于 bind 执行)', async () => {
178
+ const Mailer = Symbol('SameBatchMailer');
179
+ @Component(Mailer)
180
+ class DefaultMailer { }
181
+ @Component({ id: Mailer, rebind: true })
182
+ class CustomMailer { }
183
+ let error: Error | undefined;
184
+ try {
185
+ await boot();
186
+ } catch (e) {
187
+ error = e as Error;
188
+ }
189
+ expect(error?.message).to.match(/unbind.*SameBatchMailer/i);
190
+ expect([DefaultMailer, CustomMailer]).to.have.length(2);
191
+ });
192
+
193
+ it('rebind 替换框架自带组件:替换后注入点拿到的是新实现', async () => {
194
+ @Component({ id: ConfigProvider, rebind: true })
195
+ class FixedConfig {
196
+ get(key: string) { return key === 'answer' ? 42 : undefined; }
197
+ }
198
+ @Component()
199
+ class ReadsConfig {
200
+ @Autowired(ConfigProvider)
201
+ readonly config: FixedConfig;
202
+ }
203
+ await boot();
204
+ expect(ContainerUtil.get(ReadsConfig).config).to.be.instanceOf(FixedConfig);
205
+ expect(ContainerUtil.get(ReadsConfig).config.get('answer')).to.equal(42);
206
+ });
207
+
208
+ it('@Constant 登记常量,多个 id 都能取到', async () => {
209
+ const Token = Symbol('Token');
210
+ const Alias = Symbol('TokenAlias');
211
+ @Constant([Token, Alias], { secret: 'abc' })
212
+ class Holder { }
213
+ await boot();
214
+ expect(ContainerUtil.get(Token)).to.deep.equal({ secret: 'abc' });
215
+ expect(ContainerUtil.get(Alias)).to.equal(ContainerUtil.get(Token));
216
+ expect(Holder).to.be.a('function');
217
+ });
218
+
219
+ it('@AutowiredProvider 注入 Provider:按 priority 从小到大排序(sortSync)', async () => {
220
+ const Step = Symbol('Step');
221
+ @Component(Step)
222
+ class Late { readonly priority = 300; readonly name = 'late'; }
223
+ @Component(Step)
224
+ class Early { readonly priority = 100; readonly name = 'early'; }
225
+ @Component(Step)
226
+ class Middle { readonly priority = 200; readonly name = 'middle'; }
227
+ @Component()
228
+ class Pipeline {
229
+ @AutowiredProvider(Step)
230
+ readonly steps: Provider<{ name: string, priority: number }>;
231
+ }
232
+ await boot();
233
+ const names = ContainerUtil.get(Pipeline).steps.sortSync().map(s => s.name);
234
+ expect(names).to.have.members(['early', 'middle', 'late']);
235
+ // Prioritizeable:priority 大的排前面
236
+ expect(names).to.deep.equal(['late', 'middle', 'early']);
237
+ expect([Late, Early, Middle]).to.have.length(3);
238
+ });
239
+
240
+ it('@PostConstruct 在注入完成后调用一次,单例只调用一次', async () => {
241
+ let calls = 0;
242
+ @Component()
243
+ class Dep { readonly ok = true; }
244
+ @Component()
245
+ class Init {
246
+ @Autowired()
247
+ readonly dep: Dep;
248
+ seenDep = false;
249
+ @PostConstruct()
250
+ protected init() {
251
+ calls++;
252
+ this.seenDep = this.dep.ok;
253
+ }
254
+ }
255
+ await boot();
256
+ expect(ContainerUtil.get(Init).seenDep).to.equal(true);
257
+ ContainerUtil.get(Init);
258
+ expect(calls).to.equal(1);
259
+ });
260
+
261
+ it('detached 的 @Autowired:不在容器里的对象也能按需从当前容器取值', async () => {
262
+ const Clock = Symbol('DetachedClock');
263
+ @Component(Clock)
264
+ class Clk { now() { return 7; } }
265
+ class NotAComponent {
266
+ @Autowired({ id: Clock, detached: true })
267
+ readonly clock: Clk;
268
+ }
269
+ await boot();
270
+ expect(new NotAComponent().clock.now()).to.equal(7);
271
+ });
272
+
273
+ it('detached 不支持构造器参数,给出明确的错误', () => {
274
+ expect(() => {
275
+ class Bad {
276
+ constructor(@Autowired({ id: Symbol('x'), detached: true }) readonly x: unknown) { }
277
+ }
278
+ return Bad;
279
+ }).to.throw(/not supported/);
280
+ });
281
+
282
+ it('每次 ApplicationFactory.create 都换成新的容器,ContainerUtil 指向最新的那个', async () => {
283
+ @Component()
284
+ class Counter { value = 0; }
285
+ await boot();
286
+ const first = ContainerProvider.provide();
287
+ ContainerUtil.get(Counter).value = 5;
288
+ await boot();
289
+ expect(ContainerProvider.provide()).not.to.equal(first);
290
+ // 新容器里没有再登记 Counter(元数据已被上一次 create 取走)
291
+ expect(() => ContainerUtil.get(Counter)).to.throw();
292
+ });
293
+ });
@@ -65,14 +65,23 @@ function resolve(metadata: ComponentMetadata, bind: interfaces.Bind, rebind: int
65
65
  mid = mid.inTransientScope();
66
66
  }
67
67
 
68
- if (name) {
69
- mid = mid.whenTargetNamed(name);
70
- } else if (tag) {
71
- mid = mid.whenTargetTagged(tag.tag, tag.value);
72
- } else if (metadata.default) {
73
- mid = mid.whenTargetIsDefault();
74
- } else if (when) {
75
- mid = mid.when(when);
68
+ const constrain = (syntax: any) => {
69
+ if (name) {
70
+ return syntax.whenTargetNamed(name);
71
+ } else if (tag) {
72
+ return syntax.whenTargetTagged(tag.tag, tag.value);
73
+ } else if (metadata.default) {
74
+ return syntax.whenTargetIsDefault();
75
+ } else if (when) {
76
+ return syntax.when(when);
77
+ }
78
+ return syntax;
79
+ };
80
+ // name / tag / default / when choose among the implementations of an id, so they go on the bindings of
81
+ // the ids (`@Component({ id, name })`); the class itself stays reachable without them.
82
+ const aliases = !metadata.rebind && (name || tag || metadata.default || when) ? _ids : [];
83
+ if (aliases.length === 0) {
84
+ mid = constrain(mid);
76
85
  }
77
86
 
78
87
  if (onActivation) {
@@ -82,7 +91,11 @@ function resolve(metadata: ComponentMetadata, bind: interfaces.Bind, rebind: int
82
91
  }
83
92
 
84
93
  for (const item of _ids) {
85
- bind(item).toService(id);
94
+ if (aliases.includes(item)) {
95
+ constrain(bind(item).toDynamicValue(context => context.container.get(id)));
96
+ } else {
97
+ bind(item).toService(id);
98
+ }
86
99
  }
87
100
  }
88
101
 
@@ -98,4 +111,4 @@ function resolveConstant(metadata: ConstantOption, bind: interfaces.Bind, rebind
98
111
  for (const item of ids) {
99
112
  bind(item!).toService(id!);
100
113
  }
101
- }
114
+ }