or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-startup.mdcontext-management.mddependency-injection.mderror-handling.mdindex.mdlogging-system.mdmodule-system.mdqualifiers-parameters.mdscoping-lifecycle.md

index.mddocs/

0

# Koin Core JavaScript

1

2

Koin is a pragmatic lightweight dependency injection framework for Kotlin Multiplatform projects. This JavaScript implementation provides a complete DI container with DSL-based configuration, scoped instances, lazy injection, and module organization designed specifically for web applications, browser extensions, and Node.js services.

3

4

## Package Information

5

6

- **Package Name**: io.insert-koin:koin-core-js

7

- **Package Type**: maven

8

- **Language**: Kotlin/JS (JavaScript target)

9

- **Installation**: Add to your Gradle build file dependencies

10

- **Documentation**: https://insert-koin.io/docs/reference/koin-mp/kmp

11

12

## Core Imports

13

14

For Kotlin Multiplatform JavaScript target, imports depend on your build configuration:

15

16

```javascript

17

// ES6 modules (if configured in your Gradle build)

18

import {

19

startKoin,

20

koinApplication,

21

module,

22

KoinComponent,

23

GlobalContext

24

} from "io.insert-koin.koin-core";

25

```

26

27

```javascript

28

// CommonJS (Node.js style)

29

const {

30

startKoin,

31

koinApplication,

32

module,

33

KoinComponent,

34

GlobalContext

35

} = require("io.insert-koin.koin-core");

36

```

37

38

Note: Actual import paths may vary based on your Kotlin Multiplatform build configuration and JavaScript module system setup.

39

40

## Basic Usage

41

42

```javascript

43

import { startKoin, koinApplication, module, named } from "io.insert-koin.koin-core";

44

45

// Define a module with dependencies

46

const appModule = module(false, (module) => {

47

// Singleton instance - created once and reused

48

module.single(null, false, () => new DatabaseService("localhost:5432"));

49

50

// Factory instance - new instance every time

51

module.factory(null, () => new ApiClient());

52

53

// Scoped instance - tied to scope lifecycle

54

module.scope(named("session"), (scope) => {

55

scope.scoped(null, () => new UserSession());

56

});

57

});

58

59

// Start Koin application

60

startKoin((app) => {

61

app.modules([appModule]);

62

app.printLogger();

63

});

64

65

// Or create application first, then start

66

const app = koinApplication(true, (koinApp) => {

67

koinApp.modules([appModule]);

68

koinApp.printLogger();

69

});

70

startKoin(app);

71

```

72

73

## Architecture

74

75

Koin Core is built around several key architectural components:

76

77

- **Application Container**: `KoinApplication` manages the overall DI configuration and lifecycle

78

- **Core Container**: `Koin` class provides runtime dependency resolution and instance management

79

- **Module System**: `Module` classes organize related dependency definitions using a fluent DSL

80

- **Scoping Engine**: `Scope` instances manage lifecycle and cleanup of scoped dependencies

81

- **Component Model**: `KoinComponent` interface provides injection capabilities to classes

82

- **Context Management**: Global and custom contexts for application-wide dependency access

83

- **Type System**: Full support for generic types, qualifiers, and parameter injection

84

85

## Capabilities

86

87

### Application Configuration and Startup

88

89

Core application setup functionality for initializing the Koin container, loading modules, and configuring logging.

90

91

