@kanjijs/store 0.2.0-beta.2 → 0.2.0-beta.20

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.
@@ -0,0 +1,27 @@
1
+ export type SchemaLike = unknown;
2
+ export interface ContractRequestSpec<T = SchemaLike> {
3
+ params?: T;
4
+ query?: T;
5
+ headers?: T;
6
+ cookies?: T;
7
+ body?: T;
8
+ }
9
+ export interface ContractResponseSpec<T = SchemaLike> {
10
+ [status: number]: T;
11
+ }
12
+ export interface ContractSpec<T = SchemaLike> {
13
+ request?: ContractRequestSpec<T>;
14
+ response?: ContractResponseSpec<T>;
15
+ }
16
+ export interface ValidatorAdapter<S = SchemaLike> {
17
+ parse<O = unknown>(schema: S, data: unknown): Promise<{
18
+ success: true;
19
+ data: O;
20
+ } | {
21
+ success: false;
22
+ issues: unknown[];
23
+ }>;
24
+ }
25
+ export declare class Contract {
26
+ static json<T = SchemaLike>(spec: ContractRequestSpec<T>): ContractSpec<T>;
27
+ }
@@ -0,0 +1,7 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ export interface RequestContext {
3
+ requestId: string;
4
+ [key: string]: any;
5
+ }
6
+ export declare const kanjijsContext: AsyncLocalStorage<RequestContext>;
7
+ export declare function getRequestId(): string | undefined;
@@ -0,0 +1,34 @@
1
+ import type { ContractSpec } from "@kanjijs/contracts";
2
+ import { type ModuleMetadata, type Token } from "./metadata";
3
+ /**
4
+ * @Module({ controllers: [...] })
5
+ */
6
+ export declare function Module(metadata: ModuleMetadata): ClassDecorator;
7
+ /**
8
+ * @Contract({ ... })
9
+ */
10
+ export declare function Contract(spec: ContractSpec): MethodDecorator;
11
+ /**
12
+ * @Controller('/users')
13
+ */
14
+ export declare function Controller(prefix?: string): ClassDecorator;
15
+ export declare function Injectable(): ClassDecorator;
16
+ export declare const Get: (path?: string) => MethodDecorator;
17
+ export declare const Post: (path?: string) => MethodDecorator;
18
+ export declare const Put: (path?: string) => MethodDecorator;
19
+ export declare const Delete: (path?: string) => MethodDecorator;
20
+ export declare const Patch: (path?: string) => MethodDecorator;
21
+ /**
22
+ * @Inject("DATABASE_CLIENT")
23
+ */
24
+ export declare function Inject(token: Token<unknown>): ParameterDecorator;
25
+ /**
26
+ * @Use(middleware1, middleware2)
27
+ * Attaches middlewares to a controller or method.
28
+ */
29
+ export declare function Use(...middlewares: unknown[]): MethodDecorator & ClassDecorator;
30
+ export declare const Body: (data?: string) => ParameterDecorator;
31
+ export declare const Query: (data?: string) => ParameterDecorator;
32
+ export declare const Param: (data?: string) => ParameterDecorator;
33
+ export declare const Headers: (data?: string) => ParameterDecorator;
34
+ export declare const Ctx: (data?: string) => ParameterDecorator;
@@ -0,0 +1,26 @@
1
+ import { type Constructor, type Token } from "../metadata";
2
+ import "reflect-metadata";
3
+ export declare class KanjijsIoC {
4
+ private static providers;
5
+ static register<T>(target: Constructor<T>): void;
6
+ static register<T>(token: Token<T>, provider: {
7
+ useValue?: T;
8
+ useClass?: Constructor<T>;
9
+ }): void;
10
+ static resolve<T>(target: Token<T>): T;
11
+ static clear(): void;
12
+ }
13
+ /**
14
+ * V2 STRICT CONTAINER
15
+ * Instance-based, no auto-registration, explicit visibility.
16
+ */
17
+ export declare class Container {
18
+ private providers;
19
+ register<T>(token: Token<T>, provider: {
20
+ useValue?: T;
21
+ useClass?: Constructor<T>;
22
+ useFactory?: (...args: unknown[]) => T;
23
+ inject?: Array<Token<unknown>>;
24
+ }): void;
25
+ resolve<T>(token: Token<T>): T;
26
+ }
@@ -0,0 +1,12 @@
1
+ import { type Constructor } from "../metadata";
2
+ import { Container } from "./container";
3
+ export declare class ModuleCompiler {
4
+ private nodes;
5
+ private globalExportedTokens;
6
+ compile(rootModule: Constructor): Container;
7
+ private scan;
8
+ private processProviders;
9
+ private validate;
10
+ private checkDependencies;
11
+ private registerProviders;
12
+ }
@@ -0,0 +1,3 @@
1
+ export interface ExceptionFilter<T = any, C = any> {
2
+ catch(exception: T, context: C): void | Promise<void> | any;
3
+ }
@@ -0,0 +1,7 @@
1
+ export declare class HttpException extends Error {
2
+ readonly response: string | object;
3
+ readonly status: number;
4
+ constructor(response: string | object, status: number);
5
+ getResponse(): string | object;
6
+ getStatus(): number;
7
+ }
@@ -0,0 +1,9 @@
1
+ export type { ContractRequestSpec, ContractResponseSpec, ContractSpec, SchemaLike, ValidatorAdapter, } from "@kanjijs/contracts";
2
+ export * from "./context";
3
+ export * from "./decorators";
4
+ export * from "./di/container";
5
+ export * from "./di/module-compiler";
6
+ export * from "./exceptions/exception.filter";
7
+ export * from "./exceptions/http.exception";
8
+ export * from "./metadata";
9
+ export declare const GLOBAL_MIDDLEWARE_TOKEN: unique symbol;
@@ -0,0 +1,64 @@
1
+ import type { ContractSpec } from "@kanjijs/contracts";
2
+ import "reflect-metadata";
3
+ export type Constructor<T = unknown> = new (...args: unknown[]) => T;
4
+ export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
5
+ export type RouteParamType = "BODY" | "QUERY" | "PARAM" | "HEADERS" | "CONTEXT";
6
+ export interface RouteParamMetadata {
7
+ index: number;
8
+ type: RouteParamType;
9
+ data?: string;
10
+ }
11
+ export interface RouteMetadata {
12
+ method: HttpMethod;
13
+ path: string;
14
+ contract?: ContractSpec;
15
+ middlewares?: unknown[];
16
+ params?: RouteParamMetadata[];
17
+ }
18
+ export interface ControllerMetadata {
19
+ prefix: string;
20
+ middlewares?: unknown[];
21
+ }
22
+ export type Token<T = unknown> = string | symbol | Constructor<T>;
23
+ export type Provider<T = unknown> = Constructor<T> | {
24
+ provide: Token<T>;
25
+ useValue: T;
26
+ } | {
27
+ provide: Token<T>;
28
+ useClass: Constructor<T>;
29
+ } | {
30
+ provide: Token<T>;
31
+ useFactory: (...args: unknown[]) => T | Promise<T>;
32
+ inject?: Token[];
33
+ };
34
+ export interface DynamicModule {
35
+ module: Constructor;
36
+ providers?: Provider[];
37
+ imports?: Array<Constructor | DynamicModule>;
38
+ exports?: Token[];
39
+ global?: boolean;
40
+ }
41
+ export interface ModuleMetadata {
42
+ controllers?: Constructor[];
43
+ providers?: Provider[];
44
+ imports?: Array<Constructor | DynamicModule>;
45
+ exports?: Token[];
46
+ global?: boolean;
47
+ }
48
+ export interface IMetadataStorage {
49
+ addRoute(target: object, methodName: string, meta: RouteMetadata): void;
50
+ addContract(target: object, methodName: string, contract: ContractSpec): void;
51
+ addMiddleware(target: object, middleware: unknown, methodName?: string): void;
52
+ getRoutes(target: object): Map<string, RouteMetadata> | undefined;
53
+ setController(target: object, meta: ControllerMetadata): void;
54
+ getController(target: object): ControllerMetadata | undefined;
55
+ defineModule(target: object, meta: ModuleMetadata): void;
56
+ getModule(target: object): ModuleMetadata | undefined;
57
+ addInjection(target: object, index: number, token: Token<unknown>): void;
58
+ getInjections(target: object): Map<number, Token<unknown>> | undefined;
59
+ addRouteParam(target: object, methodName: string, param: RouteParamMetadata): void;
60
+ }
61
+ declare global {
62
+ var KANJI_METADATA_STORAGE: IMetadataStorage | undefined;
63
+ }
64
+ export declare const MetadataStorage: IMetadataStorage;
@@ -0,0 +1,12 @@
1
+ import { type DynamicModule } from "@kanjijs/core";
2
+ import { drizzle } from "drizzle-orm/postgres-js";
3
+ export declare const DATABASE_CLIENT: unique symbol;
4
+ export interface StoreModuleOptions {
5
+ url: string;
6
+ schema?: Record<string, unknown>;
7
+ }
8
+ export declare const InjectDb: () => ParameterDecorator;
9
+ export type DrizzleDb = ReturnType<typeof drizzle>;
10
+ export declare class StoreModule {
11
+ static forRoot(options: StoreModuleOptions): DynamicModule;
12
+ }
package/dist/index.js CHANGED
@@ -1,17 +1,4 @@
1
1
  // @bun
