@siggn/react 0.1.1 → 0.1.2
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.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +275 -24
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react");class u{nextId=0;subscriptions;globalSubscriptions=[];registry=new FinalizationRegistry(s=>{this.unsubscribe(s)});registryGlobal=new FinalizationRegistry(s=>{this.unsubscribeGlobal(s)});constructor(){this.subscriptions=new Map}createClone(){return new u}makeId(s){return s??`sub_${(this.nextId++).toString(36)}`}make(s){return{subscribe:(i,e)=>{this.subscribe(s,i,e)},unsubscribe:()=>{this.unsubscribe(s)},subscribeMany:i=>{this.subscribeMany(s,i)},subscribeAll:i=>{this.subscribeAll(s,i)}}}subscribeMany(s,i){i((e,t)=>this.subscribe(s,e,t))}subscribe(s,i,e){this.subscriptions.has(i)||this.subscriptions.set(i,[]),this.registry.register(e,s),this.subscriptions.get(i)?.push({id:s,ref:new WeakRef(e)})}subscribeAll(s,i){this.registryGlobal.register(i,s),this.globalSubscriptions.push({id:s,ref:new WeakRef(i)})}publish(s){this.globalSubscriptions.forEach(i=>{const e=i.ref.deref();if(!e){this.unsubscribeGlobal(i.id);return}e(s)}),this.subscriptions.has(s.type)&&this.subscriptions.get(s.type)?.forEach(i=>{const e=i.ref.deref();if(!e){this.unsubscribe(i.id);return}e(s)})}unsubscribe(s){this.unsubscribeGlobal(s);for(const[i,e]of this.subscriptions)this.subscriptions.set(i,e.filter(t=>t.id!==s))}unsubscribeGlobal(s){this.globalSubscriptions=this.globalSubscriptions.filter(i=>i.id!==s)}get subscriptionsCount(){let s=0;return this.subscriptions.forEach(i=>{s+=i.length}),s+=this.globalSubscriptions.length,s}}function b(){return n.useRef(new u).current}function c(r,s,i=[]){const e=n.useMemo(()=>r instanceof u?r:r.instance,[r]),t=n.useMemo(()=>e.makeId("id"in r?r.id:void 0),[e]);n.useEffect(()=>(e.subscribeMany(t,s),()=>{e.unsubscribe(t)}),[e,t,...i])}function o(r,s,i=[]){const e=n.useMemo(()=>r instanceof u?r:r.instance,[r]),t=n.useMemo(()=>e.makeId("id"in r?r.id:void 0),[e]);n.useEffect(()=>(e.subscribeAll(t,s),()=>{e.unsubscribeGlobal(t)}),[e,t,...i])}exports.Siggn=u;exports.useSiggn=b;exports.useSubscribe=c;exports.useSubscribeAll=o;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/hooks.ts"],"sourcesContent":["import { type Msg, Siggn } from '@siggn/core';\nimport type { SubscriptionOptions } from 'packages/react/src/types';\nimport { useEffect, useMemo, useRef, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const siggn = useRef(new Siggn<T>());\n return siggn.current;\n}\n\n/**\n * Subscribes to messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<T extends Msg>(\n options: SubscriptionOptions<T>,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: SubscriptionOptions<T>,\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["useSiggn","useRef","Siggn","useSubscribe","options","setup","deps","instance","useMemo","id","useEffect","useSubscribeAll","callback"],"mappings":"kIAqBO,SAASA,GAAoC,CAElD,OADcC,EAAAA,OAAO,IAAIC,EAAAA,KAAU,EACtB,OACf,CAwBO,SAASC,EACdC,EACAC,EAMAC,EAAuB,CAAA,EACvB,CACA,MAAMC,EAAWC,EAAAA,QACf,IAAOJ,aAAmBF,EAAAA,MAAQE,EAAUA,EAAQ,SACpD,CAACA,CAAO,CAAA,EAEJK,EAAKD,EAAAA,QAAQ,IAAMD,EAAS,OAAO,OAAQH,EAAUA,EAAQ,GAAK,MAAS,EAAG,CAACG,CAAQ,CAAC,EAE9FG,EAAAA,UAAU,KACRH,EAAS,cAAcE,EAAIJ,CAAK,EAEzB,IAAM,CACXE,EAAS,YAAYE,CAAE,CACzB,GACC,CAACF,EAAUE,EAAI,GAAGH,CAAI,CAAC,CAC5B,CAyBO,SAASK,EACdP,EACAQ,EACAN,EAAuB,CAAA,EACvB,CACA,MAAMC,EAAWC,EAAAA,QACf,IAAOJ,aAAmBF,EAAAA,MAAQE,EAAUA,EAAQ,SACpD,CAACA,CAAO,CAAA,EAEJK,EAAKD,EAAAA,QAAQ,IAAMD,EAAS,OAAO,OAAQH,EAAUA,EAAQ,GAAK,MAAS,EAAG,CAACG,CAAQ,CAAC,EAE9FG,EAAAA,UAAU,KACRH,EAAS,aAAaE,EAAIG,CAAQ,EAE3B,IAAM,CACXL,EAAS,kBAAkBE,CAAE,CAC/B,GACC,CAACF,EAAUE,EAAI,GAAGH,CAAI,CAAC,CAC5B"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../../core/src/siggn.ts","../src/hooks.ts"],"sourcesContent":["import type { Msg, Subscription, SiggnId } from './types.js';\n\n/**\n * A type-safe message bus for dispatching and subscribing to events.\n * @template T A union of all possible message types.\n * @since 0.0.5\n */\nexport class Siggn<T extends Msg> {\n private nextId = 0;\n private subscriptions: Map<T['type'], Array<Subscription<T, any>>>;\n private globalSubscriptions: Array<Subscription<T, any>> = [];\n\n /**\n * A FinalizationRegistry to automatically unregister specific subscriptions\n * when the subscribed callback function is garbage collected.\n */\n private readonly registry = new FinalizationRegistry<SiggnId>((id) => {\n this.unsubscribe(id);\n });\n\n /**\n * A FinalizationRegistry to automatically unregister global subscriptions\n * when the subscribed callback function is garbage collected.\n */\n private readonly registryGlobal = new FinalizationRegistry<SiggnId>((id) => {\n this.unsubscribeGlobal(id);\n });\n\n /**\n * Creates a new Siggn instance.\n * @category Lifecycle\n * @since 0.0.5\n */\n constructor() {\n this.subscriptions = new Map();\n }\n\n /**\n * Creates a new, independent `Siggn` instance that inherits the message\n * types of its parent and adds new ones.\n *\n * @template C The new message types to add.\n * @returns A new `Siggn` instance with combined message types.\n * @category Lifecycle\n * @since 0.0.5\n * @example\n * \n```typescript\n * const baseSiggn = new Siggn<{ type: 'A' }>();\n * const childSiggn = baseSiggn.createClone<{ type: 'B' }>();\n * // childSiggn can now publish and subscribe to types 'A' and 'B'.\n * ```\n */\n createClone<C extends Msg>() {\n return new Siggn<C | T>();\n }\n\n /**\n * Generates a unique ID for a subscriber.\n * If an ID is provided, it will be used; otherwise, a new one is generated.\n *\n * @param id An optional ID to use.\n * @returns A unique subscriber ID.\n * @category Utilities\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn();\n * const id1 = siggn.makeId(); // e.g., \"sub_0\"\n * const id2 = siggn.makeId('custom-id'); // \"custom-id\"\n * ```\n */\n makeId(id?: string): SiggnId {\n return id ?? `sub_${(this.nextId++).toString(36)}`;\n }\n\n /**\n * Creates a subscription helper object that is pre-configured with a\n * specific subscriber ID. This simplifies managing multiple subscriptions\n * for a single component or service.\n *\n * @param id The subscriber ID to use for all subscriptions.\n * @returns An object with `subscribe`, `unsubscribe`, `subscribeMany`, and `subscribeAll` methods.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'event' }>();\n * const component = siggn.make('my-component');\n * component.subscribe('event', () => console.log('event received!'));\n * component.unsubscribe();\n * ```\n */\n make(id: SiggnId): {\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void;\n unsubscribe: () => void;\n subscribeMany: (\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n ) => void;\n subscribeAll: (callback: (msg: T) => void) => void;\n } {\n return {\n subscribe: (type, callback) => {\n this.subscribe(id, type, callback);\n },\n unsubscribe: () => {\n this.unsubscribe(id);\n },\n subscribeMany: (setup) => {\n this.subscribeMany(id, setup);\n },\n subscribeAll: (callback) => {\n this.subscribeAll(id, callback);\n },\n };\n }\n\n /**\n * Subscribes to multiple message types using a single subscriber ID.\n *\n * @param id The subscriber ID.\n * @param setup A function that receives a `subscribe` helper to register callbacks.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeMany('subscriber-1', (subscribe) => {\n * subscribe('A', () => console.log('A received'));\n * subscribe('B', () => console.log('B received'));\n * });\n * ```\n */\n subscribeMany(\n id: SiggnId,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n ) {\n setup((type, callback) => this.subscribe(id, type, callback));\n }\n\n /**\n * Subscribes to a specific message type.\n *\n * @param id The subscriber ID.\n * @param type The message type to subscribe to.\n * @param callback The function to call when a message of the specified type is published.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event', payload: string }>();\n * siggn.subscribe('subscriber-1', 'my-event', (msg) => {\n * console.log(msg.payload);\n * });\n * ```\n */\n subscribe<K extends T['type']>(\n id: SiggnId,\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) {\n if (!this.subscriptions.has(type)) {\n this.subscriptions.set(type, []);\n }\n\n this.registry.register(callback, id);\n this.subscriptions.get(type)?.push({ id, ref: new WeakRef(callback) });\n }\n\n /**\n * Subscribes to all message types. The callback will be invoked for every\n * message published on the bus.\n *\n * @param id The subscriber ID.\n * @param callback The function to call for any message.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeAll('logger', (msg) => {\n * console.log(`Received message of type: ${msg.type}`);\n * });\n * ```\n */\n subscribeAll(id: SiggnId, callback: (msg: T) => void) {\n this.registryGlobal.register(callback, id);\n this.globalSubscriptions.push({ id, ref: new WeakRef(callback) });\n }\n\n /**\n * Publishes a message to all relevant subscribers.\n *\n * @param msg The message to publish.\n * @category Publishing\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.publish({ type: 'my-event' }); // \"received\"\n * ```\n */\n publish(msg: T) {\n this.globalSubscriptions.forEach((sub) => {\n const fn = sub.ref.deref();\n\n if (!fn) {\n this.unsubscribeGlobal(sub.id);\n return;\n }\n\n fn(msg as Extract<T, { type: any }>);\n });\n\n if (!this.subscriptions.has(msg.type)) {\n return;\n }\n\n this.subscriptions.get(msg.type)?.forEach((sub) => {\n const fn = sub.ref.deref();\n\n if (!fn) {\n this.unsubscribe(sub.id);\n return;\n }\n\n fn(msg as Extract<T, { type: any }>);\n });\n }\n\n /**\n * Removes all subscriptions (both specific and global) for a given\n * subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.unsubscribe('sub-1');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribe(id: SiggnId) {\n this.unsubscribeGlobal(id);\n\n for (const [type, subscriptions] of this.subscriptions) {\n this.subscriptions.set(\n type,\n subscriptions.filter((sub) => sub.id !== id),\n );\n }\n }\n\n /**\n * Removes a global subscription for a given subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribeAll('logger', console.log);\n * siggn.unsubscribeGlobal('logger');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribeGlobal(id: SiggnId) {\n this.globalSubscriptions = this.globalSubscriptions.filter((s) => s.id !== id);\n }\n\n /**\n * Returns the total number of subscriptions (both specific and global).\n *\n * @category Subscription\n * @since 0.1.0\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => {});\n * siggn.subscribeAll('logger', () => {});\n * console.log(siggn.subscriptionsCount); // 2\n * ```\n */\n get subscriptionsCount() {\n let count = 0;\n\n this.subscriptions.forEach((subs) => {\n count += subs.length;\n });\n\n count += this.globalSubscriptions.length;\n\n return count;\n }\n}\n","import { type Msg, Siggn } from '@siggn/core';\nimport type { SubscriptionOptions } from 'packages/react/src/types';\nimport { useEffect, useMemo, useRef, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const siggn = useRef(new Siggn<T>());\n return siggn.current;\n}\n\n/**\n * Subscribes to messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<T extends Msg>(\n options: SubscriptionOptions<T>,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: SubscriptionOptions<T>,\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["Siggn","id","type","callback","setup","msg","sub","fn","subscriptions","s","count","subs","useSiggn","useRef","useSubscribe","options","deps","instance","useMemo","useEffect","useSubscribeAll"],"mappings":"yGAOO,MAAMA,CAAqB,CACxB,OAAS,EACT,cACA,oBAAmD,CAAA,EAM1C,SAAW,IAAI,qBAA+BC,GAAO,CACpE,KAAK,YAAYA,CAAE,CACrB,CAAC,EAMgB,eAAiB,IAAI,qBAA+BA,GAAO,CAC1E,K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AO,CAAA,EAEJd,EAAKiB,EAAAA,QAAQ,IAAMD,EAAS,OAAO,OAAQF,EAAUA,EAAQ,GAAK,MAAS,EAAG,CAACE,CAAQ,CAAC,EAE9FE,EAAAA,UAAU,KACRF,EAAS,aAAahB,EAAIE,CAAQ,EAE3B,IAAM,CACXc,EAAS,kBAAkBhB,CAAE,CAC/B,GACC,CAACgB,EAAUhB,EAAI,GAAGe,CAAI,CAAC,CAC5B"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,30 +1,281 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { useRef as c, useMemo as b, useEffect as u } from "react";
|
|
2
|
+
class n {
|
|
3
|
+
nextId = 0;
|
|
4
|
+
subscriptions;
|
|
5
|
+
globalSubscriptions = [];
|
|
6
|
+
/**
|
|
7
|
+
* A FinalizationRegistry to automatically unregister specific subscriptions
|
|
8
|
+
* when the subscribed callback function is garbage collected.
|
|
9
|
+
*/
|
|
10
|
+
registry = new FinalizationRegistry((s) => {
|
|
11
|
+
this.unsubscribe(s);
|
|
12
|
+
});
|
|
13
|
+
/**
|
|
14
|
+
* A FinalizationRegistry to automatically unregister global subscriptions
|
|
15
|
+
* when the subscribed callback function is garbage collected.
|
|
16
|
+
*/
|
|
17
|
+
registryGlobal = new FinalizationRegistry((s) => {
|
|
18
|
+
this.unsubscribeGlobal(s);
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* Creates a new Siggn instance.
|
|
22
|
+
* @category Lifecycle
|
|
23
|
+
* @since 0.0.5
|
|
24
|
+
*/
|
|
25
|
+
constructor() {
|
|
26
|
+
this.subscriptions = /* @__PURE__ */ new Map();
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Creates a new, independent `Siggn` instance that inherits the message
|
|
30
|
+
* types of its parent and adds new ones.
|
|
31
|
+
*
|
|
32
|
+
* @template C The new message types to add.
|
|
33
|
+
* @returns A new `Siggn` instance with combined message types.
|
|
34
|
+
* @category Lifecycle
|
|
35
|
+
* @since 0.0.5
|
|
36
|
+
* @example
|
|
37
|
+
*
|
|
38
|
+
```typescript
|
|
39
|
+
* const baseSiggn = new Siggn<{ type: 'A' }>();
|
|
40
|
+
* const childSiggn = baseSiggn.createClone<{ type: 'B' }>();
|
|
41
|
+
* // childSiggn can now publish and subscribe to types 'A' and 'B'.
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
createClone() {
|
|
45
|
+
return new n();
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Generates a unique ID for a subscriber.
|
|
49
|
+
* If an ID is provided, it will be used; otherwise, a new one is generated.
|
|
50
|
+
*
|
|
51
|
+
* @param id An optional ID to use.
|
|
52
|
+
* @returns A unique subscriber ID.
|
|
53
|
+
* @category Utilities
|
|
54
|
+
* @since 0.0.5
|
|
55
|
+
* @example
|
|
56
|
+
*
|
|
57
|
+
```typescript
|
|
58
|
+
* const siggn = new Siggn();
|
|
59
|
+
* const id1 = siggn.makeId(); // e.g., "sub_0"
|
|
60
|
+
* const id2 = siggn.makeId('custom-id'); // "custom-id"
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
makeId(s) {
|
|
64
|
+
return s ?? `sub_${(this.nextId++).toString(36)}`;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Creates a subscription helper object that is pre-configured with a
|
|
68
|
+
* specific subscriber ID. This simplifies managing multiple subscriptions
|
|
69
|
+
* for a single component or service.
|
|
70
|
+
*
|
|
71
|
+
* @param id The subscriber ID to use for all subscriptions.
|
|
72
|
+
* @returns An object with `subscribe`, `unsubscribe`, `subscribeMany`, and `subscribeAll` methods.
|
|
73
|
+
* @category Subscription
|
|
74
|
+
* @since 0.0.5
|
|
75
|
+
* @example
|
|
76
|
+
*
|
|
77
|
+
```typescript
|
|
78
|
+
* const siggn = new Siggn<{ type: 'event' }>();
|
|
79
|
+
* const component = siggn.make('my-component');
|
|
80
|
+
* component.subscribe('event', () => console.log('event received!'));
|
|
81
|
+
* component.unsubscribe();
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
make(s) {
|
|
85
|
+
return {
|
|
86
|
+
subscribe: (i, e) => {
|
|
87
|
+
this.subscribe(s, i, e);
|
|
88
|
+
},
|
|
89
|
+
unsubscribe: () => {
|
|
90
|
+
this.unsubscribe(s);
|
|
91
|
+
},
|
|
92
|
+
subscribeMany: (i) => {
|
|
93
|
+
this.subscribeMany(s, i);
|
|
94
|
+
},
|
|
95
|
+
subscribeAll: (i) => {
|
|
96
|
+
this.subscribeAll(s, i);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Subscribes to multiple message types using a single subscriber ID.
|
|
102
|
+
*
|
|
103
|
+
* @param id The subscriber ID.
|
|
104
|
+
* @param setup A function that receives a `subscribe` helper to register callbacks.
|
|
105
|
+
* @category Subscription
|
|
106
|
+
* @since 0.0.5
|
|
107
|
+
* @example
|
|
108
|
+
*
|
|
109
|
+
```typescript
|
|
110
|
+
* const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();
|
|
111
|
+
* siggn.subscribeMany('subscriber-1', (subscribe) => {
|
|
112
|
+
* subscribe('A', () => console.log('A received'));
|
|
113
|
+
* subscribe('B', () => console.log('B received'));
|
|
114
|
+
* });
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
subscribeMany(s, i) {
|
|
118
|
+
i((e, t) => this.subscribe(s, e, t));
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Subscribes to a specific message type.
|
|
122
|
+
*
|
|
123
|
+
* @param id The subscriber ID.
|
|
124
|
+
* @param type The message type to subscribe to.
|
|
125
|
+
* @param callback The function to call when a message of the specified type is published.
|
|
126
|
+
* @category Subscription
|
|
127
|
+
* @since 0.0.5
|
|
128
|
+
* @example
|
|
129
|
+
*
|
|
130
|
+
```typescript
|
|
131
|
+
* const siggn = new Siggn<{ type: 'my-event', payload: string }>();
|
|
132
|
+
* siggn.subscribe('subscriber-1', 'my-event', (msg) => {
|
|
133
|
+
* console.log(msg.payload);
|
|
134
|
+
* });
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
subscribe(s, i, e) {
|
|
138
|
+
this.subscriptions.has(i) || this.subscriptions.set(i, []), this.registry.register(e, s), this.subscriptions.get(i)?.push({ id: s, ref: new WeakRef(e) });
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Subscribes to all message types. The callback will be invoked for every
|
|
142
|
+
* message published on the bus.
|
|
143
|
+
*
|
|
144
|
+
* @param id The subscriber ID.
|
|
145
|
+
* @param callback The function to call for any message.
|
|
146
|
+
* @category Subscription
|
|
147
|
+
* @since 0.0.5
|
|
148
|
+
* @example
|
|
149
|
+
*
|
|
150
|
+
```typescript
|
|
151
|
+
* const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();
|
|
152
|
+
* siggn.subscribeAll('logger', (msg) => {
|
|
153
|
+
* console.log(`Received message of type: ${msg.type}`);
|
|
154
|
+
* });
|
|
155
|
+
* ```
|
|
156
|
+
*/
|
|
157
|
+
subscribeAll(s, i) {
|
|
158
|
+
this.registryGlobal.register(i, s), this.globalSubscriptions.push({ id: s, ref: new WeakRef(i) });
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Publishes a message to all relevant subscribers.
|
|
162
|
+
*
|
|
163
|
+
* @param msg The message to publish.
|
|
164
|
+
* @category Publishing
|
|
165
|
+
* @since 0.0.5
|
|
166
|
+
* @example
|
|
167
|
+
*
|
|
168
|
+
```typescript
|
|
169
|
+
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
170
|
+
* siggn.subscribe('sub-1', 'my-event', () => console.log('received'));
|
|
171
|
+
* siggn.publish({ type: 'my-event' }); // "received"
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
174
|
+
publish(s) {
|
|
175
|
+
this.globalSubscriptions.forEach((i) => {
|
|
176
|
+
const e = i.ref.deref();
|
|
177
|
+
if (!e) {
|
|
178
|
+
this.unsubscribeGlobal(i.id);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
e(s);
|
|
182
|
+
}), this.subscriptions.has(s.type) && this.subscriptions.get(s.type)?.forEach((i) => {
|
|
183
|
+
const e = i.ref.deref();
|
|
184
|
+
if (!e) {
|
|
185
|
+
this.unsubscribe(i.id);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
e(s);
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Removes all subscriptions (both specific and global) for a given
|
|
193
|
+
* subscriber ID.
|
|
194
|
+
*
|
|
195
|
+
* @param id The subscriber ID to unsubscribe.
|
|
196
|
+
* @category Subscription
|
|
197
|
+
* @since 0.0.5
|
|
198
|
+
* @example
|
|
199
|
+
*
|
|
200
|
+
```typescript
|
|
201
|
+
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
202
|
+
* siggn.subscribe('sub-1', 'my-event', () => console.log('received'));
|
|
203
|
+
* siggn.unsubscribe('sub-1');
|
|
204
|
+
* siggn.publish({ type: 'my-event' }); // (nothing is logged)
|
|
205
|
+
* ```
|
|
206
|
+
*/
|
|
207
|
+
unsubscribe(s) {
|
|
208
|
+
this.unsubscribeGlobal(s);
|
|
209
|
+
for (const [i, e] of this.subscriptions)
|
|
210
|
+
this.subscriptions.set(
|
|
211
|
+
i,
|
|
212
|
+
e.filter((t) => t.id !== s)
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Removes a global subscription for a given subscriber ID.
|
|
217
|
+
*
|
|
218
|
+
* @param id The subscriber ID to unsubscribe.
|
|
219
|
+
* @category Subscription
|
|
220
|
+
* @since 0.0.5
|
|
221
|
+
* @example
|
|
222
|
+
*
|
|
223
|
+
```typescript
|
|
224
|
+
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
225
|
+
* siggn.subscribeAll('logger', console.log);
|
|
226
|
+
* siggn.unsubscribeGlobal('logger');
|
|
227
|
+
* siggn.publish({ type: 'my-event' }); // (nothing is logged)
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
unsubscribeGlobal(s) {
|
|
231
|
+
this.globalSubscriptions = this.globalSubscriptions.filter((i) => i.id !== s);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Returns the total number of subscriptions (both specific and global).
|
|
235
|
+
*
|
|
236
|
+
* @category Subscription
|
|
237
|
+
* @since 0.1.0
|
|
238
|
+
* @example
|
|
239
|
+
*
|
|
240
|
+
```typescript
|
|
241
|
+
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
242
|
+
* siggn.subscribe('sub-1', 'my-event', () => {});
|
|
243
|
+
* siggn.subscribeAll('logger', () => {});
|
|
244
|
+
* console.log(siggn.subscriptionsCount); // 2
|
|
245
|
+
* ```
|
|
246
|
+
*/
|
|
247
|
+
get subscriptionsCount() {
|
|
248
|
+
let s = 0;
|
|
249
|
+
return this.subscriptions.forEach((i) => {
|
|
250
|
+
s += i.length;
|
|
251
|
+
}), s += this.globalSubscriptions.length, s;
|
|
252
|
+
}
|
|
6
253
|
}
|
|
7
|
-
function
|
|
8
|
-
|
|
9
|
-
() => e instanceof s ? e : e.instance,
|
|
10
|
-
[e]
|
|
11
|
-
), c = i(() => n.makeId("id" in e ? e.id : void 0), [n]);
|
|
12
|
-
b(() => (n.subscribeMany(c, r), () => {
|
|
13
|
-
n.unsubscribe(c);
|
|
14
|
-
}), [n, c, ...u]);
|
|
254
|
+
function l() {
|
|
255
|
+
return c(new n()).current;
|
|
15
256
|
}
|
|
16
|
-
function
|
|
17
|
-
const
|
|
18
|
-
() =>
|
|
19
|
-
[
|
|
20
|
-
),
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}), [
|
|
257
|
+
function a(r, s, i = []) {
|
|
258
|
+
const e = b(
|
|
259
|
+
() => r instanceof n ? r : r.instance,
|
|
260
|
+
[r]
|
|
261
|
+
), t = b(() => e.makeId("id" in r ? r.id : void 0), [e]);
|
|
262
|
+
u(() => (e.subscribeMany(t, s), () => {
|
|
263
|
+
e.unsubscribe(t);
|
|
264
|
+
}), [e, t, ...i]);
|
|
265
|
+
}
|
|
266
|
+
function h(r, s, i = []) {
|
|
267
|
+
const e = b(
|
|
268
|
+
() => r instanceof n ? r : r.instance,
|
|
269
|
+
[r]
|
|
270
|
+
), t = b(() => e.makeId("id" in r ? r.id : void 0), [e]);
|
|
271
|
+
u(() => (e.subscribeAll(t, s), () => {
|
|
272
|
+
e.unsubscribeGlobal(t);
|
|
273
|
+
}), [e, t, ...i]);
|
|
24
274
|
}
|
|
25
275
|
export {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
276
|
+
n as Siggn,
|
|
277
|
+
l as useSiggn,
|
|
278
|
+
a as useSubscribe,
|
|
279
|
+
h as useSubscribeAll
|
|
29
280
|
};
|
|
30
281
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/hooks.ts"],"sourcesContent":["import { type Msg, Siggn } from '@siggn/core';\nimport type { SubscriptionOptions } from 'packages/react/src/types';\nimport { useEffect, useMemo, useRef, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const siggn = useRef(new Siggn<T>());\n return siggn.current;\n}\n\n/**\n * Subscribes to messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<T extends Msg>(\n options: SubscriptionOptions<T>,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: SubscriptionOptions<T>,\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["useSiggn","useRef","Siggn","useSubscribe","options","setup","deps","instance","useMemo","id","useEffect","useSubscribeAll","callback"],"mappings":";;;AAqBO,SAASA,IAAoC;AAElD,SADcC,EAAO,IAAIC,GAAU,EACtB;AACf;AAwBO,SAASC,EACdC,GACAC,GAMAC,IAAuB,CAAA,GACvB;AACA,QAAMC,IAAWC;AAAA,IACf,MAAOJ,aAAmBF,IAAQE,IAAUA,EAAQ;AAAA,IACpD,CAACA,CAAO;AAAA,EAAA,GAEJK,IAAKD,EAAQ,MAAMD,EAAS,OAAO,QAAQH,IAAUA,EAAQ,KAAK,MAAS,GAAG,CAACG,CAAQ,CAAC;AAE9F,EAAAG,EAAU,OACRH,EAAS,cAAcE,GAAIJ,CAAK,GAEzB,MAAM;AACX,IAAAE,EAAS,YAAYE,CAAE;AAAA,EACzB,IACC,CAACF,GAAUE,GAAI,GAAGH,CAAI,CAAC;AAC5B;AAyBO,SAASK,EACdP,GACAQ,GACAN,IAAuB,CAAA,GACvB;AACA,QAAMC,IAAWC;AAAA,IACf,MAAOJ,aAAmBF,IAAQE,IAAUA,EAAQ;AAAA,IACpD,CAACA,CAAO;AAAA,EAAA,GAEJK,IAAKD,EAAQ,MAAMD,EAAS,OAAO,QAAQH,IAAUA,EAAQ,KAAK,MAAS,GAAG,CAACG,CAAQ,CAAC;AAE9F,EAAAG,EAAU,OACRH,EAAS,aAAaE,GAAIG,CAAQ,GAE3B,MAAM;AACX,IAAAL,EAAS,kBAAkBE,CAAE;AAAA,EAC/B,IACC,CAACF,GAAUE,GAAI,GAAGH,CAAI,CAAC;AAC5B;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../../core/src/siggn.ts","../src/hooks.ts"],"sourcesContent":["import type { Msg, Subscription, SiggnId } from './types.js';\n\n/**\n * A type-safe message bus for dispatching and subscribing to events.\n * @template T A union of all possible message types.\n * @since 0.0.5\n */\nexport class Siggn<T extends Msg> {\n private nextId = 0;\n private subscriptions: Map<T['type'], Array<Subscription<T, any>>>;\n private globalSubscriptions: Array<Subscription<T, any>> = [];\n\n /**\n * A FinalizationRegistry to automatically unregister specific subscriptions\n * when the subscribed callback function is garbage collected.\n */\n private readonly registry = new FinalizationRegistry<SiggnId>((id) => {\n this.unsubscribe(id);\n });\n\n /**\n * A FinalizationRegistry to automatically unregister global subscriptions\n * when the subscribed callback function is garbage collected.\n */\n private readonly registryGlobal = new FinalizationRegistry<SiggnId>((id) => {\n this.unsubscribeGlobal(id);\n });\n\n /**\n * Creates a new Siggn instance.\n * @category Lifecycle\n * @since 0.0.5\n */\n constructor() {\n this.subscriptions = new Map();\n }\n\n /**\n * Creates a new, independent `Siggn` instance that inherits the message\n * types of its parent and adds new ones.\n *\n * @template C The new message types to add.\n * @returns A new `Siggn` instance with combined message types.\n * @category Lifecycle\n * @since 0.0.5\n * @example\n * \n```typescript\n * const baseSiggn = new Siggn<{ type: 'A' }>();\n * const childSiggn = baseSiggn.createClone<{ type: 'B' }>();\n * // childSiggn can now publish and subscribe to types 'A' and 'B'.\n * ```\n */\n createClone<C extends Msg>() {\n return new Siggn<C | T>();\n }\n\n /**\n * Generates a unique ID for a subscriber.\n * If an ID is provided, it will be used; otherwise, a new one is generated.\n *\n * @param id An optional ID to use.\n * @returns A unique subscriber ID.\n * @category Utilities\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn();\n * const id1 = siggn.makeId(); // e.g., \"sub_0\"\n * const id2 = siggn.makeId('custom-id'); // \"custom-id\"\n * ```\n */\n makeId(id?: string): SiggnId {\n return id ?? `sub_${(this.nextId++).toString(36)}`;\n }\n\n /**\n * Creates a subscription helper object that is pre-configured with a\n * specific subscriber ID. This simplifies managing multiple subscriptions\n * for a single component or service.\n *\n * @param id The subscriber ID to use for all subscriptions.\n * @returns An object with `subscribe`, `unsubscribe`, `subscribeMany`, and `subscribeAll` methods.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'event' }>();\n * const component = siggn.make('my-component');\n * component.subscribe('event', () => console.log('event received!'));\n * component.unsubscribe();\n * ```\n */\n make(id: SiggnId): {\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void;\n unsubscribe: () => void;\n subscribeMany: (\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n ) => void;\n subscribeAll: (callback: (msg: T) => void) => void;\n } {\n return {\n subscribe: (type, callback) => {\n this.subscribe(id, type, callback);\n },\n unsubscribe: () => {\n this.unsubscribe(id);\n },\n subscribeMany: (setup) => {\n this.subscribeMany(id, setup);\n },\n subscribeAll: (callback) => {\n this.subscribeAll(id, callback);\n },\n };\n }\n\n /**\n * Subscribes to multiple message types using a single subscriber ID.\n *\n * @param id The subscriber ID.\n * @param setup A function that receives a `subscribe` helper to register callbacks.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeMany('subscriber-1', (subscribe) => {\n * subscribe('A', () => console.log('A received'));\n * subscribe('B', () => console.log('B received'));\n * });\n * ```\n */\n subscribeMany(\n id: SiggnId,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n ) {\n setup((type, callback) => this.subscribe(id, type, callback));\n }\n\n /**\n * Subscribes to a specific message type.\n *\n * @param id The subscriber ID.\n * @param type The message type to subscribe to.\n * @param callback The function to call when a message of the specified type is published.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event', payload: string }>();\n * siggn.subscribe('subscriber-1', 'my-event', (msg) => {\n * console.log(msg.payload);\n * });\n * ```\n */\n subscribe<K extends T['type']>(\n id: SiggnId,\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) {\n if (!this.subscriptions.has(type)) {\n this.subscriptions.set(type, []);\n }\n\n this.registry.register(callback, id);\n this.subscriptions.get(type)?.push({ id, ref: new WeakRef(callback) });\n }\n\n /**\n * Subscribes to all message types. The callback will be invoked for every\n * message published on the bus.\n *\n * @param id The subscriber ID.\n * @param callback The function to call for any message.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeAll('logger', (msg) => {\n * console.log(`Received message of type: ${msg.type}`);\n * });\n * ```\n */\n subscribeAll(id: SiggnId, callback: (msg: T) => void) {\n this.registryGlobal.register(callback, id);\n this.globalSubscriptions.push({ id, ref: new WeakRef(callback) });\n }\n\n /**\n * Publishes a message to all relevant subscribers.\n *\n * @param msg The message to publish.\n * @category Publishing\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.publish({ type: 'my-event' }); // \"received\"\n * ```\n */\n publish(msg: T) {\n this.globalSubscriptions.forEach((sub) => {\n const fn = sub.ref.deref();\n\n if (!fn) {\n this.unsubscribeGlobal(sub.id);\n return;\n }\n\n fn(msg as Extract<T, { type: any }>);\n });\n\n if (!this.subscriptions.has(msg.type)) {\n return;\n }\n\n this.subscriptions.get(msg.type)?.forEach((sub) => {\n const fn = sub.ref.deref();\n\n if (!fn) {\n this.unsubscribe(sub.id);\n return;\n }\n\n fn(msg as Extract<T, { type: any }>);\n });\n }\n\n /**\n * Removes all subscriptions (both specific and global) for a given\n * subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.unsubscribe('sub-1');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribe(id: SiggnId) {\n this.unsubscribeGlobal(id);\n\n for (const [type, subscriptions] of this.subscriptions) {\n this.subscriptions.set(\n type,\n subscriptions.filter((sub) => sub.id !== id),\n );\n }\n }\n\n /**\n * Removes a global subscription for a given subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribeAll('logger', console.log);\n * siggn.unsubscribeGlobal('logger');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribeGlobal(id: SiggnId) {\n this.globalSubscriptions = this.globalSubscriptions.filter((s) => s.id !== id);\n }\n\n /**\n * Returns the total number of subscriptions (both specific and global).\n *\n * @category Subscription\n * @since 0.1.0\n * @example\n * \n```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => {});\n * siggn.subscribeAll('logger', () => {});\n * console.log(siggn.subscriptionsCount); // 2\n * ```\n */\n get subscriptionsCount() {\n let count = 0;\n\n this.subscriptions.forEach((subs) => {\n count += subs.length;\n });\n\n count += this.globalSubscriptions.length;\n\n return count;\n }\n}\n","import { type Msg, Siggn } from '@siggn/core';\nimport type { SubscriptionOptions } from 'packages/react/src/types';\nimport { useEffect, useMemo, useRef, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const siggn = useRef(new Siggn<T>());\n return siggn.current;\n}\n\n/**\n * Subscribes to messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<T extends Msg>(\n options: SubscriptionOptions<T>,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: SubscriptionOptions<T>,\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["Siggn","id","type","callback","setup","msg","sub","fn","subscriptions","s","count","subs","useSiggn","useRef","useSubscribe","options","deps","instance","useMemo","useEffect","useSubscribeAll"],"mappings":";AAOO,MAAMA,EAAqB;AAAA,EACxB,SAAS;AAAA,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