@celljs/core 4.6.1 → 4.7.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 (2) hide show
  1. package/README.en.md +1113 -0
  2. package/package.json +1 -1
package/README.en.md ADDED
@@ -0,0 +1,1113 @@
1
+ # Cell - Core Component
2
+
3
+ ## Overview
4
+
5
+ Cell Core is a lightweight application framework for building modern applications. It provides a straightforward API through dependency injection, AOP (aspect-oriented programming), configuration properties, and logging, supporting registration, resolution, and lifecycle management of class objects. The dependency injection container (`Container`) is implemented by Cell itself with no third-party IoC dependencies and full TypeScript support.
6
+
7
+ ## Features
8
+
9
+ - Dependency Injection
10
+ - Aspect-Oriented Programming
11
+ - Configuration Properties
12
+ - Logging
13
+
14
+ ## Installation
15
+
16
+ Install Cell Core Component using npm:
17
+
18
+ ```bash
19
+ npm install @celljs/core
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ Below is a simple dependency injection example that shows how to register a class object in the IoC container:
25
+
26
+ ```typescript
27
+ import { Component } from '@celljs/core';
28
+
29
+ @Component()
30
+ export class HelloWorld {
31
+ greet() {
32
+ return 'Hello, World!';
33
+ }
34
+ }
35
+ ```
36
+
37
+
38
+ Next, use the `@Autowired` decorator in another object to inject the `HelloWorld` class:
39
+
40
+ ```typescript
41
+ import { Autowired } from '@celljs/core';
42
+ import { ApplicationFactory } from '@celljs/core/lib/common/application/application-factory';
43
+ import { HelloWorld } from './hello-world';
44
+
45
+ export class SampleService {
46
+ @Autowired()
47
+ helloWorld: HelloWorld;
48
+
49
+ run() {
50
+ console.log(this.helloWorld.greet());
51
+ }
52
+ }
53
+ ```
54
+
55
+ Next, import these two files in the DI module and export `autoBind()`. A Cell project's backend module is `src/node/module.ts`, and the toolchain (`cell dev`, `cell build`, `createTestApp()`) loads it automatically; files not imported by the module are not loaded:
56
+
57
+ ```typescript
58
+ // src/node/module.ts
59
+ import './hello-world';
60
+ import './sample-service';
61
+ import { autoBind } from '@celljs/core';
62
+
63
+ export default autoBind();
64
+ ```
65
+
66
+ Run `npx cell dev` to start the application and `npx cell check` to verify that DI bindings resolve correctly. Create a new project with `npx @celljs/cli init backend my-app`; see [Getting Started](https://cell.cellbang.com/guide/getting-started) for details.
67
+
68
+ To assemble the container in your own script without the toolchain, use `ApplicationFactory`:
69
+
70
+ ```typescript
71
+ import { autoBind } from '@celljs/core';
72
+ import { ApplicationFactory } from '@celljs/core/lib/common/application/application-factory';
73
+ import './hello-world';
74
+ import './sample-service';
75
+
76
+ const app = await ApplicationFactory.create({}, autoBind());
77
+ await app.start();
78
+ ```
79
+
80
+ ## Dependency Injection
81
+
82
+ Cell Core provides dependency injection capabilities: register class objects in the IoC container with `@Component`, then inject them in other classes using `@Autowired`. Here's a simple example:
83
+
84
+ ```typescript
85
+ import { Component, Autowired } from '@celljs/core';
86
+
87
+ @Component()
88
+ export class HelloWorld {
89
+ greet() {
90
+ return 'Hello, World!';
91
+ }
92
+ }
93
+
94
+ @Component()
95
+ export class SampleService {
96
+ @Autowired()
97
+ helloWorld: HelloWorld;
98
+
99
+ run() {
100
+ console.log(this.helloWorld.greet());
101
+ }
102
+ }
103
+ ```
104
+
105
+ ## Property Injection
106
+
107
+ Cell Core supports property injection with the `@Value` decorator, which injects configuration properties into class objects. Here's a simple example:
108
+
109
+ ```typescript
110
+ import { Component, Value } from '@celljs/core';
111
+
112
+ @Component()
113
+ export class SampleService {
114
+ @Value('app.name')
115
+ appName: string;
116
+
117
+ run() {
118
+ console.log(`App Name: ${this.appName}`);
119
+ }
120
+ }
121
+ ```
122
+
123
+ Inject properties by passing the `appProps` object to `ApplicationFactory.create()` at application startup. For example:
124
+
125
+ ```typescript
126
+ import { ApplicationFactory } from '@celljs/core/lib/common/application/application-factory';
127
+ import { SampleService } from './sample-service';
128
+
129
+ (async () => {
130
+ const appProps = {
131
+ app: { name: 'MyApp' }
132
+ };
133
+ const app = await ApplicationFactory.create(appProps, SampleModule);
134
+ app.start();
135
+ })();
136
+ ```
137
+
138
+ Use `.` to access nested properties in `@Value`, for example `@Value('app.name')`.
139
+
140
+ The `@Value` string supports EL expressions, evaluated by Cell's built-in `ExpressionEngine` (syntax identical to jexl 2; Cell previously used jexl but now has no third-party dependencies, evaluation is synchronous, and expressions cannot call object methods). For example:
141
+
142
+ ```typescript
143
+ import { Component, Value } from '@celljs/core';
144
+
145
+ @Component()
146
+ export class SampleService {
147
+
148
+ // Object access
149
+ @Value('app.name')
150
+ appName: string;
151
+
152
+ // Ternary expression
153
+ @Value('app.name == "MyApp" ? "Hello, MyApp!" : "Hello, World!"')
154
+ greeting: string;
155
+
156
+ // Provide default value
157
+ @Value('app.version ?? "1.0.0"')
158
+ appVersion: string;
159
+
160
+ // Mathematical operations
161
+ @Value('app.port + 1')
162
+ port: number;
163
+
164
+ // Logical operations
165
+ @Value('app.debug && app.env == "dev"')
166
+ debug: boolean;
167
+
168
+ // Array access
169
+ @Value('app.tags[0]')
170
+ tag: string;
171
+
172
+ // Array filtering
173
+ @Value('employees[.age >= 30 && .age < 40]')
174
+ middleAgedEmployees: Employee[];
175
+
176
+ // Transformation
177
+ // Suppose the following two transforms were added to ExpressionEngine:
178
+ // engine.addTransform('split', (val, char) => val.split(char))
179
+ // engine.addTransform('lower', (val) => val.toLowerCase())
180
+ @Value('"Pam Poovey"|lower|split(" ")[1]')
181
+ lastName: string;
182
+
183
+ // Function call
184
+ // Suppose the following function was added:
185
+ // engine.addFunction('min', Math.min)
186
+ @Value('min(3, 5)')
187
+ min: number;
188
+
189
+ }
190
+ ```
191
+
192
+ ## IoC Container
193
+
194
+ Cell Core Component provides a lightweight IoC container for managing the lifecycle and dependencies of class objects. Use the `@Component` decorator to register class objects in the IoC container, and the `@Autowired` decorator to inject dependency objects in other class objects.
195
+
196
+ The IoC container `Container` is implemented by Cell itself, supporting class object registration, resolution, and lifecycle management: identified by class or Symbol, singleton/transient scope, multiple injections, selection by name (`@Named`) or tag (`@Tagged`), and activation hooks (AOP proxies are created here). Inspired by Spring Framework's design philosophy, it provides a set of decorators similar to Spring, such as `@Component`, `@Autowired`, `@Value`, etc. Container resolution is synchronous, and singletons are created on first access.
197
+
198
+ The IoC container is composed of a series of container modules, each containing class objects registered with the `@Component` decorator. For convenient registration of class objects to container modules, Cell Core Component provides the `autoBind` method, which automatically registers class objects to container modules without manual registration. `autoBind` performs file module dependency analysis to automatically register class objects to container modules.
199
+
200
+ Below is a simple IoC container example:
201
+
202
+ ```typescript
203
+ import { Component, Autowired } from '@celljs/core';
204
+ import { ApplicationFactory } from '@celljs/core/lib/common/application/application-factory';
205
+
206
+ @Component()
207
+ export class HelloWorld {
208
+ greet() {
209
+ return 'Hello, World!';
210
+ }
211
+ }
212
+
213
+ @Component()
214
+ export class SampleService {
215
+ @Autowired()
216
+ helloWorld: HelloWorld;
217
+
218
+ run() {
219
+ console.log(this.helloWorld.greet());
220
+ }
221
+ }
222
+
223
+ export const SampleModule = autoBind();
224
+ ```
225
+
226
+ The `autoBind` method also provides a series of callback functions for customizing binding behavior. For example:
227
+
228
+ ```typescript
229
+ import { autoBind } from '@celljs/core';
230
+
231
+ export const SampleModule = autoBind((bind, unbind, isBound, rebind) => {
232
+ bind(HelloWorld).to(HelloWorld).inSingletonScope();
233
+ bind(Greeting).toConstantValue('Hello');
234
+ bind(Clock).toDynamicValue(({ container, target }) => new SystemClock()).inSingletonScope();
235
+ bind(Store).to(RedisStore).whenTargetNamed('redis');
236
+ rebind(Logger).to(MyLogger).inSingletonScope();
237
+ });
238
+ ```
239
+
240
+ Binding syntax: `to(Class)`, `toConstantValue(value)`, `toDynamicValue(context => value)` (where `context.target` is the injection point: identifier, `name`, `tags`, owning class `owner`, and property name `key`), `toService(id)` (alias for another identifier); scopes `inSingletonScope()` / `inTransientScope()` (`bind` defaults to transient, `@Component` defaults to singleton); constraints `whenTargetNamed(name)`, `whenTargetTagged(key, value)`, `whenTargetIsDefault()`, `when(target => boolean)`; `onActivation((context, instance) => instance)` runs after each new instance is created.
241
+
242
+ You can also create a container directly, such as in tests:
243
+
244
+ ```typescript
245
+ import { Container } from '@celljs/core';
246
+ import { SampleModule } from './sample-module';
247
+
248
+ const container = new Container(SampleModule);
249
+ const sampleService = container.get(SampleService);
250
+ sampleService.run();
251
+ ```
252
+
253
+ Container query methods: `get(id)` returns the unique matching implementation, `getAll(id)` returns all implementations, `isBound(id)` checks if a binding exists. All support query conditions like `{ name }` or `{ tags: { key: value } }`, for example `container.get(Store, { name: 'redis' })`. Without conditions, `getAll` and `isBound` ignore constraints; `get` matches only bindings with no constraints or with `whenTargetIsDefault()`.
254
+
255
+ On error, containers throw `ContainerError` with a stable `code`, a one-line fix suggestion `hint`, and the identifier chain being resolved `path` (what `cell check` reports):
256
+
257
+ | code | Meaning |
258
+ | --- | --- |
259
+ | `CELL_DI_NO_BINDING` | No matching binding; message shows who needs it (`HomeController.mailer`), the resolution chain, and unmatched bindings or another identifier with the same name |
260
+ | `CELL_DI_AMBIGUOUS` | Expected one implementation but multiple bindings match; message lists all candidates |
261
+ | `CELL_DI_CIRCULAR` | Circular dependency, e.g., `A → B → A` |
262
+ | `CELL_DI_MISSING_INJECT` | Constructor parameter or property missing `@Autowired`, and the type cannot serve as an identifier (interface, union type, primitive type) |
263
+ | `CELL_DI_INCOMPLETE_BINDING` | `bind(id)` has no `to...` clause |
264
+ | `CELL_DI_NO_CONTAINER` | Object reading `detached` property was not created by the container (created with `new`) |
265
+
266
+ There is no global container; components access each other only through injection. The container binds itself, so when a component needs to retrieve another component by a runtime-determined identifier, inject `Container`:
267
+
268
+ ```typescript
269
+ import { Autowired, Component, Container } from '@celljs/core';
270
+
271
+ @Component()
272
+ export class HandlerRegistry {
273
+
274
+ @Autowired(Container)
275
+ protected readonly container: Container;
276
+
277
+ handler(id: symbol) {
278
+ return this.container.get(id);
279
+ }
280
+ }
281
+ ```
282
+
283
+ Non-component code (scripts, tests) obtains the container from where it was created: `ApplicationFactory.createContainer(props, ...modules)` returns it, and test hosts receive it in `ApplicationHost.started()`.
284
+
285
+ ## Configuration Properties
286
+
287
+ Cell Core provides configuration property capabilities: inject configuration properties into class objects with `@Value`, which supports EL expressions.
288
+
289
+ Define configuration properties in the `appProps` object passed to `ApplicationFactory.create()` at startup. For example:
290
+
291
+ ```typescript
292
+ import { ApplicationFactory } from '@celljs/core/lib/common/application/application-factory';
293
+ import { SampleService } from './sample-service';
294
+
295
+ (async () => {
296
+ const appProps = {
297
+ app: { name: 'MyApp' }
298
+ };
299
+ const app = await ApplicationFactory.create(appProps, SampleModule);
300
+ app.start();
301
+ })();
302
+ ```
303
+
304
+ Cell Core also provides a `ConfigProvider` interface for loading configuration files with a default implementation; you can provide a custom implementation. For example:
305
+
306
+ ```typescript
307
+ import { ConfigProvider } from '@celljs/core';
308
+
309
+ @Component({ id: ConfigProvider, rebind: true })
310
+ export class MyConfigProvider implements ConfigProvider {
311
+ get<T>(key: string, defaultValue?: T): T {
312
+ return process.env[key] || defaultValue;
313
+ }
314
+ }
315
+ ```
316
+
317
+ Besides `@Value`, you can also inject `ConfigProvider` and retrieve values by key at runtime. For example:
318
+
319
+ ```typescript
320
+ import { Autowired, Component, ConfigProvider } from '@celljs/core';
321
+
322
+ @Component()
323
+ export class SampleService {
324
+
325
+ @Autowired(ConfigProvider)
326
+ protected readonly config: ConfigProvider;
327
+
328
+ run() {
329
+ console.log(`App Name: ${this.config.get('app.name')}`);
330
+ }
331
+ }
332
+ ```
333
+
334
+ ## Decorators
335
+
336
+ Cell Core provides Spring-like decorators for registering class objects in the IoC container. Here are the commonly used ones:
337
+
338
+ - `@Component`: Register a class in the IoC container.
339
+ - `@Autowired`: Inject a dependency.
340
+ - `@Value`: Inject a configuration property.
341
+ - `@PostConstruct`: Execute after property injection completes (one per class, inherited by subclasses).
342
+ - `@Service`: Alias for `@Component`; registers a service object.
343
+ - `@Named`: Select the implementation to inject by name (corresponds to `@Component({ id, name })`).
344
+ - `@Optional`: Inject `undefined` when no implementation exists (array becomes `[]`); property retains its initial value.
345
+ - `@Tagged`: Select the implementation to inject by tag (corresponds to `@Component({ id, tag })`).
346
+ - `@Aspect`: Define an aspect object and provide AOP capability.
347
+ - `@AutowiredProvider`: Inject a dependency provider; access a list of objects of a class with sorting support.
348
+ - `@Constant`: Register a constant in the IoC container.
349
+
350
+ `@Autowired`, `@Value`, and `@AutowiredProvider` all have a `detached` form (option `{ detached: true }`, or import from `@celljs/core/lib/common/annotation/detached`): the property is retrieved from the container that created the instance only on first read, which breaks circular dependencies. It applies only to properties, and instances must be created by the container; reading on objects created with `new` throws `CELL_DI_NO_CONTAINER`. React components use `@celljs/react`'s `useInject` / `useValue`.
351
+
352
+ ```typescript
353
+ import { Autowired, Component } from '@celljs/core';
354
+
355
+ @Component()
356
+ export class OrderService {
357
+
358
+ // InvoiceService also depends on OrderService: retrieve on first use
359
+ @Autowired({ id: InvoiceService, detached: true })
360
+ protected readonly invoices: InvoiceService;
361
+ }
362
+ ```
363
+
364
+ ## @Component Decorator
365
+
366
+ `@Component` registers class objects in the IoC container. It has these properties:
367
+
368
+ - `id`: The identifier of the class, can be one or multiple.
369
+ - `scope`: The scope of the class, defaults to `Scope.Singleton`.
370
+ - `name`: The name of the class.
371
+ - `tag`: The tag of the class.
372
+ - `default`: Whether this is the default class. When multiple bindings exist for a service identifier, set this to specify which one is returned by default.
373
+ - `when`: A function that determines whether to create the class. Returns `true` to create it; `false` otherwise.
374
+ - `rebind`: Whether to rebind the class. Defaults to `false`.
375
+ - `proxy`: Whether to use a proxy for the class. Defaults to `false`. When `true`, AOP aspects can intercept it.
376
+ - `sysTags`: System tags to identify the class. In AOP aspects, you can intercept classes by system tag.
377
+ - `onActivation`: A callback function executed when the class is activated.
378
+
379
+ For example:
380
+
381
+ ```typescript
382
+ import { Component, Scope } from '@celljs/core';
383
+
384
+ @Component({ id: 'HelloWorld', scope: Scope.Singleton })
385
+ export class HelloWorld {
386
+ greet() {
387
+ return 'Hello, World!';
388
+ }
389
+ }
390
+ ```
391
+
392
+ When `id` is an array, the class has multiple identifiers. For example:
393
+
394
+ ```typescript
395
+ import { Component } from '@celljs/core';
396
+
397
+ @Component({ id: ['HelloWorld', 'Hello'] })
398
+ export class HelloWorld {
399
+ greet() {
400
+ return 'Hello, World!';
401
+ }
402
+ }
403
+ ```
404
+
405
+ When `id` is not set, the class itself is used as the identifier. For example:
406
+
407
+ ```typescript
408
+ import { Component } from '@celljs/core';
409
+
410
+ @Component()
411
+ export class HelloWorld {
412
+ greet() {
413
+ return 'Hello, World!';
414
+ }
415
+ }
416
+ ```
417
+
418
+ Regardless of whether `id` is set, the decorated class is always an identifier and can be used to retrieve the class object. For example:
419
+
420
+ ```typescript
421
+ import { Component } from '@celljs/core';
422
+
423
+ @Component()
424
+ export class HelloWorld {
425
+ greet() {
426
+ return 'Hello, World!';
427
+ }
428
+ }
429
+
430
+ @Component()
431
+ export class SampleService {
432
+ @Autowired()
433
+ helloWorld: HelloWorld;
434
+
435
+ run() {
436
+ console.log(this.helloWorld.greet());
437
+ }
438
+ }
439
+ ```
440
+
441
+ ## @Autowired Decorator
442
+
443
+ `@Autowired` injects dependencies. It has these properties:
444
+
445
+ - `id`: The identifier of the class.
446
+ - `multi`: Whether to inject multiple objects. Defaults to automatic detection based on whether the property type is an array; explicitly set to `true` when needed.
447
+ - `detached`: The property is retrieved from the container that created the instance only on first read (`@Value` retrieves on each read); used to break circular dependencies. Defaults to `false`.
448
+
449
+ For example:
450
+
451
+ ```typescript
452
+ import { Autowired } from '@celljs/core';
453
+
454
+ @Component()
455
+ export class SampleService {
456
+ @Autowired({ id: HelloWorld })
457
+ helloWorld: HelloWorld;
458
+
459
+ run() {
460
+ console.log(this.helloWorld.greet());
461
+ }
462
+ }
463
+ ```
464
+
465
+ When `id` is not set, the property type is used as the identifier. For example:
466
+
467
+ ```typescript
468
+ import { Autowired } from '@celljs/core';
469
+
470
+ @Component()
471
+ export class SampleService {
472
+ @Autowired()
473
+ helloWorld: HelloWorld;
474
+
475
+ run() {
476
+ console.log(this.helloWorld.greet());
477
+ }
478
+ }
479
+ ```
480
+
481
+ When multiple objects exist for an identifier, set the property type to an array to inject all of them. For example:
482
+
483
+ ```typescript
484
+ import { Autowired } from '@celljs/core';
485
+
486
+ @Component()
487
+ export class SampleService {
488
+ @Autowired()
489
+ helloWorlds: HelloWorld[];
490
+
491
+ run() {
492
+ console.log(this.helloWorlds.map(helloWorld => helloWorld.greet()));
493
+ }
494
+ }
495
+ ```
496
+
497
+ Alternatively, use `@AutowiredProvider` to inject a dependency provider that gives you a list of objects with sorting support. For example:
498
+
499
+ ```typescript
500
+ import { AutowiredProvider } from '@celljs/core';
501
+
502
+ @Component()
503
+ export class SampleService {
504
+ @AutowiredProvider({ id: HelloWorld })
505
+ helloWorldProvider: Provider<HelloWorld>;
506
+
507
+ run() {
508
+ const helloWorlds = this.helloWorldProvider.sortSync();
509
+ console.log(helloWorlds.map(helloWorld => helloWorld.greet()));
510
+ }
511
+ }
512
+ ```
513
+
514
+ In esbuild-compiled projects, type information is absent, so you cannot automatically detect multiple dependencies. Explicitly set `multi` to `true`, or use `@AutowiredProvider`.
515
+
516
+ ## @Value Decorator
517
+
518
+ `@Value` injects configuration properties. It has these properties:
519
+
520
+ - `el`: The EL expression for the property.
521
+ - `detached`: The property is retrieved from the container that created the instance only on first read (`@Value` retrieves on each read); used to break circular dependencies. Defaults to `false`.
522
+
523
+ For example:
524
+
525
+ ```typescript
526
+ import { Value } from '@celljs/core';
527
+
528
+ @Component()
529
+ export class SampleService {
530
+ @Value('app.name')
531
+ appName: string;
532
+
533
+ run() {
534
+ console.log(`App Name: ${this.appName}`);
535
+ }
536
+ }
537
+ ```
538
+
539
+ ## @Constant Decorator
540
+
541
+ `@Constant` registers constants in the IoC container. It has these properties:
542
+
543
+ - `id`: The identifier for the constant.
544
+ - `constantValue`: The constant's value.
545
+ - `rebind`: Whether to rebind the constant. Defaults to `false`.
546
+
547
+ For example:
548
+
549
+ ```typescript
550
+ import { Constant } from '@celljs/core';
551
+
552
+ @Constant('app.name', 'MyApp')
553
+ @Constant('app.version', '1.0.0')
554
+ export default class {
555
+ }
556
+
557
+ @Component()
558
+ export class SampleService {
559
+ @Autowired('app.name')
560
+ name: string;
561
+
562
+ @Autowired('app.version')
563
+ version: string;
564
+ }
565
+ ```
566
+
567
+ ## @PostConstruct Decorator
568
+
569
+ `@PostConstruct` executes after a class object is initialized. For example:
570
+
571
+ ```typescript
572
+ import { Component, PostConstruct } from '@celljs/core';
573
+
574
+ @Component()
575
+ export class SampleService {
576
+ @PostConstruct()
577
+ init() {
578
+ console.log('SampleService initialized.');
579
+ }
580
+ }
581
+ ```
582
+
583
+ ## @Named Decorator
584
+
585
+ `@Named` specifies the name of the injected object. For example:
586
+
587
+ ```typescript
588
+ import { Autowired, Named } from '@celljs/core';
589
+
590
+ @Component({ name: 'HelloWorld' })
591
+ export class HelloWorld {
592
+ greet() {
593
+ return 'Hello, World!';
594
+ }
595
+ }
596
+
597
+ @Component()
598
+ export class SampleService {
599
+ @Autowired()
600
+ @Named('HelloWorld')
601
+ helloWorld: HelloWorld;
602
+
603
+ run() {
604
+ console.log(this.helloWorld.greet());
605
+ }
606
+ }
607
+ ```
608
+
609
+ ## @Tagged Decorator
610
+
611
+ `@Tagged` marks the injected object with a tag. For example:
612
+
613
+ tag?: { tag: string | number | symbol, value: any };
614
+
615
+
616
+ ```typescript
617
+ import { Autowired, Tagged } from '@celljs/core';
618
+
619
+ @Component({ tag: { tag: 'tag1', value: 'HelloWorld' } })
620
+ export class HelloWorld {
621
+ greet() {
622
+ return 'Hello, World!';
623
+ }
624
+ }
625
+
626
+ @Component()
627
+ export class SampleService {
628
+ @Autowired()
629
+ @Tagged('tag1', 'HelloWorld')
630
+ helloWorld: HelloWorld;
631
+
632
+ run() {
633
+ console.log(this.helloWorld.greet());
634
+ }
635
+ }
636
+ ```
637
+
638
+ ## @Optional Decorator
639
+
640
+ `@Optional` marks the injected object as optional. Without it, `@Autowired` throws if the object is not found. With `@Optional`, the property is set to `undefined` if not found. For example:
641
+
642
+ ```typescript
643
+ import { Autowired, Optional } from '@celljs/core';
644
+
645
+ @Component()
646
+ export class SampleService {
647
+ @Autowired()
648
+ @Optional()
649
+ helloWorld: HelloWorld;
650
+
651
+ run() {
652
+ console.log(this.helloWorld?.greet());
653
+ }
654
+ }
655
+ ```
656
+
657
+ ## @Aspect Decorator
658
+
659
+ `@Aspect` defines an aspect object and provides AOP capability. It inherits all `@Component` properties and adds a `pointcut` property. It has these properties:
660
+
661
+ - `id`: The class identifier. Unlike `@Component`, `id` must be a single identifier, not an array.
662
+ - `pointcut`: The pointcut. Defaults to `COMPONENT_TAG`, which intercepts all `@Component`-registered classes. You can define custom pointcuts, such as `AOP_TAG`.
663
+
664
+ For example:
665
+
666
+ ```typescript
667
+ import { MethodBeforeAdvice, Autowired, Aspect, AfterReturningAdvice, Value, ConfigUtil } from '@celljs/core';
668
+ import { AccessDecisionManager, MethodSecurityMetadataContext, ResourceNameResolver, SecurityMetadataSource, SECURITY_EXPRESSION_CONTEXT_KEY } from './access-protocol';
669
+ import { AOP_POINTCUT } from '@celljs/web';
670
+ import { SecurityContext } from '../context';
671
+ import { AuthorizeType } from '../../common';
672
+ import { Context } from '@celljs/web/lib/node';
673
+
674
+ const pointcut = ConfigUtil.getRaw().security.aop?.pointcut || AOP_POINTCUT;
675
+
676
+ export abstract class AbstractSecurityMethodAdivice {
677
+
678
+ @Autowired(AccessDecisionManager)
679
+ protected readonly accessDecisionManager: AccessDecisionManager;
680
+
681
+ @Autowired(SecurityMetadataSource)
682
+ protected readonly securityMetadataSource: SecurityMetadataSource;
683
+
684
+ @Autowired(ResourceNameResolver)
685
+ protected readonly resourceNameResolver: ResourceNameResolver;
686
+
687
+ @Value('security.enabled')
688
+ protected readonly enabled: boolean;
689
+
690
+ protected needAccessDecision(method: string | number | symbol) {
691
+ return this.enabled && typeof method === 'string' && SecurityContext.getCurrent();
692
+ }
693
+ }
694
+
695
+ @Aspect({ id: MethodBeforeAdvice, pointcut })
696
+ export class SecurityMethodBeforeAdivice extends AbstractSecurityMethodAdivice implements MethodBeforeAdvice {
697
+
698
+ async before(method: string | number | symbol, args: any[], target: any): Promise<void> {
699
+ if (this.needAccessDecision(method)) {
700
+ const ctx: MethodSecurityMetadataContext = { method: method as string, args, target, authorizeType: AuthorizeType.Pre, grant: 0 };
701
+ const securityMetadata = await this.securityMetadataSource.load(ctx);
702
+ const resouces = await this.resourceNameResolver.resolve(ctx);
703
+ for (const resource of resouces) {
704
+ securityMetadata.resource = resource;
705
+ await this.accessDecisionManager.decide(securityMetadata);
706
+ }
707
+ }
708
+ }
709
+
710
+ }
711
+
712
+ @Aspect({ id: AfterReturningAdvice, pointcut })
713
+ export class SecurityAfterReturningAdvice extends AbstractSecurityMethodAdivice implements AfterReturningAdvice {
714
+
715
+ async afterReturning(returnValue: any, method: string | number | symbol, args: any[], target: any): Promise<void> {
716
+ if (this.needAccessDecision(method)) {
717
+ const oldCtx = Context.getAttr<MethodSecurityMetadataContext>(SECURITY_EXPRESSION_CONTEXT_KEY);
718
+ const newCtx = { method: method as string, args, target, returnValue, authorizeType: AuthorizeType.Post, grant: oldCtx.grant };
719
+ const securityMetadata = await this.securityMetadataSource.load(newCtx);
720
+ const resouces = await this.resourceNameResolver.resolve(newCtx);
721
+ for (const resource of resouces) {
722
+ securityMetadata.resource = resource;
723
+ await this.accessDecisionManager.decide(securityMetadata);
724
+ }
725
+ }
726
+ }
727
+
728
+ }
729
+ ```
730
+
731
+
732
+ ## AOP Aspect-Oriented Programming
733
+
734
+ Cell Core provides aspect-oriented programming capability: execute operations before, after, and on exception during method execution. Use `@Aspect` to define aspects and `MethodBeforeAdvice`, `AfterReturningAdvice`, `AfterThrowsAdvice` interfaces to define advice.
735
+
736
+ AOP involves these interfaces:
737
+
738
+ - `MethodBeforeAdvice`: Execute before the method.
739
+ - `AfterReturningAdvice`: Execute after the method.
740
+ - `AfterThrowsAdvice`: Execute on method exception.
741
+
742
+ Use `@Aspect` to define aspects and specify the pointcut with the `pointcut` property. For example:
743
+
744
+ ```typescript
745
+ import { MethodBeforeAdvice, Autowired, Aspect, AfterReturningAdvice, Value, ConfigUtil } from '@celljs/core';
746
+
747
+ const pointcut = 'test';
748
+
749
+ @Component({ id: MethodBeforeAdvice, pointcut })
750
+ export class TestMethodBeforeAdvice implements MethodBeforeAdvice {
751
+
752
+ async before(method: string | number | symbol, args: any[], target: any): Promise<void> {
753
+ console.log('before');
754
+ }
755
+
756
+ }
757
+
758
+ @Component({ id: AfterReturningAdvice, pointcut })
759
+ export class TestAfterReturningAdvice implements AfterReturningAdvice {
760
+
761
+ async afterReturning(returnValue: any, method: string | number | symbol, args: any[], target: any): Promise<void> {
762
+ console.log('after');
763
+ }
764
+
765
+ }
766
+
767
+ @Component({ id: AfterThrowsAdvice, pointcut })
768
+ export class TestAfterThrowsAdvice implements AfterThrowsAdvice {
769
+
770
+ async afterThrows(error: any, method: string | number | symbol, args: any[], target: any): Promise<void> {
771
+ console.log('throws');
772
+ }
773
+
774
+ }
775
+ ```
776
+
777
+ The example above defines an aspect with pointcut `test`. When a method of a class with sysTag `test` executes before, after, or on exception, the corresponding operations run. The pointcut `test` intercepts all `@Component`-registered classes with sysTag `test`.
778
+
779
+
780
+ ## Building Applications
781
+
782
+ Cell Core provides a lightweight application framework. Use the `Application` interface to define applications, `ApplicationLifecycle` to define lifecycle, and `ApplicationStateService` for state management. `ApplicationFactory` creates application instances.
783
+
784
+ Use `ApplicationFactory` to create instances, load IoC modules, and assemble a complete container (`createContainer` returns the container, `create` returns the application). For example:
785
+
786
+ ```typescript
787
+ import { ApplicationFactory } from '@celljs/core/lib/common/application/application-factory';
788
+ import { SampleService } from './sample-service';
789
+ import { SampleModule } from './sample-module';
790
+
791
+ (async () => {
792
+ const appProps = {
793
+ app: { name: 'MyApp' }
794
+ };
795
+ const app = await ApplicationFactory.create(appProps, SampleModule);
796
+ app.start();
797
+ })();
798
+ ```
799
+
800
+ Define application lifecycle with the `ApplicationLifecycle` interface. For example:
801
+
802
+ ```typescript
803
+ import { ApplicationLifecycle, Application } from '@celljs/core';
804
+
805
+ export class SampleLifecycle implements ApplicationLifecycle {
806
+ onStart(app: Application): Promise<void> {
807
+ return Promise.resolve();
808
+ }
809
+
810
+ onStop(app: Application): void {
811
+ console.log('Application stopped.');
812
+ }
813
+ }
814
+ ```
815
+
816
+ `Application` has one implementation, the same on frontend and backend: lifecycle runs sequentially, then mounts `ApplicationShell` if present (bound by `@celljs/core/lib/browser` on the browser, replaced by `@celljs/react`). On Node.js, `ExitSignalLifecycle` stops the application and exits the process on SIGINT / SIGTERM.
817
+
818
+ ## Directory Structure
819
+
820
+ ```shell
821
+ .
822
+ ├── browser # Browser-side application
823
+ │ ├── browser.ts # Browser utility methods
824
+ │ ├── index.ts # Export module
825
+ │ ├── shell # Frontend startup entry
826
+ │ └── static-module.ts # IoC container module with static-loaded types
827
+ ├── common # Common module
828
+ │ ├── annotation # Decorator definitions
829
+ │ ├── aop # AOP-related code
830
+ │ ├── application # Application (same implementation on frontend and backend)
831
+ │ ├── config # Configuration properties
832
+ │ ├── constants.ts # Constants
833
+ │ ├── container # IoC container
834
+ │ ├── el # EL expressions
835
+ │ ├── error # Error handling
836
+ │ ├── index.ts # Export module
837
+ │ ├── logger # Logging
838
+ │ ├── provider # Dependency provider
839
+ │ ├── static-module.ts # IoC container module with static-loaded types
840
+ │ ├── test # Testing
841
+ │ └── utils # Utility methods
842
+ ├── node # Node.js-side application
843
+ │ ├── application # Exit signal lifecycle
844
+ │ ├── constants.ts # Constants
845
+ │ ├── context # Context
846
+ │ ├── index.ts # Export module
847
+ │ ├── static-module.ts # IoC container module with static-loaded types
848
+ │ └── utils # Utility methods
849
+ └── package.spec.ts # Unit tests
850
+ ```
851
+
852
+ ## Error Types
853
+
854
+ Cell Core provides common error types for exception handling:
855
+
856
+ - `CustomError`: Custom error.
857
+ - `IllegalArgumentError`: Illegal argument error.
858
+ - `IllegalStateError`: Illegal state error.
859
+ - `InvalidMimeTypeError`: Invalid MIME type error.
860
+
861
+ For example:
862
+
863
+ ```typescript
864
+ import { IllegalArgumentError } from '@celljs/core';
865
+
866
+ if (condition) {
867
+ throw new IllegalArgumentError('Invalid argument.');
868
+ }
869
+ ```
870
+
871
+ Since JavaScript's built-in error types cannot be checked with `instanceof`, Cell Core provides a `CustomError` base class. All custom error types should inherit from `CustomError`.
872
+
873
+ ## Security Checks
874
+
875
+ Components can report settings unsafe in production (public default keys, overly short keys, etc.): implement `SecurityCheck`, bind it, and `check()` returns `SecurityWarning` with a stable `code` (`CELL_SECURITY_*`) and a one-sentence `hint`.
876
+
877
+ ```typescript
878
+ import { Component, SecurityCheck, SecurityWarning, Value } from '@celljs/core';
879
+
880
+ @Component(SecurityCheck)
881
+ export class ApiKeySecurityCheck implements SecurityCheck {
882
+ @Value('app.apiKey')
883
+ protected readonly apiKey?: string;
884
+
885
+ check(): SecurityWarning[] {
886
+ return this.apiKey === 'changeme'
887
+ ? [{ code: 'CELL_SECURITY_DEFAULT_API_KEY', message: 'app.apiKey is the example key.', hint: 'Set app.apiKey from the environment.' }]
888
+ : [];
889
+ }
890
+ }
891
+ ```
892
+
893
+ These warnings take effect in two places:
894
+
895
+ - The `security` check in `cell check` reports them in any environment (warning, does not fail).
896
+ - At startup (`AbstractApplication.doStart`, before lifecycle hooks), only in `NODE_ENV=production` per `securityChecks`: `warn` (default) logs each warning, `fail` throws `SecurityCheckError` (`CELL_SECURITY_CHECK_FAILED`) and exits with code 1, `off` skips the check. Override with `CELL_SECURITY_CHECKS=fail`.
897
+
898
+ Built-in checks: cookie signing keys in `@celljs/web` (`CELL_SECURITY_DEFAULT_COOKIE_KEYS`, `CELL_SECURITY_COOKIE_KEYS_MISSING`, `CELL_SECURITY_WEAK_COOKIE_KEYS`), HMAC key length in `@celljs/jwt` (`CELL_SECURITY_WEAK_JWT_SECRET`).
899
+
900
+ ## Logging
901
+
902
+ Cell Core provides logging with log levels, formats, and output. Use the `Logger` interface to define loggers and the `TraceIdProvider` interface for trace IDs.
903
+
904
+ Log levels are:
905
+
906
+ - `verbose`: Verbose output.
907
+ - `debug`: Debug output.
908
+ - `info`: Informational messages.
909
+ - `warn`: Warnings.
910
+ - `error`: Errors.
911
+
912
+ For example:
913
+
914
+ ```typescript
915
+ import { Logger } from '@celljs/core';
916
+
917
+ @Component()
918
+ export class SampleService {
919
+
920
+ @Autowired(Logger)
921
+ logger: Logger;
922
+
923
+ run() {
924
+ this.logger.info('Info message.');
925
+ this.logger.error('Error message.');
926
+ }
927
+ }
928
+ ```
929
+
930
+ `Error` objects passed to logging methods are written with the call stack and `cause` chain (`ErrorUtil.describe(error)` can also be used standalone).
931
+
932
+ By default, output is `console`. Injected logger objects are independent to support different classes; set context information with `setContext`. For example:
933
+
934
+ ```typescript
935
+ import { Logger } from '@celljs/core';
936
+
937
+ @Component()
938
+ export class SampleService {
939
+
940
+ @Autowired(Logger)
941
+ logger: Logger;
942
+
943
+ run() {
944
+ this.logger.setContext('SampleService');
945
+ this.logger.info('Info message.');
946
+ this.logger.error('Error message.');
947
+ }
948
+ }
949
+ ```
950
+
951
+ Customize the `Logger` interface to replace the default. For example:
952
+
953
+ ```typescript
954
+ import { Component } from '@celljs/core';
955
+
956
+ @Component({ id: Logger, rebind: true })
957
+ export class MyLogger implements Logger {
958
+ // TODO
959
+ }
960
+ ```
961
+
962
+
963
+ ## Context Capabilities
964
+
965
+ Cell Core provides context capabilities: application context, request context, session context. Use the `Context` class to set and retrieve context information.
966
+
967
+ Context types include:
968
+
969
+ - `App`: Application context
970
+ - `Request`: Request context
971
+ - `Session`: Session context
972
+
973
+
974
+ ```typescript
975
+ import { Context, AttributeScope } from '@celljs/core';
976
+
977
+ Context.setAttr('key', 'value', AttributeScope.Request);
978
+ const value = Context.getAttr('key', AttributeScope.Request);
979
+ ```
980
+
981
+
982
+ Context execution ensures context information persists during function execution. For example:
983
+
984
+ ```typescript
985
+ import { Context } from '@celljs/core';
986
+
987
+ Context.run(async () => {
988
+ Context.setAttr('key', 'value1', AttributeScope.Request);
989
+ const value = Context.getAttr('key', AttributeScope.Request);
990
+ console.log(value); // value1
991
+ });
992
+
993
+ Context.run(() => {
994
+ Context.setAttr('key', 'value2', AttributeScope.Request);
995
+ const value = Context.getAttr('key', AttributeScope.Request);
996
+ console.log(value); // value2
997
+ });
998
+ ```
999
+
1000
+ ## Common Utility Classes and Methods
1001
+
1002
+ Cell Core provides common utility classes and methods:
1003
+
1004
+ - `AnnotationUtil`: Annotation utilities
1005
+ - `Assert`: Assertions
1006
+ - `Async`: Async utilities
1007
+ - `Cancellation`: Cancellation utilities
1008
+ - `ClassUtil`: Class utilities
1009
+ - `Disposable`: Disposable utilities
1010
+ - `Emitter`: Event emission
1011
+ - `Event`: Event utilities
1012
+ - `GlobalUtil`: Global utilities
1013
+ - `MetadataUtil`: Metadata utilities
1014
+ - `Prioritizeable`: Prioritization utilities
1015
+ - `PromiseUtil`: Promise utilities
1016
+ - `ProxyUtil`: Proxy utilities
1017
+ - `Types`: Type utilities
1018
+ - `UrlUtil`: URL utilities
1019
+ - `generateUUID`: UUID generation
1020
+ - `OS`: Operating system utilities
1021
+ - `MimeTypeUtil`: MIME type utilities
1022
+ - `MimeType`: MIME type definitions
1023
+
1024
+ For example:
1025
+
1026
+ ```typescript
1027
+ import { Assert } from '@celljs/core';
1028
+
1029
+ Assert.isTrue(condition, 'Invalid argument.');
1030
+ ```
1031
+
1032
+ ## EL Expressions
1033
+
1034
+ Cell Core supports EL expressions, a simple templating language for dynamic content generation. Use `ExpressionCompiler` to compile and `ExpressionHandler` to handle them.
1035
+
1036
+ Key interfaces:
1037
+
1038
+ - `ExpressionCompiler`: Compiles EL expressions
1039
+ - `ExpressionHandler`: Handles EL expressions
1040
+ - `ExpressionContext`: EL expression context
1041
+ - `ContextInitializer`: Context initializer
1042
+ - `ExpressionContextProvider`: EL expression context provider
1043
+ - `ExpressionEngine`: The expression engine; use `@Autowired(ExpressionEngine)` to get the app's engine, extend with `addTransform` and `addFunction`, evaluate with `compile(source)` / `evaluate(source, context)`. Syntax errors or undefined transforms/functions throw `ExpressionSyntaxError` (`CELL_EL_SYNTAX`, `CELL_EL_UNKNOWN_TRANSFORM`, `CELL_EL_UNKNOWN_FUNCTION`) with error location in the message
1044
+
1045
+ For example:
1046
+
1047
+ ```typescript
1048
+ import { ExpressionHandler } from '@celljs/core';
1049
+
1050
+ @Component()
1051
+ export class SampleService {
1052
+
1053
+ @Autowired(ExpressionHandler)
1054
+ expressionHandler: ExpressionHandler;
1055
+
1056
+ run() {
1057
+ const result = this.expressionHandler.handle('Hello, ${name}!', { name: 'World' });
1058
+ console.log(result); // Hello, World!
1059
+ }
1060
+ }
1061
+ ```
1062
+
1063
+ Add context variables, functions, and transforms to EL expressions. For example:
1064
+
1065
+ ```typescript
1066
+ import { ContextInitializer } from '@celljs/core';
1067
+
1068
+ @Component(ContextInitializer)
1069
+ export class CoreContextInitializer implements ContextInitializer {
1070
+
1071
+ @Autowired(ExpressionEngine)
1072
+ protected readonly engine: ExpressionEngine;
1073
+
1074
+ @Autowired({ id: ExpressionHandler, detached: true })
1075
+ protected readonly expressionHandler: ExpressionHandler;
1076
+
1077
+ initialize(ctx: ExpressionContext): void {
1078
+ if (typeof process !== 'undefined') {
1079
+ ctx.env = { ...process.env, _ignoreEl: true };
1080
+ }
1081
+ this.engine.addTransforms({
1082
+ replace: (val: string, searchValue: string | RegExp, replaceValue: string) => val && val.replace(new RegExp(searchValue, 'g'), replaceValue),
1083
+ regexp: (pattern: string, flags?: string) => new RegExp(pattern, flags),
1084
+ eval: (text: string) => this.expressionHandler.handle(text)
1085
+ });
1086
+ }
1087
+
1088
+ priority = 500;
1089
+
1090
+ }
1091
+ ```
1092
+
1093
+ Application properties support EL expression template strings by default. For example:
1094
+
1095
+ ```typescript
1096
+ import { ApplicationFactory } from '@celljs/core/lib/common/application/application-factory';
1097
+
1098
+ (async () => {
1099
+ const appProps = {
1100
+ app: { name: 'MyApp' },
1101
+ env: '${env}',
1102
+ version: '${version}',
1103
+ appVersion: '${app.name}-${version}',
1104
+ appVersion2: '${app.name}-${version}-${env}',
1105
+ };
1106
+ const app = await ApplicationFactory.create(appProps, SampleModule);
1107
+ app.start();
1108
+ })();
1109
+ ```
1110
+
1111
+ ## License
1112
+
1113
+ This project is licensed under the MIT License.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/core",
3
- "version": "4.6.1",
3
+ "version": "4.7.0",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "cell-component"