2
- var __legacyDecorateClassTS = function(decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
5
- r = Reflect.decorate(decorators, target, key, desc);
6
- else
7
- for (var i = decorators.length - 1;i >= 0; i--)
8
- if (d = decorators[i])
9
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
10
- return c > 3 && r && Object.defineProperty(target, key, r), r;
11
- };
12
-
13
- // ../core/dist/index.js
14
- import { AsyncLocalStorage } from "async_hooks";
15
2
  var __create = Object.create;
16
3
  var __getProtoOf = Object.getPrototypeOf;
17
4
  var __defProp = Object.defineProperty;
@@ -29,21 +16,33 @@ var __toESM = (mod, isNodeMode, target) => {
29
16
  return to;
30
17
  };
31
18
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
20
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
22
+ r = Reflect.decorate(decorators, target, key, desc);
23
+ else
24
+ for (var i = decorators.length - 1;i >= 0; i--)
25
+ if (d = decorators[i])
26
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
27
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
28
+ };
29
+
30
+ // ../../node_modules/.bun/reflect-metadata@0.2.2/node_modules/reflect-metadata/Reflect.js
32
31
  var require_Reflect = __commonJS(() => {
33
32
  /*! *****************************************************************************
34
- Copyright (C) Microsoft. All rights reserved.
35
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
36
- this file except in compliance with the License. You may obtain a copy of the
37
- License at http://www.apache.org/licenses/LICENSE-2.0
38
-
39
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
40
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
41
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
42
- MERCHANTABLITY OR NON-INFRINGEMENT.
43
-
44
- See the Apache Version 2.0 License for specific language governing permissions
45
- and limitations under the License.
46
- ***************************************************************************** */
33
+ Copyright (C) Microsoft. All rights reserved.
34
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
35
+ this file except in compliance with the License. You may obtain a copy of the
36
+ License at http://www.apache.org/licenses/LICENSE-2.0
37
+
38
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
39
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
40
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
41
+ MERCHANTABLITY OR NON-INFRINGEMENT.
42
+
43
+ See the Apache Version 2.0 License for specific language governing permissions
44
+ and limitations under the License.
45
+ ***************************************************************************** */
47
46
  var Reflect2;
48
47
  (function(Reflect3) {
49
48
  (function(factory) {
@@ -1023,74 +1022,95 @@ var require_Reflect = __commonJS(() => {
1023
1022
  });
1024
1023
  })(Reflect2 || (Reflect2 = {}));
1025
1024
  });
1025
+
1026
+ // ../core/src/context.ts
1027
+ import { AsyncLocalStorage } from "async_hooks";
1028
+ var kanjijsContext = new AsyncLocalStorage;
1029
+ // ../core/src/metadata.ts
1026
1030
  var import_reflect_metadata = __toESM(require_Reflect(), 1);
1027
1031
  var methodMetadataStore = new WeakMap;
1028
1032
  var controllerMetadataStore = new WeakMap;
1029
1033
  var moduleMetadataStore = new WeakMap;
1030
1034
  var injectionMetadataStore = new WeakMap;
1031
- var MetadataStorage = {
1032
- addRoute(target, methodName, meta) {
1033
- let methods = methodMetadataStore.get(target);
1034
- if (!methods) {
1035
- methods = new Map;
1036
- methodMetadataStore.set(target, methods);
1037
- }
1038
- const existing = methods.get(methodName) || {};
1039
- methods.set(methodName, { ...existing, ...meta });
1040
- },
1041
- addContract(target, methodName, contract) {
1042
- let methods = methodMetadataStore.get(target);
1043
- if (!methods) {
1044
- methods = new Map;
1045
- methodMetadataStore.set(target, methods);
1046
- }
1047
- const existing = methods.get(methodName) || {};
1048
- existing.contract = contract;
1049
- methods.set(methodName, existing);
1050
- },
1051
- addMiddleware(target, middleware, methodName) {
1052
- if (methodName) {
1035
+ var globalStore = globalThis;
1036
+ if (!globalStore.KANJI_METADATA_STORAGE) {
1037
+ globalStore.KANJI_METADATA_STORAGE = {
1038
+ addRoute(target, methodName, meta) {
1053
1039
  let methods = methodMetadataStore.get(target);
1054
1040
  if (!methods) {
1055
1041
  methods = new Map;
1056
1042
  methodMetadataStore.set(target, methods);
1057
1043
  }
1058
1044
  const existing = methods.get(methodName) || {};
1059
- existing.middlewares = [...existing.middlewares || [], middleware];
1045
+ methods.set(methodName, { ...existing, ...meta });
1046
+ },
1047
+ addContract(target, methodName, contract) {
1048
+ let methods = methodMetadataStore.get(target);
1049
+ if (!methods) {
1050
+ methods = new Map;
1051
+ methodMetadataStore.set(target, methods);
1052
+ }
1053
+ const existing = methods.get(methodName) || {};
1054
+ existing.contract = contract;
1060
1055
  methods.set(methodName, existing);
1061
- } else {
1062
- const existing = controllerMetadataStore.get(target) || { prefix: "/" };
1063
- existing.middlewares = [...existing.middlewares || [], middleware];
1064
- controllerMetadataStore.set(target, existing);
1065
- }
1066
- },
1067
- getRoutes(target) {
1068
- return methodMetadataStore.get(target);
1069
- },
1070
- setController(target, meta) {
1071
- controllerMetadataStore.set(target, meta);
1072
- },
1073
- getController(target) {
1074
- return controllerMetadataStore.get(target);
1075
- },
1076
- defineModule(target, meta) {
1077
- moduleMetadataStore.set(target, meta);
1078
- },
1079
- getModule(target) {
1080
- return moduleMetadataStore.get(target);
1081
- },
1082
- addInjection(target, index, token) {
1083
- let injections = injectionMetadataStore.get(target);
1084
- if (!injections) {
1085
- injections = new Map;
1086
- injectionMetadataStore.set(target, injections);
1056
+ },
1057
+ addRouteParam(target, methodName, param) {
1058
+ let methods = methodMetadataStore.get(target);
1059
+ if (!methods) {
1060
+ methods = new Map;
1061
+ methodMetadataStore.set(target, methods);
1062
+ }
1063
+ const existing = methods.get(methodName) || {};
1064
+ existing.params = [...existing.params || [], param];
1065
+ methods.set(methodName, existing);
1066
+ },
1067
+ addMiddleware(target, middleware, methodName) {
1068
+ if (methodName) {
1069
+ let methods = methodMetadataStore.get(target);
1070
+ if (!methods) {
1071
+ methods = new Map;
1072
+ methodMetadataStore.set(target, methods);
1073
+ }
1074
+ const existing = methods.get(methodName) || {};
1075
+ existing.middlewares = [...existing.middlewares || [], middleware];
1076
+ methods.set(methodName, existing);
1077
+ } else {
1078
+ const existing = controllerMetadataStore.get(target) || { prefix: "/" };
1079
+ existing.middlewares = [...existing.middlewares || [], middleware];
1080
+ controllerMetadataStore.set(target, existing);
1081
+ }
1082
+ },
1083
+ getRoutes(target) {
1084
+ return methodMetadataStore.get(target);
1085
+ },
1086
+ setController(target, meta) {
1087
+ controllerMetadataStore.set(target, meta);
1088
+ },
1089
+ getController(target) {
1090
+ return controllerMetadataStore.get(target);
1091
+ },
1092
+ defineModule(target, meta) {
1093
+ moduleMetadataStore.set(target, meta);
1094
+ },
1095
+ getModule(target) {
1096
+ return moduleMetadataStore.get(target);
1097
+ },
1098
+ addInjection(target, index, token) {
1099
+ let injections = injectionMetadataStore.get(target);
1100
+ if (!injections) {
1101
+ injections = new Map;
1102
+ injectionMetadataStore.set(target, injections);
1103
+ }
1104
+ injections.set(index, token);
1105
+ },
1106
+ getInjections(target) {
1107
+ return injectionMetadataStore.get(target);
1087
1108
  }
1088
- injections.set(index, token);
1089
- },
1090
- getInjections(target) {
1091
- return injectionMetadataStore.get(target);
1092
- }
1093
- };
1109
+ };
1110
+ }
1111
+ var MetadataStorage = globalStore.KANJI_METADATA_STORAGE;
1112
+
1113
+ // ../core/src/decorators.ts
1094
1114
  function Module(metadata) {
1095
1115
  return (target) => {
1096
1116
  MetadataStorage.defineModule(target, metadata);
@@ -1112,10 +1132,29 @@ var Put = createMethodDecorator("PUT");
1112
1132
  var Delete = createMethodDecorator("DELETE");
1113
1133
  var Patch = createMethodDecorator("PATCH");
1114
1134
  function Inject(token) {
1115
- return (target, propertyKey, parameterIndex) => {
1135
+ return (target, _propertyKey, parameterIndex) => {
1116
1136
  MetadataStorage.addInjection(target, parameterIndex, token);
1117
1137
  };
1118
1138
  }
1139
+ function createParamDecorator(type) {
1140
+ return (data) => {
1141
+ return (target, propertyKey, parameterIndex) => {
1142
+ if (propertyKey) {
1143
+ MetadataStorage.addRouteParam(target, propertyKey, {
1144
+ index: parameterIndex,
1145
+ type,
1146
+ data
1147
+ });
1148
+ }
1149
+ };
1150
+ };
1151
+ }
1152
+ var Body = createParamDecorator("BODY");
1153
+ var Query = createParamDecorator("QUERY");
1154
+ var Param = createParamDecorator("PARAM");
1155
+ var Headers = createParamDecorator("HEADERS");
1156
+ var Ctx = createParamDecorator("CONTEXT");
1157
+ // ../core/src/di/container.ts
1119
1158
  var import_reflect_metadata2 = __toESM(require_Reflect(), 1);
1120
1159
 
1121
1160
  class KanjijsIoC {
@@ -1123,43 +1162,48 @@ class KanjijsIoC {
1123
1162
  static register(tokenOrTarget, provider) {
1124
1163
  if (provider) {
1125
1164
  if ("useValue" in provider) {
1126
- this.providers.set(tokenOrTarget, { useValue: provider.useValue });
1165
+ KanjijsIoC.providers.set(tokenOrTarget, { useValue: provider.useValue });
1127
1166
  } else if ("useClass" in provider) {
1128
- this.providers.set(tokenOrTarget, { useClass: provider.useClass });
1167
+ KanjijsIoC.providers.set(tokenOrTarget, { useClass: provider.useClass });
1129
1168
  }
1130
1169
  } else {
1131
- this.providers.set(tokenOrTarget, { useClass: tokenOrTarget });
1170
+ KanjijsIoC.providers.set(tokenOrTarget, {
1171
+ useClass: tokenOrTarget
1172
+ });
1132
1173
  }
1133
1174
  }
1134
1175
  static resolve(target) {
1135
- let provider = this.providers.get(target);
1176
+ let provider = KanjijsIoC.providers.get(target);
1136
1177
  if (!provider && typeof target === "function") {
1137
1178
  provider = { useClass: target };
1138
- this.providers.set(target, provider);
1179
+ KanjijsIoC.providers.set(target, provider);
1139
1180
  }
1140
1181
  if (!provider) {
1141
- throw new Error(`Provider not found for token: ${target?.name || target}`);
1182
+ const targetName2 = typeof target === "function" ? target.name ?? "anonymous" : String(target);
1183
+ throw new Error(`Provider not found for token: ${targetName2}`);
1142
1184
  }
1143
1185
  if (provider.instance) {
1144
1186
  return provider.instance;
1145
1187
  }
1146
- console.log(`[DI] Creating NEW instance for ${target?.name || String(target)}`);
1188
+ const targetName = typeof target === "function" ? target.name ?? "anonymous" : String(target);
1189
+ console.log(`[DI] Creating NEW instance for ${targetName}`);
1147
1190
  if (provider.useValue !== undefined) {
1148
1191
  provider.instance = provider.useValue;
1149
1192
  } else if (provider.useClass) {
1150
1193
  const ConcreteClass = provider.useClass;
1151
1194
  const paramTypes = Reflect.getMetadata("design:paramtypes", ConcreteClass) || [];
1152
1195
  const injectionTokens = MetadataStorage.getInjections(ConcreteClass) || new Map;
1153
- const injections = paramTypes.map((token, index) => {
1196
+ const injections = paramTypes.map((paramToken, index) => {
1154
1197
  const overrideToken = injectionTokens.get(index);
1155
- return KanjijsIoC.resolve(overrideToken || token);
1198
+ const resolvedToken = overrideToken || paramToken;
1199
+ return KanjijsIoC.resolve(resolvedToken);
1156
1200
  });
1157
1201
  provider.instance = new ConcreteClass(...injections);
1158
1202
  }
1159
1203
  return provider.instance;
1160
1204
  }
1161
1205
  static clear() {
1162
- this.providers.clear();
1206
+ KanjijsIoC.providers.clear();
1163
1207
  }
1164
1208
  }
1165
1209
 
@@ -1171,7 +1215,8 @@ class Container {
1171
1215
  resolve(token) {
1172
1216
  const provider = this.providers.get(token);
1173
1217
  if (!provider) {
1174
- throw new Error(`[DI] Provider not found for token: ${token?.name || String(token)}`);
1218
+ const tokenName = typeof token === "function" ? token.name ?? "anonymous" : String(token);
1219
+ throw new Error(`[DI] Provider not found for token: ${tokenName}`);
1175
1220
  }
1176
1221
  if (provider.instance) {
1177
1222
  return provider.instance;
@@ -1184,7 +1229,8 @@ class Container {
1184
1229
  const injectionTokens = MetadataStorage.getInjections(ConcreteClass) || new Map;
1185
1230
  const injections = paramTypes.map((paramToken, index) => {
1186
1231
  const overrideToken = injectionTokens.get(index);
1187
- return this.resolve(overrideToken || paramToken);
1232
+ const resolvedToken = overrideToken || paramToken;
1233
+ return this.resolve(resolvedToken);
1188
1234
  });
1189
1235
  provider.instance = new ConcreteClass(...injections);
1190
1236
  } else if (provider.useFactory) {
@@ -1194,7 +1240,7 @@ class Container {
1194
1240
  return provider.instance;
1195
1241
  }
1196
1242
  }
1197
- var kanjijsContext = new AsyncLocalStorage;
1243
+ // ../core/src/di/module-compiler.ts
1198
1244
  class ModuleCompiler {
1199
1245
  nodes = new Map;
1200
1246
  globalExportedTokens = new Set;
@@ -1202,11 +1248,11 @@ class ModuleCompiler {
1202
1248
  this.scan(rootModule);
1203
1249
  this.validate();
1204
1250
  const container = new Container;
1205
- for (const node of this.nodes.values()) {
1206
- for (const [token, provider] of node.providers) {
1207
- container.register(token, provider);
1208
- }
1251
+ const rootNode = this.nodes.get(rootModule);
1252
+ if (!rootNode) {
1253
+ return container;
1209
1254
  }
1255
+ this.registerProviders(rootNode, container, new Set);
1210
1256
  return container;
1211
1257
  }
1212
1258
  scan(target) {
@@ -1223,20 +1269,20 @@ class ModuleCompiler {
1223
1269
  };
1224
1270
  this.nodes.set(moduleClass, node);
1225
1271
  const meta = MetadataStorage.getModule(moduleClass) || {};
1226
- const dynamicMeta = "module" in target ? target : {};
1227
- const allProviders = [...meta.providers || [], ...dynamicMeta.providers || []];
1272
+ const dynamicMeta = "module" in target ? target : undefined;
1273
+ const allProviders = [...meta.providers || [], ...dynamicMeta?.providers || []];
1228
1274
  this.processProviders(node, allProviders);
1229
- const allExports = [...meta.exports || [], ...dynamicMeta.exports || []];
1275
+ const allExports = [...meta.exports || [], ...dynamicMeta?.exports || []];
1230
1276
  for (const token of allExports) {
1231
1277
  node.exports.add(token);
1232
1278
  }
1233
- if (meta.global || dynamicMeta.global) {
1279
+ if (meta.global || dynamicMeta?.global) {
1234
1280
  node.isGlobal = true;
1235
1281
  for (const token of node.exports) {
1236
1282
  this.globalExportedTokens.add(token);
1237
1283
  }
1238
1284
  }
1239
- const allImports = [...meta.imports || [], ...dynamicMeta.imports || []];
1285
+ const allImports = [...meta.imports || [], ...dynamicMeta?.imports || []];
1240
1286
  for (const imp of allImports) {
1241
1287
  const importedNode = this.scan(imp);
1242
1288
  node.imports.add(importedNode);
@@ -1275,7 +1321,7 @@ class ModuleCompiler {
1275
1321
  for (const globalToken of this.globalExportedTokens) {
1276
1322
  visibleTokens.add(globalToken);
1277
1323
  }
1278
- for (const [token, provider] of node.providers) {
1324
+ for (const [_token, provider] of node.providers) {
1279
1325
  this.checkDependencies(provider, visibleTokens, node.module.name);
1280
1326
  }
1281
1327
  }
@@ -1288,19 +1334,36 @@ class ModuleCompiler {
1288
1334
  targetName = clazz.name;
1289
1335
  const paramTypes = Reflect.getMetadata("design:paramtypes", clazz) || [];
1290
1336
  const injectionTokens = MetadataStorage.getInjections(clazz) || new Map;
1291
- dependencies = paramTypes.map((t, i) => injectionTokens.get(i) || t);
1292
- } else if ("useFactory" in provider && provider.useFactory) {
1293
- targetName = provider.provide?.name || String(provider.provide);
1337
+ dependencies = paramTypes.map((paramType, index) => {
1338
+ const overrideToken = injectionTokens.get(index);
1339
+ return overrideToken || paramType;
1340
+ });
1341
+ } else if ("useFactory" in provider) {
1342
+ targetName = typeof provider.provide === "function" ? provider.provide.name ?? "anonymous" : String(provider.provide);
1294
1343
  dependencies = provider.inject || [];
1295
1344
  }
1296
1345
  for (const dep of dependencies) {
1297
1346
  if (!visibleTokens.has(dep)) {
1298
- const depName = dep?.name || String(dep);
1347
+ const depName = typeof dep === "function" ? dep.name ?? "anonymous" : String(dep);
1299
1348
  throw new Error(`[Kanjijs] strict-di-error: Provider '${targetName}' in Module '${moduleName}' ` + `depends on '${depName}', but it is not visible. ` + `Make sure it is imported and exported by the source module.`);
1300
1349
  }
1301
1350
  }
1302
1351
  }
1352
+ registerProviders(node, container, visited) {
1353
+ if (visited.has(node))
1354
+ return;
1355
+ visited.add(node);
1356
+ for (const imp of node.imports) {
1357
+ this.registerProviders(imp, container, visited);
1358
+ }
1359
+ for (const [token, provider] of node.providers) {
1360
+ const { provide: _provide, ...definition } = provider;
1361
+ container.register(token, definition);
1362
+ }
1363
+ }
1303
1364
  }
1365
+
1366
+ // ../core/src/index.ts
1304
1367
  var GLOBAL_MIDDLEWARE_TOKEN = Symbol("GLOBAL_MIDDLEWARE_TOKEN");
1305
1368
 
1306
1369
  // ../../node_modules/.bun/drizzle-orm@0.30.10+45912b99425c1f32/node_modules/drizzle-orm/entity.js
@@ -1676,7 +1739,7 @@ class SQL {
1676
1739
  params: []
1677
1740
  };
1678
1741
  }
1679
- if (is(chunk, Param)) {
1742
+ if (is(chunk, Param2)) {
1680
1743
  const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
1681
1744
  if (is(mappedValue, SQL)) {
1682
1745
  return this.buildQueryFromSourceParams([mappedValue], config);
@@ -1791,7 +1854,7 @@ var noopMapper = {
1791
1854
  ...noopEncoder
1792
1855
  };
1793
1856
 
1794
- class Param {
1857
+ class Param2 {
1795
1858
  constructor(value, encoder = noopEncoder) {
1796
1859
  this.value = value;
1797
1860
  this.encoder = encoder;
@@ -1845,7 +1908,7 @@ function sql(strings, ...params) {
1845
1908
  }
1846
1909
  sql2.placeholder = placeholder2;
1847
1910
  function param2(value, encoder) {
1848
- return new Param(value, encoder);
1911
+ return new Param2(value, encoder);
1849
1912
  }
1850
1913
  sql2.param = param2;
1851
1914
  })(sql || (sql = {}));
@@ -1994,7 +2057,7 @@ function mapUpdateSet(table, values) {
1994
2057
  if (is(value, SQL)) {
1995
2058
  return [key, value];
1996
2059
  } else {
1997
- return [key, new Param(value, table[Table.Symbol.Columns][key])];
2060
+ return [key, new Param2(value, table[Table.Symbol.Columns][key])];
1998
2061
  }
1999
2062
  });
2000
2063
  if (entries.length === 0) {
@@ -2080,7 +2143,7 @@ class PgInsertBuilder {
2080
2143
  const cols = this.table[Table.Symbol.Columns];
2081
2144
  for (const colKey of Object.keys(entry)) {
2082
2145
  const colValue = entry[colKey];
2083
- result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
2146
+ result[colKey] = is(colValue, SQL) ? colValue : new Param2(colValue, cols[colKey]);
2084
2147
  }
2085
2148
  return result;
2086
2149
  });
@@ -2425,8 +2488,8 @@ class PrimaryKey {
2425
2488
 
2426
2489
  // ../../node_modules/.bun/drizzle-orm@0.30.10+45912b99425c1f32/node_modules/drizzle-orm/sql/expressions/conditions.js
2427
2490
  function bindIfParam(value, column) {
2428
- if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
2429
- return new Param(value, column);
2491
+ if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param2) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
2492
+ return new Param2(value, column);
2430
2493
  }
2431
2494
  return value;
2432
2495
  }
@@ -3023,7 +3086,7 @@ class PgDialect {
3023
3086
  const valueList = [];
3024
3087
  for (const [fieldName, col] of colEntries) {
3025
3088
  const colValue = value[fieldName];
3026
- if (colValue === undefined || is(colValue, Param) && colValue.value === undefined) {
3089
+ if (colValue === undefined || is(colValue, Param2) && colValue.value === undefined) {
3027
3090
  if (col.defaultFn !== undefined) {
3028
3091
  const defaultFnResult = col.defaultFn();
3029
3092
  const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
@@ -4229,7 +4292,7 @@ var originStackCache = new Map;
4229
4292
  var originError = Symbol("OriginError");
4230
4293
  var CLOSE = {};
4231
4294
 
4232
- class Query extends Promise {
4295
+ class Query2 extends Promise {
4233
4296
  constructor(strings, args, handler, canceller, options = {}) {
4234
4297
  let resolve, reject;
4235
4298
  super((a, b) => {
@@ -4500,7 +4563,7 @@ function stringify(q, string, value, parameters, types2, options) {
4500
4563
  return string;
4501
4564
  }
4502
4565
  function stringifyValue(string, value, parameters, types2, o) {
4503
- return value instanceof Builder ? value.build(string, parameters, types2, o) : value instanceof Query ? fragment(value, parameters, types2, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types2, o), "") : handleValue(value, parameters, types2, o);
4566
+ return value instanceof Builder ? value.build(string, parameters, types2, o) : value instanceof Query2 ? fragment(value, parameters, types2, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query2 ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types2, o), "") : handleValue(value, parameters, types2, o);
4504
4567
  }
4505
4568
  function fragment(q, parameters, types2, options) {
4506
4569
  q.fragment = true;
@@ -4522,7 +4585,7 @@ function select(first, rest, parameters, types2, options) {
4522
4585
  const columns = rest.length ? rest.flat() : Object.keys(first);
4523
4586
  return columns.map((x) => {
4524
4587
  value = first[x];
4525
- return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
4588
+ return (value instanceof Query2 ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
4526
4589
  }).join(",");
4527
4590
  }
4528
4591
  var builders = Object.entries({
@@ -5304,7 +5367,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5304
5367
  }
5305
5368
  async function fetchArrayTypes() {
5306
5369
  needsTypes = false;
5307
- const types2 = await new Query([`
5370
+ const types2 = await new Query2([`
5308
5371
  select b.oid, b.typarray
5309
5372
  from pg_catalog.pg_type a
5310
5373
  left join pg_catalog.pg_type b on b.oid = a.typelem
@@ -5327,7 +5390,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5327
5390
  return x === "read-write" && xs.default_transaction_read_only === "on" || x === "read-only" && xs.default_transaction_read_only === "off" || x === "primary" && xs.in_hot_standby === "on" || x === "standby" && xs.in_hot_standby === "off" || x === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries];
5328
5391
  }
5329
5392
  function fetchState() {
5330
- const query2 = new Query([`
5393
+ const query2 = new Query2([`
5331
5394
  show transaction_read_only;
5332
5395
  select pg_catalog.pg_is_in_recovery()
5333
5396
  `], [], execute, null, { simple: true });
@@ -5857,12 +5920,12 @@ function Postgres(a, b2) {
5857
5920
  return new Parameter(value, type);
5858
5921
  }
5859
5922
  function sql3(strings, ...args) {
5860
- const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
5923
+ const query = strings && Array.isArray(strings.raw) ? new Query2(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
5861
5924
  return query;
5862
5925
  }
5863
5926
  function unsafe(string, args = [], options2 = {}) {
5864
5927
  arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
5865
- const query = new Query([string], args, handler2, cancel, {
5928
+ const query = new Query2([string], args, handler2, cancel, {
5866
5929
  prepare: false,
5867
5930
  ...options2,
5868
5931
  simple: "simple" in options2 ? options2.simple : args.length === 0
@@ -5871,7 +5934,7 @@ function Postgres(a, b2) {
5871
5934
  }
5872
5935
  function file(path, args = [], options2 = {}) {
5873
5936
  arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
5874
- const query = new Query([], args, (query2) => {
5937
+ const query = new Query2([], args, (query2) => {
5875
5938
  fs.readFile(path, "utf8", (err, string) => {
5876
5939
  if (err)
5877
5940
  return query2.reject(err);
@@ -6204,7 +6267,7 @@ class StoreModule {
6204
6267
  return {
6205
6268
  module: StoreModule,
6206
6269
  providers: [dbProvider],
6207
- exports: [dbProvider],
6270
+ exports: [DATABASE_CLIENT],
6208
6271
  global: true
6209
6272
  };
6210
6273
  }
@@ -0,0 +1,12 @@
1
+ import { type DynamicModule } from "@kanjijs/core";
2
+ import { drizzle } from "drizzle-orm/postgres-js";
3
+ export declare const DATABASE_CLIENT: unique symbol;
4
+ export interface StoreModuleOptions {
5
+ url: string;
6
+ schema?: Record<string, unknown>;
7
+ }
8
+ export declare const InjectDb: () => ParameterDecorator;
9
+ export type DrizzleDb = ReturnType<typeof drizzle>;
10
+ export declare class StoreModule {
11
+ static forRoot(options: StoreModuleOptions): DynamicModule;
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanjijs/store",
3
- "version": "0.2.0-beta.2",
3
+ "version": "0.2.0-beta.20",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -10,14 +10,16 @@
10
10
  "LICENSE"
11
11
  ],
12
12
  "scripts": {
13
- "build": "bun build src/index.ts --outdir dist --target bun"
13
+ "build": "bun build src/index.ts --outdir dist --target bun && tsc --emitDeclarationOnly --declaration --outDir dist"
14
14
  },
15
15
  "dependencies": {
16
- "@kanjijs/core": "^0.2.0-beta.2",
17
16
  "drizzle-orm": "^0.30.0",
18
17
  "postgres": "^3.4.3"
19
18
  },
19
+ "peerDependencies": {
20
+ "@kanjijs/core": "^0.2.0-beta.20"
21
+ },
20
22
  "devDependencies": {
21
23
  "bun-types": "latest"
22
24
  }
23
- }
25
+ }