```javascript { .api }

92

/**

93

* Create a new Koin application with configuration

94

* @param createEagerInstances - Whether to create eager instances (default: true)

95

* @param appDeclaration - Application configuration function

96

* @returns KoinApplication instance

97

*/

98

function koinApplication(createEagerInstances?: boolean, appDeclaration?: KoinAppDeclaration): KoinApplication;

99

function koinApplication(appDeclaration?: KoinAppDeclaration): KoinApplication;

100

function koinApplication(configuration?: KoinConfiguration): KoinApplication;

101

102

/**

103

* Start Koin globally with application or configuration

104

* @param koinApplication - Pre-configured KoinApplication instance

105

* @returns KoinApplication instance

106

*/

107

function startKoin(koinApplication: KoinApplication): KoinApplication;

108

function startKoin(appDeclaration: KoinAppDeclaration): KoinApplication;

109

function startKoin(appConfiguration: KoinConfiguration): KoinApplication;

110

111

/**

112

* Stop the global Koin instance and cleanup resources

113

*/

114

function stopKoin(): void;

115

116

/**

117

* Load additional modules into the global Koin instance

118

*/

119

function loadKoinModules(module: Module): void;

120

function loadKoinModules(modules: Module[]): void;

121

122

/**

123

* Unload modules from the global Koin instance

124

*/

125

function unloadKoinModules(module: Module): void;

126

function unloadKoinModules(modules: Module[]): void;

127

128

class KoinApplication {

129

/** Load dependency modules into the application */

130

modules(modules: Module): KoinApplication;

131

modules(...modules: Module[]): KoinApplication;

132

modules(modules: Module[]): KoinApplication;

133

/** Set application properties */

134

properties(values: Map<string, any>): KoinApplication;

135

/** Set application options */

136

options(...optionValue: [KoinOption, any][]): KoinApplication;

137

/** Configure logging with custom logger */

138

logger(logger: Logger): KoinApplication;

139

/** Use default console logger */

140

printLogger(level?: Level): KoinApplication;

141

/** Allow definition override */

142

allowOverride(override: boolean): void;

143

/** Create eager instances */

144

createEagerInstances(): void;

145

/** Close the application and cleanup resources */

146

close(): void;

147

/** Get the underlying Koin container */

148

readonly koin: Koin;

149

}

150

```

151

152

[Application and Startup](./application-startup.md)

153

154

### Module System and Dependency Definitions

155

156

Module definition DSL for organizing and declaring dependencies with singletons, factories, and scoped instances.

157

158

```javascript { .api }

159

/**

160

* Define a module with dependency definitions

161

* @param createdAtStart - Whether to create instances immediately (default: false)

162

* @param moduleDeclaration - Module configuration function

163

* @returns Module instance

164

*/

165

function module(

166

createdAtStart?: boolean,

167

moduleDeclaration: ModuleDeclaration

168

): Module;

169

function module(moduleDeclaration: ModuleDeclaration): Module;

170

171

/**

172

* Create a Koin configuration

173

* @param declaration - Configuration function

174

* @returns KoinConfiguration instance

175

*/

176

function koinConfiguration(declaration: KoinAppDeclaration): KoinConfiguration;

177

178

class Module {

179

/** Module unique identifier */

180

readonly id: string;

181

/** Whether module is loaded */

182

readonly isLoaded: boolean;

183

184

/** Define singleton instance - created once and reused */

185

single<T>(qualifier?: Qualifier, createdAtStart?: boolean, definition: Definition<T>): KoinDefinition<T>;

186

/** Define factory instance - new instance every request */

187

factory<T>(qualifier?: Qualifier, definition: Definition<T>): KoinDefinition<T>;

188

/** Define scoped instances within named scope */

189

scope(qualifier: Qualifier, scopeSet: (scopeDSL: ScopeDSL) => void): void;

190

scope<T>(scopeSet: (scopeDSL: ScopeDSL) => void): void;

191

/** Include other modules */

192

includes(...modules: Module[]): void;

193

includes(modules: Module[]): void;

194

/** Module composition operators */

195

plus(module: Module): Module[];

196

plus(modules: Module[]): Module[];

197

}

198

```

199

200

[Module System](./module-system.md)

201

202

### Dependency Resolution and Injection

203

204

Core dependency injection functionality for retrieving instances, lazy injection, and parameter passing.

205

206

