@venizia/ignis-kernel 0.5.0-6 → 0.5.0-7

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.
@@ -26,7 +26,7 @@ export declare class ArtifactGroup implements IArtifactGroup {
26
26
  ignore?: ReadonlyArray<string>;
27
27
  content?: IArtifactIndex;
28
28
  }): ArtifactGroup;
29
- /** A group carrying only `kinds` - for a slicer that splits `configs.artifacts` by run mode. The source group is resolved when artifacts are registered, never here. */
29
+ /** A group carrying only `kinds` - for a slicer that splits `configs.artifacts` by run mode. `custom` is one kind for every type the application defined: a slice keeps all of them or none. The source group is resolved when artifacts are registered, never here. */
30
30
  static pick(opts: {
31
31
  group: IArtifactGroup;
32
32
  kinds: ReadonlyArray<keyof IArtifactIndex>;
@@ -51,6 +51,7 @@ export declare class ArtifactGroup implements IArtifactGroup {
51
51
  get repositories(): never;
52
52
  get services(): never;
53
53
  get controllers(): never;
54
+ get custom(): never;
54
55
  private static holder;
55
56
  /** The module that declared the group, read from the call stack. */
56
57
  private static callSite;
@@ -32,7 +32,7 @@ export class ArtifactGroup {
32
32
  ignore: opts.ignore,
33
33
  });
34
34
  }
35
- /** A group carrying only `kinds` - for a slicer that splits `configs.artifacts` by run mode. The source group is resolved when artifacts are registered, never here. */
35
+ /** A group carrying only `kinds` - for a slicer that splits `configs.artifacts` by run mode. `custom` is one kind for every type the application defined: a slice keeps all of them or none. The source group is resolved when artifacts are registered, never here. */
36
36
  static pick(opts) {
37
37
  const { group, kinds } = opts;
38
38
  const slice = (index) => Object.fromEntries(kinds.filter((kind) => index[kind] !== undefined).map((kind) => [kind, index[kind]]));
@@ -102,6 +102,9 @@ export class ArtifactGroup {
102
102
  get controllers() {
103
103
  throw ArtifactGroup.unreadKindError({ folder: this.folder });
104
104
  }
105
+ get custom() {
106
+ throw ArtifactGroup.unreadKindError({ folder: this.folder });
107
+ }
105
108
  static holder() {
106
109
  return SingletonRealm.resolve({
107
110
  key: ArtifactGroup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AAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;YAC5F,IAAI,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;YAE7C,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;gBAC/B,IAAI,GAAG,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAAC,CAAC;YAC5F,CAAC;YAED,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAEpE,IAAI,MAAM,IAAI,CAAC,uCAAuC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC","sourcesContent":["import { SingletonRealm } from '@/helpers/singleton-realm';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IArtifactGroup, IArtifactIndex } from './common';\n\ntype TGroupResolver = (opts: { group: IArtifactGroup }) => Promise<IArtifactIndex>;\n\n/** A typed slice of a shared package's artifacts - every decorated class under a directory named `folder` in the package that defined it. A package declares one per domain, once; an application borrows it in `configs.artifacts`. The content is filled by `@venizia/ignis-boot`: inlined when the application is built, or resolved from source when artifacts are registered. */\nexport class ArtifactGroup implements IArtifactGroup {\n /** A string brand, so the group protocol is structural: `@venizia/ignis-boot/auto` builds one without depending on the kernel. */\n static readonly BRAND_KEY = 'isArtifactGroup';\n /** The realm slot `@venizia/ignis-boot` fills with the resolver for groups defined without content. */\n static readonly SINGLETON_REALM_KEY = 'artifact-group-resolver';\n\n readonly isArtifactGroup = true as const;\n readonly resolve: (() => Promise<IArtifactIndex>) | undefined;\n readonly kinds: ReadonlyArray<keyof IArtifactIndex> | undefined;\n\n private constructor(opts: {\n folder: string | undefined;\n site: string | undefined;\n content: IArtifactIndex | undefined;\n resolve?: () => Promise<IArtifactIndex>;\n kinds?: ReadonlyArray<keyof IArtifactIndex>;\n ignore?: ReadonlyArray<string>;\n }) {\n this.folder = opts.folder;\n this.site = opts.site;\n this.content = opts.content;\n this.resolve = opts.resolve;\n this.kinds = opts.kinds;\n this.ignore = opts.ignore;\n }\n\n readonly folder: string | undefined;\n readonly site: string | undefined;\n readonly content: IArtifactIndex | undefined;\n readonly ignore: ReadonlyArray<string> | undefined;\n\n /** `content` is written by the build plugin; a hand-written group passes only `folder`. */\n static define(opts: { folder: string; content?: IArtifactIndex }): ArtifactGroup {\n return new ArtifactGroup({\n folder: opts.folder,\n site: ArtifactGroup.callSite(),\n content: opts.content,\n });\n }\n\n /** Every decorated class of the calling package - an application's own artifacts, picked by its call site, so several applications in one process each get their own. `ignore` takes the globs `ignis-artifacts --ignore` takes, relative to the package `src`. `content` is written by the build plugin. */\n static application(\n opts: { ignore?: ReadonlyArray<string>; content?: IArtifactIndex } = {},\n ): ArtifactGroup {\n return new ArtifactGroup({\n folder: undefined,\n site: ArtifactGroup.callSite(),\n content: opts.content,\n ignore: opts.ignore,\n });\n }\n\n /** A group carrying only `kinds` - for a slicer that splits `configs.artifacts` by run mode. The source group is resolved when artifacts are registered, never here. */\n static pick(opts: {\n group: IArtifactGroup;\n kinds: ReadonlyArray<keyof IArtifactIndex>;\n }): ArtifactGroup {\n const { group, kinds } = opts;\n const slice = (index: IArtifactIndex): IArtifactIndex =>\n Object.fromEntries(\n kinds.filter((kind) => index[kind] !== undefined).map((kind) => [kind, index[kind]]),\n );\n\n return new ArtifactGroup({\n folder: group.folder,\n site: group.site,\n content: group.content ? slice(group.content) : undefined,\n resolve: async () => {\n const content = await ArtifactGroup.resolveContent({ group });\n\n return slice(content);\n },\n kinds,\n ignore: group.ignore,\n });\n }\n\n /** A group's classes: inlined by a build, else its own `resolve()`, else the resolver `@venizia/ignis-boot/auto` installs. */\n static async resolveContent(opts: { group: IArtifactGroup }): Promise<IArtifactIndex> {\n const { group } = opts;\n\n if (group.content) {\n return group.content;\n }\n\n if (group.resolve) {\n return group.resolve();\n }\n\n const resolve = ArtifactGroup.getResolver();\n\n if (!resolve) {\n throw getError({\n message: `[ArtifactGroup] '${group.folder ?? '<application>'}' has no content | Import @venizia/ignis-boot/auto in the application (it resolves groups from source), or add IgnisArtifactsPlugin to the build's plugins`,\n });\n }\n\n return resolve({ group });\n }\n\n /** Positional on purpose: a type predicate narrows its own parameter, and an options object would narrow the wrapper instead of `value`. */\n static isGroup(value: unknown): value is IArtifactGroup {\n return (\n typeof value === 'object' &&\n value !== null &&\n ArtifactGroup.BRAND_KEY in value &&\n value[ArtifactGroup.BRAND_KEY] === true\n );\n }\n\n static setResolver(opts: { resolve: TGroupResolver | undefined }): void {\n ArtifactGroup.holder().resolve = opts.resolve;\n }\n\n static getResolver(): TGroupResolver | undefined {\n return ArtifactGroup.holder().resolve;\n }\n\n /** The error a walker over `configs.artifacts` gets for reading a kind off a group - loud, never an empty list. */\n static unreadKindError(opts: { folder: string | undefined }): Error {\n return getError({\n message: `[ArtifactGroup] '${opts.folder ?? '<application>'}' is resolved when artifacts are registered | A function that walks configs.artifacts must pass a group through untouched (ArtifactGroup.isGroup) instead of reading its kinds`,\n });\n }\n\n get configurations(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get dataSources(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get components(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get repositories(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get services(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get controllers(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n private static holder(): { resolve: TGroupResolver | undefined } {\n return SingletonRealm.resolve({\n key: ArtifactGroup.SINGLETON_REALM_KEY,\n create: () => ({ resolve: undefined }),\n });\n }\n\n /** The module that declared the group, read from the call stack. */\n private static callSite(): string | undefined {\n // A stack trace, not a failure: reading the call site needs an Error object, and nothing is thrown.\n // eslint-disable-next-line venizia/no-new-error\n return ArtifactGroup.siteFromStack({ stack: new Error().stack ?? '' });\n }\n\n /** The first frame outside the kernel's own `artifact-group` file: POSIX and Windows paths, `file://` URLs (decoded, drive kept), parentheses inside a path. */\n static siteFromStack(opts: { stack: string }): string | undefined {\n for (const raw of opts.stack.split('\\n').slice(1)) {\n const frame = raw.trim().replace(/^at\\s+/, '');\n const opening = frame.indexOf(' (');\n const location = frame.endsWith(')') && opening >= 0 ? frame.slice(opening + 2, -1) : frame;\n let file = location.replace(/:\\d+:\\d+$/, '');\n\n if (file.startsWith('file://')) {\n file = decodeURIComponent(file.slice('file://'.length)).replace(/^\\/([A-Za-z]:\\/)/, '$1');\n }\n\n const isPath = file.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(file);\n\n if (isPath && !/(?:^|[\\\\/])artifact-group\\.(?:ts|js)$/.test(file)) {\n return file;\n }\n }\n\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"artifact-group.js","sourceRoot":"","sources":["../../../../src/base/applications/artifact-group.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAKvD,sXAAsX;AACtX,MAAM,OAAO,aAAa;IACxB,kIAAkI;aAClH,cAAS,GAAG,iBAAiB,AAApB,CAAqB;IAC9C,uGAAuG;aACvF,wBAAmB,GAAG,yBAAyB,AAA5B,CAA6B;IAMhE,YAAoB,IAOnB;QAXQ,oBAAe,GAAG,IAAa,CAAC;QAYvC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;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I,CAAC,uCAAuC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC","sourcesContent":["import { SingletonRealm } from '@/helpers/singleton-realm';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IArtifactGroup, IArtifactIndex } from './common';\n\ntype TGroupResolver = (opts: { group: IArtifactGroup }) => Promise<IArtifactIndex>;\n\n/** A typed slice of a shared package's artifacts - every decorated class under a directory named `folder` in the package that defined it. A package declares one per domain, once; an application borrows it in `configs.artifacts`. The content is filled by `@venizia/ignis-boot`: inlined when the application is built, or resolved from source when artifacts are registered. */\nexport class ArtifactGroup implements IArtifactGroup {\n /** A string brand, so the group protocol is structural: `@venizia/ignis-boot/auto` builds one without depending on the kernel. */\n static readonly BRAND_KEY = 'isArtifactGroup';\n /** The realm slot `@venizia/ignis-boot` fills with the resolver for groups defined without content. */\n static readonly SINGLETON_REALM_KEY = 'artifact-group-resolver';\n\n readonly isArtifactGroup = true as const;\n readonly resolve: (() => Promise<IArtifactIndex>) | undefined;\n readonly kinds: ReadonlyArray<keyof IArtifactIndex> | undefined;\n\n private constructor(opts: {\n folder: string | undefined;\n site: string | undefined;\n content: IArtifactIndex | undefined;\n resolve?: () => Promise<IArtifactIndex>;\n kinds?: ReadonlyArray<keyof IArtifactIndex>;\n ignore?: ReadonlyArray<string>;\n }) {\n this.folder = opts.folder;\n this.site = opts.site;\n this.content = opts.content;\n this.resolve = opts.resolve;\n this.kinds = opts.kinds;\n this.ignore = opts.ignore;\n }\n\n readonly folder: string | undefined;\n readonly site: string | undefined;\n readonly content: IArtifactIndex | undefined;\n readonly ignore: ReadonlyArray<string> | undefined;\n\n /** `content` is written by the build plugin; a hand-written group passes only `folder`. */\n static define(opts: { folder: string; content?: IArtifactIndex }): ArtifactGroup {\n return new ArtifactGroup({\n folder: opts.folder,\n site: ArtifactGroup.callSite(),\n content: opts.content,\n });\n }\n\n /** Every decorated class of the calling package - an application's own artifacts, picked by its call site, so several applications in one process each get their own. `ignore` takes the globs `ignis-artifacts --ignore` takes, relative to the package `src`. `content` is written by the build plugin. */\n static application(\n opts: { ignore?: ReadonlyArray<string>; content?: IArtifactIndex } = {},\n ): ArtifactGroup {\n return new ArtifactGroup({\n folder: undefined,\n site: ArtifactGroup.callSite(),\n content: opts.content,\n ignore: opts.ignore,\n });\n }\n\n /** A group carrying only `kinds` - for a slicer that splits `configs.artifacts` by run mode. `custom` is one kind for every type the application defined: a slice keeps all of them or none. The source group is resolved when artifacts are registered, never here. */\n static pick(opts: {\n group: IArtifactGroup;\n kinds: ReadonlyArray<keyof IArtifactIndex>;\n }): ArtifactGroup {\n const { group, kinds } = opts;\n const slice = (index: IArtifactIndex): IArtifactIndex =>\n Object.fromEntries(\n kinds.filter((kind) => index[kind] !== undefined).map((kind) => [kind, index[kind]]),\n );\n\n return new ArtifactGroup({\n folder: group.folder,\n site: group.site,\n content: group.content ? slice(group.content) : undefined,\n resolve: async () => {\n const content = await ArtifactGroup.resolveContent({ group });\n\n return slice(content);\n },\n kinds,\n ignore: group.ignore,\n });\n }\n\n /** A group's classes: inlined by a build, else its own `resolve()`, else the resolver `@venizia/ignis-boot/auto` installs. */\n static async resolveContent(opts: { group: IArtifactGroup }): Promise<IArtifactIndex> {\n const { group } = opts;\n\n if (group.content) {\n return group.content;\n }\n\n if (group.resolve) {\n return group.resolve();\n }\n\n const resolve = ArtifactGroup.getResolver();\n\n if (!resolve) {\n throw getError({\n message: `[ArtifactGroup] '${group.folder ?? '<application>'}' has no content | Import @venizia/ignis-boot/auto in the application (it resolves groups from source), or add IgnisArtifactsPlugin to the build's plugins`,\n });\n }\n\n return resolve({ group });\n }\n\n /** Positional on purpose: a type predicate narrows its own parameter, and an options object would narrow the wrapper instead of `value`. */\n static isGroup(value: unknown): value is IArtifactGroup {\n return (\n typeof value === 'object' &&\n value !== null &&\n ArtifactGroup.BRAND_KEY in value &&\n value[ArtifactGroup.BRAND_KEY] === true\n );\n }\n\n static setResolver(opts: { resolve: TGroupResolver | undefined }): void {\n ArtifactGroup.holder().resolve = opts.resolve;\n }\n\n static getResolver(): TGroupResolver | undefined {\n return ArtifactGroup.holder().resolve;\n }\n\n /** The error a walker over `configs.artifacts` gets for reading a kind off a group - loud, never an empty list. */\n static unreadKindError(opts: { folder: string | undefined }): Error {\n return getError({\n message: `[ArtifactGroup] '${opts.folder ?? '<application>'}' is resolved when artifacts are registered | A function that walks configs.artifacts must pass a group through untouched (ArtifactGroup.isGroup) instead of reading its kinds`,\n });\n }\n\n get configurations(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get dataSources(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get components(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get repositories(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get services(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get controllers(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n get custom(): never {\n throw ArtifactGroup.unreadKindError({ folder: this.folder });\n }\n\n private static holder(): { resolve: TGroupResolver | undefined } {\n return SingletonRealm.resolve({\n key: ArtifactGroup.SINGLETON_REALM_KEY,\n create: () => ({ resolve: undefined }),\n });\n }\n\n /** The module that declared the group, read from the call stack. */\n private static callSite(): string | undefined {\n // A stack trace, not a failure: reading the call site needs an Error object, and nothing is thrown.\n // eslint-disable-next-line venizia/no-new-error\n return ArtifactGroup.siteFromStack({ stack: new Error().stack ?? '' });\n }\n\n /** The first frame outside the kernel's own `artifact-group` file: POSIX and Windows paths, `file://` URLs (decoded, drive kept), parentheses inside a path. */\n static siteFromStack(opts: { stack: string }): string | undefined {\n for (const raw of opts.stack.split('\\n').slice(1)) {\n const frame = raw.trim().replace(/^at\\s+/, '');\n const opening = frame.indexOf(' (');\n const location = frame.endsWith(')') && opening >= 0 ? frame.slice(opening + 2, -1) : frame;\n let file = location.replace(/:\\d+:\\d+$/, '');\n\n if (file.startsWith('file://')) {\n file = decodeURIComponent(file.slice('file://'.length)).replace(/^\\/([A-Za-z]:\\/)/, '$1');\n }\n\n const isPath = file.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(file);\n\n if (isPath && !/(?:^|[\\\\/])artifact-group\\.(?:ts|js)$/.test(file)) {\n return file;\n }\n }\n\n return undefined;\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { TClass } from '@venizia/ignis-helpers/common';
2
2
  import { BaseHelper } from '@venizia/ignis-helpers/core';
3
3
  import type { IArtifactIndex, TArtifactIndexInput } from './common/index.js';
4
+ import { type TArtifactIndexField } from './common/index.js';
4
5
  /** Turns a `configs.artifacts` input into the classes to register: flattens nested indexes, drops the classes whose `when` says no, orders the rest. It never touches the container - `registerArtifacts` does the binding. */
5
6
  export declare class ArtifactIndexHelper extends BaseHelper {
6
7
  static readonly SINGLETON_REALM_KEY = "artifact-index-helper";
@@ -15,6 +16,8 @@ export declare class ArtifactIndexHelper extends BaseHelper {
15
16
  input: TArtifactIndexInput;
16
17
  application: unknown;
17
18
  }): Promise<Required<IArtifactIndex>>;
19
+ /** The classes of each custom type across every index, each type chosen like a built-in field (`when`, `order`, no duplicates). Types come in the order they are first named. */
20
+ private selectCustom;
18
21
  /**
19
22
  * Topologically sort configurations based on `after` dependencies.
20
23
  * Siblings with no dependency relation are sorted deterministically by class name.
@@ -35,11 +38,13 @@ export declare class ArtifactIndexHelper extends BaseHelper {
35
38
  /** Positional on purpose: a type predicate narrows its own parameter, and an options object would narrow the wrapper instead of `input`. */
36
39
  private isConditional;
37
40
  /** The classes of one kind across every index, minus those whose `when` says no, sorted by `order` (stable). The `when` conditions run concurrently: each reads config and environment, never another artifact. */
38
- select<Field extends keyof IArtifactIndex>(opts: {
41
+ select<Field extends TArtifactIndexField>(opts: {
39
42
  indexes: IArtifactIndex[];
40
43
  field: Field;
41
44
  application: unknown;
42
45
  }): Promise<NonNullable<IArtifactIndex[Field]>[number][]>;
46
+ /** The shared half of `select` and `selectCustom`: the listed classes de-duplicated, minus those whose `when` says no, sorted by `order`. */
47
+ private choose;
43
48
  private isSelected;
44
49
  }
45
50
  //# sourceMappingURL=artifact-index.d.ts.map
@@ -29,6 +29,7 @@ export class ArtifactIndexHelper extends BaseHelper {
29
29
  buildDiscoveredIndex() {
30
30
  const registry = MetadataRegistry.getInstance();
31
31
  const index = {};
32
+ const custom = {};
32
33
  const discoveredArtifacts = registry.getDiscoveredArtifacts();
33
34
  for (const target of discoveredArtifacts) {
34
35
  if (!isClass(target)) {
@@ -36,12 +37,16 @@ export class ArtifactIndexHelper extends BaseHelper {
36
37
  }
37
38
  const type = registry.getArtifactMetadata({ target })?.type;
38
39
  const field = type ? ArtifactIndexHelper.INDEX_FIELD_BY_TYPE[type] : undefined;
40
+ if (type && !field && ArtifactTypes.definitionOf({ type })) {
41
+ custom[type] = [...(custom[type] ?? []), target];
42
+ continue;
43
+ }
39
44
  if (!field) {
40
45
  continue;
41
46
  }
42
47
  index[field] = [...(index[field] ?? []), target];
43
48
  }
44
- return index;
49
+ return Object.keys(custom).length > 0 ? { ...index, custom } : index;
45
50
  }
46
51
  /** Every kind of the input, each already filtered by `when` and sorted by `order`, keyed the way `IArtifactIndex` is. */
47
52
  async resolve(opts) {
@@ -80,7 +85,23 @@ export class ArtifactIndexHelper extends BaseHelper {
80
85
  field: ArtifactIndexFields.CONTROLLERS,
81
86
  application,
82
87
  });
83
- return { configurations, dataSources, components, repositories, services, controllers };
88
+ const custom = await this.selectCustom({ indexes, application });
89
+ return { configurations, dataSources, components, repositories, services, controllers, custom };
90
+ }
91
+ /** The classes of each custom type across every index, each type chosen like a built-in field (`when`, `order`, no duplicates). Types come in the order they are first named. */
92
+ async selectCustom(opts) {
93
+ const { indexes, application } = opts;
94
+ const types = [...new Set(indexes.flatMap((index) => Object.keys(index.custom ?? {})))];
95
+ const custom = {};
96
+ for (const type of types) {
97
+ const chosen = await this.choose({
98
+ listed: indexes.flatMap((index) => [...(index.custom?.[type] ?? [])]),
99
+ label: `custom.${type}`,
100
+ application,
101
+ });
102
+ custom[type] = chosen;
103
+ }
104
+ return custom;
84
105
  }
85
106
  /**
86
107
  * Topologically sort configurations based on `after` dependencies.
@@ -180,11 +201,18 @@ export class ArtifactIndexHelper extends BaseHelper {
180
201
  async contentOf(opts) {
181
202
  const { group } = opts;
182
203
  const content = await ArtifactGroup.resolveContent({ group });
204
+ const { custom = {}, ...lists } = content;
183
205
  // One element type for the six kinds, so `.map` is callable on every member of the union.
184
- for (const [field, classes] of Object.entries(content)) {
206
+ for (const [field, classes] of Object.entries(lists)) {
185
207
  this.assertClasses({ field, classes });
186
208
  }
187
- const kinds = Object.values(content);
209
+ for (const [type, classes] of Object.entries(custom)) {
210
+ this.assertClasses({ field: `custom.${type}`, classes });
211
+ }
212
+ const kinds = [
213
+ ...Object.values(lists),
214
+ ...Object.values(custom),
215
+ ];
188
216
  const names = kinds.flatMap((classes) => (classes ?? []).map((target) => target.name));
189
217
  if (names.length === 0 && !group.kinds) {
190
218
  throw getError({
@@ -201,17 +229,26 @@ export class ArtifactIndexHelper extends BaseHelper {
201
229
  /** The classes of one kind across every index, minus those whose `when` says no, sorted by `order` (stable). The `when` conditions run concurrently: each reads config and environment, never another artifact. */
202
230
  async select(opts) {
203
231
  const { indexes, field, application } = opts;
232
+ return this.choose({
233
+ listed: indexes.flatMap((index) => [...(index[field] ?? [])]),
234
+ label: field,
235
+ application,
236
+ });
237
+ }
238
+ /** The shared half of `select` and `selectCustom`: the listed classes de-duplicated, minus those whose `when` says no, sorted by `order`. */
239
+ async choose(opts) {
240
+ const { label, application } = opts;
204
241
  const registry = MetadataRegistry.getInstance();
205
242
  // De-duplicated: discovery and a declared index can name the same class, and registering it
206
243
  // twice trips `bootChecks.binding.allowOverride: false`. First mention wins its position.
207
- const listed = [...new Set(indexes.flatMap((index) => [...(index[field] ?? [])]))];
208
- this.assertClasses({ field, classes: listed });
244
+ const listed = [...new Set(opts.listed)];
245
+ this.assertClasses({ field: label, classes: listed });
209
246
  const decisions = await Promise.all(listed.map((target) => this.isSelected({ target, application })));
210
247
  const kept = listed.filter((target, position) => {
211
248
  if (decisions[position]) {
212
249
  return true;
213
250
  }
214
- this.logger.debug('Skipped by condition | kind: %s | class: %s', field, target.name);
251
+ this.logger.debug('Skipped by condition | field: %s | class: %s', label, target.name);
215
252
  return false;
216
253
  });
217
254
  return kept
@@ -1 +1 @@
1
- {"version":3,"file":"artifact-index.js","sourceRoot":"","sources":["../../../../src/base/applications/artifact-index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAOjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAE/C,+NAA+N;AAC/N,MAAM,OAAO,mBAAoB,SAAQ,UAAU;aACjC,wBAAmB,GAAG,uBAAuB,CAAC;IAE9D;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,OAAO,cAAc,CAAC,OAAO,CAAC;YAC5B,GAAG,EAAE,mBAAmB,CAAC,mBAAmB;YAC5C,MAAM,EAAE,GAAG,EAAE,CAAC,IAAI,mBAAmB,EAAE;SACxC,CAAC,CAAC;IACL,CAAC;IAED,uMAAuM;aAC/K,wBAAmB,GAA2B;QACpE,CAAC,aAAa,CAAC,aAAa,CAAC,EAAE,mBAAmB,CAAC,cAAc;QACjE,CAAC,aAAa,CAAC,UAA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AC;QAEF,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE;YAC9C,IAAI,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACxB,OAAO,IAAI,CAAC;YACd,CAAC;YAED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;YAErF,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI;aACR,GAAG,CAAC,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;YAC1B,MAAM;YACN,QAAQ;YACR,KAAK,EAAE,QAAQ,CAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK,IAAI,CAAC;SAC5D,CAAC,CAAC;aACF,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC;aAC5D,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;IAEO,KAAK,CAAC,UAAU,CAAC,IAGxB;QACC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;QACrC,MAAM,IAAI,GAAG,gBAAgB,CAAC,WAAW,EAAE,CAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,CAAC;QAElF,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;IAC/B,CAAC","sourcesContent":["import { MetadataRegistry } from '@/helpers/inversion';\nimport { SingletonRealm } from '@/helpers/singleton-realm';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport { ArtifactTypes, isClass } from '@/helpers/inversion';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { ArtifactGroup } from './artifact-group';\nimport type {\n IArtifactGroup,\n IArtifactIndex,\n IConditionalArtifactIndex,\n TArtifactIndexInput,\n} from './common';\nimport { ArtifactIndexFields } from './common';\n\n/** Turns a `configs.artifacts` input into the classes to register: flattens nested indexes, drops the classes whose `when` says no, orders the rest. It never touches the container - `registerArtifacts` does the binding. */\nexport class ArtifactIndexHelper extends BaseHelper {\n static readonly SINGLETON_REALM_KEY = 'artifact-index-helper';\n\n private constructor() {\n super({ scope: ArtifactIndexHelper.name });\n }\n\n static getInstance(): ArtifactIndexHelper {\n return SingletonRealm.resolve({\n key: ArtifactIndexHelper.SINGLETON_REALM_KEY,\n create: () => new ArtifactIndexHelper(),\n });\n }\n\n /** Maps an artifact type to the index field that carries it. `ArtifactTypes.MODEL` is deliberately absent: a model has a binding namespace but no index field, because its repository registers it. */\n private static readonly INDEX_FIELD_BY_TYPE: Record<string, string> = {\n [ArtifactTypes.CONFIGURATION]: ArtifactIndexFields.CONFIGURATIONS,\n [ArtifactTypes.DATASOURCE]: ArtifactIndexFields.DATA_SOURCES,\n [ArtifactTypes.COMPONENT]: ArtifactIndexFields.COMPONENTS,\n [ArtifactTypes.REPOSITORY]: ArtifactIndexFields.REPOSITORIES,\n [ArtifactTypes.SERVICE]: ArtifactIndexFields.SERVICES,\n [ArtifactTypes.CONTROLLER]: ArtifactIndexFields.CONTROLLERS,\n };\n\n /** The index a decorator-only application has: every class a stereotype saw at import time, bucketed by its type. `when` and `order` still apply - `resolve` does that, exactly as it does for a declared index. */\n buildDiscoveredIndex(): IArtifactIndex {\n const registry = MetadataRegistry.getInstance();\n const index: Record<string, TClass<unknown>[]> = {};\n\n const discoveredArtifacts = registry.getDiscoveredArtifacts();\n\n for (const target of discoveredArtifacts) {\n if (!isClass<unknown>(target)) {\n continue;\n }\n\n const type = registry.getArtifactMetadata({ target })?.type;\n const field = type ? ArtifactIndexHelper.INDEX_FIELD_BY_TYPE[type] : undefined;\n\n if (!field) {\n continue;\n }\n\n index[field] = [...(index[field] ?? []), target];\n }\n\n return index;\n }\n\n /** Every kind of the input, each already filtered by `when` and sorted by `order`, keyed the way `IArtifactIndex` is. */\n async resolve(opts: {\n input: TArtifactIndexInput;\n application: unknown;\n }): Promise<Required<IArtifactIndex>> {\n const { input, application } = opts;\n const indexes = await this.flatten({ input, application });\n\n const rawConfigurations = await this.select({\n indexes,\n field: ArtifactIndexFields.CONFIGURATIONS,\n application,\n });\n const configurations = this.sortConfigurationsTopologically({\n classes: rawConfigurations,\n });\n\n const dataSources = await this.select({\n indexes,\n field: ArtifactIndexFields.DATA_SOURCES,\n application,\n });\n const components = await this.select({\n indexes,\n field: ArtifactIndexFields.COMPONENTS,\n application,\n });\n const repositories = await this.select({\n indexes,\n field: ArtifactIndexFields.REPOSITORIES,\n application,\n });\n const services = await this.select({\n indexes,\n field: ArtifactIndexFields.SERVICES,\n application,\n });\n const controllers = await this.select({\n indexes,\n field: ArtifactIndexFields.CONTROLLERS,\n application,\n });\n\n return { configurations, dataSources, components, repositories, services, controllers };\n }\n\n /**\n * Topologically sort configurations based on `after` dependencies.\n * Siblings with no dependency relation are sorted deterministically by class name.\n * Throws if an unknown `after` dependency is referenced or if a dependency cycle is detected.\n */\n sortConfigurationsTopologically<T>(opts: { classes: ReadonlyArray<TClass<T>> }): TClass<T>[] {\n const { classes } = opts;\n\n if (classes.length === 0) {\n return [];\n }\n\n const registry = MetadataRegistry.getInstance();\n\n // Keyed by the class itself: two configurations may share a name (a minified build renames them),\n // and a name-keyed graph silently drops one of them.\n const inDegree = new Map<TClass<T>, number>();\n const adjacency = new Map<TClass<T>, TClass<T>[]>();\n\n for (const target of classes) {\n inDegree.set(target, 0);\n adjacency.set(target, []);\n }\n\n for (const target of classes) {\n const metadata = registry.getArtifactMetadata({ target });\n const afterList = metadata?.after ?? [];\n\n for (const prereq of afterList) {\n // A string names a class, the only form that can; a class is matched by identity.\n const prereqClass =\n typeof prereq === 'function'\n ? classes.find((candidate) => candidate === prereq)\n : classes.find((candidate) => candidate.name === String(prereq));\n\n if (!prereqClass) {\n const prereqName = typeof prereq === 'function' ? prereq.name : String(prereq);\n throw getError({\n message: `[sortConfigurationsTopologically][${target.name}] Declared 'after' dependency '${prereqName}' is not registered as a configuration`,\n });\n }\n\n adjacency.get(prereqClass)!.push(target);\n inDegree.set(target, (inDegree.get(target) ?? 0) + 1);\n }\n }\n\n // Kahn's algorithm. Siblings run in class-name order; a minified build renames classes, so an\n // order that matters belongs in `after`.\n const byName = (a: TClass<T>, b: TClass<T>) => a.name.localeCompare(b.name);\n const available = classes.filter((target) => inDegree.get(target) === 0).sort(byName);\n const sorted: TClass<T>[] = [];\n\n while (available.length > 0) {\n const current = available.shift()!;\n sorted.push(current);\n\n for (const dependent of adjacency.get(current) ?? []) {\n const newDeg = inDegree.get(dependent)! - 1;\n inDegree.set(dependent, newDeg);\n\n if (newDeg === 0) {\n available.push(dependent);\n available.sort(byName);\n }\n }\n }\n\n if (sorted.length !== classes.length) {\n const unvisited = classes\n .filter((target) => !sorted.includes(target))\n .map((target) => target.name);\n throw getError({\n message: `[sortConfigurationsTopologically] Dependency cycle detected in configurations: ${unvisited.join(', ')}`,\n });\n }\n\n return sorted;\n }\n\n /** Every entry of a kind must be a class. `undefined` is what an import cycle leaves - the index was read before a class's module finished loading - so it gets a message that names the cause instead of a crash on `.name`. */\n private assertClasses(opts: {\n field: string;\n classes: ReadonlyArray<unknown> | undefined;\n }): void {\n const position = (opts.classes ?? []).findIndex((target) => typeof target !== 'function');\n\n if (position >= 0) {\n throw getError({\n message: `[ArtifactIndex] '${opts.field}' lists an entry that is not a class (position ${position}) | Usually an import cycle: the index was read before that class's module finished loading. The module that imports the index (or @venizia/ignis-boot/auto) must not define decorated classes or be imported by them`,\n });\n }\n }\n\n /** One index, or arrays nested to any depth, as a flat list in input order; a conditional entry contributes its subtree only when its `when` answers true. */\n async flatten(opts: {\n input: TArtifactIndexInput;\n application: unknown;\n }): Promise<IArtifactIndex[]> {\n const { input, application } = opts;\n\n if (ArtifactGroup.isGroup(input)) {\n const result = await this.contentOf({ group: input });\n\n return this.flatten({ input: result, application });\n }\n\n if (Array.isArray(input)) {\n const nested = await Promise.all(\n input.map((entry) => this.flatten({ input: entry, application })),\n );\n\n return nested.flat();\n }\n\n if (this.isConditional(input)) {\n const isSelected = await input.when({ application });\n\n if (!isSelected) {\n this.logger.debug('Skipped by condition | conditional index entry');\n\n return [];\n }\n\n return this.flatten({ input: input.index, application });\n }\n\n return [input];\n }\n\n /** A group's classes: inlined at build time, else the resolver `@venizia/ignis-boot/auto` installs. Never empty - a group that names nothing is a typo or a moved folder. */\n private async contentOf(opts: { group: IArtifactGroup }): Promise<IArtifactIndex> {\n const { group } = opts;\n const content = await ArtifactGroup.resolveContent({ group });\n\n // One element type for the six kinds, so `.map` is callable on every member of the union.\n for (const [field, classes] of Object.entries(content)) {\n this.assertClasses({ field, classes });\n }\n\n const kinds: Array<ReadonlyArray<TClass<unknown>> | undefined> = Object.values(content);\n const names = kinds.flatMap((classes) => (classes ?? []).map((target) => target.name));\n\n if (names.length === 0 && !group.kinds) {\n throw getError({\n message: `[ArtifactGroup] '${group.folder ?? '<application>'}' resolved to no class | Defined in ${group.site ?? 'an unknown module'} - check the folder name and that its classes carry a stereotype decorator`,\n });\n }\n\n this.logger.info('[ArtifactGroup] %s -> %s', group.folder ?? '<application>', names.join(', '));\n\n return content;\n }\n\n /** Positional on purpose: a type predicate narrows its own parameter, and an options object would narrow the wrapper instead of `input`. */\n private isConditional(\n entry: IArtifactIndex | IConditionalArtifactIndex,\n ): entry is IConditionalArtifactIndex {\n return 'when' in entry && 'index' in entry;\n }\n\n /** The classes of one kind across every index, minus those whose `when` says no, sorted by `order` (stable). The `when` conditions run concurrently: each reads config and environment, never another artifact. */\n async select<Field extends keyof IArtifactIndex>(opts: {\n indexes: IArtifactIndex[];\n field: Field;\n application: unknown;\n }): Promise<NonNullable<IArtifactIndex[Field]>[number][]> {\n const { indexes, field, application } = opts;\n const registry = MetadataRegistry.getInstance();\n\n // De-duplicated: discovery and a declared index can name the same class, and registering it\n // twice trips `bootChecks.binding.allowOverride: false`. First mention wins its position.\n const listed = [...new Set(indexes.flatMap((index) => [...(index[field] ?? [])]))];\n this.assertClasses({ field, classes: listed });\n const decisions = await Promise.all(\n listed.map((target) => this.isSelected({ target, application })),\n );\n\n const kept = listed.filter((target, position) => {\n if (decisions[position]) {\n return true;\n }\n\n this.logger.debug('Skipped by condition | kind: %s | class: %s', field, target.name);\n\n return false;\n });\n\n return kept\n .map((target, position) => ({\n target,\n position,\n order: registry.getArtifactMetadata({ target })?.order ?? 0,\n }))\n .sort((a, b) => a.order - b.order || a.position - b.position)\n .map((entry) => entry.target);\n }\n\n private async isSelected(opts: {\n target: TClass<unknown>;\n application: unknown;\n }): Promise<boolean> {\n const { target, application } = opts;\n const when = MetadataRegistry.getInstance().getArtifactMetadata({ target })?.when;\n\n if (!when) {\n return true;\n }\n\n return when({ application });\n }\n}\n"]}
1
+ {"version":3,"file":"artifact-index.js","sourceRoot":"","sources":["../../../../src/base/applications/artifact-index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAOjD,OAAO,EAAE,mBAAmB,EAA4B,MAAM,UAAU,CAAC;AAEzE,+NAA+N;AAC/N,MAAM,OAAO,mBAAoB,SAAQ,UAAU;aACjC,wBAAmB,GAAG,uBAAuB,CAAC;IAE9D;QACE,KAAK,CAAC,EAAE,KAAK,EAA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,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;YAEtF,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI;aACR,GAAG,CAAC,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;YAC1B,MAAM;YACN,QAAQ;YACR,KAAK,EAAE,QAAQ,CAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK,IAAI,CAAC;SAC5D,CAAC,CAAC;aACF,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC;aAC5D,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;IAEO,KAAK,CAAC,UAAU,CAAC,IAGxB;QACC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;QACrC,MAAM,IAAI,GAAG,gBAAgB,CAAC,WAAW,EAAE,CAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,CAAC;QAElF,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;IAC/B,CAAC","sourcesContent":["import { MetadataRegistry } from '@/helpers/inversion';\nimport { SingletonRealm } from '@/helpers/singleton-realm';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport { ArtifactTypes, isClass } from '@/helpers/inversion';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { ArtifactGroup } from './artifact-group';\nimport type {\n IArtifactGroup,\n IArtifactIndex,\n IConditionalArtifactIndex,\n TArtifactIndexInput,\n} from './common';\nimport { ArtifactIndexFields, type TArtifactIndexField } from './common';\n\n/** Turns a `configs.artifacts` input into the classes to register: flattens nested indexes, drops the classes whose `when` says no, orders the rest. It never touches the container - `registerArtifacts` does the binding. */\nexport class ArtifactIndexHelper extends BaseHelper {\n static readonly SINGLETON_REALM_KEY = 'artifact-index-helper';\n\n private constructor() {\n super({ scope: ArtifactIndexHelper.name });\n }\n\n static getInstance(): ArtifactIndexHelper {\n return SingletonRealm.resolve({\n key: ArtifactIndexHelper.SINGLETON_REALM_KEY,\n create: () => new ArtifactIndexHelper(),\n });\n }\n\n /** Maps an artifact type to the index field that carries it. `ArtifactTypes.MODEL` is deliberately absent: a model has a binding namespace but no index field, because its repository registers it. */\n private static readonly INDEX_FIELD_BY_TYPE: Record<string, string> = {\n [ArtifactTypes.CONFIGURATION]: ArtifactIndexFields.CONFIGURATIONS,\n [ArtifactTypes.DATASOURCE]: ArtifactIndexFields.DATA_SOURCES,\n [ArtifactTypes.COMPONENT]: ArtifactIndexFields.COMPONENTS,\n [ArtifactTypes.REPOSITORY]: ArtifactIndexFields.REPOSITORIES,\n [ArtifactTypes.SERVICE]: ArtifactIndexFields.SERVICES,\n [ArtifactTypes.CONTROLLER]: ArtifactIndexFields.CONTROLLERS,\n };\n\n /** The index a decorator-only application has: every class a stereotype saw at import time, bucketed by its type. `when` and `order` still apply - `resolve` does that, exactly as it does for a declared index. */\n buildDiscoveredIndex(): IArtifactIndex {\n const registry = MetadataRegistry.getInstance();\n const index: Record<string, TClass<unknown>[]> = {};\n const custom: Record<string, TClass<unknown>[]> = {};\n\n const discoveredArtifacts = registry.getDiscoveredArtifacts();\n\n for (const target of discoveredArtifacts) {\n if (!isClass<unknown>(target)) {\n continue;\n }\n\n const type = registry.getArtifactMetadata({ target })?.type;\n const field = type ? ArtifactIndexHelper.INDEX_FIELD_BY_TYPE[type] : undefined;\n\n if (type && !field && ArtifactTypes.definitionOf({ type })) {\n custom[type] = [...(custom[type] ?? []), target];\n continue;\n }\n\n if (!field) {\n continue;\n }\n\n index[field] = [...(index[field] ?? []), target];\n }\n\n return Object.keys(custom).length > 0 ? { ...index, custom } : index;\n }\n\n /** Every kind of the input, each already filtered by `when` and sorted by `order`, keyed the way `IArtifactIndex` is. */\n async resolve(opts: {\n input: TArtifactIndexInput;\n application: unknown;\n }): Promise<Required<IArtifactIndex>> {\n const { input, application } = opts;\n const indexes = await this.flatten({ input, application });\n\n const rawConfigurations = await this.select({\n indexes,\n field: ArtifactIndexFields.CONFIGURATIONS,\n application,\n });\n const configurations = this.sortConfigurationsTopologically({\n classes: rawConfigurations,\n });\n\n const dataSources = await this.select({\n indexes,\n field: ArtifactIndexFields.DATA_SOURCES,\n application,\n });\n const components = await this.select({\n indexes,\n field: ArtifactIndexFields.COMPONENTS,\n application,\n });\n const repositories = await this.select({\n indexes,\n field: ArtifactIndexFields.REPOSITORIES,\n application,\n });\n const services = await this.select({\n indexes,\n field: ArtifactIndexFields.SERVICES,\n application,\n });\n const controllers = await this.select({\n indexes,\n field: ArtifactIndexFields.CONTROLLERS,\n application,\n });\n\n const custom = await this.selectCustom({ indexes, application });\n\n return { configurations, dataSources, components, repositories, services, controllers, custom };\n }\n\n /** The classes of each custom type across every index, each type chosen like a built-in field (`when`, `order`, no duplicates). Types come in the order they are first named. */\n private async selectCustom(opts: {\n indexes: IArtifactIndex[];\n application: unknown;\n }): Promise<Record<string, TClass<unknown>[]>> {\n const { indexes, application } = opts;\n const types = [...new Set(indexes.flatMap((index) => Object.keys(index.custom ?? {})))];\n const custom: Record<string, TClass<unknown>[]> = {};\n\n for (const type of types) {\n const chosen = await this.choose({\n listed: indexes.flatMap((index) => [...(index.custom?.[type] ?? [])]),\n label: `custom.${type}`,\n application,\n });\n custom[type] = chosen;\n }\n\n return custom;\n }\n\n /**\n * Topologically sort configurations based on `after` dependencies.\n * Siblings with no dependency relation are sorted deterministically by class name.\n * Throws if an unknown `after` dependency is referenced or if a dependency cycle is detected.\n */\n sortConfigurationsTopologically<T>(opts: { classes: ReadonlyArray<TClass<T>> }): TClass<T>[] {\n const { classes } = opts;\n\n if (classes.length === 0) {\n return [];\n }\n\n const registry = MetadataRegistry.getInstance();\n\n // Keyed by the class itself: two configurations may share a name (a minified build renames them),\n // and a name-keyed graph silently drops one of them.\n const inDegree = new Map<TClass<T>, number>();\n const adjacency = new Map<TClass<T>, TClass<T>[]>();\n\n for (const target of classes) {\n inDegree.set(target, 0);\n adjacency.set(target, []);\n }\n\n for (const target of classes) {\n const metadata = registry.getArtifactMetadata({ target });\n const afterList = metadata?.after ?? [];\n\n for (const prereq of afterList) {\n // A string names a class, the only form that can; a class is matched by identity.\n const prereqClass =\n typeof prereq === 'function'\n ? classes.find((candidate) => candidate === prereq)\n : classes.find((candidate) => candidate.name === String(prereq));\n\n if (!prereqClass) {\n const prereqName = typeof prereq === 'function' ? prereq.name : String(prereq);\n throw getError({\n message: `[sortConfigurationsTopologically][${target.name}] Declared 'after' dependency '${prereqName}' is not registered as a configuration`,\n });\n }\n\n adjacency.get(prereqClass)!.push(target);\n inDegree.set(target, (inDegree.get(target) ?? 0) + 1);\n }\n }\n\n // Kahn's algorithm. Siblings run in class-name order; a minified build renames classes, so an\n // order that matters belongs in `after`.\n const byName = (a: TClass<T>, b: TClass<T>) => a.name.localeCompare(b.name);\n const available = classes.filter((target) => inDegree.get(target) === 0).sort(byName);\n const sorted: TClass<T>[] = [];\n\n while (available.length > 0) {\n const current = available.shift()!;\n sorted.push(current);\n\n for (const dependent of adjacency.get(current) ?? []) {\n const newDeg = inDegree.get(dependent)! - 1;\n inDegree.set(dependent, newDeg);\n\n if (newDeg === 0) {\n available.push(dependent);\n available.sort(byName);\n }\n }\n }\n\n if (sorted.length !== classes.length) {\n const unvisited = classes\n .filter((target) => !sorted.includes(target))\n .map((target) => target.name);\n throw getError({\n message: `[sortConfigurationsTopologically] Dependency cycle detected in configurations: ${unvisited.join(', ')}`,\n });\n }\n\n return sorted;\n }\n\n /** Every entry of a kind must be a class. `undefined` is what an import cycle leaves - the index was read before a class's module finished loading - so it gets a message that names the cause instead of a crash on `.name`. */\n private assertClasses(opts: {\n field: string;\n classes: ReadonlyArray<unknown> | undefined;\n }): void {\n const position = (opts.classes ?? []).findIndex((target) => typeof target !== 'function');\n\n if (position >= 0) {\n throw getError({\n message: `[ArtifactIndex] '${opts.field}' lists an entry that is not a class (position ${position}) | Usually an import cycle: the index was read before that class's module finished loading. The module that imports the index (or @venizia/ignis-boot/auto) must not define decorated classes or be imported by them`,\n });\n }\n }\n\n /** One index, or arrays nested to any depth, as a flat list in input order; a conditional entry contributes its subtree only when its `when` answers true. */\n async flatten(opts: {\n input: TArtifactIndexInput;\n application: unknown;\n }): Promise<IArtifactIndex[]> {\n const { input, application } = opts;\n\n if (ArtifactGroup.isGroup(input)) {\n const result = await this.contentOf({ group: input });\n\n return this.flatten({ input: result, application });\n }\n\n if (Array.isArray(input)) {\n const nested = await Promise.all(\n input.map((entry) => this.flatten({ input: entry, application })),\n );\n\n return nested.flat();\n }\n\n if (this.isConditional(input)) {\n const isSelected = await input.when({ application });\n\n if (!isSelected) {\n this.logger.debug('Skipped by condition | conditional index entry');\n\n return [];\n }\n\n return this.flatten({ input: input.index, application });\n }\n\n return [input];\n }\n\n /** A group's classes: inlined at build time, else the resolver `@venizia/ignis-boot/auto` installs. Never empty - a group that names nothing is a typo or a moved folder. */\n private async contentOf(opts: { group: IArtifactGroup }): Promise<IArtifactIndex> {\n const { group } = opts;\n const content = await ArtifactGroup.resolveContent({ group });\n\n const { custom = {}, ...lists } = content;\n\n // One element type for the six kinds, so `.map` is callable on every member of the union.\n for (const [field, classes] of Object.entries(lists)) {\n this.assertClasses({ field, classes });\n }\n\n for (const [type, classes] of Object.entries(custom)) {\n this.assertClasses({ field: `custom.${type}`, classes });\n }\n\n const kinds: Array<ReadonlyArray<TClass<unknown>> | undefined> = [\n ...Object.values(lists),\n ...Object.values(custom),\n ];\n const names = kinds.flatMap((classes) => (classes ?? []).map((target) => target.name));\n\n if (names.length === 0 && !group.kinds) {\n throw getError({\n message: `[ArtifactGroup] '${group.folder ?? '<application>'}' resolved to no class | Defined in ${group.site ?? 'an unknown module'} - check the folder name and that its classes carry a stereotype decorator`,\n });\n }\n\n this.logger.info('[ArtifactGroup] %s -> %s', group.folder ?? '<application>', names.join(', '));\n\n return content;\n }\n\n /** Positional on purpose: a type predicate narrows its own parameter, and an options object would narrow the wrapper instead of `input`. */\n private isConditional(\n entry: IArtifactIndex | IConditionalArtifactIndex,\n ): entry is IConditionalArtifactIndex {\n return 'when' in entry && 'index' in entry;\n }\n\n /** The classes of one kind across every index, minus those whose `when` says no, sorted by `order` (stable). The `when` conditions run concurrently: each reads config and environment, never another artifact. */\n async select<Field extends TArtifactIndexField>(opts: {\n indexes: IArtifactIndex[];\n field: Field;\n application: unknown;\n }): Promise<NonNullable<IArtifactIndex[Field]>[number][]> {\n const { indexes, field, application } = opts;\n\n return this.choose({\n listed: indexes.flatMap((index) => [...(index[field] ?? [])]),\n label: field,\n application,\n });\n }\n\n /** The shared half of `select` and `selectCustom`: the listed classes de-duplicated, minus those whose `when` says no, sorted by `order`. */\n private async choose<Listed extends TClass<unknown>>(opts: {\n listed: ReadonlyArray<Listed>;\n label: string;\n application: unknown;\n }): Promise<Listed[]> {\n const { label, application } = opts;\n const registry = MetadataRegistry.getInstance();\n\n // De-duplicated: discovery and a declared index can name the same class, and registering it\n // twice trips `bootChecks.binding.allowOverride: false`. First mention wins its position.\n const listed = [...new Set(opts.listed)];\n this.assertClasses({ field: label, classes: listed });\n const decisions = await Promise.all(\n listed.map((target) => this.isSelected({ target, application })),\n );\n\n const kept = listed.filter((target, position) => {\n if (decisions[position]) {\n return true;\n }\n\n this.logger.debug('Skipped by condition | field: %s | class: %s', label, target.name);\n\n return false;\n });\n\n return kept\n .map((target, position) => ({\n target,\n position,\n order: registry.getArtifactMetadata({ target })?.order ?? 0,\n }))\n .sort((a, b) => a.order - b.order || a.position - b.position)\n .map((entry) => entry.target);\n }\n\n private async isSelected(opts: {\n target: TClass<unknown>;\n application: unknown;\n }): Promise<boolean> {\n const { target, application } = opts;\n const when = MetadataRegistry.getInstance().getArtifactMetadata({ target })?.when;\n\n if (!when) {\n return true;\n }\n\n return when({ application });\n }\n}\n"]}
@@ -5,7 +5,7 @@ import type { BaseConfiguration } from '../../../configurations/index.js';
5
5
  import type { IDataSource } from '../../../datasources/index.js';
6
6
  import type { IRepository } from '../../../repositories/index.js';
7
7
  import type { IService } from '../../../services/index.js';
8
- /** The shape `@venizia/ignis-boot`'s generator emits and `registerArtifacts()` consumes. Kinds are registered in this field order. */
8
+ /** The shape `@venizia/ignis-boot`'s generator emits and `registerArtifacts()` consumes. Fields are registered in this order. */
9
9
  export interface IArtifactIndex {
10
10
  configurations?: ReadonlyArray<TClass<BaseConfiguration>>;
11
11
  dataSources?: ReadonlyArray<TClass<IDataSource>>;
@@ -13,6 +13,8 @@ export interface IArtifactIndex {
13
13
  repositories?: ReadonlyArray<TClass<IRepository>>;
14
14
  services?: ReadonlyArray<TClass<IService>>;
15
15
  controllers?: ReadonlyArray<TClass<unknown>>;
16
+ /** The classes of the types the application declared with `ArtifactTypes.define`, by type name. Registered after the services and before the controllers; a type with no loaded definition is an error. */
17
+ custom?: Readonly<Record<string, ReadonlyArray<TClass<unknown>>>>;
16
18
  }
17
19
  /** An index (or nested indexes) registered only when `when` answers true - the run-mode gate: a worker keeps its controllers out of the container instead of mounting routes no security step guards. Extends the never-typed kind fields so code that destructures kinds from a non-array input still compiles against the union. */
18
20
  export interface IConditionalArtifactIndex extends Partial<Record<keyof IArtifactIndex, never>> {
@@ -1 +1 @@
1
- {"version":3,"file":"artifacts.js","sourceRoot":"","sources":["../../../../../../src/base/applications/common/types/artifacts.ts"],"names":[],"mappings":"","sourcesContent":["import type { TArtifactCondition } from '@/helpers/inversion/common/types';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport type { BaseComponent } from '../../../components';\nimport type { BaseConfiguration } from '../../../configurations';\nimport type { IDataSource } from '../../../datasources';\nimport type { IRepository } from '../../../repositories';\nimport type { IService } from '../../../services';\n\n/** The shape `@venizia/ignis-boot`'s generator emits and `registerArtifacts()` consumes. Kinds are registered in this field order. */\nexport interface IArtifactIndex {\n configurations?: ReadonlyArray<TClass<BaseConfiguration>>;\n dataSources?: ReadonlyArray<TClass<IDataSource>>;\n components?: ReadonlyArray<TClass<BaseComponent>>;\n repositories?: ReadonlyArray<TClass<IRepository>>;\n services?: ReadonlyArray<TClass<IService>>;\n controllers?: ReadonlyArray<TClass<unknown>>;\n}\n\n/** An index (or nested indexes) registered only when `when` answers true - the run-mode gate: a worker keeps its controllers out of the container instead of mounting routes no security step guards. Extends the never-typed kind fields so code that destructures kinds from a non-array input still compiles against the union. */\nexport interface IConditionalArtifactIndex extends Partial<Record<keyof IArtifactIndex, never>> {\n when: TArtifactCondition;\n index: TArtifactIndexInput;\n}\n\n/** A slice of artifacts whose classes are known only when they are registered: a shared package's `ArtifactGroup`, or `@venizia/ignis-boot/auto`. `content` is inlined by a build; otherwise `resolve` (or the resolver `@venizia/ignis-boot` installs) supplies it. The kind fields are typed never so a walker that destructures kinds still compiles - reading one throws. */\nexport interface IArtifactGroup extends Partial<Record<keyof IArtifactIndex, never>> {\n readonly isArtifactGroup: true;\n /** The directory name the group covers; undefined for the application's own root. */\n readonly folder: string | undefined;\n /** The module that defined the group, for the resolver and the error messages. */\n readonly site: string | undefined;\n readonly content: IArtifactIndex | undefined;\n /** Globs relative to the package `src` whose classes the group leaves out (`ArtifactGroup.application`). */\n readonly ignore?: ReadonlyArray<string>;\n resolve?(): Promise<IArtifactIndex>;\n /** Set on a slice (`ArtifactGroup.pick`): only these kinds are registered, and an empty slice is not an error. */\n readonly kinds?: ReadonlyArray<keyof IArtifactIndex>;\n}\n\n/** One index, a conditional entry, a group, or any nesting of arrays of them - a library exports one, an application composes several. */\nexport type TArtifactIndexInput =\n | IArtifactIndex\n | IConditionalArtifactIndex\n | IArtifactGroup\n | TArtifactIndexInput[];\n"]}
1
+ {"version":3,"file":"artifacts.js","sourceRoot":"","sources":["../../../../../../src/base/applications/common/types/artifacts.ts"],"names":[],"mappings":"","sourcesContent":["import type { TArtifactCondition } from '@/helpers/inversion/common/types';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport type { BaseComponent } from '../../../components';\nimport type { BaseConfiguration } from '../../../configurations';\nimport type { IDataSource } from '../../../datasources';\nimport type { IRepository } from '../../../repositories';\nimport type { IService } from '../../../services';\n\n/** The shape `@venizia/ignis-boot`'s generator emits and `registerArtifacts()` consumes. Fields are registered in this order. */\nexport interface IArtifactIndex {\n configurations?: ReadonlyArray<TClass<BaseConfiguration>>;\n dataSources?: ReadonlyArray<TClass<IDataSource>>;\n components?: ReadonlyArray<TClass<BaseComponent>>;\n repositories?: ReadonlyArray<TClass<IRepository>>;\n services?: ReadonlyArray<TClass<IService>>;\n controllers?: ReadonlyArray<TClass<unknown>>;\n /** The classes of the types the application declared with `ArtifactTypes.define`, by type name. Registered after the services and before the controllers; a type with no loaded definition is an error. */\n custom?: Readonly<Record<string, ReadonlyArray<TClass<unknown>>>>;\n}\n\n/** An index (or nested indexes) registered only when `when` answers true - the run-mode gate: a worker keeps its controllers out of the container instead of mounting routes no security step guards. Extends the never-typed kind fields so code that destructures kinds from a non-array input still compiles against the union. */\nexport interface IConditionalArtifactIndex extends Partial<Record<keyof IArtifactIndex, never>> {\n when: TArtifactCondition;\n index: TArtifactIndexInput;\n}\n\n/** A slice of artifacts whose classes are known only when they are registered: a shared package's `ArtifactGroup`, or `@venizia/ignis-boot/auto`. `content` is inlined by a build; otherwise `resolve` (or the resolver `@venizia/ignis-boot` installs) supplies it. The kind fields are typed never so a walker that destructures kinds still compiles - reading one throws. */\nexport interface IArtifactGroup extends Partial<Record<keyof IArtifactIndex, never>> {\n readonly isArtifactGroup: true;\n /** The directory name the group covers; undefined for the application's own root. */\n readonly folder: string | undefined;\n /** The module that defined the group, for the resolver and the error messages. */\n readonly site: string | undefined;\n readonly content: IArtifactIndex | undefined;\n /** Globs relative to the package `src` whose classes the group leaves out (`ArtifactGroup.application`). */\n readonly ignore?: ReadonlyArray<string>;\n resolve?(): Promise<IArtifactIndex>;\n /** Set on a slice (`ArtifactGroup.pick`): only these kinds are registered, and an empty slice is not an error. */\n readonly kinds?: ReadonlyArray<keyof IArtifactIndex>;\n}\n\n/** One index, a conditional entry, a group, or any nesting of arrays of them - a library exports one, an application composes several. */\nexport type TArtifactIndexInput =\n | IArtifactIndex\n | IConditionalArtifactIndex\n | IArtifactGroup\n | TArtifactIndexInput[];\n"]}
@@ -1,5 +1,5 @@
1
1
  import { ArtifactNamespaces, BindingNamespaces, CoreBindings } from '../../common/bindings.js';
2
- import { BindingScopes, MetadataRegistry } from '../../helpers/inversion/index.js';
2
+ import { ArtifactTypes, BindingScopes, MetadataRegistry } from '../../helpers/inversion/index.js';
3
3
  import { BindingVerifier } from '@venizia/ignis-inversion';
4
4
  import { PerformanceUtility, getError, RequestIdGenerator, RetryUtility, } from '@venizia/ignis-helpers/core';
5
5
  import { showRoutes as showApplicationRoutes } from 'hono/dev';
@@ -557,12 +557,29 @@ export class RestApplication extends AbstractApplication {
557
557
  [resolved.services, BindingNamespaces.SERVICE],
558
558
  [resolved.controllers, BindingNamespaces.CONTROLLER],
559
559
  ];
560
+ // An application's own types: each needs its definition loaded, or the class has no namespace and no default scope.
561
+ const custom = Object.entries(resolved.custom).flatMap(([type, targets]) => {
562
+ const definition = ArtifactTypes.definitionOf({ type });
563
+ if (!definition) {
564
+ throw getError({
565
+ message: `[registerArtifacts] '${targets[0]?.name ?? type}' is listed under the artifact type '${type}', which is not defined | Import the module that calls ArtifactTypes.define({ type: '${type}', ... }) before the application boots`,
566
+ });
567
+ }
568
+ return targets.map((target) => ({ target, definition }));
569
+ });
560
570
  const collisions = ArtifactBindingKeys.findDerivedCollisions({
561
- entries: kinds.flatMap(([targets, namespace]) => targets.map((target) => ({
562
- target,
563
- namespace,
564
- binding: registry.getArtifactMetadata({ target })?.binding,
565
- }))),
571
+ entries: [
572
+ ...kinds.flatMap(([targets, namespace]) => targets.map((target) => ({
573
+ target,
574
+ namespace,
575
+ binding: registry.getArtifactMetadata({ target })?.binding,
576
+ }))),
577
+ ...custom.map(({ target, definition }) => ({
578
+ target,
579
+ namespace: definition.namespace,
580
+ binding: registry.getArtifactMetadata({ target })?.binding,
581
+ })),
582
+ ],
566
583
  });
567
584
  for (const key of collisions) {
568
585
  const message = ArtifactBindingKeys.describeCollision({ key, caller: 'registerArtifacts' });
@@ -588,6 +605,14 @@ export class RestApplication extends AbstractApplication {
588
605
  for (const target of resolved.services) {
589
606
  this.service(target);
590
607
  }
608
+ for (const { target, definition } of custom) {
609
+ this.registerArtifact({
610
+ target,
611
+ namespace: definition.namespace,
612
+ defaultScope: definition.scope,
613
+ caller: definition.type,
614
+ });
615
+ }
591
616
  for (const target of resolved.controllers) {
592
617
  this.controller(target);
593
618
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rest.js","sourceRoot":"","sources":["../../../../src/base/applications/rest.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAExF,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAE3D,OAAO,EACL,kBAAkB,EAClB,QAAQ,EACR,kBAAkB,EAClB,YAAY,GACb,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,UAAU,IAAI,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,8CAA8C,CAAC;AAE7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAEvE,OAAO,EAAE,mBAAmB,EAAE,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AAC;gBACf,IAAI,YAAY,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC5C,MAAM,CAAC,KAAK,CAAC,2CAA2C,EAAE,GAAG,EAAE,SAAS,CAAC,CAAC;oBAC1E,SAAS;gBACX,CAAC;gBAED,MAAM,CAAC,KAAK,CAAC,kDAAkD,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;gBAC7E,SAAS;YACX,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE,GAAG,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TBindingNamespace } from '@/common/bindings';\nimport { ArtifactNamespaces, BindingNamespaces, CoreBindings } from '@/common/bindings';\nimport type { Binding, TBindingKey, TBindingScope } from '@/helpers/inversion';\nimport { BindingScopes, MetadataRegistry } from '@/helpers/inversion';\nimport { BindingVerifier } from '@venizia/ignis-inversion';\nimport type { IConfigurable, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n PerformanceUtility,\n getError,\n RequestIdGenerator,\n RetryUtility,\n} from '@venizia/ignis-helpers/core';\nimport type { Env, Hono, MiddlewareHandler, Schema } from 'hono';\nimport { showRoutes as showApplicationRoutes } from 'hono/dev';\nimport { requestId } from 'hono/request-id';\nimport type { BaseComponent } from '../components';\nimport { ArtifactBindingKeys } from '../metadata/artifact-keys';\nimport { RestComponent } from '../components/controller/rest/rest.component';\nimport type { BaseConfiguration } from '../configurations';\nimport { ControllerTransports } from '../controllers/common/constants';\nimport type { IDataSource, IDataSourceOpening } from '../datasources';\nimport { DataSourceOpenModes } from '../datasources';\nimport { OPENING_HANDLES } from '../datasources/opening-handles';\nimport { BaseAppErrorMiddleware } from '../middlewares/app-error/app-error.middleware';\nimport { notFoundHandler } from '../middlewares/not-found/not-found.middleware';\nimport type { TMixinOpts } from '../mixins/common';\nimport type { IRepository } from '../repositories';\nimport type { IService } from '../services';\nimport { AbstractApplication } from './abstract';\nimport { BodyLimits } from './body-limit';\nimport { RouterFactories } from './router-factory';\nimport { CorsUtility } from './cors';\nimport { ArtifactIndexHelper } from './artifact-index';\nimport type { IBootSequenceStep } from './boot-sequence';\nimport { BootSteps } from './boot-sequence';\nimport type { IApplicationConfigs, IBodyLimitOptions, TArtifactIndexInput } from './common';\n\ninterface IRegisterDynamicBindingsOptions<T extends IConfigurable = IConfigurable> {\n namespace: TBindingNamespace;\n\n onBeforeConfigure?: (opts: { binding: Binding<T> }) => Promise<void>;\n onAfterConfigure?: (opts: { binding: Binding<T>; instance: T }) => Promise<void>;\n}\n\n/**\n * Runtime checks that narrow a bound instance to the members the boot calls on it. Positional: a type predicate narrows\n * its own parameter.\n */\nclass BootTargets {\n private static isObjectLike(value: unknown): value is object {\n return (typeof value === 'object' && value !== null) || typeof value === 'function';\n }\n\n /** Has `isOpenDeferred()`, so the boot can ask whether its open waits for the first use. */\n static canDeferOpen(\n value: unknown,\n ): value is Pick<IDataSource, 'deferOpen'> & Required<Pick<IDataSource, 'isOpenDeferred'>> {\n return (\n BootTargets.isObjectLike(value) &&\n 'isOpenDeferred' in value &&\n typeof value.isOpenDeferred === 'function'\n );\n }\n\n /** Has `configure()`; a datasource's takes the opening handles in its second argument. */\n static isConfigurable(value: unknown): value is Pick<IDataSource, 'configure'> {\n return (\n BootTargets.isObjectLike(value) &&\n 'configure' in value &&\n typeof value.configure === 'function'\n );\n }\n\n /** Carries the opening handles every datasource root defines. */\n static hasOpeningHandles(\n value: unknown,\n ): value is { [OPENING_HANDLES]: () => IDataSourceOpening } {\n return (\n BootTargets.isObjectLike(value) &&\n OPENING_HANDLES in value &&\n typeof value[OPENING_HANDLES] === 'function'\n );\n }\n}\n\n/** Adds the Hono router surface on top of `AbstractApplication` - no listening server, so this is the layer a browser Worker or gRPC-only host can extend without pulling in `Bun.serve`. */\nexport abstract class RestApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n> extends AbstractApplication {\n private registeredBindings: Record<string, Set<TBindingKey>> = {};\n private artifactOptions = new Map<string, object>();\n\n /** The router, and nothing else. What runtime is underneath and what socket is bound are `ServerApplication`'s to know - a browser Worker has neither, and carrying the union here made `RuntimeModules.detect()` answer `'node'` inside a Worker. */\n protected server: { hono: Hono<AppEnv, AppSchema, BasePath> };\n\n protected rootRouter: Hono<AppEnv, AppSchema, BasePath>;\n protected readonly requestIdGenerator: RequestIdGenerator;\n\n /** A copy of the `bodyLimit` the default stack installed, absent until `registerDefaultMiddlewares()` ran. */\n private installedBodyLimit?: { options?: IBodyLimitOptions };\n\n constructor(opts: { scope: string; config: IApplicationConfigs }) {\n super(opts);\n\n // A config built from the environment can lose `path.base` at run time; the router would only fail later, inside `route()`, with a message that names nothing.\n if (typeof this.configs.path?.base !== 'string') {\n throw getError({\n message: `[${opts.scope}] configs.path.base must be a string | value: ${String(this.configs.path?.base)} | an empty string mounts the application at the root`,\n });\n }\n\n // The index signature accepts any key, so a leftover `strictPath` would compile and be ignored.\n if (this.configs.strictPath !== undefined) {\n throw getError({\n message: `[${opts.scope}] configs.strictPath was removed | value: ${String(this.configs.strictPath)} | Use configs.path.isStrict`,\n });\n }\n\n this.requestIdGenerator = new RequestIdGenerator({ scope: opts.scope });\n\n const strict = this.configs.path.isStrict ?? true;\n this.server = { hono: this.createRouter({ strict }) };\n this.rootRouter = this.createRouter({ strict });\n }\n\n /**\n * Builds one of the two routers: a plain `Hono`, or an `OpenAPIHono` once the REST controller layer is\n * loaded. Called from the constructor, so an override must not read its own instance fields.\n */\n protected createRouter(opts: { strict: boolean }): Hono<AppEnv, AppSchema, BasePath> {\n return RouterFactories.create<AppEnv, AppSchema, BasePath>({ strict: opts.strict });\n }\n\n getRootRouter(): Hono<AppEnv, AppSchema, BasePath> {\n return this.rootRouter;\n }\n\n getServer(): Hono<AppEnv, AppSchema, BasePath> {\n return this.server.hono;\n }\n\n protected override registerCoreBindings() {\n super.registerCoreBindings();\n\n this.bind<typeof this.server>({\n key: CoreBindings.APPLICATION_SERVER,\n }).toProvider((_) => this.server);\n this.bind<typeof this.rootRouter>({\n key: CoreBindings.APPLICATION_ROOT_ROUTER,\n }).toProvider((_) => this.rootRouter);\n }\n\n /** The correlation id every host stamps - see {@link RequestIdGenerator} for why `crypto.randomUUID` is refused. */\n protected generateRequestId(): string {\n return this.requestIdGenerator.nextId();\n }\n\n /** The error handler the default stack installs. `@venizia/ignis` overrides it to swap in the `ErrorPrettier`-backed formatter, which reaches `node:util` and so cannot live here. */\n protected buildErrorMiddleware(): BaseAppErrorMiddleware {\n const environment = this.configs.error?.environment;\n\n return new BaseAppErrorMiddleware({\n logger: this.logger,\n rootKey: this.configs.error?.rootKey ?? undefined,\n // Spread, not `environment: () => environment`: the option's PRESENCE is what claims this host\n // has an ambient environment at all, so an unset config must leave it absent.\n ...(environment === undefined ? {} : { environment: () => environment }),\n });\n }\n\n /**\n * The three registrations every host needs: request id, error envelope, JSON 404 - without them a\n * thrown `ApplicationError` is a generic 500, a 404 is `text/plain`, and no response carries a request id.\n * Registered before `initialize()`, so an application's own handlers still win.\n */\n protected registerDefaultMiddlewares(): ValueOrPromise<void> {\n const server = this.getServer();\n\n // First of all, so every response the framework produces on its own - a bodyLimit 413, a body the\n // request spy cannot parse, the error envelope - leaves with the headers a browser needs to read it.\n CorsUtility.registerCors({ server, options: this.configs.middlewares?.cors });\n\n server.use(requestId({ generator: () => this.generateRequestId() }));\n\n // Ahead of every middleware a host adds after this one, so none of them buffers a body over it.\n // Unset, every route gets BodyLimits.DEFAULT_MAX_SIZE; a configured bodyLimit replaces it, and `enable: false` removes it.\n const bodyLimitOptions = this.resolveBodyLimit({\n options: this.configs.middlewares?.bodyLimit,\n });\n this.installedBodyLimit = { options: this.toInstalledBodyLimit({ options: bodyLimitOptions }) };\n\n if (bodyLimitOptions && bodyLimitOptions.enable !== false) {\n const { maxSize, path, onError } = bodyLimitOptions;\n\n if (typeof maxSize !== 'number' || !Number.isFinite(maxSize) || maxSize < 0) {\n throw getError({\n message: `[registerDefaultMiddlewares] configs.middlewares.bodyLimit.maxSize must be a non-negative number of bytes | value: ${String(maxSize)}`,\n });\n }\n\n const defaultLimiter = BodyLimits.limiter({ maxSize, onError });\n\n // A route with its own limit (BodyLimits.route) is held to that one, not to this.\n const limiter: MiddlewareHandler = (context, next) =>\n BodyLimits.hasRouteLimit(context) ? next() : defaultLimiter(context, next);\n\n if (path) {\n server.use(path, limiter);\n } else {\n server.use(limiter);\n }\n }\n\n server.onError(this.buildErrorMiddleware().value());\n server.notFound(notFoundHandler({ logger: this.logger }));\n }\n\n /** The configured `bodyLimit`, or the default one when none is configured. */\n private resolveBodyLimit(opts: { options?: IBodyLimitOptions }): IBodyLimitOptions {\n return opts.options ?? { maxSize: BodyLimits.DEFAULT_MAX_SIZE };\n }\n\n /** What a `bodyLimit` config installs: nothing when absent or disabled, else a copy, so a later in-place edit shows. */\n private toInstalledBodyLimit(opts: {\n options?: IBodyLimitOptions;\n }): IBodyLimitOptions | undefined {\n const { options } = opts;\n\n if (!options || options.enable === false) {\n return undefined;\n }\n\n return { ...options };\n }\n\n private isSameBodyLimit(opts: { left?: IBodyLimitOptions; right?: IBodyLimitOptions }): boolean {\n const { left, right } = opts;\n\n if (!left || !right) {\n return left === right;\n }\n\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n\n for (const key of keys) {\n if (!Object.is(left[key], right[key])) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * `configs.middlewares` is read by `registerDefaultMiddlewares()`, which runs before `staticConfigure()`.\n * A limit assigned in a boot hook would read back as configured while every request ran unlimited.\n */\n private assertBodyLimitUnchanged(opts: { step: string }): void {\n if (!this.installedBodyLimit) {\n return;\n }\n\n const installed = this.installedBodyLimit.options;\n const current = this.toInstalledBodyLimit({\n options: this.resolveBodyLimit({ options: this.configs.middlewares?.bodyLimit }),\n });\n\n if (this.isSameBodyLimit({ left: installed, right: current })) {\n return;\n }\n\n throw getError({\n message: `[${opts.step}] configs.middlewares.bodyLimit changed after registerDefaultMiddlewares() installed it | installed maxSize: ${installed?.maxSize ?? 'none'} | now maxSize: ${current?.maxSize ?? 'none'} | Pass it through the constructor config: new Application({ config: { middlewares: { bodyLimit } } })`,\n });\n }\n\n /**\n * The artifact order, stated once: datasources before the repositories that auto-resolve them,\n * components before the controllers they may contribute. `BaseApplication` splices its server-only\n * steps around these by name instead of rewriting the list.\n */\n protected getBootSequence(): IBootSequenceStep[] {\n return [\n {\n name: BootSteps.STATIC_CONFIGURE,\n run: async () => {\n // Declared `void`, but an override may be async; the step has always waited on it.\n await Promise.resolve(this.staticConfigure());\n this.assertBodyLimitUnchanged({ step: BootSteps.STATIC_CONFIGURE });\n },\n },\n { name: BootSteps.REGISTER_ARTIFACTS, run: () => this.registerConfiguredArtifacts() },\n {\n name: BootSteps.PRE_CONFIGURE,\n run: async () => {\n await this.runApplicationHook({\n name: BootSteps.PRE_CONFIGURE,\n hook: () => this.preConfigure(),\n });\n this.assertBodyLimitUnchanged({ step: BootSteps.PRE_CONFIGURE });\n },\n },\n {\n name: BootSteps.REGISTER_CONFIGURATIONS,\n run: () => this.registerConfigurations(),\n },\n { name: BootSteps.REGISTER_DATA_SOURCES, run: () => this.registerDataSources() },\n { name: BootSteps.REGISTER_COMPONENTS, run: () => this.registerComponents() },\n {\n name: BootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n run: () => this.registerContributedDataSources(),\n },\n { name: BootSteps.REGISTER_CONTROLLERS, run: () => this.registerControllers() },\n {\n name: BootSteps.POST_CONFIGURE,\n run: () =>\n this.runApplicationHook({\n name: BootSteps.POST_CONFIGURE,\n hook: () => this.postConfigure(),\n }),\n },\n { name: BootSteps.VERIFY_BINDINGS, run: () => this.verifyBindings() },\n ];\n }\n\n async initialize(): Promise<void> {\n await this.runBootSequence({ steps: this.getBootSequence() });\n }\n\n /** The application hook currently running, so `registerArtifact` can tell a hand registration inside `preConfigure`/`postConfigure` from one the index step made. */\n private runningApplicationHook: string | undefined;\n\n private async runApplicationHook(opts: {\n name: string;\n hook: () => ValueOrPromise<void>;\n }): Promise<void> {\n this.runningApplicationHook = opts.name;\n\n try {\n await opts.hook();\n } finally {\n this.runningApplicationHook = undefined;\n }\n }\n\n /**\n * Bound keys carrying one of `tags` that nothing has resolved since the counts were last reset.\n * The counter answers \"who was read\", never \"who is dead\" - an unread binding may be an\n * allow-list entry or a technical floor, and only the application can tell those apart.\n *\n * Counting is off by default. Call `startResolutionCounting()` after `initialize()` and run the\n * traffic that exercises the application, then read this.\n */\n getUnresolvedBindings(opts?: { tags?: string[] }): string[] {\n if (!this.hasStartedResolutionCounting) {\n throw getError({\n message: `[${this.getUnresolvedBindings.name}] Resolution counting never started | Call startResolutionCounting() after initialize(), run the traffic that exercises the application, then read this - without it every binding would be reported unresolved`,\n });\n }\n\n const tags = opts?.tags ?? [BindingNamespaces.SERVICE, BindingNamespaces.REPOSITORY];\n const counts = this.getResolutionCounts();\n const unresolved: string[] = [];\n\n for (const tag of tags) {\n const bindings = this.findByTag({ tag });\n\n for (const binding of bindings) {\n if (counts.has(binding.key)) {\n continue;\n }\n\n unresolved.push(binding.key);\n }\n }\n\n return unresolved;\n }\n\n /** `bootChecks.binding.doVerify`: resolve every service and repository once, collect every failure, throw once with the whole list - a made-up `@inject` key or a dependency a `when` excluded then fails the boot, not the first request. */\n protected verifyBindings(): void {\n if (!this.configs.bootChecks?.binding?.doVerify) {\n return;\n }\n\n const logger = this.logger.for(this.verifyBindings.name);\n const { verified } = BindingVerifier.assertResolve({\n container: this,\n namespaces: [BindingNamespaces.SERVICE, BindingNamespaces.REPOSITORY],\n scope: this.verifyBindings.name,\n });\n\n logger.info('Every service and repository binding resolves | verified: %d', verified.length);\n }\n\n /** One measured log line per step, and a failure names its step before rethrowing, so a hung or failed boot is attributable without reading the sequence. */\n protected async runBootSequence(opts: { steps: IBootSequenceStep[] }): Promise<void> {\n const { steps } = opts;\n const logger = this.logger.for(this.initialize.name);\n const t = performance.now();\n\n const stepsEntries = steps.entries();\n\n for (const [index, step] of stepsEntries) {\n try {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.initialize.name,\n description: `Boot step ${index + 1}/${steps.length} ${step.name}`,\n task: () => step.run(),\n });\n } catch (error) {\n logger.error(\n 'Boot step failed | step: %s (%d/%d) | error: %s',\n step.name,\n index + 1,\n steps.length,\n error,\n );\n throw error;\n }\n }\n\n logger.info(\n 'Boot sequence complete | %d step(s) | Took: %s (ms) | %s',\n steps.length,\n performance.now() - t,\n steps.map((step) => step.name).join(' -> '),\n );\n }\n\n protected inspectRoutes() {\n const t = performance.now();\n const shouldShowRoutes = this.configs?.debug?.shouldShowRoutes ?? false;\n\n if (!shouldShowRoutes) {\n return;\n }\n\n this.logger.for(this.inspectRoutes.name).info('START | Inspect all application route(s)');\n showApplicationRoutes(this.getServer());\n this.logger\n .for(this.inspectRoutes.name)\n .info('DONE | Inspect all application route(s) | Took: %s (ms)', performance.now() - t);\n }\n\n /**\n * `configured` is the drain's state, mutated in place: a fresh `Set` gives a one-shot complete\n * drain (`RestComponent`); `registerDynamicBindings` passes its persistent per-namespace `Set`,\n * which is why a second sweep touches only what the first one missed.\n */\n async drainByTag<T>(opts: {\n tag: string;\n configured: Set<string>;\n onEach: (opts: { binding: Binding<T> }) => Promise<void>;\n }): Promise<void> {\n const { tag, configured, onEach } = opts;\n\n // A whole batch is drained before re-scanning: the re-scan exists only to pick up bindings a\n // `configure()` added, and asking after every single item makes boot N+1 full scans of the\n // binding map - 3.5ms at 200 controllers, against 0.04ms for this shape.\n let bindings = this.findByTag<T>({ tag, exclude: configured });\n\n while (bindings.length > 0) {\n for (const binding of bindings) {\n // Within a batch a nested `configure()` may already have taken this one.\n if (configured.has(binding.key)) {\n continue;\n }\n\n await onEach({ binding });\n configured.add(binding.key);\n }\n\n // Re-fetch excluding already configured - picks up dynamically added bindings\n bindings = this.findByTag<T>({ tag, exclude: configured });\n }\n }\n\n protected async registerDynamicBindings<T extends IConfigurable = IConfigurable>(\n opts: IRegisterDynamicBindingsOptions<T>,\n ): Promise<void> {\n const logger = this.logger.for(this.registerDynamicBindings.name);\n const { namespace, onBeforeConfigure, onAfterConfigure } = opts;\n\n if (!this.registeredBindings[namespace]) {\n this.registeredBindings[namespace] = new Set<TBindingKey>();\n }\n\n const configured = this.registeredBindings[namespace];\n\n await this.drainByTag<T>({\n tag: namespace,\n configured,\n onEach: async ({ binding }) => {\n if (onBeforeConfigure) {\n await onBeforeConfigure({ binding });\n }\n\n const instance = this.get<T>({ key: binding.key, isOptional: false });\n\n if (!instance) {\n logger.debug('No binding instance | namespace: %s | key: %s', namespace, binding.key);\n\n return;\n }\n\n // A family on `DataSourceRoot` does not read `@datasource` metadata, so the boot reads the declaration itself: `first-use` on a family that cannot honour it is refused by `deferOpen`, never ignored.\n const isDeclaredDeferred =\n namespace === BindingNamespaces.DATASOURCE &&\n MetadataRegistry.getInstance().getDataSourceMetadata({ target: instance.constructor })\n ?.open?.on === DataSourceOpenModes.FIRST_USE;\n\n if (\n namespace === BindingNamespaces.DATASOURCE &&\n BootTargets.canDeferOpen(instance) &&\n (instance.isOpenDeferred() === true || isDeclaredDeferred)\n ) {\n // Opens at the first call that needs it; the application starts, and listens, without it.\n instance.deferOpen?.({ options: this.artifactOptions.get(binding.key) });\n logger.info('Datasource opens on first use | key: %s', binding.key);\n } else if (BootTargets.isConfigurable(instance)) {\n const options = this.artifactOptions.get(binding.key);\n // A datasource also gets the handles of its open (the same body works at start and on first use).\n const opening =\n namespace === BindingNamespaces.DATASOURCE && BootTargets.hasOpeningHandles(instance)\n ? instance[OPENING_HANDLES]()\n : undefined;\n\n await instance.configure(options, opening);\n }\n\n // Marked before the after-hook runs, so the hook sees its own binding as configured.\n configured.add(binding.key);\n\n if (onAfterConfigure) {\n await onAfterConfigure({ binding, instance });\n }\n },\n });\n }\n\n /** The same-key guard behind every artifact registration (`component`/`controller`/`service`/`repository`/`dataSource`). `allowOverride` defaults true to match `bind()`'s overwrite behavior; `allowOverride: false` on one registration, or `bootChecks.binding.allowOverride: false` for the whole application, opts into strict mode. */\n protected assertNoBindingCollision(opts: {\n key: TBindingKey;\n allowOverride?: boolean;\n caller: string;\n }): void {\n const { key, caller } = opts;\n const allowOverride =\n opts.allowOverride ?? this.configs.bootChecks?.binding?.allowOverride ?? true;\n\n if (allowOverride || !this.isBound({ key })) {\n return;\n }\n\n const reason =\n opts.allowOverride === false\n ? `'allowOverride: false' was set and this key collides with an existing binding | Use a distinct 'opts.binding' key, or drop 'allowOverride: false' if overriding is intentional`\n : `'bootChecks.binding.allowOverride' is false and this key collides with an existing binding | Use a distinct 'opts.binding' key, or set 'allowOverride: true' on this registration if overriding is intentional`;\n\n throw getError({\n message: `[${caller}] Binding key already registered: '${key}' | ${reason}`,\n });\n }\n\n /** Resolution order for every registration: explicit `opts` > the class's `@injectable` defaults > the derived key and the kind's default scope. `order` and `when` are `registerArtifacts`' concern, not this one. */\n private registerArtifact<Base>(opts: {\n target: TClass<Base>;\n namespace: TBindingNamespace;\n defaultScope: TBindingScope;\n caller: string;\n opts?: TMixinOpts;\n }): Binding<Base> {\n const { target, namespace, defaultScope, caller } = opts;\n const declared = MetadataRegistry.getInstance().getArtifactMetadata({ target });\n\n if (\n this.runningApplicationHook &&\n this.configs.artifacts &&\n this.configs.bootChecks?.binding?.allowManual === false\n ) {\n throw getError({\n message: `[${caller}] '${target.name}' is registered by hand inside ${this.runningApplicationHook}() while 'configs.artifacts' is set and 'bootChecks.binding.allowManual' is false | Move the class into the generated index (or an explicit entry of 'configs.artifacts'), or allow manual registration`,\n });\n }\n\n const pinned = opts.opts?.binding ?? declared?.binding;\n BindingNamespaces.assertArtifactNamespace({\n namespace: pinned?.namespace ?? namespace,\n artifact: target.name,\n caller,\n });\n\n const { key } = ArtifactBindingKeys.resolve({ target, namespace, binding: pinned });\n\n // What `@inject({ target })` reads back. Only here knows the call site's `binding`, and a\n // class registered by hand has no stereotype metadata to derive one from.\n MetadataRegistry.getInstance().setBindingKey({ target, key });\n\n if (opts.opts?.options !== undefined) {\n this.artifactOptions.set(key, opts.opts.options);\n }\n\n this.assertNoBindingCollision({\n key,\n allowOverride: opts.opts?.allowOverride ?? declared?.allowOverride,\n caller,\n });\n\n return this.bind<Base>({ key })\n .toClass(target)\n .setScope(declared?.scope ?? defaultScope);\n }\n\n configuration<Base extends BaseConfiguration<Options>, Options extends object = {}>(\n target: TClass<Base>,\n opts?: TMixinOpts<Options>,\n ): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.CONFIGURATION,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.configuration.name,\n opts,\n });\n }\n\n async registerConfigurations(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerConfigurations.name,\n description: 'Register application configurations',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.CONFIGURATION });\n },\n });\n }\n\n component<Base extends BaseComponent<Options>, Options extends object = {}>(\n target: TClass<Base>,\n opts?: TMixinOpts<Options>,\n ): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.COMPONENT,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.component.name,\n opts,\n });\n }\n\n async registerComponents(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerComponents.name,\n description: 'Register application components',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.COMPONENT });\n },\n });\n }\n\n /**\n * Second DATASOURCE sweep, for datasources components contributed at any depth. Calls\n * `registerDynamicBindings` directly: `this.registerDataSources()` is polymorphic and an override\n * would run twice. Runs after every component, so a component a datasource registers is never configured.\n */\n async registerContributedDataSources(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerContributedDataSources.name,\n description: 'Register application contributed data sources',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.DATASOURCE });\n },\n });\n }\n\n /** REST only - the kernel has no gRPC (it reaches `node:module`). `BaseApplication` adds the gRPC branch on top. */\n async registerControllers(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n description: 'Register application REST controllers',\n scope: this.registerControllers.name,\n task: async () => {\n const transports = this.configs.transports ?? [ControllerTransports.REST];\n\n if (!transports.includes(ControllerTransports.REST)) {\n return;\n }\n\n const restComponent = new RestComponent(this);\n await restComponent.configure();\n },\n });\n }\n\n /** SINGLETON like `component()`: `RestComponent` mounts the one instance it resolves, so a second resolution must be that instance, not an unmounted twin. */\n controller<Base>(target: TClass<Base>, opts?: TMixinOpts): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.CONTROLLER,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.controller.name,\n opts,\n });\n }\n\n service<Base extends IService>(target: TClass<Base>, opts?: TMixinOpts): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.SERVICE,\n defaultScope: BindingScopes.TRANSIENT,\n caller: this.service.name,\n opts,\n });\n }\n\n repository<Base extends IRepository>(target: TClass<Base>, opts?: TMixinOpts): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.REPOSITORY,\n defaultScope: BindingScopes.TRANSIENT,\n caller: this.repository.name,\n opts,\n });\n }\n\n dataSource<Base extends IDataSource<Options>, Options extends object = {}>(\n target: TClass<Base>,\n opts?: TMixinOpts<Options>,\n ): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.DATASOURCE,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.dataSource.name,\n opts,\n });\n }\n\n /** The boot step body behind `configs.artifacts`, also callable by hand: registers every kind in dependency order across the given indexes. */\n async registerArtifacts(index: TArtifactIndexInput): Promise<void> {\n const resolved = await ArtifactIndexHelper.getInstance().resolve({\n input: index,\n application: this,\n });\n\n const registry = MetadataRegistry.getInstance();\n const kinds: Array<[ReadonlyArray<TClass<unknown>>, TBindingNamespace]> = [\n [resolved.configurations, BindingNamespaces.CONFIGURATION],\n [resolved.dataSources, BindingNamespaces.DATASOURCE],\n [resolved.components, BindingNamespaces.COMPONENT],\n [resolved.repositories, BindingNamespaces.REPOSITORY],\n [resolved.services, BindingNamespaces.SERVICE],\n [resolved.controllers, BindingNamespaces.CONTROLLER],\n ];\n const collisions = ArtifactBindingKeys.findDerivedCollisions({\n entries: kinds.flatMap(([targets, namespace]) =>\n targets.map((target) => ({\n target,\n namespace,\n binding: registry.getArtifactMetadata({ target })?.binding,\n })),\n ),\n });\n\n for (const key of collisions) {\n const message = ArtifactBindingKeys.describeCollision({ key, caller: 'registerArtifacts' });\n\n if (!this.configs.bootChecks?.allowDerivedKeyCollision) {\n throw getError({ message });\n }\n\n this.logger.warn('%s', message);\n }\n\n for (const target of resolved.configurations) {\n this.configuration(target);\n this.bindProvidedKeys({ target });\n }\n\n for (const target of resolved.dataSources) {\n this.dataSource(target);\n }\n\n for (const target of resolved.components) {\n this.component(target);\n this.bindProvidedKeys({ target });\n }\n\n for (const target of resolved.repositories) {\n this.repository(target);\n }\n\n for (const target of resolved.services) {\n this.service(target);\n }\n\n for (const target of resolved.controllers) {\n this.controller(target);\n }\n }\n\n /** Registers every class a stereotype decorated, with no `configs.artifacts` entry anywhere. `when` and `order` apply exactly as they do to a declared index - which is how one process running several applications keeps them apart. */\n async registerDiscoveredArtifacts(): Promise<void> {\n await this.registerArtifacts(ArtifactIndexHelper.getInstance().buildDiscoveredIndex());\n }\n\n /**\n * The artifact boot step. `configs.discoverArtifacts` adds every decorated class in the import\n * graph; `configs.artifacts` adds exactly what it lists. Both together register the union.\n *\n * An absent `artifacts` still registers nothing. Reading it as \"register everything\" would change\n * what an existing application boots with, silently, and the failure would surface as ten times\n * the bindings rather than as an error.\n */\n protected async registerConfiguredArtifacts(): Promise<void> {\n const inputs: TArtifactIndexInput[] = [];\n\n if (this.configs.discoverArtifacts) {\n inputs.push(ArtifactIndexHelper.getInstance().buildDiscoveredIndex());\n }\n\n if (this.configs.artifacts) {\n inputs.push(this.configs.artifacts);\n }\n\n if (inputs.length === 0) {\n return;\n }\n\n await this.registerArtifacts(inputs);\n }\n\n /** Each `@provide` method becomes a lazy provider: the component is resolved (SINGLETON) and the method called on first `get`, so a provided value may depend on datasources or secrets that do not exist yet at registration time. */\n private bindProvidedKeys(opts: { target: TClass<unknown> }): void {\n const { target } = opts;\n const registry = MetadataRegistry.getInstance();\n const provides = registry.getProvideMetadata({ target });\n\n if (provides.length === 0) {\n return;\n }\n\n const declared = registry.getArtifactMetadata({ target });\n const defaultNamespace = declared?.type\n ? ArtifactNamespaces.resolve({ type: declared.type })\n : BindingNamespaces.COMPONENT;\n // The key the registration actually bound - a call-site override included.\n const componentKey =\n registry.getBindingKey({ target }) ??\n ArtifactBindingKeys.resolve({\n target,\n namespace: defaultNamespace,\n binding: declared?.binding,\n }).key;\n\n for (const entry of provides) {\n this.bind({ key: entry.key })\n .toProvider((container) => {\n const instance = container.get<Record<string | symbol, () => unknown>>({\n key: componentKey,\n });\n\n return instance[entry.methodName]();\n })\n .setScope(entry.scope ?? BindingScopes.SINGLETON);\n }\n }\n\n async registerDataSources(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerDataSources.name,\n description: 'Register application data sources',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.DATASOURCE });\n },\n });\n }\n\n /**\n * Closes every datasource the boot configured, so a stopped application holds no pool, socket or\n * WASM instance. A failure, or a `close()` still pending after `dataSourceCloseTimeoutMs`, is logged\n * and never stops the rest. A datasource configured by hand is closed by whoever configured it.\n */\n protected async closeDataSources(): Promise<void> {\n const keys = this.registeredBindings[BindingNamespaces.DATASOURCE] ?? new Set<TBindingKey>();\n const timeoutMs = this.configs.dataSourceCloseTimeoutMs ?? 10_000;\n const logger = this.logger.for(this.closeDataSources.name);\n\n for (const key of keys) {\n try {\n const dataSource = this.get<IDataSource>({ key, isOptional: true });\n\n if (!dataSource?.close) {\n logger.debug('Nothing to close | key: %s', key);\n continue;\n }\n\n const closing = dataSource.close();\n await RetryUtility.runWithTimeout({ operation: key, timeoutMs, execution: () => closing });\n } catch (error) {\n if (RetryUtility.isRetryTimeoutError(error)) {\n logger.error('Close timed out | key: %s | timeoutMs: %d', key, timeoutMs);\n continue;\n }\n\n logger.error('Failed to close datasource | key: %s | error: %s', key, error);\n continue;\n }\n\n logger.info('Closed datasource | key: %s', key);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"rest.js","sourceRoot":"","sources":["../../../../src/base/applications/rest.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAExF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAE3D,OAAO,EACL,kBAAkB,EAClB,QAAQ,EACR,kBAAkB,EAClB,YAAY,GACb,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,UAAU,IAAI,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,8CAA8C,CAAC;AAE7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAEvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,EAAE,eAAe,EAAE,MAAM,+CAA+C,CAAC;AAIhF,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,E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AAiB,CAAC,UAAU,CAAC,IAAI,IAAI,GAAG,EAAe,CAAC;QAC7F,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,wBAAwB,IAAI,MAAM,CAAC;QAClE,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAE3D,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC;gBACH,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAc,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;gBAEpE,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE,CAAC;oBACvB,MAAM,CAAC,KAAK,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAC;oBAChD,SAAS;gBACX,CAAC;gBAED,MAAM,OAAO,GAAG,UAAU,CAAC,KAAK,EAAE,CAAC;gBACnC,MAAM,YAAY,CAAC,cAAc,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;YAC7F,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,YAAY,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC5C,MAAM,CAAC,KAAK,CAAC,2CAA2C,EAAE,GAAG,EAAE,SAAS,CAAC,CAAC;oBAC1E,SAAS;gBACX,CAAC;gBAED,MAAM,CAAC,KAAK,CAAC,kDAAkD,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;gBAC7E,SAAS;YACX,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE,GAAG,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TBindingNamespace } from '@/common/bindings';\nimport { ArtifactNamespaces, BindingNamespaces, CoreBindings } from '@/common/bindings';\nimport type { Binding, TBindingKey, TBindingScope } from '@/helpers/inversion';\nimport { ArtifactTypes, BindingScopes, MetadataRegistry } from '@/helpers/inversion';\nimport { BindingVerifier } from '@venizia/ignis-inversion';\nimport type { IConfigurable, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n PerformanceUtility,\n getError,\n RequestIdGenerator,\n RetryUtility,\n} from '@venizia/ignis-helpers/core';\nimport type { Env, Hono, MiddlewareHandler, Schema } from 'hono';\nimport { showRoutes as showApplicationRoutes } from 'hono/dev';\nimport { requestId } from 'hono/request-id';\nimport type { BaseComponent } from '../components';\nimport { ArtifactBindingKeys } from '../metadata/artifact-keys';\nimport { RestComponent } from '../components/controller/rest/rest.component';\nimport type { BaseConfiguration } from '../configurations';\nimport { ControllerTransports } from '../controllers/common/constants';\nimport type { IDataSource, IDataSourceOpening } from '../datasources';\nimport { DataSourceOpenModes } from '../datasources';\nimport { OPENING_HANDLES } from '../datasources/opening-handles';\nimport { BaseAppErrorMiddleware } from '../middlewares/app-error/app-error.middleware';\nimport { notFoundHandler } from '../middlewares/not-found/not-found.middleware';\nimport type { TMixinOpts } from '../mixins/common';\nimport type { IRepository } from '../repositories';\nimport type { IService } from '../services';\nimport { AbstractApplication } from './abstract';\nimport { BodyLimits } from './body-limit';\nimport { RouterFactories } from './router-factory';\nimport { CorsUtility } from './cors';\nimport { ArtifactIndexHelper } from './artifact-index';\nimport type { IBootSequenceStep } from './boot-sequence';\nimport { BootSteps } from './boot-sequence';\nimport type { IApplicationConfigs, IBodyLimitOptions, TArtifactIndexInput } from './common';\n\ninterface IRegisterDynamicBindingsOptions<T extends IConfigurable = IConfigurable> {\n namespace: TBindingNamespace;\n\n onBeforeConfigure?: (opts: { binding: Binding<T> }) => Promise<void>;\n onAfterConfigure?: (opts: { binding: Binding<T>; instance: T }) => Promise<void>;\n}\n\n/**\n * Runtime checks that narrow a bound instance to the members the boot calls on it. Positional: a type predicate narrows\n * its own parameter.\n */\nclass BootTargets {\n private static isObjectLike(value: unknown): value is object {\n return (typeof value === 'object' && value !== null) || typeof value === 'function';\n }\n\n /** Has `isOpenDeferred()`, so the boot can ask whether its open waits for the first use. */\n static canDeferOpen(\n value: unknown,\n ): value is Pick<IDataSource, 'deferOpen'> & Required<Pick<IDataSource, 'isOpenDeferred'>> {\n return (\n BootTargets.isObjectLike(value) &&\n 'isOpenDeferred' in value &&\n typeof value.isOpenDeferred === 'function'\n );\n }\n\n /** Has `configure()`; a datasource's takes the opening handles in its second argument. */\n static isConfigurable(value: unknown): value is Pick<IDataSource, 'configure'> {\n return (\n BootTargets.isObjectLike(value) &&\n 'configure' in value &&\n typeof value.configure === 'function'\n );\n }\n\n /** Carries the opening handles every datasource root defines. */\n static hasOpeningHandles(\n value: unknown,\n ): value is { [OPENING_HANDLES]: () => IDataSourceOpening } {\n return (\n BootTargets.isObjectLike(value) &&\n OPENING_HANDLES in value &&\n typeof value[OPENING_HANDLES] === 'function'\n );\n }\n}\n\n/** Adds the Hono router surface on top of `AbstractApplication` - no listening server, so this is the layer a browser Worker or gRPC-only host can extend without pulling in `Bun.serve`. */\nexport abstract class RestApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n> extends AbstractApplication {\n private registeredBindings: Record<string, Set<TBindingKey>> = {};\n private artifactOptions = new Map<string, object>();\n\n /** The router, and nothing else. What runtime is underneath and what socket is bound are `ServerApplication`'s to know - a browser Worker has neither, and carrying the union here made `RuntimeModules.detect()` answer `'node'` inside a Worker. */\n protected server: { hono: Hono<AppEnv, AppSchema, BasePath> };\n\n protected rootRouter: Hono<AppEnv, AppSchema, BasePath>;\n protected readonly requestIdGenerator: RequestIdGenerator;\n\n /** A copy of the `bodyLimit` the default stack installed, absent until `registerDefaultMiddlewares()` ran. */\n private installedBodyLimit?: { options?: IBodyLimitOptions };\n\n constructor(opts: { scope: string; config: IApplicationConfigs }) {\n super(opts);\n\n // A config built from the environment can lose `path.base` at run time; the router would only fail later, inside `route()`, with a message that names nothing.\n if (typeof this.configs.path?.base !== 'string') {\n throw getError({\n message: `[${opts.scope}] configs.path.base must be a string | value: ${String(this.configs.path?.base)} | an empty string mounts the application at the root`,\n });\n }\n\n // The index signature accepts any key, so a leftover `strictPath` would compile and be ignored.\n if (this.configs.strictPath !== undefined) {\n throw getError({\n message: `[${opts.scope}] configs.strictPath was removed | value: ${String(this.configs.strictPath)} | Use configs.path.isStrict`,\n });\n }\n\n this.requestIdGenerator = new RequestIdGenerator({ scope: opts.scope });\n\n const strict = this.configs.path.isStrict ?? true;\n this.server = { hono: this.createRouter({ strict }) };\n this.rootRouter = this.createRouter({ strict });\n }\n\n /**\n * Builds one of the two routers: a plain `Hono`, or an `OpenAPIHono` once the REST controller layer is\n * loaded. Called from the constructor, so an override must not read its own instance fields.\n */\n protected createRouter(opts: { strict: boolean }): Hono<AppEnv, AppSchema, BasePath> {\n return RouterFactories.create<AppEnv, AppSchema, BasePath>({ strict: opts.strict });\n }\n\n getRootRouter(): Hono<AppEnv, AppSchema, BasePath> {\n return this.rootRouter;\n }\n\n getServer(): Hono<AppEnv, AppSchema, BasePath> {\n return this.server.hono;\n }\n\n protected override registerCoreBindings() {\n super.registerCoreBindings();\n\n this.bind<typeof this.server>({\n key: CoreBindings.APPLICATION_SERVER,\n }).toProvider((_) => this.server);\n this.bind<typeof this.rootRouter>({\n key: CoreBindings.APPLICATION_ROOT_ROUTER,\n }).toProvider((_) => this.rootRouter);\n }\n\n /** The correlation id every host stamps - see {@link RequestIdGenerator} for why `crypto.randomUUID` is refused. */\n protected generateRequestId(): string {\n return this.requestIdGenerator.nextId();\n }\n\n /** The error handler the default stack installs. `@venizia/ignis` overrides it to swap in the `ErrorPrettier`-backed formatter, which reaches `node:util` and so cannot live here. */\n protected buildErrorMiddleware(): BaseAppErrorMiddleware {\n const environment = this.configs.error?.environment;\n\n return new BaseAppErrorMiddleware({\n logger: this.logger,\n rootKey: this.configs.error?.rootKey ?? undefined,\n // Spread, not `environment: () => environment`: the option's PRESENCE is what claims this host\n // has an ambient environment at all, so an unset config must leave it absent.\n ...(environment === undefined ? {} : { environment: () => environment }),\n });\n }\n\n /**\n * The three registrations every host needs: request id, error envelope, JSON 404 - without them a\n * thrown `ApplicationError` is a generic 500, a 404 is `text/plain`, and no response carries a request id.\n * Registered before `initialize()`, so an application's own handlers still win.\n */\n protected registerDefaultMiddlewares(): ValueOrPromise<void> {\n const server = this.getServer();\n\n // First of all, so every response the framework produces on its own - a bodyLimit 413, a body the\n // request spy cannot parse, the error envelope - leaves with the headers a browser needs to read it.\n CorsUtility.registerCors({ server, options: this.configs.middlewares?.cors });\n\n server.use(requestId({ generator: () => this.generateRequestId() }));\n\n // Ahead of every middleware a host adds after this one, so none of them buffers a body over it.\n // Unset, every route gets BodyLimits.DEFAULT_MAX_SIZE; a configured bodyLimit replaces it, and `enable: false` removes it.\n const bodyLimitOptions = this.resolveBodyLimit({\n options: this.configs.middlewares?.bodyLimit,\n });\n this.installedBodyLimit = { options: this.toInstalledBodyLimit({ options: bodyLimitOptions }) };\n\n if (bodyLimitOptions && bodyLimitOptions.enable !== false) {\n const { maxSize, path, onError } = bodyLimitOptions;\n\n if (typeof maxSize !== 'number' || !Number.isFinite(maxSize) || maxSize < 0) {\n throw getError({\n message: `[registerDefaultMiddlewares] configs.middlewares.bodyLimit.maxSize must be a non-negative number of bytes | value: ${String(maxSize)}`,\n });\n }\n\n const defaultLimiter = BodyLimits.limiter({ maxSize, onError });\n\n // A route with its own limit (BodyLimits.route) is held to that one, not to this.\n const limiter: MiddlewareHandler = (context, next) =>\n BodyLimits.hasRouteLimit(context) ? next() : defaultLimiter(context, next);\n\n if (path) {\n server.use(path, limiter);\n } else {\n server.use(limiter);\n }\n }\n\n server.onError(this.buildErrorMiddleware().value());\n server.notFound(notFoundHandler({ logger: this.logger }));\n }\n\n /** The configured `bodyLimit`, or the default one when none is configured. */\n private resolveBodyLimit(opts: { options?: IBodyLimitOptions }): IBodyLimitOptions {\n return opts.options ?? { maxSize: BodyLimits.DEFAULT_MAX_SIZE };\n }\n\n /** What a `bodyLimit` config installs: nothing when absent or disabled, else a copy, so a later in-place edit shows. */\n private toInstalledBodyLimit(opts: {\n options?: IBodyLimitOptions;\n }): IBodyLimitOptions | undefined {\n const { options } = opts;\n\n if (!options || options.enable === false) {\n return undefined;\n }\n\n return { ...options };\n }\n\n private isSameBodyLimit(opts: { left?: IBodyLimitOptions; right?: IBodyLimitOptions }): boolean {\n const { left, right } = opts;\n\n if (!left || !right) {\n return left === right;\n }\n\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n\n for (const key of keys) {\n if (!Object.is(left[key], right[key])) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * `configs.middlewares` is read by `registerDefaultMiddlewares()`, which runs before `staticConfigure()`.\n * A limit assigned in a boot hook would read back as configured while every request ran unlimited.\n */\n private assertBodyLimitUnchanged(opts: { step: string }): void {\n if (!this.installedBodyLimit) {\n return;\n }\n\n const installed = this.installedBodyLimit.options;\n const current = this.toInstalledBodyLimit({\n options: this.resolveBodyLimit({ options: this.configs.middlewares?.bodyLimit }),\n });\n\n if (this.isSameBodyLimit({ left: installed, right: current })) {\n return;\n }\n\n throw getError({\n message: `[${opts.step}] configs.middlewares.bodyLimit changed after registerDefaultMiddlewares() installed it | installed maxSize: ${installed?.maxSize ?? 'none'} | now maxSize: ${current?.maxSize ?? 'none'} | Pass it through the constructor config: new Application({ config: { middlewares: { bodyLimit } } })`,\n });\n }\n\n /**\n * The artifact order, stated once: datasources before the repositories that auto-resolve them,\n * components before the controllers they may contribute. `BaseApplication` splices its server-only\n * steps around these by name instead of rewriting the list.\n */\n protected getBootSequence(): IBootSequenceStep[] {\n return [\n {\n name: BootSteps.STATIC_CONFIGURE,\n run: async () => {\n // Declared `void`, but an override may be async; the step has always waited on it.\n await Promise.resolve(this.staticConfigure());\n this.assertBodyLimitUnchanged({ step: BootSteps.STATIC_CONFIGURE });\n },\n },\n { name: BootSteps.REGISTER_ARTIFACTS, run: () => this.registerConfiguredArtifacts() },\n {\n name: BootSteps.PRE_CONFIGURE,\n run: async () => {\n await this.runApplicationHook({\n name: BootSteps.PRE_CONFIGURE,\n hook: () => this.preConfigure(),\n });\n this.assertBodyLimitUnchanged({ step: BootSteps.PRE_CONFIGURE });\n },\n },\n {\n name: BootSteps.REGISTER_CONFIGURATIONS,\n run: () => this.registerConfigurations(),\n },\n { name: BootSteps.REGISTER_DATA_SOURCES, run: () => this.registerDataSources() },\n { name: BootSteps.REGISTER_COMPONENTS, run: () => this.registerComponents() },\n {\n name: BootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n run: () => this.registerContributedDataSources(),\n },\n { name: BootSteps.REGISTER_CONTROLLERS, run: () => this.registerControllers() },\n {\n name: BootSteps.POST_CONFIGURE,\n run: () =>\n this.runApplicationHook({\n name: BootSteps.POST_CONFIGURE,\n hook: () => this.postConfigure(),\n }),\n },\n { name: BootSteps.VERIFY_BINDINGS, run: () => this.verifyBindings() },\n ];\n }\n\n async initialize(): Promise<void> {\n await this.runBootSequence({ steps: this.getBootSequence() });\n }\n\n /** The application hook currently running, so `registerArtifact` can tell a hand registration inside `preConfigure`/`postConfigure` from one the index step made. */\n private runningApplicationHook: string | undefined;\n\n private async runApplicationHook(opts: {\n name: string;\n hook: () => ValueOrPromise<void>;\n }): Promise<void> {\n this.runningApplicationHook = opts.name;\n\n try {\n await opts.hook();\n } finally {\n this.runningApplicationHook = undefined;\n }\n }\n\n /**\n * Bound keys carrying one of `tags` that nothing has resolved since the counts were last reset.\n * The counter answers \"who was read\", never \"who is dead\" - an unread binding may be an\n * allow-list entry or a technical floor, and only the application can tell those apart.\n *\n * Counting is off by default. Call `startResolutionCounting()` after `initialize()` and run the\n * traffic that exercises the application, then read this.\n */\n getUnresolvedBindings(opts?: { tags?: string[] }): string[] {\n if (!this.hasStartedResolutionCounting) {\n throw getError({\n message: `[${this.getUnresolvedBindings.name}] Resolution counting never started | Call startResolutionCounting() after initialize(), run the traffic that exercises the application, then read this - without it every binding would be reported unresolved`,\n });\n }\n\n const tags = opts?.tags ?? [BindingNamespaces.SERVICE, BindingNamespaces.REPOSITORY];\n const counts = this.getResolutionCounts();\n const unresolved: string[] = [];\n\n for (const tag of tags) {\n const bindings = this.findByTag({ tag });\n\n for (const binding of bindings) {\n if (counts.has(binding.key)) {\n continue;\n }\n\n unresolved.push(binding.key);\n }\n }\n\n return unresolved;\n }\n\n /** `bootChecks.binding.doVerify`: resolve every service and repository once, collect every failure, throw once with the whole list - a made-up `@inject` key or a dependency a `when` excluded then fails the boot, not the first request. */\n protected verifyBindings(): void {\n if (!this.configs.bootChecks?.binding?.doVerify) {\n return;\n }\n\n const logger = this.logger.for(this.verifyBindings.name);\n const { verified } = BindingVerifier.assertResolve({\n container: this,\n namespaces: [BindingNamespaces.SERVICE, BindingNamespaces.REPOSITORY],\n scope: this.verifyBindings.name,\n });\n\n logger.info('Every service and repository binding resolves | verified: %d', verified.length);\n }\n\n /** One measured log line per step, and a failure names its step before rethrowing, so a hung or failed boot is attributable without reading the sequence. */\n protected async runBootSequence(opts: { steps: IBootSequenceStep[] }): Promise<void> {\n const { steps } = opts;\n const logger = this.logger.for(this.initialize.name);\n const t = performance.now();\n\n const stepsEntries = steps.entries();\n\n for (const [index, step] of stepsEntries) {\n try {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.initialize.name,\n description: `Boot step ${index + 1}/${steps.length} ${step.name}`,\n task: () => step.run(),\n });\n } catch (error) {\n logger.error(\n 'Boot step failed | step: %s (%d/%d) | error: %s',\n step.name,\n index + 1,\n steps.length,\n error,\n );\n throw error;\n }\n }\n\n logger.info(\n 'Boot sequence complete | %d step(s) | Took: %s (ms) | %s',\n steps.length,\n performance.now() - t,\n steps.map((step) => step.name).join(' -> '),\n );\n }\n\n protected inspectRoutes() {\n const t = performance.now();\n const shouldShowRoutes = this.configs?.debug?.shouldShowRoutes ?? false;\n\n if (!shouldShowRoutes) {\n return;\n }\n\n this.logger.for(this.inspectRoutes.name).info('START | Inspect all application route(s)');\n showApplicationRoutes(this.getServer());\n this.logger\n .for(this.inspectRoutes.name)\n .info('DONE | Inspect all application route(s) | Took: %s (ms)', performance.now() - t);\n }\n\n /**\n * `configured` is the drain's state, mutated in place: a fresh `Set` gives a one-shot complete\n * drain (`RestComponent`); `registerDynamicBindings` passes its persistent per-namespace `Set`,\n * which is why a second sweep touches only what the first one missed.\n */\n async drainByTag<T>(opts: {\n tag: string;\n configured: Set<string>;\n onEach: (opts: { binding: Binding<T> }) => Promise<void>;\n }): Promise<void> {\n const { tag, configured, onEach } = opts;\n\n // A whole batch is drained before re-scanning: the re-scan exists only to pick up bindings a\n // `configure()` added, and asking after every single item makes boot N+1 full scans of the\n // binding map - 3.5ms at 200 controllers, against 0.04ms for this shape.\n let bindings = this.findByTag<T>({ tag, exclude: configured });\n\n while (bindings.length > 0) {\n for (const binding of bindings) {\n // Within a batch a nested `configure()` may already have taken this one.\n if (configured.has(binding.key)) {\n continue;\n }\n\n await onEach({ binding });\n configured.add(binding.key);\n }\n\n // Re-fetch excluding already configured - picks up dynamically added bindings\n bindings = this.findByTag<T>({ tag, exclude: configured });\n }\n }\n\n protected async registerDynamicBindings<T extends IConfigurable = IConfigurable>(\n opts: IRegisterDynamicBindingsOptions<T>,\n ): Promise<void> {\n const logger = this.logger.for(this.registerDynamicBindings.name);\n const { namespace, onBeforeConfigure, onAfterConfigure } = opts;\n\n if (!this.registeredBindings[namespace]) {\n this.registeredBindings[namespace] = new Set<TBindingKey>();\n }\n\n const configured = this.registeredBindings[namespace];\n\n await this.drainByTag<T>({\n tag: namespace,\n configured,\n onEach: async ({ binding }) => {\n if (onBeforeConfigure) {\n await onBeforeConfigure({ binding });\n }\n\n const instance = this.get<T>({ key: binding.key, isOptional: false });\n\n if (!instance) {\n logger.debug('No binding instance | namespace: %s | key: %s', namespace, binding.key);\n\n return;\n }\n\n // A family on `DataSourceRoot` does not read `@datasource` metadata, so the boot reads the declaration itself: `first-use` on a family that cannot honour it is refused by `deferOpen`, never ignored.\n const isDeclaredDeferred =\n namespace === BindingNamespaces.DATASOURCE &&\n MetadataRegistry.getInstance().getDataSourceMetadata({ target: instance.constructor })\n ?.open?.on === DataSourceOpenModes.FIRST_USE;\n\n if (\n namespace === BindingNamespaces.DATASOURCE &&\n BootTargets.canDeferOpen(instance) &&\n (instance.isOpenDeferred() === true || isDeclaredDeferred)\n ) {\n // Opens at the first call that needs it; the application starts, and listens, without it.\n instance.deferOpen?.({ options: this.artifactOptions.get(binding.key) });\n logger.info('Datasource opens on first use | key: %s', binding.key);\n } else if (BootTargets.isConfigurable(instance)) {\n const options = this.artifactOptions.get(binding.key);\n // A datasource also gets the handles of its open (the same body works at start and on first use).\n const opening =\n namespace === BindingNamespaces.DATASOURCE && BootTargets.hasOpeningHandles(instance)\n ? instance[OPENING_HANDLES]()\n : undefined;\n\n await instance.configure(options, opening);\n }\n\n // Marked before the after-hook runs, so the hook sees its own binding as configured.\n configured.add(binding.key);\n\n if (onAfterConfigure) {\n await onAfterConfigure({ binding, instance });\n }\n },\n });\n }\n\n /** The same-key guard behind every artifact registration (`component`/`controller`/`service`/`repository`/`dataSource`). `allowOverride` defaults true to match `bind()`'s overwrite behavior; `allowOverride: false` on one registration, or `bootChecks.binding.allowOverride: false` for the whole application, opts into strict mode. */\n protected assertNoBindingCollision(opts: {\n key: TBindingKey;\n allowOverride?: boolean;\n caller: string;\n }): void {\n const { key, caller } = opts;\n const allowOverride =\n opts.allowOverride ?? this.configs.bootChecks?.binding?.allowOverride ?? true;\n\n if (allowOverride || !this.isBound({ key })) {\n return;\n }\n\n const reason =\n opts.allowOverride === false\n ? `'allowOverride: false' was set and this key collides with an existing binding | Use a distinct 'opts.binding' key, or drop 'allowOverride: false' if overriding is intentional`\n : `'bootChecks.binding.allowOverride' is false and this key collides with an existing binding | Use a distinct 'opts.binding' key, or set 'allowOverride: true' on this registration if overriding is intentional`;\n\n throw getError({\n message: `[${caller}] Binding key already registered: '${key}' | ${reason}`,\n });\n }\n\n /** Resolution order for every registration: explicit `opts` > the class's `@injectable` defaults > the derived key and the kind's default scope. `order` and `when` are `registerArtifacts`' concern, not this one. */\n private registerArtifact<Base>(opts: {\n target: TClass<Base>;\n namespace: TBindingNamespace;\n defaultScope: TBindingScope;\n caller: string;\n opts?: TMixinOpts;\n }): Binding<Base> {\n const { target, namespace, defaultScope, caller } = opts;\n const declared = MetadataRegistry.getInstance().getArtifactMetadata({ target });\n\n if (\n this.runningApplicationHook &&\n this.configs.artifacts &&\n this.configs.bootChecks?.binding?.allowManual === false\n ) {\n throw getError({\n message: `[${caller}] '${target.name}' is registered by hand inside ${this.runningApplicationHook}() while 'configs.artifacts' is set and 'bootChecks.binding.allowManual' is false | Move the class into the generated index (or an explicit entry of 'configs.artifacts'), or allow manual registration`,\n });\n }\n\n const pinned = opts.opts?.binding ?? declared?.binding;\n BindingNamespaces.assertArtifactNamespace({\n namespace: pinned?.namespace ?? namespace,\n artifact: target.name,\n caller,\n });\n\n const { key } = ArtifactBindingKeys.resolve({ target, namespace, binding: pinned });\n\n // What `@inject({ target })` reads back. Only here knows the call site's `binding`, and a\n // class registered by hand has no stereotype metadata to derive one from.\n MetadataRegistry.getInstance().setBindingKey({ target, key });\n\n if (opts.opts?.options !== undefined) {\n this.artifactOptions.set(key, opts.opts.options);\n }\n\n this.assertNoBindingCollision({\n key,\n allowOverride: opts.opts?.allowOverride ?? declared?.allowOverride,\n caller,\n });\n\n return this.bind<Base>({ key })\n .toClass(target)\n .setScope(declared?.scope ?? defaultScope);\n }\n\n configuration<Base extends BaseConfiguration<Options>, Options extends object = {}>(\n target: TClass<Base>,\n opts?: TMixinOpts<Options>,\n ): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.CONFIGURATION,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.configuration.name,\n opts,\n });\n }\n\n async registerConfigurations(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerConfigurations.name,\n description: 'Register application configurations',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.CONFIGURATION });\n },\n });\n }\n\n component<Base extends BaseComponent<Options>, Options extends object = {}>(\n target: TClass<Base>,\n opts?: TMixinOpts<Options>,\n ): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.COMPONENT,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.component.name,\n opts,\n });\n }\n\n async registerComponents(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerComponents.name,\n description: 'Register application components',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.COMPONENT });\n },\n });\n }\n\n /**\n * Second DATASOURCE sweep, for datasources components contributed at any depth. Calls\n * `registerDynamicBindings` directly: `this.registerDataSources()` is polymorphic and an override\n * would run twice. Runs after every component, so a component a datasource registers is never configured.\n */\n async registerContributedDataSources(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerContributedDataSources.name,\n description: 'Register application contributed data sources',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.DATASOURCE });\n },\n });\n }\n\n /** REST only - the kernel has no gRPC (it reaches `node:module`). `BaseApplication` adds the gRPC branch on top. */\n async registerControllers(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n description: 'Register application REST controllers',\n scope: this.registerControllers.name,\n task: async () => {\n const transports = this.configs.transports ?? [ControllerTransports.REST];\n\n if (!transports.includes(ControllerTransports.REST)) {\n return;\n }\n\n const restComponent = new RestComponent(this);\n await restComponent.configure();\n },\n });\n }\n\n /** SINGLETON like `component()`: `RestComponent` mounts the one instance it resolves, so a second resolution must be that instance, not an unmounted twin. */\n controller<Base>(target: TClass<Base>, opts?: TMixinOpts): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.CONTROLLER,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.controller.name,\n opts,\n });\n }\n\n service<Base extends IService>(target: TClass<Base>, opts?: TMixinOpts): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.SERVICE,\n defaultScope: BindingScopes.TRANSIENT,\n caller: this.service.name,\n opts,\n });\n }\n\n repository<Base extends IRepository>(target: TClass<Base>, opts?: TMixinOpts): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.REPOSITORY,\n defaultScope: BindingScopes.TRANSIENT,\n caller: this.repository.name,\n opts,\n });\n }\n\n dataSource<Base extends IDataSource<Options>, Options extends object = {}>(\n target: TClass<Base>,\n opts?: TMixinOpts<Options>,\n ): Binding<Base> {\n return this.registerArtifact({\n target,\n namespace: BindingNamespaces.DATASOURCE,\n defaultScope: BindingScopes.SINGLETON,\n caller: this.dataSource.name,\n opts,\n });\n }\n\n /** The boot step body behind `configs.artifacts`, also callable by hand: registers every kind in dependency order across the given indexes. */\n async registerArtifacts(index: TArtifactIndexInput): Promise<void> {\n const resolved = await ArtifactIndexHelper.getInstance().resolve({\n input: index,\n application: this,\n });\n\n const registry = MetadataRegistry.getInstance();\n const kinds: Array<[ReadonlyArray<TClass<unknown>>, TBindingNamespace]> = [\n [resolved.configurations, BindingNamespaces.CONFIGURATION],\n [resolved.dataSources, BindingNamespaces.DATASOURCE],\n [resolved.components, BindingNamespaces.COMPONENT],\n [resolved.repositories, BindingNamespaces.REPOSITORY],\n [resolved.services, BindingNamespaces.SERVICE],\n [resolved.controllers, BindingNamespaces.CONTROLLER],\n ];\n // An application's own types: each needs its definition loaded, or the class has no namespace and no default scope.\n const custom = Object.entries(resolved.custom).flatMap(([type, targets]) => {\n const definition = ArtifactTypes.definitionOf({ type });\n\n if (!definition) {\n throw getError({\n message: `[registerArtifacts] '${targets[0]?.name ?? type}' is listed under the artifact type '${type}', which is not defined | Import the module that calls ArtifactTypes.define({ type: '${type}', ... }) before the application boots`,\n });\n }\n\n return targets.map((target) => ({ target, definition }));\n });\n const collisions = ArtifactBindingKeys.findDerivedCollisions({\n entries: [\n ...kinds.flatMap(([targets, namespace]) =>\n targets.map((target) => ({\n target,\n namespace,\n binding: registry.getArtifactMetadata({ target })?.binding,\n })),\n ),\n ...custom.map(({ target, definition }) => ({\n target,\n namespace: definition.namespace,\n binding: registry.getArtifactMetadata({ target })?.binding,\n })),\n ],\n });\n\n for (const key of collisions) {\n const message = ArtifactBindingKeys.describeCollision({ key, caller: 'registerArtifacts' });\n\n if (!this.configs.bootChecks?.allowDerivedKeyCollision) {\n throw getError({ message });\n }\n\n this.logger.warn('%s', message);\n }\n\n for (const target of resolved.configurations) {\n this.configuration(target);\n this.bindProvidedKeys({ target });\n }\n\n for (const target of resolved.dataSources) {\n this.dataSource(target);\n }\n\n for (const target of resolved.components) {\n this.component(target);\n this.bindProvidedKeys({ target });\n }\n\n for (const target of resolved.repositories) {\n this.repository(target);\n }\n\n for (const target of resolved.services) {\n this.service(target);\n }\n\n for (const { target, definition } of custom) {\n this.registerArtifact({\n target,\n namespace: definition.namespace,\n defaultScope: definition.scope,\n caller: definition.type,\n });\n }\n\n for (const target of resolved.controllers) {\n this.controller(target);\n }\n }\n\n /** Registers every class a stereotype decorated, with no `configs.artifacts` entry anywhere. `when` and `order` apply exactly as they do to a declared index - which is how one process running several applications keeps them apart. */\n async registerDiscoveredArtifacts(): Promise<void> {\n await this.registerArtifacts(ArtifactIndexHelper.getInstance().buildDiscoveredIndex());\n }\n\n /**\n * The artifact boot step. `configs.discoverArtifacts` adds every decorated class in the import\n * graph; `configs.artifacts` adds exactly what it lists. Both together register the union.\n *\n * An absent `artifacts` still registers nothing. Reading it as \"register everything\" would change\n * what an existing application boots with, silently, and the failure would surface as ten times\n * the bindings rather than as an error.\n */\n protected async registerConfiguredArtifacts(): Promise<void> {\n const inputs: TArtifactIndexInput[] = [];\n\n if (this.configs.discoverArtifacts) {\n inputs.push(ArtifactIndexHelper.getInstance().buildDiscoveredIndex());\n }\n\n if (this.configs.artifacts) {\n inputs.push(this.configs.artifacts);\n }\n\n if (inputs.length === 0) {\n return;\n }\n\n await this.registerArtifacts(inputs);\n }\n\n /** Each `@provide` method becomes a lazy provider: the component is resolved (SINGLETON) and the method called on first `get`, so a provided value may depend on datasources or secrets that do not exist yet at registration time. */\n private bindProvidedKeys(opts: { target: TClass<unknown> }): void {\n const { target } = opts;\n const registry = MetadataRegistry.getInstance();\n const provides = registry.getProvideMetadata({ target });\n\n if (provides.length === 0) {\n return;\n }\n\n const declared = registry.getArtifactMetadata({ target });\n const defaultNamespace = declared?.type\n ? ArtifactNamespaces.resolve({ type: declared.type })\n : BindingNamespaces.COMPONENT;\n // The key the registration actually bound - a call-site override included.\n const componentKey =\n registry.getBindingKey({ target }) ??\n ArtifactBindingKeys.resolve({\n target,\n namespace: defaultNamespace,\n binding: declared?.binding,\n }).key;\n\n for (const entry of provides) {\n this.bind({ key: entry.key })\n .toProvider((container) => {\n const instance = container.get<Record<string | symbol, () => unknown>>({\n key: componentKey,\n });\n\n return instance[entry.methodName]();\n })\n .setScope(entry.scope ?? BindingScopes.SINGLETON);\n }\n }\n\n async registerDataSources(): Promise<void> {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerDataSources.name,\n description: 'Register application data sources',\n task: async () => {\n await this.registerDynamicBindings({ namespace: BindingNamespaces.DATASOURCE });\n },\n });\n }\n\n /**\n * Closes every datasource the boot configured, so a stopped application holds no pool, socket or\n * WASM instance. A failure, or a `close()` still pending after `dataSourceCloseTimeoutMs`, is logged\n * and never stops the rest. A datasource configured by hand is closed by whoever configured it.\n */\n protected async closeDataSources(): Promise<void> {\n const keys = this.registeredBindings[BindingNamespaces.DATASOURCE] ?? new Set<TBindingKey>();\n const timeoutMs = this.configs.dataSourceCloseTimeoutMs ?? 10_000;\n const logger = this.logger.for(this.closeDataSources.name);\n\n for (const key of keys) {\n try {\n const dataSource = this.get<IDataSource>({ key, isOptional: true });\n\n if (!dataSource?.close) {\n logger.debug('Nothing to close | key: %s', key);\n continue;\n }\n\n const closing = dataSource.close();\n await RetryUtility.runWithTimeout({ operation: key, timeoutMs, execution: () => closing });\n } catch (error) {\n if (RetryUtility.isRetryTimeoutError(error)) {\n logger.error('Close timed out | key: %s | timeoutMs: %d', key, timeoutMs);\n continue;\n }\n\n logger.error('Failed to close datasource | key: %s | error: %s', key, error);\n continue;\n }\n\n logger.info('Closed datasource | key: %s', key);\n }\n }\n}\n"]}
@@ -5,9 +5,9 @@ import { getError } from '@venizia/ignis-helpers/core';
5
5
  /** The root stereotype: marks a class as an artifact the application registers, with its registration defaults. Every other stereotype calls it. */
6
6
  export const injectable = (opts) => {
7
7
  return (target) => {
8
- if (!ArtifactTypes.isValid(opts.type)) {
8
+ if (!ArtifactTypes.isValid(opts.type) && !ArtifactTypes.definitionOf({ type: opts.type })) {
9
9
  throw getError({
10
- message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${ArtifactTypes.values().join(', ')}`,
10
+ message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${ArtifactTypes.values().join(', ')} | or a type defined with ArtifactTypes.define${ArtifactTypes.definedTypes().length > 0 ? `: ${ArtifactTypes.definedTypes().join(', ')}` : ''}`,
11
11
  });
12
12
  }
13
13
  // At import time, so the failure lands where the binding is written, not at boot.
@@ -1 +1 @@
1
- {"version":3,"file":"injectable.js","sourceRoot":"","sources":["../../../../src/base/metadata/injectable.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAoB,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,oJAAoJ;AACpJ,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,IAAwC,EACxB,EAAE;IAClB,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,CAAC,aAAa,CA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;YAC1B,YAAY,CAAC,OAAO,GAAG,OAAO,CAAC;QACjC,CAAC;QAED,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,YAAY,CAAC,aAAa,GAAG,aAAa,CAAC;QAC7C,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,YAAY,CAAC,IAAI,GAAG,IAAI,CAAC;QAC3B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["import type {\n IArtifactMetadata,\n IArtifactRegistrationOptions,\n TBindingScope,\n} from '@/helpers/inversion';\nimport { ArtifactNamespaces, BindingNamespaces } from '@/common/bindings';\nimport { ArtifactTypes, MetadataRegistry, type TBindingKey } from '@/helpers/inversion';\nimport { ArtifactBindingKeys } from './artifact-keys';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** The root stereotype: marks a class as an artifact the application registers, with its registration defaults. Every other stereotype calls it. */\nexport const injectable = <ApplicationType = unknown>(\n opts: IArtifactMetadata<ApplicationType>,\n): ClassDecorator => {\n return (target) => {\n if (!ArtifactTypes.isValid(opts.type)) {\n throw getError({\n message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${ArtifactTypes.values().join(', ')}`,\n });\n }\n\n // At import time, so the failure lands where the binding is written, not at boot.\n if (opts.binding) {\n BindingNamespaces.assertArtifactNamespace({\n namespace: opts.binding.namespace,\n artifact: target.name,\n caller: 'injectable',\n });\n }\n\n const registry = MetadataRegistry.getInstance();\n registry.setArtifactMetadata({ target, metadata: opts });\n\n // Discovery happens HERE, at import time. A boot-time filesystem scan cannot see a compiled\n // single-file binary, and a class exists at run time only because something imported it.\n registry.addDiscoveredArtifact({ target });\n\n // The key this class WOULD get; `registerArtifact` overwrites it with the one actually bound.\n registry.setBindingKey({\n target,\n key: ArtifactBindingKeys.resolve({\n target,\n namespace: ArtifactNamespaces.resolve({ type: opts.type }),\n binding: opts.binding,\n }).key,\n isProvisional: true,\n });\n };\n};\n\n/**\n * Class decorator that registers the class as a service artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseService, service } from '@venizia/ignis';\n *\n * export @service()\n * class MailService extends BaseService {\n * constructor() {\n * super({ scope: MailService.name });\n * }\n * }\n * ```\n */\nexport const service = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.SERVICE, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a component artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseComponent, component } from '@venizia/ignis';\n *\n * export @component()\n * class AuditComponent extends BaseComponent {\n * constructor() {\n * super({ scope: AuditComponent.name });\n * }\n *\n * override binding(): void {}\n * }\n * ```\n */\nexport const component = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.COMPONENT, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a configuration artifact; `after` orders it behind other configuration classes.\n *\n * @example\n * ```typescript\n * import { BaseConfiguration, configuration } from '@venizia/ignis';\n *\n * export @configuration()\n * class SeedConfiguration extends BaseConfiguration {}\n *\n * export @configuration({ after: [SeedConfiguration] })\n * class IndexConfiguration extends BaseConfiguration {}\n * ```\n */\nexport const configuration = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.CONFIGURATION, ...opts });\n};\n\n/** Marks a component method as the provider of `key`. `registerArtifacts` binds the key to a lazy provider that resolves the component and calls the method; SINGLETON unless `scope` says otherwise. */\nexport const provide = (opts: { key: TBindingKey; scope?: TBindingScope }): MethodDecorator => {\n return (target, propertyKey) => {\n MetadataRegistry.getInstance().addProvideMetadata({\n target: target.constructor,\n metadata: {\n methodName: propertyKey,\n key: opts.key,\n ...(opts.scope ? { scope: opts.scope } : {}),\n },\n });\n };\n};\n\n/** Helpers of the stereotype decorators; the decorators themselves stay functions. */\nexport class InjectableUtility {\n /** The registration defaults a stereotype forwards to `@injectable`, copied field by field so an absent option stays absent. */\n static pickRegistrationOptions<ApplicationType = unknown>(opts: {\n metadata: IArtifactRegistrationOptions<ApplicationType>;\n }): IArtifactRegistrationOptions<ApplicationType> {\n const { binding, allowOverride, scope, order, when, after } = opts.metadata;\n const registration: IArtifactRegistrationOptions<ApplicationType> = {};\n\n if (binding !== undefined) {\n registration.binding = binding;\n }\n\n if (allowOverride !== undefined) {\n registration.allowOverride = allowOverride;\n }\n\n if (scope !== undefined) {\n registration.scope = scope;\n }\n\n if (order !== undefined) {\n registration.order = order;\n }\n\n if (when !== undefined) {\n registration.when = when;\n }\n\n if (after !== undefined) {\n registration.after = after;\n }\n\n return registration;\n }\n}\n"]}
1
+ {"version":3,"file":"injectable.js","sourceRoot":"","sources":["../../../../src/base/metadata/injectable.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAoB,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,oJAAoJ;AACpJ,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,IAAwC,EACxB,EAAE;IAClB,OAAO,CAAC,MAAM,EAAE,EAAE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MAAM,OAAO,iBAAiB;IAC5B,gIAAgI;IAChI,MAAM,CAAC,uBAAuB,CAA4B,IAEzD;QACC,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC5E,MAAM,YAAY,GAAkD,EAAE,CAAC;QAEvE,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1B,YAAY,CAAC,OAAO,GAAG,OAAO,CAAC;QACjC,CAAC;QAED,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,YAAY,CAAC,aAAa,GAAG,aAAa,CAAC;QAC7C,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,YAAY,CAAC,IAAI,GAAG,IAAI,CAAC;QAC3B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["import type {\n IArtifactMetadata,\n IArtifactRegistrationOptions,\n TBindingScope,\n} from '@/helpers/inversion';\nimport { ArtifactNamespaces, BindingNamespaces } from '@/common/bindings';\nimport { ArtifactTypes, MetadataRegistry, type TBindingKey } from '@/helpers/inversion';\nimport { ArtifactBindingKeys } from './artifact-keys';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** The root stereotype: marks a class as an artifact the application registers, with its registration defaults. Every other stereotype calls it. */\nexport const injectable = <ApplicationType = unknown>(\n opts: IArtifactMetadata<ApplicationType>,\n): ClassDecorator => {\n return (target) => {\n if (!ArtifactTypes.isValid(opts.type) && !ArtifactTypes.definitionOf({ type: opts.type })) {\n throw getError({\n message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${ArtifactTypes.values().join(', ')} | or a type defined with ArtifactTypes.define${ArtifactTypes.definedTypes().length > 0 ? `: ${ArtifactTypes.definedTypes().join(', ')}` : ''}`,\n });\n }\n\n // At import time, so the failure lands where the binding is written, not at boot.\n if (opts.binding) {\n BindingNamespaces.assertArtifactNamespace({\n namespace: opts.binding.namespace,\n artifact: target.name,\n caller: 'injectable',\n });\n }\n\n const registry = MetadataRegistry.getInstance();\n registry.setArtifactMetadata({ target, metadata: opts });\n\n // Discovery happens HERE, at import time. A boot-time filesystem scan cannot see a compiled\n // single-file binary, and a class exists at run time only because something imported it.\n registry.addDiscoveredArtifact({ target });\n\n // The key this class WOULD get; `registerArtifact` overwrites it with the one actually bound.\n registry.setBindingKey({\n target,\n key: ArtifactBindingKeys.resolve({\n target,\n namespace: ArtifactNamespaces.resolve({ type: opts.type }),\n binding: opts.binding,\n }).key,\n isProvisional: true,\n });\n };\n};\n\n/**\n * Class decorator that registers the class as a service artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseService, service } from '@venizia/ignis';\n *\n * export @service()\n * class MailService extends BaseService {\n * constructor() {\n * super({ scope: MailService.name });\n * }\n * }\n * ```\n */\nexport const service = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.SERVICE, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a component artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseComponent, component } from '@venizia/ignis';\n *\n * export @component()\n * class AuditComponent extends BaseComponent {\n * constructor() {\n * super({ scope: AuditComponent.name });\n * }\n *\n * override binding(): void {}\n * }\n * ```\n */\nexport const component = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.COMPONENT, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a configuration artifact; `after` orders it behind other configuration classes.\n *\n * @example\n * ```typescript\n * import { BaseConfiguration, configuration } from '@venizia/ignis';\n *\n * export @configuration()\n * class SeedConfiguration extends BaseConfiguration {}\n *\n * export @configuration({ after: [SeedConfiguration] })\n * class IndexConfiguration extends BaseConfiguration {}\n * ```\n */\nexport const configuration = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.CONFIGURATION, ...opts });\n};\n\n/** Marks a component method as the provider of `key`. `registerArtifacts` binds the key to a lazy provider that resolves the component and calls the method; SINGLETON unless `scope` says otherwise. */\nexport const provide = (opts: { key: TBindingKey; scope?: TBindingScope }): MethodDecorator => {\n return (target, propertyKey) => {\n MetadataRegistry.getInstance().addProvideMetadata({\n target: target.constructor,\n metadata: {\n methodName: propertyKey,\n key: opts.key,\n ...(opts.scope ? { scope: opts.scope } : {}),\n },\n });\n };\n};\n\n/** Helpers of the stereotype decorators; the decorators themselves stay functions. */\nexport class InjectableUtility {\n /** The registration defaults a stereotype forwards to `@injectable`, copied field by field so an absent option stays absent. */\n static pickRegistrationOptions<ApplicationType = unknown>(opts: {\n metadata: IArtifactRegistrationOptions<ApplicationType>;\n }): IArtifactRegistrationOptions<ApplicationType> {\n const { binding, allowOverride, scope, order, when, after } = opts.metadata;\n const registration: IArtifactRegistrationOptions<ApplicationType> = {};\n\n if (binding !== undefined) {\n registration.binding = binding;\n }\n\n if (allowOverride !== undefined) {\n registration.allowOverride = allowOverride;\n }\n\n if (scope !== undefined) {\n registration.scope = scope;\n }\n\n if (order !== undefined) {\n registration.order = order;\n }\n\n if (when !== undefined) {\n registration.when = when;\n }\n\n if (after !== undefined) {\n registration.after = after;\n }\n\n return registration;\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { BindingKeys } from '../helpers/inversion/index.js';
1
+ import { BindingKeys } from '@venizia/ignis-inversion';
2
2
  import type { TConstValue } from '@venizia/ignis-helpers/common';
3
3
  /** Valid `BindingNamespaces` values. */
4
4
  export type TBindingNamespace = TConstValue<typeof BindingNamespaces>;
@@ -21,6 +21,10 @@ export declare class BindingNamespaces {
21
21
  static isValid(opts: {
22
22
  name: string;
23
23
  }): boolean;
24
+ /** Whether `name` is the namespace of a built-in artifact type (or of the middlewares and providers the framework binds). */
25
+ static isBuiltIn(opts: {
26
+ name: string;
27
+ }): boolean;
24
28
  static createNamespace(opts: {
25
29
  name: string;
26
30
  }): string;
@@ -31,9 +35,12 @@ export declare class BindingNamespaces {
31
35
  caller: string;
32
36
  }): string;
33
37
  }
34
- /** Artifact kind -> namespace. `registerArtifact` gets its namespace from the call site; `@injectable` has only the class. */
38
+ /** Artifact type -> namespace. `registerArtifact` gets its namespace from the call site; `@injectable` has only the class. */
35
39
  export declare class ArtifactNamespaces {
36
- private static readonly BY_TYPE;
40
+ private static builtInByType?;
41
+ /** Built on first use: `ArtifactTypes.define` reaches `BindingNamespaces`, so this module must not read `ArtifactTypes` while it loads. */
42
+ private static builtIn;
43
+ /** A built-in type's namespace, else the namespace its `ArtifactTypes.define` gave. */
37
44
  static resolve(opts: {
38
45
  type: string;
39
46
  }): TBindingNamespace;
@@ -1,4 +1,5 @@
1
- import { ArtifactTypes, BindingKeys } from '../helpers/inversion/index.js';
1
+ import { BindingKeys } from '@venizia/ignis-inversion';
2
+ import { ArtifactTypes } from '../helpers/inversion/index.js';
2
3
  import { getError } from '@venizia/ignis-helpers/core';
3
4
  /** Static binding namespaces for dependency injection. */
4
5
  export class BindingNamespaces {
@@ -21,6 +22,10 @@ export class BindingNamespaces {
21
22
  const { name } = opts;
22
23
  return typeof name === 'string' && BindingNamespaces.NAME_PATTERN.test(name);
23
24
  }
25
+ /** Whether `name` is the namespace of a built-in artifact type (or of the middlewares and providers the framework binds). */
26
+ static isBuiltIn(opts) {
27
+ return Object.values(BindingNamespaces).some((value) => value === opts.name);
28
+ }
24
29
  static createNamespace(opts) {
25
30
  const { name } = opts;
26
31
  if (!BindingNamespaces.isValid({ name })) {
@@ -41,22 +46,28 @@ export class BindingNamespaces {
41
46
  });
42
47
  }
43
48
  }
44
- /** Artifact kind -> namespace. `registerArtifact` gets its namespace from the call site; `@injectable` has only the class. */
49
+ /** Artifact type -> namespace. `registerArtifact` gets its namespace from the call site; `@injectable` has only the class. */
45
50
  export class ArtifactNamespaces {
46
- static { this.BY_TYPE = {
47
- [ArtifactTypes.CONFIGURATION]: BindingNamespaces.CONFIGURATION,
48
- [ArtifactTypes.COMPONENT]: BindingNamespaces.COMPONENT,
49
- [ArtifactTypes.CONTROLLER]: BindingNamespaces.CONTROLLER,
50
- [ArtifactTypes.SERVICE]: BindingNamespaces.SERVICE,
51
- [ArtifactTypes.REPOSITORY]: BindingNamespaces.REPOSITORY,
52
- [ArtifactTypes.DATASOURCE]: BindingNamespaces.DATASOURCE,
53
- [ArtifactTypes.MODEL]: BindingNamespaces.MODEL,
54
- }; }
51
+ /** Built on first use: `ArtifactTypes.define` reaches `BindingNamespaces`, so this module must not read `ArtifactTypes` while it loads. */
52
+ static builtIn() {
53
+ ArtifactNamespaces.builtInByType ??= {
54
+ [ArtifactTypes.CONFIGURATION]: BindingNamespaces.CONFIGURATION,
55
+ [ArtifactTypes.COMPONENT]: BindingNamespaces.COMPONENT,
56
+ [ArtifactTypes.CONTROLLER]: BindingNamespaces.CONTROLLER,
57
+ [ArtifactTypes.SERVICE]: BindingNamespaces.SERVICE,
58
+ [ArtifactTypes.REPOSITORY]: BindingNamespaces.REPOSITORY,
59
+ [ArtifactTypes.DATASOURCE]: BindingNamespaces.DATASOURCE,
60
+ [ArtifactTypes.MODEL]: BindingNamespaces.MODEL,
61
+ };
62
+ return ArtifactNamespaces.builtInByType;
63
+ }
64
+ /** A built-in type's namespace, else the namespace its `ArtifactTypes.define` gave. */
55
65
  static resolve(opts) {
56
- const namespace = ArtifactNamespaces.BY_TYPE[opts.type];
66
+ const builtIn = ArtifactNamespaces.builtIn();
67
+ const namespace = builtIn[opts.type] ?? ArtifactTypes.definitionOf({ type: opts.type })?.namespace;
57
68
  if (namespace === undefined) {
58
69
  throw getError({
59
- message: `[ArtifactNamespaces][resolve] No namespace for artifact type | type: '${opts.type}' | known: ${Object.keys(ArtifactNamespaces.BY_TYPE).join(', ')}`,
70
+ message: `[ArtifactNamespaces][resolve] No namespace for artifact type | type: '${opts.type}' | known: ${Object.keys(builtIn).join(', ')} | defined: ${ArtifactTypes.definedTypes().join(', ') || 'none'}`,
60
71
  });
61
72
  }
62
73
  return namespace;
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.js","sourceRoot":"","sources":["../../../src/common/bindings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEjE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAKvD,0DAA0D;AAC1D,MAAM,OAAO,iBAAiB;IAC5B,kGAAkG;aAC1E,iBAAY,GAAG,WAAW,CAAC;aAEnC,cAAS,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;aAEtE,eAAU,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;aACxE,eAAU,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAC;aACzE,UAAK,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;aAE9D,YAAO,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;aAClE,eAAU,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;aACxE,aAAQ,G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CAAC,KAAK,CAAU;QACnE,GAAG,EAAE,kBAAkB;KACxB,CAAC,CAAC;aAEa,6BAAwB,GAAG,WAAW,CAAC,KAAK,CAAU;QACpE,GAAG,EAAE,mBAAmB;KACzB,CAAC,CAAC;aAEa,mCAA8B,GAAG,WAAW,CAAC,KAAK,CAAU;QAC1E,GAAG,EAAE,yBAAyB;KAC/B,CAAC,CAAC","sourcesContent":["import { ArtifactTypes, BindingKeys } from '@/helpers/inversion';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** Valid `BindingNamespaces` values. */\nexport type TBindingNamespace = TConstValue<typeof BindingNamespaces>;\n\n/** Static binding namespaces for dependency injection. */\nexport class BindingNamespaces {\n // Declared first: every constant below runs through createNamespace while this class initializes.\n private static readonly NAME_PATTERN = /^[^.\\s]+$/;\n\n static readonly COMPONENT = BindingNamespaces.createNamespace({ name: 'components' });\n\n static readonly DATASOURCE = BindingNamespaces.createNamespace({ name: 'datasources' });\n static readonly REPOSITORY = BindingNamespaces.createNamespace({ name: 'repositories' });\n static readonly MODEL = BindingNamespaces.createNamespace({ name: 'models' });\n\n static readonly SERVICE = BindingNamespaces.createNamespace({ name: 'services' });\n static readonly MIDDLEWARE = BindingNamespaces.createNamespace({ name: 'middlewares' });\n static readonly PROVIDER = BindingNamespaces.createNamespace({ name: 'providers' });\n static readonly CONTROLLER = BindingNamespaces.createNamespace({ name: 'controllers' });\n\n static readonly CONFIGURATION = BindingNamespaces.createNamespace({ name: 'configurations' });\n\n /**\n * A namespace is the leading segment of a binding key, and a binding is tagged with that segment\n * alone - a name carrying '.' or whitespace yields a key no boot step can drain by tag.\n */\n static isValid(opts: { name: string }): boolean {\n const { name } = opts;\n\n return typeof name === 'string' && BindingNamespaces.NAME_PATTERN.test(name);\n }\n\n static createNamespace(opts: { name: string }) {\n const { name } = opts;\n\n if (!BindingNamespaces.isValid({ name })) {\n throw getError({\n message: `[BindingNamespaces][createNamespace] Invalid namespace | Expected a single non-empty segment without '.' or whitespace | Got: '${name}'`,\n });\n }\n\n return name;\n }\n\n /** A namespace-less key is untagged: no boot step drains it and `doVerify` never sees it. */\n static assertArtifactNamespace(opts: { namespace: string; artifact: string; caller: string }) {\n const { namespace, artifact, caller } = opts;\n\n if (BindingNamespaces.isValid({ name: namespace })) {\n return namespace;\n }\n\n throw getError({\n message: `[${caller}] '${artifact}' declares a binding with no usable namespace | namespace: '${namespace}' | A key with no leading namespace segment carries no tag, so no boot step drains it and 'bootChecks.binding.doVerify' never sees it`,\n });\n }\n}\n\n/** Artifact kind -> namespace. `registerArtifact` gets its namespace from the call site; `@injectable` has only the class. */\nexport class ArtifactNamespaces {\n private static readonly BY_TYPE: Record<string, TBindingNamespace> = {\n [ArtifactTypes.CONFIGURATION]: BindingNamespaces.CONFIGURATION,\n [ArtifactTypes.COMPONENT]: BindingNamespaces.COMPONENT,\n [ArtifactTypes.CONTROLLER]: BindingNamespaces.CONTROLLER,\n [ArtifactTypes.SERVICE]: BindingNamespaces.SERVICE,\n [ArtifactTypes.REPOSITORY]: BindingNamespaces.REPOSITORY,\n [ArtifactTypes.DATASOURCE]: BindingNamespaces.DATASOURCE,\n [ArtifactTypes.MODEL]: BindingNamespaces.MODEL,\n };\n\n static resolve(opts: { type: string }): TBindingNamespace {\n const namespace = ArtifactNamespaces.BY_TYPE[opts.type];\n\n if (namespace === undefined) {\n throw getError({\n message: `[ArtifactNamespaces][resolve] No namespace for artifact type | type: '${opts.type}' | known: ${Object.keys(ArtifactNamespaces.BY_TYPE).join(', ')}`,\n });\n }\n\n return namespace;\n }\n}\n\n/** Core binding keys for fundamental application components and configuration. */\nexport class CoreBindings extends BindingKeys {\n static readonly APPLICATION_INSTANCE = BindingKeys.build<unknown>({\n key: '@app/instance',\n });\n\n static readonly APPLICATION_SERVER = BindingKeys.build<unknown>({\n key: '@app/server',\n });\n\n static readonly APPLICATION_CONFIG = BindingKeys.build<unknown>({\n key: '@app/config',\n });\n\n static readonly APPLICATION_PROJECT_ROOT = BindingKeys.build<string>({\n key: '@app/project_root',\n });\n\n static readonly APPLICATION_ROOT_ROUTER = BindingKeys.build<unknown>({\n key: '@app/router/root',\n });\n\n static readonly APPLICATION_ENVIRONMENTS = BindingKeys.build<unknown>({\n key: '@app/environments',\n });\n\n static readonly APPLICATION_MIDDLEWARE_OPTIONS = BindingKeys.build<unknown>({\n key: '@app/middleware_options',\n });\n}\n"]}
1
+ {"version":3,"file":"bindings.js","sourceRoot":"","sources":["../../../src/common/bindings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAKvD,0DAA0D;AAC1D,MAAM,OAAO,iBAAiB;IAC5B,kGAAkG;aAC1E,iBAAY,GAAG,WAAW,CAAC;aAEnC,cAAS,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;aAEtE,eAAU,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;aACxE,eAAU,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAC;aACzE,UAAK,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;aAE9D,YAAO,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;aAClE,eAAU,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;aACxE,aAAQ,GAAG,iBAAiB,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;aACpE,eAAU,GAAG,iBAAiB,CAAC,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F,MAAM,OAAO,YAAa,SAAQ,WAAW;aAC3B,yBAAoB,GAAG,WAAW,CAAC,KAAK,CAAU;QAChE,GAAG,EAAE,eAAe;KACrB,CAAC,CAAC;aAEa,uBAAkB,GAAG,WAAW,CAAC,KAAK,CAAU;QAC9D,GAAG,EAAE,aAAa;KACnB,CAAC,CAAC;aAEa,uBAAkB,GAAG,WAAW,CAAC,KAAK,CAAU;QAC9D,GAAG,EAAE,aAAa;KACnB,CAAC,CAAC;aAEa,6BAAwB,GAAG,WAAW,CAAC,KAAK,CAAS;QACnE,GAAG,EAAE,mBAAmB;KACzB,CAAC,CAAC;aAEa,4BAAuB,GAAG,WAAW,CAAC,KAAK,CAAU;QACnE,GAAG,EAAE,kBAAkB;KACxB,CAAC,CAAC;aAEa,6BAAwB,GAAG,WAAW,CAAC,KAAK,CAAU;QACpE,GAAG,EAAE,mBAAmB;KACzB,CAAC,CAAC;aAEa,mCAA8B,GAAG,WAAW,CAAC,KAAK,CAAU;QAC1E,GAAG,EAAE,yBAAyB;KAC/B,CAAC,CAAC","sourcesContent":["import { BindingKeys } from '@venizia/ignis-inversion';\nimport { ArtifactTypes } from '@/helpers/inversion';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** Valid `BindingNamespaces` values. */\nexport type TBindingNamespace = TConstValue<typeof BindingNamespaces>;\n\n/** Static binding namespaces for dependency injection. */\nexport class BindingNamespaces {\n // Declared first: every constant below runs through createNamespace while this class initializes.\n private static readonly NAME_PATTERN = /^[^.\\s]+$/;\n\n static readonly COMPONENT = BindingNamespaces.createNamespace({ name: 'components' });\n\n static readonly DATASOURCE = BindingNamespaces.createNamespace({ name: 'datasources' });\n static readonly REPOSITORY = BindingNamespaces.createNamespace({ name: 'repositories' });\n static readonly MODEL = BindingNamespaces.createNamespace({ name: 'models' });\n\n static readonly SERVICE = BindingNamespaces.createNamespace({ name: 'services' });\n static readonly MIDDLEWARE = BindingNamespaces.createNamespace({ name: 'middlewares' });\n static readonly PROVIDER = BindingNamespaces.createNamespace({ name: 'providers' });\n static readonly CONTROLLER = BindingNamespaces.createNamespace({ name: 'controllers' });\n\n static readonly CONFIGURATION = BindingNamespaces.createNamespace({ name: 'configurations' });\n\n /**\n * A namespace is the leading segment of a binding key, and a binding is tagged with that segment\n * alone - a name carrying '.' or whitespace yields a key no boot step can drain by tag.\n */\n static isValid(opts: { name: string }): boolean {\n const { name } = opts;\n\n return typeof name === 'string' && BindingNamespaces.NAME_PATTERN.test(name);\n }\n\n /** Whether `name` is the namespace of a built-in artifact type (or of the middlewares and providers the framework binds). */\n static isBuiltIn(opts: { name: string }): boolean {\n return Object.values(BindingNamespaces).some((value) => value === opts.name);\n }\n\n static createNamespace(opts: { name: string }) {\n const { name } = opts;\n\n if (!BindingNamespaces.isValid({ name })) {\n throw getError({\n message: `[BindingNamespaces][createNamespace] Invalid namespace | Expected a single non-empty segment without '.' or whitespace | Got: '${name}'`,\n });\n }\n\n return name;\n }\n\n /** A namespace-less key is untagged: no boot step drains it and `doVerify` never sees it. */\n static assertArtifactNamespace(opts: { namespace: string; artifact: string; caller: string }) {\n const { namespace, artifact, caller } = opts;\n\n if (BindingNamespaces.isValid({ name: namespace })) {\n return namespace;\n }\n\n throw getError({\n message: `[${caller}] '${artifact}' declares a binding with no usable namespace | namespace: '${namespace}' | A key with no leading namespace segment carries no tag, so no boot step drains it and 'bootChecks.binding.doVerify' never sees it`,\n });\n }\n}\n\n/** Artifact type -> namespace. `registerArtifact` gets its namespace from the call site; `@injectable` has only the class. */\nexport class ArtifactNamespaces {\n private static builtInByType?: Record<string, TBindingNamespace>;\n\n /** Built on first use: `ArtifactTypes.define` reaches `BindingNamespaces`, so this module must not read `ArtifactTypes` while it loads. */\n private static builtIn(): Record<string, TBindingNamespace> {\n ArtifactNamespaces.builtInByType ??= {\n [ArtifactTypes.CONFIGURATION]: BindingNamespaces.CONFIGURATION,\n [ArtifactTypes.COMPONENT]: BindingNamespaces.COMPONENT,\n [ArtifactTypes.CONTROLLER]: BindingNamespaces.CONTROLLER,\n [ArtifactTypes.SERVICE]: BindingNamespaces.SERVICE,\n [ArtifactTypes.REPOSITORY]: BindingNamespaces.REPOSITORY,\n [ArtifactTypes.DATASOURCE]: BindingNamespaces.DATASOURCE,\n [ArtifactTypes.MODEL]: BindingNamespaces.MODEL,\n };\n\n return ArtifactNamespaces.builtInByType;\n }\n\n /** A built-in type's namespace, else the namespace its `ArtifactTypes.define` gave. */\n static resolve(opts: { type: string }): TBindingNamespace {\n const builtIn = ArtifactNamespaces.builtIn();\n const namespace =\n builtIn[opts.type] ?? ArtifactTypes.definitionOf({ type: opts.type })?.namespace;\n\n if (namespace === undefined) {\n throw getError({\n message: `[ArtifactNamespaces][resolve] No namespace for artifact type | type: '${opts.type}' | known: ${Object.keys(builtIn).join(', ')} | defined: ${ArtifactTypes.definedTypes().join(', ') || 'none'}`,\n });\n }\n\n return namespace;\n }\n}\n\n/** Core binding keys for fundamental application components and configuration. */\nexport class CoreBindings extends BindingKeys {\n static readonly APPLICATION_INSTANCE = BindingKeys.build<unknown>({\n key: '@app/instance',\n });\n\n static readonly APPLICATION_SERVER = BindingKeys.build<unknown>({\n key: '@app/server',\n });\n\n static readonly APPLICATION_CONFIG = BindingKeys.build<unknown>({\n key: '@app/config',\n });\n\n static readonly APPLICATION_PROJECT_ROOT = BindingKeys.build<string>({\n key: '@app/project_root',\n });\n\n static readonly APPLICATION_ROOT_ROUTER = BindingKeys.build<unknown>({\n key: '@app/router/root',\n });\n\n static readonly APPLICATION_ENVIRONMENTS = BindingKeys.build<unknown>({\n key: '@app/environments',\n });\n\n static readonly APPLICATION_MIDDLEWARE_OPTIONS = BindingKeys.build<unknown>({\n key: '@app/middleware_options',\n });\n}\n"]}
@@ -1,7 +1,16 @@
1
1
  import type { TConstValue } from '@venizia/ignis-helpers/common';
2
2
  import { ConstClass } from '@venizia/ignis-helpers/common';
3
- /** What a decorated class is to the application - the one fact the artifact generator and the registration methods both read. */
3
+ import type { TBindingScope } from '@venizia/ignis-inversion';
4
+ import type { IArtifactRegistrationOptions } from './types/artifact.js';
5
+ /** What an application declares about an artifact type of its own: the binding namespace its classes get and the scope they bind with unless a class says otherwise. */
6
+ export interface IArtifactTypeDefinition {
7
+ type: string;
8
+ namespace: string;
9
+ scope: TBindingScope;
10
+ }
11
+ /** What a decorated class is to the application - the one fact the artifact generator and the registration methods both read. The seven constants are the built-in types; an application adds its own with `define`. */
4
12
  export declare class ArtifactTypes extends ConstClass {
13
+ #private;
5
14
  static readonly CONFIGURATION = "configuration";
6
15
  static readonly COMPONENT = "component";
7
16
  static readonly CONTROLLER = "controller";
@@ -9,6 +18,30 @@ export declare class ArtifactTypes extends ConstClass {
9
18
  static readonly REPOSITORY = "repository";
10
19
  static readonly DATASOURCE = "datasource";
11
20
  static readonly MODEL = "model";
21
+ /**
22
+ * Declares an artifact type of the application and returns its decorator: `@emitter()` registers the class like a
23
+ * stereotype does, in `namespace`, bound with `scope`. Declaring the same type again with the same namespace and scope
24
+ * (a module imported twice) changes nothing; with another one, it throws.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * export const emitter = ArtifactTypes.define({
29
+ * type: 'emitter',
30
+ * namespace: 'emitters',
31
+ * scope: BindingScopes.SINGLETON,
32
+ * });
33
+ *
34
+ * export @emitter()
35
+ * class OrderEmitter {}
36
+ * ```
37
+ */
38
+ static define(opts: IArtifactTypeDefinition): <ApplicationType = unknown>(registration?: IArtifactRegistrationOptions<ApplicationType>) => ClassDecorator;
39
+ /** The names of the types `define` recorded, in the order they were defined. */
40
+ static definedTypes(): string[];
41
+ /** The definition `define` recorded for `type`; `undefined` for a built-in type and for a name nobody defined. */
42
+ static definitionOf(opts: {
43
+ type: string;
44
+ }): IArtifactTypeDefinition | undefined;
12
45
  }
13
46
  /** The `format` of `getAuthorizeModelPrincipals` and `getAuthorizeModelSettings`: ARRAY or RECORD. */
14
47
  export declare class AuthorizeModelFormats extends ConstClass {
@@ -1,5 +1,9 @@
1
+ import { BindingNamespaces } from '../../../common/bindings.js';
1
2
  import { ConstClass } from '@venizia/ignis-helpers/common';
2
- /** What a decorated class is to the application - the one fact the artifact generator and the registration methods both read. */
3
+ import { getError } from '@venizia/ignis-helpers/core';
4
+ import { injectable } from '../../../base/metadata/injectable.js';
5
+ import { SingletonRealm } from '../../singleton-realm.js';
6
+ /** What a decorated class is to the application - the one fact the artifact generator and the registration methods both read. The seven constants are the built-in types; an application adds its own with `define`. */
3
7
  export class ArtifactTypes extends ConstClass {
4
8
  static { this.CONFIGURATION = 'configuration'; }
5
9
  static { this.COMPONENT = 'component'; }
@@ -8,6 +12,77 @@ export class ArtifactTypes extends ConstClass {
8
12
  static { this.REPOSITORY = 'repository'; }
9
13
  static { this.DATASOURCE = 'datasource'; }
10
14
  static { this.MODEL = 'model'; }
15
+ /**
16
+ * The types an application declared, on the realm and not on this module: a second copy of the kernel in one install
17
+ * shares them, as it shares the metadata registry. A true private member, so `values()` and `isValid` keep answering for
18
+ * the built-in types alone.
19
+ */
20
+ static #definitions() {
21
+ return SingletonRealm.resolve({
22
+ key: 'artifact-type-definitions',
23
+ create: () => new Map(),
24
+ });
25
+ }
26
+ /**
27
+ * Declares an artifact type of the application and returns its decorator: `@emitter()` registers the class like a
28
+ * stereotype does, in `namespace`, bound with `scope`. Declaring the same type again with the same namespace and scope
29
+ * (a module imported twice) changes nothing; with another one, it throws.
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * export const emitter = ArtifactTypes.define({
34
+ * type: 'emitter',
35
+ * namespace: 'emitters',
36
+ * scope: BindingScopes.SINGLETON,
37
+ * });
38
+ *
39
+ * export @emitter()
40
+ * class OrderEmitter {}
41
+ * ```
42
+ */
43
+ static define(opts) {
44
+ const { type, namespace, scope } = opts;
45
+ if (typeof type !== 'string' || !/^[^\s]+$/.test(type)) {
46
+ throw getError({
47
+ message: `[ArtifactTypes][define] Invalid type | Expected a non-empty name without whitespace | Got: '${type}'`,
48
+ });
49
+ }
50
+ if (ArtifactTypes.isValid(type)) {
51
+ throw getError({
52
+ message: `[ArtifactTypes][define] '${type}' is a built-in artifact type | Choose a name of your own`,
53
+ });
54
+ }
55
+ BindingNamespaces.createNamespace({ name: namespace });
56
+ if (BindingNamespaces.isBuiltIn({ name: namespace })) {
57
+ throw getError({
58
+ message: `[ArtifactTypes][define] '${namespace}' is the namespace of a built-in artifact type | type: '${type}' | Choose a namespace of your own`,
59
+ });
60
+ }
61
+ const sharing = [...ArtifactTypes.#definitions().values()].find((definition) => definition.namespace === namespace && definition.type !== type);
62
+ if (sharing) {
63
+ throw getError({
64
+ message: `[ArtifactTypes][define] '${namespace}' is already the namespace of the type '${sharing.type}' | type: '${type}' | A tag names one namespace, so two types in it could not be drained apart`,
65
+ });
66
+ }
67
+ const existing = ArtifactTypes.#definitions().get(type);
68
+ if (existing && (existing.namespace !== namespace || existing.scope !== scope)) {
69
+ throw getError({
70
+ message: `[ArtifactTypes][define] '${type}' is already defined with namespace '${existing.namespace}' and scope '${existing.scope}' | Got: namespace '${namespace}', scope '${scope}'`,
71
+ });
72
+ }
73
+ if (!existing) {
74
+ ArtifactTypes.#definitions().set(type, { type, namespace, scope });
75
+ }
76
+ return (registration) => injectable({ type, ...registration });
77
+ }
78
+ /** The names of the types `define` recorded, in the order they were defined. */
79
+ static definedTypes() {
80
+ return [...ArtifactTypes.#definitions().keys()];
81
+ }
82
+ /** The definition `define` recorded for `type`; `undefined` for a built-in type and for a name nobody defined. */
83
+ static definitionOf(opts) {
84
+ return ArtifactTypes.#definitions().get(opts.type);
85
+ }
11
86
  }
12
87
  /** The `format` of `getAuthorizeModelPrincipals` and `getAuthorizeModelSettings`: ARRAY or RECORD. */
13
88
  export class AuthorizeModelFormats extends ConstClass {
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/helpers/inversion/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAE3D,iIAAiI;AACjI,MAAM,OAAO,aAAc,SAAQ,UAAU;aAC3B,kBAAa,GAAG,eAAe,CAAC;aAChC,cAAS,GAAG,WAAW,CAAC;aACxB,eAAU,GAAG,YAAY,CAAC;aAC1B,YAAO,GAAG,SAAS,CAAC;aACpB,eAAU,GAAG,YAAY,CAAC;aAC1B,eAAU,GAAG,YAAY,CAAC;aAC1B,UAAK,GAAG,OAAO,CAAC;;AAGlC,sGAAsG;AACtG,MAAM,OAAO,qBAAsB,SAAQ,UAAU;aACnC,UAAK,GAAG,OAAO,CAAC;aAChB,WAAM,GAAG,QAAQ,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { ConstClass } from '@venizia/ignis-helpers/common';\n\n/** What a decorated class is to the application - the one fact the artifact generator and the registration methods both read. */\nexport class ArtifactTypes extends ConstClass {\n static readonly CONFIGURATION = 'configuration';\n static readonly COMPONENT = 'component';\n static readonly CONTROLLER = 'controller';\n static readonly SERVICE = 'service';\n static readonly REPOSITORY = 'repository';\n static readonly DATASOURCE = 'datasource';\n static readonly MODEL = 'model';\n}\n\n/** The `format` of `getAuthorizeModelPrincipals` and `getAuthorizeModelSettings`: ARRAY or RECORD. */\nexport class AuthorizeModelFormats extends ConstClass {\n static readonly ARRAY = 'array';\n static readonly RECORD = 'record';\n}\n\n/** Valid authorize model format values. */\nexport type TAuthorizeModelFormat = TConstValue<typeof AuthorizeModelFormats>;\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/helpers/inversion/common/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,OAAO,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AA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G,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACrD,CAAC;;AAGH,sGAAsG;AACtG,MAAM,OAAO,qBAAsB,SAAQ,UAAU;aACnC,UAAK,GAAG,OAAO,CAAC;aAChB,WAAM,GAAG,QAAQ,CAAC","sourcesContent":["import { BindingNamespaces } from '@/common/bindings';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { ConstClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { TBindingScope } from '@venizia/ignis-inversion';\nimport type { IArtifactRegistrationOptions } from './types/artifact';\nimport { injectable } from '@/base/metadata/injectable';\nimport { SingletonRealm } from '@/helpers/singleton-realm';\n\n/** What an application declares about an artifact type of its own: the binding namespace its classes get and the scope they bind with unless a class says otherwise. */\nexport interface IArtifactTypeDefinition {\n type: string;\n namespace: string;\n scope: TBindingScope;\n}\n\n/** What a decorated class is to the application - the one fact the artifact generator and the registration methods both read. The seven constants are the built-in types; an application adds its own with `define`. */\nexport class ArtifactTypes extends ConstClass {\n static readonly CONFIGURATION = 'configuration';\n static readonly COMPONENT = 'component';\n static readonly CONTROLLER = 'controller';\n static readonly SERVICE = 'service';\n static readonly REPOSITORY = 'repository';\n static readonly DATASOURCE = 'datasource';\n static readonly MODEL = 'model';\n\n /**\n * The types an application declared, on the realm and not on this module: a second copy of the kernel in one install\n * shares them, as it shares the metadata registry. A true private member, so `values()` and `isValid` keep answering for\n * the built-in types alone.\n */\n static #definitions(): Map<string, IArtifactTypeDefinition> {\n return SingletonRealm.resolve({\n key: 'artifact-type-definitions',\n create: () => new Map<string, IArtifactTypeDefinition>(),\n });\n }\n\n /**\n * Declares an artifact type of the application and returns its decorator: `@emitter()` registers the class like a\n * stereotype does, in `namespace`, bound with `scope`. Declaring the same type again with the same namespace and scope\n * (a module imported twice) changes nothing; with another one, it throws.\n *\n * @example\n * ```typescript\n * export const emitter = ArtifactTypes.define({\n * type: 'emitter',\n * namespace: 'emitters',\n * scope: BindingScopes.SINGLETON,\n * });\n *\n * export @emitter()\n * class OrderEmitter {}\n * ```\n */\n static define(opts: IArtifactTypeDefinition) {\n const { type, namespace, scope } = opts;\n\n if (typeof type !== 'string' || !/^[^\\s]+$/.test(type)) {\n throw getError({\n message: `[ArtifactTypes][define] Invalid type | Expected a non-empty name without whitespace | Got: '${type}'`,\n });\n }\n\n if (ArtifactTypes.isValid(type)) {\n throw getError({\n message: `[ArtifactTypes][define] '${type}' is a built-in artifact type | Choose a name of your own`,\n });\n }\n\n BindingNamespaces.createNamespace({ name: namespace });\n\n if (BindingNamespaces.isBuiltIn({ name: namespace })) {\n throw getError({\n message: `[ArtifactTypes][define] '${namespace}' is the namespace of a built-in artifact type | type: '${type}' | Choose a namespace of your own`,\n });\n }\n\n const sharing = [...ArtifactTypes.#definitions().values()].find(\n (definition) => definition.namespace === namespace && definition.type !== type,\n );\n\n if (sharing) {\n throw getError({\n message: `[ArtifactTypes][define] '${namespace}' is already the namespace of the type '${sharing.type}' | type: '${type}' | A tag names one namespace, so two types in it could not be drained apart`,\n });\n }\n\n const existing = ArtifactTypes.#definitions().get(type);\n\n if (existing && (existing.namespace !== namespace || existing.scope !== scope)) {\n throw getError({\n message: `[ArtifactTypes][define] '${type}' is already defined with namespace '${existing.namespace}' and scope '${existing.scope}' | Got: namespace '${namespace}', scope '${scope}'`,\n });\n }\n\n if (!existing) {\n ArtifactTypes.#definitions().set(type, { type, namespace, scope });\n }\n\n return <ApplicationType = unknown>(\n registration?: IArtifactRegistrationOptions<ApplicationType>,\n ): ClassDecorator => injectable<ApplicationType>({ type, ...registration });\n }\n\n /** The names of the types `define` recorded, in the order they were defined. */\n static definedTypes(): string[] {\n return [...ArtifactTypes.#definitions().keys()];\n }\n\n /** The definition `define` recorded for `type`; `undefined` for a built-in type and for a name nobody defined. */\n static definitionOf(opts: { type: string }): IArtifactTypeDefinition | undefined {\n return ArtifactTypes.#definitions().get(opts.type);\n }\n}\n\n/** The `format` of `getAuthorizeModelPrincipals` and `getAuthorizeModelSettings`: ARRAY or RECORD. */\nexport class AuthorizeModelFormats extends ConstClass {\n static readonly ARRAY = 'array';\n static readonly RECORD = 'record';\n}\n\n/** Valid authorize model format values. */\nexport type TAuthorizeModelFormat = TConstValue<typeof AuthorizeModelFormats>;\n"]}
@@ -27,9 +27,9 @@ export interface IArtifactRegistrationOptions<ApplicationType = unknown> {
27
27
  /** Topological ordering for configurations: must run after these configuration classes. */
28
28
  after?: ReadonlyArray<TClass<unknown>>;
29
29
  }
30
- /** Registration options of an artifact plus its `type`. */
30
+ /** Registration options of an artifact plus its `type`: a built-in one (`TArtifactType`) or one `ArtifactTypes.define` declared. */
31
31
  export interface IArtifactMetadata<ApplicationType = unknown> extends IArtifactRegistrationOptions<ApplicationType> {
32
- type: TArtifactType;
32
+ type: TArtifactType | (string & {});
33
33
  }
34
34
  /** One `@provide` method: the key it binds, and the binding scope of the value. */
35
35
  export interface IProvideMetadata {
@@ -1 +1 @@
1
- {"version":3,"file":"artifact.js","sourceRoot":"","sources":["../../../../../../src/helpers/inversion/common/types/artifact.ts"],"names":[],"mappings":"","sourcesContent":["import type { TClass, TConstValue, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { TBindingKey, TBindingScope } from '@venizia/ignis-inversion';\nimport { type ArtifactTypes } from '../constants';\n\n/** Decorator target for any constructable class (includes Function for ClassDecorator). */\nexport type TDecoratorTarget<T = unknown> = TClass<T> | Function;\n\n/** Valid `ArtifactTypes` values. */\nexport type TArtifactType = TConstValue<typeof ArtifactTypes>;\n\n/** Decides at registration time whether the class is registered at all. Sync or async; runs before `preConfigure`, so it may read config and env, never another artifact's binding. */\nexport type TArtifactCondition<ApplicationType = unknown> = (opts: {\n application: ApplicationType;\n}) => ValueOrPromise<boolean>;\n\n/** Registration defaults a class carries for itself; an explicit `TMixinOpts` at the call site still wins. */\nexport interface IArtifactRegistrationOptions<ApplicationType = unknown> {\n binding?: { namespace: string; key: string };\n allowOverride?: boolean;\n scope?: TBindingScope;\n /**\n * Lower registers first within its kind; ties keep index order.\n *\n * @default 0\n */\n order?: number;\n when?: TArtifactCondition<ApplicationType>;\n /** Topological ordering for configurations: must run after these configuration classes. */\n after?: ReadonlyArray<TClass<unknown>>;\n}\n\n/** Registration options of an artifact plus its `type`. */\nexport interface IArtifactMetadata<\n ApplicationType = unknown,\n> extends IArtifactRegistrationOptions<ApplicationType> {\n type: TArtifactType;\n}\n\n/** One `@provide` method: the key it binds, and the binding scope of the value. */\nexport interface IProvideMetadata {\n methodName: string | symbol;\n key: TBindingKey;\n\n /** @default BindingScopes.SINGLETON */\n scope?: TBindingScope;\n}\n"]}
1
+ {"version":3,"file":"artifact.js","sourceRoot":"","sources":["../../../../../../src/helpers/inversion/common/types/artifact.ts"],"names":[],"mappings":"","sourcesContent":["import type { TClass, TConstValue, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { TBindingKey, TBindingScope } from '@venizia/ignis-inversion';\nimport { type ArtifactTypes } from '../constants';\n\n/** Decorator target for any constructable class (includes Function for ClassDecorator). */\nexport type TDecoratorTarget<T = unknown> = TClass<T> | Function;\n\n/** Valid `ArtifactTypes` values. */\nexport type TArtifactType = TConstValue<typeof ArtifactTypes>;\n\n/** Decides at registration time whether the class is registered at all. Sync or async; runs before `preConfigure`, so it may read config and env, never another artifact's binding. */\nexport type TArtifactCondition<ApplicationType = unknown> = (opts: {\n application: ApplicationType;\n}) => ValueOrPromise<boolean>;\n\n/** Registration defaults a class carries for itself; an explicit `TMixinOpts` at the call site still wins. */\nexport interface IArtifactRegistrationOptions<ApplicationType = unknown> {\n binding?: { namespace: string; key: string };\n allowOverride?: boolean;\n scope?: TBindingScope;\n /**\n * Lower registers first within its kind; ties keep index order.\n *\n * @default 0\n */\n order?: number;\n when?: TArtifactCondition<ApplicationType>;\n /** Topological ordering for configurations: must run after these configuration classes. */\n after?: ReadonlyArray<TClass<unknown>>;\n}\n\n/** Registration options of an artifact plus its `type`: a built-in one (`TArtifactType`) or one `ArtifactTypes.define` declared. */\nexport interface IArtifactMetadata<\n ApplicationType = unknown,\n> extends IArtifactRegistrationOptions<ApplicationType> {\n type: TArtifactType | (string & {});\n}\n\n/** One `@provide` method: the key it binds, and the binding scope of the value. */\nexport interface IProvideMetadata {\n methodName: string | symbol;\n key: TBindingKey;\n\n /** @default BindingScopes.SINGLETON */\n scope?: TBindingScope;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-kernel",
3
- "version": "0.5.0-6",
3
+ "version": "0.5.0-7",
4
4
  "description": "Browser-pure kernel of the IGNIS framework: dependency injection, lifecycle, REST controllers, repository and datasource abstractions, and the authentication and authorization seams. No node builtin and no server-only peer, so the same kernel serves a Bun server and a browser Worker.",
5
5
  "keywords": [
6
6
  "authentication",
@@ -73,9 +73,9 @@
73
73
  "force-update": "sh ../../scripts/build/force-update.sh"
74
74
  },
75
75
  "dependencies": {
76
- "@venizia/ignis-filter": "0.5.0-2",
77
- "@venizia/ignis-helpers": "0.5.0-5",
78
- "@venizia/ignis-inversion": "0.5.0-2",
76
+ "@venizia/ignis-filter": "0.5.0-3",
77
+ "@venizia/ignis-helpers": "0.5.0-6",
78
+ "@venizia/ignis-inversion": "0.5.0-3",
79
79
  "reflect-metadata": "^0.2.2"
80
80
  },
81
81
  "devDependencies": {