{"id":20624267,"url":"https://github.com/ortense/mediator","last_synced_at":"2025-10-16T20:21:48.076Z","repository":{"id":198114408,"uuid":"700106910","full_name":"ortense/mediator","owner":"ortense","description":"A minimalistic and dependency-free event mediator with internal context for front-end.","archived":false,"fork":false,"pushed_at":"2024-03-16T00:44:41.000Z","size":1615,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-01T02:34:41.811Z","etag":null,"topics":["dependency-free","emitter","events","mediator","observer","pubsub","typescript","typescript-library"],"latest_commit_sha":null,"homepage":"https://ortense.github.io/mediator/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ortense.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-04T00:41:33.000Z","updated_at":"2024-01-22T02:04:19.000Z","dependencies_parsed_at":null,"dependency_job_id":"b6849eee-6a2f-4752-83fc-3b46fb344a87","html_url":"https://github.com/ortense/mediator","commit_stats":{"total_commits":40,"total_committers":1,"mean_commits":40.0,"dds":0.0,"last_synced_commit":"0088be7ed2fbf5258be2348af9644423a5c6af79"},"previous_names":["ortense/minimal-context-mediator","ortense/mediator"],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ortense%2Fmediator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ortense%2Fmediator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ortense%2Fmediator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ortense%2Fmediator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ortense","download_url":"https://codeload.github.com/ortense/mediator/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242332574,"owners_count":20110345,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency-free","emitter","events","mediator","observer","pubsub","typescript","typescript-library"],"created_at":"2024-11-16T12:30:14.982Z","updated_at":"2025-10-16T20:21:48.069Z","avatar_url":"https://github.com/ortense.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"![Mediator banner - the mediator mascot generated by dall-e 2](https://raw.githubusercontent.com/ortense/mediator/main/media/mediator.jpg)\n\n# @ortense/mediator\n[![npm version](https://badgen.net/npm/v/@ortense/mediator)](https://bundlephobia.com/package/@ortense/mediator) [![bundle size](https://badgen.net/bundlephobia/minzip/@ortense/mediator)](https://bundlephobia.com/package/@ortense/mediator) [![install size](https://packagephobia.com/badge?p=@ortense/mediator)](https://packagephobia.com/result?p=@ortense/mediator) [![Coverage Status](https://coveralls.io/repos/github/ortense/mediator/badge.svg?branch=github-actions)](https://coveralls.io/github/ortense/mediator?branch=github-actions) [![JSR Score](https://jsr.io/badges/@ortense/mediator/score)](https://jsr.io/@ortense/mediator) \n\nA minimalistic and dependency-free event mediator with internal context and middleware support for front-end.\nWritten typescript for a good development experience and incredibly lightweight at less than 550 bytes!\n\nAccess the complete documentation at [ortense.github.io/mediator/](https://ortense.github.io/mediator/)\n\n## Use case\n\nYou want to simplify communication between independent components in your web app. The mediator can be used to facilitate the exchange of data and events between different parts of the application without crate a strong coupling, keeping the separation of concerns between the components of your app or external integrations like third party scripts or extensions.\n\n![Mediator flow chart - made in excalidraw.com](https://raw.githubusercontent.com/ortense/mediator/main/media/flow.png)\n\n## Install\n\nPick your favorite package manager.\n\n```sh\nnpm install @ortense/mediator  # npm\nyarn add  @ortense/mediator    # yarn\npnpm add @ortense/mediator     # pnpm\nbun add @ortense/mediator      # bun\n```\n\n## Usage\n\nFirst, define an interface that extends `MediatorContext` to represent your context, this interface must be an object with properties serializable to JSON.\n\n```typescript\nexport interface MyContext extends MediatorContext {\n  value: string\n  active: boolean\n  nested: {\n    items: number[]\n  }\n}\n```\nNow create an object to be your initial context.\n\n```typescript\nconst initialContext: MyContext = {\n  value: 'hello world',\n  active: true,\n  nested: {\n    items: [],\n  },\n}\n```\n\nThen create the mediator object:\n\n```typescript\nexport const myMediator = createMediator(initialContext)\n```\n\nThe complete setup file should look like this:\n\n```typescript\nimport { MediatorContext, createMediator, MediatorMiddleware } from '@ortense/mediator'\n\nexport interface MyContext extends MediatorContext {\n  value: string\n  active: boolean\n  nested: {\n    items: number[]\n  }\n}\n\nconst initialContext: MyContext = {\n  value: 'hello world',\n  active: true,\n  nested: {\n    items: [],\n  },\n}\n\n// Optional: Add middleware for logging\nconst logger: MediatorMiddleware\u003cMyContext, string\u003e = (context, input, event) =\u003e {\n  console.log(`Event ${event} triggered with context:`, context)\n}\n\nexport const myMediator = createMediator(initialContext, {\n  middlewares: [\n    { event: '*', handler: logger }\n  ]\n})\n```\n\n### Events\n\nThe mediator use simple strings to identify events, think of it as a unique identifier to be used to send or listen to events.\n\nOptionally, you can define a type that extends from `string` to represent the events that your mediator has.\n\n```typescript\ntype MyEvents = 'loaded' | 'value:change' | 'item:added' | 'item:removed'\n\nexport const myMediator = createMediator\u003cMyContext, MyEvents\u003e(initialContext)\n```\n\nThis is a good practice to help developers who will interact with the mediator, providing predictability of the events that can be listened or send.\n\n### Middlewares\n\nMiddlewares provide a powerful way to intercept, transform, and control event flow in your mediator. They execute **before** event listeners and can:\n\n- **Observe events**: Log, track, or monitor events without side effects\n- **Transform data**: Modify pending changes before they're applied to the context\n- **Validate changes**: Ensure data integrity and business rules\n- **Cancel propagation**: Stop event processing entirely when needed\n\nMiddlewares are configured during mediator creation and run in the order they're declared.\n\n#### Creating a Mediator with Middlewares\n\n```typescript\nimport { createMediator, MediatorMiddleware } from '@ortense/mediator'\n\ninterface AppContext extends MediatorContext {\n  user: string\n  count: number\n}\n\n// Logger middleware (observes only)\nconst logEvents: MediatorMiddleware\u003cAppContext, string\u003e = (context, input, event) =\u003e {\n  console.log(`[${event}] Context:`, context, 'Changes:', input.pendingChanges)\n  // No return - passes through unchanged\n}\n\n// Validation middleware\nconst validateCount: MediatorMiddleware\u003cAppContext, string\u003e = (context, input, event) =\u003e {\n  if (input.pendingChanges \u0026\u0026 'count' in input.pendingChanges \u0026\u0026 input.pendingChanges.count \u003c 0) {\n    console.warn('Invalid count, cancelling event')\n    return { cancel: true } // Stop propagation\n  }\n  return input // Pass through\n}\n\n// Transformation middleware - adds timestamp to all changes\nconst addTimestamp: MediatorMiddleware\u003cAppContext, string\u003e = (context, input, event) =\u003e {\n  return {\n    pendingChanges: { \n      ...(input.pendingChanges ?? {}), \n      timestamp: Date.now() \n    }\n  }\n}\n\nconst mediator = createMediator\u003cAppContext\u003e(\n  { user: 'anonymous', count: 0 },\n  {\n    middlewares: [\n      { event: '*', handler: logEvents },           // Runs for all events\n      { event: 'counter:decrement', handler: validateCount },\n      { event: 'counter:increment', handler: addTimestamp },\n    ]\n  }\n)\n```\n\n#### Middleware Types\n\n```typescript\n// Input data passed to middleware functions\ntype MediatorMiddlewareInput\u003cContext extends MediatorContext\u003e = {\n  pendingChanges: Nullable\u003cAtLeastOneOf\u003cContext\u003e\u003e\n}\n\n// Cancel event propagation\ntype MediatorCancelEvent = {\n  cancel: true\n}\n\n// Middleware function signature\ntype MediatorMiddleware\u003cContext extends MediatorContext, EventName extends string = string\u003e = (\n  context: Readonly\u003cContext\u003e,\n  input: MediatorMiddlewareInput\u003cContext\u003e,\n  event: EventName,\n) =\u003e MediatorMiddlewareInput\u003cContext\u003e | MediatorCancelEvent | void\n```\n\n#### Middleware Return Types\n\n```typescript\n// Void middleware - observes only, passes through unchanged\nconst logger: MediatorMiddleware\u003cAppContext, string\u003e = (context, input, event) =\u003e {\n  console.log(`Event ${event} triggered`)\n  // No return - middleware passes through\n}\n\n// Transform middleware - modifies pending changes\nconst enrichData: MediatorMiddleware\u003cAppContext, string\u003e = (context, input, event) =\u003e {\n  return {\n    pendingChanges: { \n      ...(input.pendingChanges ?? {}), \n      timestamp: Date.now() \n    }\n  }\n}\n\n// Cancel middleware - stops event processing\nconst authGuard: MediatorMiddleware\u003cAppContext, string\u003e = (context, input, event) =\u003e {\n  if (context.user === 'anonymous') {\n    return { cancel: true } // Stop processing\n  }\n  return input\n}\n```\n\n#### Execution Flow\n\n1. `mediator.send(event, modifier)` is called\n2. A frozen snapshot of the current context is created\n3. Modifier generates initial `pendingChanges` if provided\n4. Middlewares execute in registration order:\n   - **Void middlewares** observe and pass through unchanged\n   - **Return middlewares** may return modified `pendingChanges`\n   - Any middleware can return `{ cancel: true }` to stop propagation\n   - **All middlewares receive the same immutable context snapshot**\n5. Final context is updated with shallow merge of all `pendingChanges`\n6. Event listeners run with the updated context unless propagation was cancelled\n\n### Listening to events\n\nTo listen to events use the `.on` method\n\n```typescript\nimport { myMediator, MyContext } from './my-mediator'\n\nfunction myEventListener(ctx: Readonly\u003cMyContext\u003e, event: MyEvents) {\n  // do what you want\n}\n\nmyMediator.on('loaded', myEventListener)\n```\n\nIf you prefer you could use the type `MediatorEventListener`\n\n```typescript\nimport { MediatorEventListener } from '@ortense/mediator'\nimport { myMediator, MyContext, MyEvents } from './my-mediator'\n\nconst myEventListener: MediatorEventListener\u003cMyContext, MyEvents\u003e = (ctx, event) =\u003e {\n  // do what you want\n}\n\nmyMediator.on('loaded', myEventListener)\n```\n\nYou also use the wildcard `*` to listen all events.\n\n```typescript\nmyMediator.on('*', (ctx, event) =\u003e console.log(ctx, event))\n```\n\nWildcard listeners could be useful for debugging, for example logging whenever an event is triggered.\n\n```typescript\nmyMediator.on('*', (ctx, event) =\u003e {\n  console.log(`Event ${event} change the context to`, ctx)\n})\n```\n\nTo stop use the `.off` method\n\n```typescript\nmyMediator.off('loaded', myEventListener)\n```\n\n### Send events\n\nTo send events use the `.send` method.\n\n```typescript\nimport { myMediator} from './my-mediator'\n\nmyMediator.send('loaded')\n```\n\nAll listener functions for the `loaded` event will be called in the order they were added to the mediator.\n\nThe `.send` method could receive a function to modifiy the context:\n\n```typescript\nimport { myMediator, MyContext } from './my-mediator'\n\nfunction changeValue(ctx: Readonly\u003cMyContext\u003e) {\n  return {\n    value: 'new value'\n  }\n}\n\nmyMediator.send('value:change', changeValue)\n```\n\nIf you prefer you could use the `MediatorContextModifier` type.\n\n```typescript\nimport { MediatorContextModifier } from '@ortense/mediator'\nimport { myMediator, MyContext } from './my-mediator'\n\nconst changeValue: MediatorContextModifier\u003cMyContext\u003e = (ctx) =\u003e ({\n  value: 'new value'\n})\n\nmyMediator.send('value:change', changeValue)\n```\n\nOr an inline declaration:\n\n```typescript\nimport { myMediator } from './my-mediator'\n\nmyMediator.send('value:change', (ctx) =\u003e ({ ...ctx, active: 'new value }))\n```\n\n### Get current context\n\nUse the method `.getContext` to get a readonly version of the current context.\n\n```typescript\nimport { myMediator } from './my-mediator'\n\nconst ctx = myMediator.getContext() //? Readonly\u003cMyContext\u003e\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fortense%2Fmediator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fortense%2Fmediator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fortense%2Fmediator/lists"}