@siggn/react 0.0.1

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/.prettierrc ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "arrowParens": "always",
3
+ "bracketSpacing": true,
4
+ "htmlWhitespaceSensitivity": "css",
5
+ "insertPragma": false,
6
+ "jsxSingleQuote": true,
7
+ "printWidth": 100,
8
+ "proseWrap": "always",
9
+ "quoteProps": "as-needed",
10
+ "requirePragma": false,
11
+ "semi": true,
12
+ "singleQuote": true,
13
+ "tabWidth": 2,
14
+ "trailingComma": "all",
15
+ "useTabs": false
16
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # @siggn/react
2
+
3
+ ## 0.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [`d2a88af`](https://github.com/Guiguerreiro39/siggn/commit/d2a88af8e484f28e436c594cd3238379295941a2)
8
+ Thanks [@Guiguerreiro39](https://github.com/Guiguerreiro39)! - Added react hooks support
9
+
10
+ - Updated dependencies
11
+ [[`d2a88af`](https://github.com/Guiguerreiro39/siggn/commit/d2a88af8e484f28e436c594cd3238379295941a2)]:
12
+ - @siggn/core@0.0.5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Guilherme Guerreiro
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,203 @@
1
+ # @siggn/core
2
+
3
+ A lightweight and type-safe event-driven pub/sub system for TypeScript projects.
4
+
5
+ ## Features
6
+
7
+ - **Type-Safe**: Leverages TypeScript to ensure that message payloads are correct at compile and
8
+ runtime.
9
+ - **Lightweight**: Zero dependencies and a minimal API surface.
10
+ - **Simple API**: Easy to learn and use, with a clear and concise API.
11
+
12
+ ## Installation
13
+
14
+ You can install the package using your favorite package manager:
15
+
16
+ ```bash
17
+ npm install @siggn/core
18
+ ```
19
+
20
+ ```bash
21
+ yarn add @siggn/core
22
+ ```
23
+
24
+ ```bash
25
+ pnpm add @siggn/core
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ Here's a basic example of how to use Siggn:
31
+
32
+ ```typescript
33
+ import { Siggn } from '@siggn/core';
34
+
35
+ // 1. Define your message types
36
+ type Message =
37
+ | { type: 'user_created'; userId: string; name: string }
38
+ | { type: 'user_deleted'; userId: string };
39
+
40
+ // 2. Create a new Siggn instance
41
+ const siggn = new Siggn<Message>();
42
+
43
+ // 3. Subscribe to events
44
+ // Use a unique ID for each subscriber to manage subscriptions
45
+ const subscriberId = 'analytics-service';
46
+
47
+ siggn.subscribe(subscriberId, 'user_created', (msg) => {
48
+ console.log(`[Analytics] New user created: ${msg.name} (ID: ${msg.userId})`);
49
+ });
50
+
51
+ // 4. Publish events
52
+ siggn.publish({ type: 'user_created', userId: '123', name: 'John Doe' });
53
+ // Output: [Analytics] New user created: John Doe (ID: 123)
54
+
55
+ // 5. Unsubscribe from all events for a given ID
56
+ siggn.unsubscribe(subscriberId);
57
+
58
+ siggn.publish({ type: 'user_created', userId: '456', name: 'Jane Doe' });
59
+ // No output, because the subscriber was removed.
60
+ ```
61
+
62
+ ### Using the `make` helper
63
+
64
+ The `make` method simplifies managing subscriptions for a specific component or service.
65
+
66
+ ```typescript
67
+ const userComponent = siggn.make('user-component');
68
+
69
+ userComponent.subscribe('user_deleted', (msg) => {
70
+ console.log(`[UI] User ${msg.userId} was deleted. Updating view...`);
71
+ });
72
+
73
+ siggn.publish({ type: 'user_deleted', userId: '123' });
74
+ // Output: [UI] User 123 was deleted. Updating view...
75
+
76
+ // Unsubscribe from all subscriptions made by 'user-component'
77
+ userComponent.unsubscribe();
78
+ ```
79
+
80
+ ### Subscribing to multiple events
81
+
82
+ You can use `subscribeMany` to group subscriptions for a single subscriber.
83
+
84
+ ```typescript
85
+ const auditService = siggn.make('audit-service');
86
+
87
+ auditService.subscribeMany((subscribe) => {
88
+ subscribe('user_created', (msg) => {
89
+ console.log(`[Audit] User created: ${msg.name}`);
90
+ });
91
+ subscribe('user_deleted', (msg) => {
92
+ console.log(`[Audit] User deleted: ${msg.userId}`);
93
+ });
94
+ });
95
+
96
+ siggn.publish({ type: 'user_created', userId: '789', name: 'Peter Pan' });
97
+ siggn.publish({ type: 'user_deleted', userId: '123' });
98
+
99
+ // Unsubscribe from all audit-service events
100
+ auditService.unsubscribe();
101
+ ```
102
+
103
+ ### Subscribing to all events
104
+
105
+ If you need to listen to every message that passes through the bus, regardless of its type, you can
106
+ use `subscribeAll`. This is useful for cross-cutting concerns like logging or debugging.
107
+
108
+ ```typescript
109
+ const logger = siggn.make('logger-service');
110
+
111
+ logger.subscribeAll((msg) => {
112
+ console.log(`[Logger] Received event of type: ${msg.type}`);
113
+ });
114
+
115
+ siggn.publish({ type: 'user_created', userId: '789', name: 'Peter Pan' });
116
+ // Output: [Logger] Received event of type: user_created
117
+
118
+ siggn.publish({ type: 'user_deleted', userId: '123' });
119
+ // Output: [Logger] Received event of type: user_deleted
120
+
121
+ // Unsubscribe from all logger-service events
122
+ logger.unsubscribe();
123
+ ```
124
+
125
+ ### Extending message types with `createChild`
126
+
127
+ The `createChild` method allows you to create a new, independent `Siggn` instance that inherits the
128
+ message types of its parent. This is useful for creating specialized message buses that extend a
129
+ base set of events without affecting the parent bus.
130
+
131
+ ```typescript
132
+ // Continuing with the previous `Message` type...
133
+ const baseSiggn = new Siggn<Message>();
134
+
135
+ // 1. Define a new set of messages for a specialized module
136
+ type AdminMessage = { type: 'admin_login'; adminId: string };
137
+
138
+ // 2. Create a child bus that understands both `Message` and `AdminMessage`
139
+ const adminSiggn = baseSiggn.createChild<AdminMessage>();
140
+
141
+ // 3. Subscribe to events on the child bus
142
+ adminSiggn.subscribe('audit-log', 'user_created', (msg) => {
143
+ console.log(`[Admin Audit] User created: ${msg.name}`);
144
+ });
145
+
146
+ adminSiggn.subscribe('auth-service', 'admin_login', (msg) => {
147
+ console.log(`[Admin Auth] Admin logged in: ${msg.adminId}`);
148
+ });
149
+
150
+ // 4. Publish events on the child bus
151
+ adminSiggn.publish({ type: 'user_created', userId: 'abc', name: 'Alice' });
152
+ // Output: [Admin Audit] User created: Alice
153
+
154
+ adminSiggn.publish({ type: 'admin_login', adminId: 'xyz' });
155
+ // Output: [Admin Auth] Admin logged in: xyz
156
+
157
+ // Note: The parent and child buses are independent.
158
+ // Publishing on the parent does not affect the child's subscribers.
159
+ baseSiggn.publish({ type: 'user_created', userId: 'def', name: 'Bob' });
160
+ // No output, because the subscription is on `adminSiggn`.
161
+ ```
162
+
163
+ ## API
164
+
165
+ ### `new Siggn<T>()`
166
+
167
+ Creates a new message bus instance. `T` is a union type of all possible messages.
168
+
169
+ ### `publish(msg)`
170
+
171
+ Publishes a message to all relevant subscribers.
172
+
173
+ ### `subscribe(id, type, callback)`
174
+
175
+ Subscribes a callback to a specific message type with a unique subscriber ID.
176
+
177
+ ### `subscribeAll(id, callback)`
178
+
179
+ Subscribes a callback to all message types with a unique subscriber ID. The callback will receive
180
+ every message published on the bus.
181
+
182
+ ### `unsubscribe(id)`
183
+
184
+ Removes all subscriptions associated with a specific subscriber ID.
185
+
186
+ ### `make(id)`
187
+
188
+ Returns a helper object with `subscribe`, `subscribeMany`, `subscribeAll`, and `unsubscribe` methods
189
+ pre-bound to the provided ID. This is useful for encapsulating subscription logic within a component
190
+ or service.
191
+
192
+ ### `subscribeMany(id, setup)`
193
+
194
+ A convenience method to subscribe to multiple message types for a single ID.
195
+
196
+ ### `createChild<C>()`
197
+
198
+ Creates a new, independent `Siggn` instance whose message types are a union of the parent's types
199
+ and the new child-specific types `C`.
200
+
201
+ ## License
202
+
203
+ This project is licensed under the [MIT License](LICENSE).
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@siggn/react",
3
+ "version": "0.0.1",
4
+ "description": "A lightweight type safe message bus system for React",
5
+ "keywords": [
6
+ "pub/sub",
7
+ "message",
8
+ "event",
9
+ "bus",
10
+ "react",
11
+ "typesafe"
12
+ ],
13
+ "publishConfig": {
14
+ "@siggn:registry": "https://registry.npmjs.org/",
15
+ "access": "public"
16
+ },
17
+ "homepage": "https://github.com/Guiguerreiro39/siggn",
18
+ "bugs": {
19
+ "url": "https://github.com/Guiguerreiro39/siggn/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/Guiguerreiro39/siggn.git/",
24
+ "directory": "packages/react"
25
+ },
26
+ "license": "MIT",
27
+ "author": "Guilherme Guerreiro (https://guilhermegr.com)",
28
+ "main": "./dist/index.cjs.js",
29
+ "module": "./dist/index.es.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.es.js",
35
+ "require": "./dist/index.cjs.js"
36
+ }
37
+ },
38
+ "type": "module",
39
+ "sideEffects": false,
40
+ "devDependencies": {
41
+ "typescript": "^5.9.3",
42
+ "vite": "^7.1.12",
43
+ "vite-plugin-dts": "^4.5.4",
44
+ "@vitejs/plugin-react": "^5.1.0",
45
+ "vitest": "^3.2.4",
46
+ "@testing-library/dom": "^10.4.1",
47
+ "@testing-library/jest-dom": "^6.9.1",
48
+ "@testing-library/react": "^16.3.0",
49
+ "@types/react": "^19.1.15",
50
+ "react": "^19.1.1",
51
+ "jsdom": "^27.0.1"
52
+ },
53
+ "peerDependencies": {
54
+ "typescript": "^5",
55
+ "react": ">=18 <20"
56
+ },
57
+ "dependencies": {
58
+ "@siggn/core": "0.0.5"
59
+ },
60
+ "scripts": {
61
+ "dev": "vite build --watch",
62
+ "clean": "rm -rf dist",
63
+ "test:watch": "vitest",
64
+ "test": "vitest run",
65
+ "build": "vite build"
66
+ }
67
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { type Msg, Siggn } from '@siggn/core';
2
+ import { useEffect, useMemo, useRef, type DependencyList } from 'react';
3
+
4
+ type SubscriptionOptions<T extends Msg> =
5
+ | Siggn<T>
6
+ | {
7
+ instance: Siggn<T>;
8
+ id?: string;
9
+ };
10
+
11
+ export function useSubscribe<T extends Msg>(
12
+ options: SubscriptionOptions<T>,
13
+ setup: (
14
+ subscribe: <K extends T['type']>(
15
+ type: K,
16
+ callback: (msg: Extract<T, { type: K }>) => void,
17
+ ) => void,
18
+ ) => void,
19
+ deps: DependencyList = [],
20
+ ) {
21
+ const instance = useMemo(
22
+ () => (options instanceof Siggn ? options : options.instance),
23
+ [options],
24
+ );
25
+ const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);
26
+
27
+ useEffect(() => {
28
+ instance.subscribeMany(id, setup);
29
+
30
+ return () => {
31
+ instance.unsubscribe(id);
32
+ };
33
+ }, [instance, id, ...deps]);
34
+ }
35
+
36
+ export function useSiggn<T extends Msg>(): Siggn<T> {
37
+ const siggn = useRef<Siggn<T>>(new Siggn<T>());
38
+ return siggn.current;
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './hooks.js';
2
+ export * from '@siggn/core';
@@ -0,0 +1,55 @@
1
+ import { test, expect, describe, beforeEach } from 'vitest';
2
+ import { useSiggn, useSubscribe } from '../src/hooks.js';
3
+ import { Siggn } from '@siggn/core';
4
+ import { act, render, renderHook, screen } from '@testing-library/react';
5
+ import { useState } from 'react';
6
+
7
+ type Msg =
8
+ | {
9
+ type: 'increment_count';
10
+ value: number;
11
+ }
12
+ | { type: 'decrement_count'; value: number };
13
+
14
+ describe('@siggn/react', () => {
15
+ let siggn: Siggn<Msg>;
16
+
17
+ beforeEach(() => {
18
+ const { result } = renderHook(() => useSiggn<Msg>());
19
+ siggn = result.current;
20
+ });
21
+
22
+ test('user should be able to create a siggn instance and subscribe using hooks', () => {
23
+ function TestComponent() {
24
+ const [count, setCount] = useState(0);
25
+
26
+ useSubscribe(siggn, (subscribe) => {
27
+ subscribe('increment_count', (msg) => {
28
+ setCount((prev) => prev + msg.value);
29
+ });
30
+
31
+ subscribe('decrement_count', (msg) => {
32
+ setCount((prev) => prev - msg.value);
33
+ });
34
+ });
35
+
36
+ return <div data-testid='value'>{count}</div>;
37
+ }
38
+
39
+ render(<TestComponent />);
40
+
41
+ expect(screen.getByTestId('value')).toHaveTextContent('0');
42
+
43
+ act(() => {
44
+ siggn.publish({ type: 'increment_count', value: 4 });
45
+ });
46
+
47
+ expect(screen.getByTestId('value')).toHaveTextContent('4');
48
+
49
+ act(() => {
50
+ siggn.publish({ type: 'decrement_count', value: 2 });
51
+ });
52
+
53
+ expect(screen.getByTestId('value')).toHaveTextContent('2');
54
+ });
55
+ });
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.src.json",
3
+ "compilerOptions": {
4
+ "tsBuildInfoFile": ".tsbuildinfo/build.tsbuildinfo",
5
+ "outDir": "dist",
6
+ "declarationDir": "dist",
7
+ "stripInternal": true
8
+ },
9
+ "references": [{ "path": "../core" }]
10
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["examples"],
4
+ "references": [
5
+ {
6
+ "path": "tsconfig.build.json"
7
+ }
8
+ ],
9
+ "compilerOptions": {
10
+ "tsBuildInfoFile": ".tsbuildinfo/examples.tsbuildinfo",
11
+ "rootDir": "examples",
12
+ "noEmit": true
13
+ }
14
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "references": [
4
+ {
5
+ "path": "tsconfig.src.json"
6
+ },
7
+ {
8
+ "path": "tsconfig.test.json"
9
+ },
10
+ {
11
+ "path": "tsconfig.examples.json"
12
+ }
13
+ ]
14
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["src"],
4
+ "compilerOptions": {
5
+ "tsBuildInfoFile": ".tsbuildinfo/src.tsbuildinfo",
6
+ "rootDir": "src",
7
+ "outDir": "dist"
8
+ },
9
+ "references": [{ "path": "../core" }]
10
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["test"],
4
+ "references": [
5
+ {
6
+ "path": "tsconfig.src.json"
7
+ }
8
+ ],
9
+ "compilerOptions": {
10
+ "tsBuildInfoFile": ".tsbuildinfo/test.tsbuildinfo",
11
+ "rootDir": "test",
12
+ "noEmit": true,
13
+ "jsx": "react-jsx",
14
+ "types": ["@testing-library/jest-dom", "vitest/globals"]
15
+ }
16
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { defineConfig } from 'vite';
2
+ import react from '@vitejs/plugin-react';
3
+ import dts from 'vite-plugin-dts';
4
+ import path from 'path';
5
+
6
+ export default defineConfig({
7
+ resolve: {
8
+ alias: {
9
+ '@siggn/core': path.resolve(__dirname, '../core/src/index.ts'),
10
+ },
11
+ },
12
+ build: {
13
+ lib: {
14
+ entry: 'src/index.ts',
15
+ name: 'SiggnReact',
16
+ formats: ['es', 'cjs'],
17
+ fileName: (format) => `index.${format}.js`,
18
+ },
19
+ sourcemap: true,
20
+ outDir: 'dist',
21
+ emptyOutDir: true,
22
+ rollupOptions: {
23
+ // Prevent bundling peer dependencies like React, etc.
24
+ external: ['react', 'react-dom', '@siggn/core'],
25
+ output: {
26
+ globals: {
27
+ react: 'React',
28
+ 'react-dom': 'ReactDOM',
29
+ '@siggn/core': 'SiggnCore',
30
+ },
31
+ },
32
+ },
33
+ },
34
+ test: {
35
+ environment: 'jsdom',
36
+ globals: true,
37
+ setupFiles: './vitest.setup.ts',
38
+ },
39
+ plugins: [
40
+ react(),
41
+ dts({
42
+ insertTypesEntry: true,
43
+ tsconfigPath: 'tsconfig.build.json',
44
+ outDir: 'dist',
45
+ include: ['src'],
46
+ exclude: ['src/**/*.test.ts', 'tests/**'],
47
+ }),
48
+ ],
49
+ });
@@ -0,0 +1,7 @@
1
+ import '@testing-library/jest-dom/vitest';
2
+ import { cleanup } from '@testing-library/react';
3
+ import { afterEach } from 'vitest';
4
+
5
+ afterEach(() => {
6
+ cleanup();
7
+ });