```javascript { .api }

207

class Koin {

208

/** Get instance of type T */

209

get<T>(qualifier?: Qualifier, parameters?: ParametersDefinition): T;

210

get<T>(clazz: any, qualifier?: Qualifier, parameters?: ParametersDefinition): T;

211

/** Get instance or null if not found */

212

getOrNull<T>(qualifier?: Qualifier, parameters?: ParametersDefinition): T | null;

213

getOrNull<T>(clazz: any, qualifier?: Qualifier, parameters?: ParametersDefinition): T | null;

214

/** Lazy injection - resolved on first access */

215

inject<T>(qualifier?: Qualifier, mode?: LazyThreadSafetyMode, parameters?: ParametersDefinition): Lazy<T>;

216

/** Lazy injection that can return null */

217

injectOrNull<T>(qualifier?: Qualifier, mode?: LazyThreadSafetyMode, parameters?: ParametersDefinition): Lazy<T | null>;

218

/** Get all instances of type T */

219

getAll<T>(): T[];

220

/** Declare existing instance in container */

221

declare<T>(instance: T, qualifier?: Qualifier, secondaryTypes?: any[], allowOverride?: boolean): void;

222

223

/** Create new scope */

224

createScope(scopeId: ScopeID, qualifier: Qualifier, source?: any, scopeArchetype?: TypeQualifier): Scope;

225

createScope<T>(scopeId: ScopeID, source?: any, scopeArchetype?: TypeQualifier): Scope;

226

createScope<T>(scopeId?: ScopeID): Scope;

227

/** Get existing scope */

228

getScope(scopeId: ScopeID): Scope;

229

getScopeOrNull(scopeId: ScopeID): Scope | null;

230

/** Delete scope */

231

deleteScope(scopeId: ScopeID): void;

232

233

/** Property management */

234

getProperty<T>(key: string, defaultValue: T): T;

235

getProperty<T>(key: string): T | null;

236

setProperty(key: string, value: any): void;

237

deleteProperty(key: string): void;

238

239

/** Module management */

240

loadModules(modules: Module[], allowOverride?: boolean, createEagerInstances?: boolean): void;

241

unloadModules(modules: Module[]): void;

242

createEagerInstances(): void;

243

/** Close and cleanup */

244

close(): void;

245

}

246

247

interface KoinComponent {

248

/** Get the Koin container instance */

249

getKoin(): Koin;

250

}

251

252

// KoinComponent extension functions available globally

253

function get<T>(component: KoinComponent, qualifier?: Qualifier, parameters?: ParametersDefinition): T;

254

function inject<T>(component: KoinComponent, qualifier?: Qualifier, mode?: LazyThreadSafetyMode, parameters?: ParametersDefinition): Lazy<T>;

255

```

256

257

[Dependency Injection](./dependency-injection.md)

258

259

### Scoping and Lifecycle Management

260

261

Scoped dependency management for controlling instance lifecycle and cleanup within defined boundaries.

262

263

```javascript { .api }

264

class Scope {

265

/** Scope qualifier */

266

readonly scopeQualifier: Qualifier;

267

/** Scope ID */

268

readonly id: ScopeID;

269

/** Whether this is a root scope */

270

readonly isRoot: boolean;

271

/** Whether scope is closed */

272

readonly closed: boolean;

273

274

/** Get scoped instance */

275

get<T>(qualifier?: Qualifier, parameters?: ParametersDefinition): T;

276

getOrNull<T>(qualifier?: Qualifier, parameters?: ParametersDefinition): T | null;

277

getAll<T>(): T[];

278

/** Lazy inject from scope */

279

inject<T>(qualifier?: Qualifier, mode?: LazyThreadSafetyMode, parameters?: ParametersDefinition): Lazy<T>;

280

injectOrNull<T>(qualifier?: Qualifier, mode?: LazyThreadSafetyMode, parameters?: ParametersDefinition): Lazy<T | null>;

281

/** Link to parent scopes for dependency resolution */

282

linkTo(...scopes: Scope[]): void;

283

unlink(...scopes: Scope[]): void;

284

/** Close scope and cleanup instances */

285

close(): void;

286

/** Declare instance in scope */

287

declare<T>(instance: T, qualifier?: Qualifier, secondaryTypes?: any[], allowOverride?: boolean, holdInstance?: boolean): void;

288

289

/** Property access */

290

getProperty<T>(key: string, defaultValue: T): T;

291

getPropertyOrNull<T>(key: string): T | null;

292

getProperty<T>(key: string): T;

293

/** Register lifecycle callback */

294

registerCallback(callback: ScopeCallback): void;

295

}

296

297

interface KoinScopeComponent extends KoinComponent {

298

/** Current scope instance */

299

readonly scope: Scope;

300

}

301

302

// KoinScopeComponent extension functions

303

function getScopeId<T>(component: T): string;

304

function getScopeName<T>(component: T): TypeQualifier;

305

function createScope<T extends KoinScopeComponent>(component: T, scopeId?: ScopeID, source?: any, scopeArchetype?: TypeQualifier): Scope;

306

function getScopeOrNull<T extends KoinScopeComponent>(component: T): Scope | null;

307

function newScope<T extends KoinScopeComponent>(component: T): Lazy<Scope>;

308

function getOrCreateScope<T extends KoinScopeComponent>(component: T): Lazy<Scope>;

309

```

310

311

[Scoping and Lifecycle](./scoping-lifecycle.md)

312

313

### Qualifiers and Parameters

314

315

Type-safe dependency identification and parameter injection for complex dependency graphs.

316

317

```javascript { .api }

318

interface Qualifier {

319

/** Qualifier value for identification */

320

value: any;

321

}

322

323

/**

324

* Create named qualifier for dependency identification

325

* @param name - Qualifier name

326

* @returns Qualifier instance

327

*/

328

function named(name: string): Qualifier;

329

330

/**

331

* Create type-based qualifier

332

* @returns Qualifier instance

333

*/

334

function named<T>(): Qualifier;

335

336

class ParametersHolder {

337

/** Get parameter by index and type */

338

elementAt<T>(index: number): T;

339

/** Get parameter by type */

340

get<T>(): T;

341

/** Check if parameters exist */

342

isEmpty(): boolean;

343

/** Parameter count */

344

size(): number;

345

}

346

347

/**

348

* Create parameters for injection

349

* @param parameters - Parameter values

350

* @returns ParametersHolder instance

351

*/

352

function parametersOf(...parameters: any[]): ParametersHolder;

353

```

354

355

[Qualifiers and Parameters](./qualifiers-parameters.md)

356

357

### Context and Global Management

358

359

Application-wide context management for accessing the DI container across your application.

360

361

```javascript { .api }

362

interface KoinContext {

363

/** Get current Koin instance */

364

get(): Koin | null;

365

/** Start Koin with application */

366

startKoin(application: KoinApplication): KoinApplication;

367

/** Stop Koin and cleanup */

368

stopKoin(): void;

369

/** Load additional modules */

370

loadKoinModules(modules: Module[]): void;

371

/** Unload modules */

372

unloadKoinModules(modules: Module[]): void;

373

}

374

375

/** Global context singleton for JavaScript */

376

const GlobalContext: KoinContext;

377

```

378

379

[Context Management](./context-management.md)

380

381

### Error Handling and Diagnostics

382

383

Comprehensive error handling with specific exception types for different failure scenarios.

384

385

```javascript { .api }

386

class NoDefinitionFoundException extends Error {

387

/** Definition not found during resolution */

388

}

389

390

class InstanceCreationException extends Error {

391

/** Error during instance creation */

392

}

393

394

class ClosedScopeException extends Error {

395

/** Attempt to use closed scope */

396

}

397

398

class ScopeNotCreatedException extends Error {

399

/** Scope doesn't exist */

400

}

401

402

class ScopeAlreadyCreatedException extends Error {

403

/** Attempting to create an already existing scope */

404

}

405

406

class KoinApplicationAlreadyStartedException extends Error {

407

/** Attempting to start Koin when already started */

408

}

409

410

class DefinitionOverrideException extends Error {

411

/** Definition override conflict */

412

}

413

414

class DefinitionParameterException extends Error {

415

/** Parameter-related definition issues */

416

}

417

418

class MissingScopeValueException extends Error {

419

/** Missing value in scope */

420

}

421

422

class MissingPropertyException extends Error {

423

/** Property not found */

424

}

425

426

class NoPropertyFileFoundException extends Error {

427

/** Property file not found */

428

}

429

430

class NoParameterFoundException extends Error {

431

/** Parameter not found */

432

}

433

434

class NoScopeDefFoundException extends Error {

435

/** Scope definition not found */

436

}

437

```

438

439

[Error Handling](./error-handling.md)

440

441

### Logging and Diagnostics

442

443

Configurable logging system with multiple levels and JavaScript console integration.

444

445

```javascript { .api }

446

abstract class Logger {

447

/** Display log message */

448

abstract display(level: Level, message: string): void;

449

/** Debug level logging */

450

debug(message: string): void;

451

/** Info level logging */

452

info(message: string): void;

453

/** Warning level logging */

454

warn(message: string): void;

455

/** Error level logging */

456

error(message: string): void;

457

}

458

459

enum Level {

460

DEBUG = "DEBUG",

461

INFO = "INFO",

462

WARNING = "WARNING",

463

ERROR = "ERROR",

464

NONE = "NONE"

465

}

466

467

/** Console-based logger for JavaScript environments */

468

class PrintLogger extends Logger {

469

display(level: Level, message: string): void;

470

}

471

```

472

473

[Logging System](./logging-system.md)

474

475

## Types

476

477

```javascript { .api }

478

/** Function type for module declarations */

479

type ModuleDeclaration = (module: Module) => void;

480

481

/** Function type for dependency definitions */

482

type Definition<T> = (scope: Scope, parameters: ParametersHolder) => T;

483

484

/** Function type for parameter definitions */

485

type ParametersDefinition = () => ParametersHolder;

486

487

/** Function type for application configuration */

488

type KoinAppDeclaration = (app: KoinApplication) => void;

489

490

/** Koin configuration type */

491

interface KoinConfiguration {

492

invoke(): KoinAppDeclaration;

493

}

494

495

/** Scope identifier type */

496

type ScopeID = string;

497

498

/** Qualifier value type */

499

type QualifierValue = any;

500

501

/** Type qualifier interface */

502

interface TypeQualifier extends Qualifier {

503

/** Type-based qualifier */

504

}

505

506

/** Message type for logging */

507

type MESSAGE = string | (() => string);

508

509

/** Koin option enumeration */

510

enum KoinOption {

511

// Koin configuration options

512

}

513

514

/** Lazy thread safety modes */

515

enum LazyThreadSafetyMode {

516

SYNCHRONIZED,

517

PUBLICATION,

518

NONE

519

}

520

521

/** Lazy wrapper for dependency injection */

522

interface Lazy<T> {

523

/** Get the lazily resolved value */

524

readonly value: T;

525

}

526

527

/** Bean definition with binding and lifecycle options */

528

interface KoinDefinition<T> {

529

/** Bind additional compatible types */

530

bind<S>(): KoinDefinition<T>;

531

/** Add cleanup callback */

532

onClose(callback: (instance: T) => void): KoinDefinition<T>;

533

}

534

535

/** Scope DSL for defining scoped dependencies */

536

class ScopeDSL {

537

/** Scope qualifier */

538

readonly scopeQualifier: Qualifier;

539

/** Associated module */

540

readonly module: Module;

541

542

/** Define scoped instance */

543

scoped<T>(qualifier?: Qualifier, definition: Definition<T>): KoinDefinition<T>;

544

/** Define factory instance in scope */

545

factory<T>(qualifier?: Qualifier, definition: Definition<T>): KoinDefinition<T>;

546

}

547

548

/** Scope lifecycle callback interface */

549

interface ScopeCallback {

550

/** Called when scope is closed */

551

onScopeClose(scope: Scope): void;

552

}

553

```