@siggn/core 0.0.1 → 0.0.4

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/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 CHANGED
@@ -1,15 +1,203 @@
1
- # siggn
1
+ # @siggn/core
2
2
 
3
- To install dependencies:
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:
4
15
 
5
16
  ```bash
6
- bun install
17
+ npm install @siggn/core
7
18
  ```
8
19
 
9
- To run:
20
+ ```bash
21
+ yarn add @siggn/core
22
+ ```
10
23
 
11
24
  ```bash
12
- bun run index.ts
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();
13
123
  ```
14
124
 
15
- This project was created using `bun init` in bun v1.2.21. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
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/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class r{subscriptions;subscribeAllSubscriptions=[];constructor(){this.subscriptions=new Map}createChild(){return new r}make(i){return{subscribe:(s,b)=>{this.subscribe(i,s,b)},unsubscribe:()=>{this.unsubscribe(i)},subscribeMany:s=>{this.subscribeMany(i,s)},subscribeAll:s=>{this.subscribeAll(i,s)}}}subscribeMany(i,s){s((b,t)=>this.subscribe(i,b,t))}subscribe(i,s,b){this.subscriptions.has(s)||this.subscriptions.set(s,[]),this.subscriptions.get(s)?.push({id:i,callback:b})}subscribeAll(i,s){this.subscribeAllSubscriptions.push({id:i,callback:s})}publish(i){this.subscribeAllSubscriptions.forEach(s=>{s.callback(i)}),this.subscriptions.has(i.type)&&this.subscriptions.get(i.type)?.forEach(s=>{s.callback(i)})}unsubscribe(i){this.subscribeAllSubscriptions=this.subscribeAllSubscriptions.filter(s=>s.id!==i);for(const[s,b]of this.subscriptions)this.subscriptions.set(s,b.filter(t=>t.id!==i))}}exports.Siggn=r;
package/dist/index.js ADDED
@@ -0,0 +1,53 @@
1
+ class t {
2
+ subscriptions;
3
+ subscribeAllSubscriptions = [];
4
+ constructor() {
5
+ this.subscriptions = /* @__PURE__ */ new Map();
6
+ }
7
+ createChild() {
8
+ return new t();
9
+ }
10
+ make(i) {
11
+ return {
12
+ subscribe: (s, b) => {
13
+ this.subscribe(i, s, b);
14
+ },
15
+ unsubscribe: () => {
16
+ this.unsubscribe(i);
17
+ },
18
+ subscribeMany: (s) => {
19
+ this.subscribeMany(i, s);
20
+ },
21
+ subscribeAll: (s) => {
22
+ this.subscribeAll(i, s);
23
+ }
24
+ };
25
+ }
26
+ subscribeMany(i, s) {
27
+ s((b, r) => this.subscribe(i, b, r));
28
+ }
29
+ subscribe(i, s, b) {
30
+ this.subscriptions.has(s) || this.subscriptions.set(s, []), this.subscriptions.get(s)?.push({ id: i, callback: b });
31
+ }
32
+ subscribeAll(i, s) {
33
+ this.subscribeAllSubscriptions.push({ id: i, callback: s });
34
+ }
35
+ publish(i) {
36
+ this.subscribeAllSubscriptions.forEach((s) => {
37
+ s.callback(i);
38
+ }), this.subscriptions.has(i.type) && this.subscriptions.get(i.type)?.forEach((s) => {
39
+ s.callback(i);
40
+ });
41
+ }
42
+ unsubscribe(i) {
43
+ this.subscribeAllSubscriptions = this.subscribeAllSubscriptions.filter((s) => s.id !== i);
44
+ for (const [s, b] of this.subscriptions)
45
+ this.subscriptions.set(
46
+ s,
47
+ b.filter((r) => r.id !== i)
48
+ );
49
+ }
50
+ }
51
+ export {
52
+ t as Siggn
53
+ };
@@ -0,0 +1,3 @@
1
+ export * from './siggn.js';
2
+ export * from './types.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { Msg } from './types.js';
2
+ export declare class Siggn<T extends Msg> {
3
+ private subscriptions;
4
+ private subscribeAllSubscriptions;
5
+ constructor();
6
+ createChild<C extends Msg>(): Siggn<T | C>;
7
+ make(id: string): {
8
+ subscribe: <K extends T['type']>(type: K, callback: (msg: Extract<T, {
9
+ type: K;
10
+ }>) => void) => void;
11
+ unsubscribe: () => void;
12
+ subscribeMany: (setup: (subscribe: <K extends T['type']>(type: K, callback: (msg: Extract<T, {
13
+ type: K;
14
+ }>) => void) => void) => void) => void;
15
+ subscribeAll: (callback: (msg: T) => void) => void;
16
+ };
17
+ subscribeMany(id: string, setup: (subscribe: <K extends T['type']>(type: K, callback: (msg: Extract<T, {
18
+ type: K;
19
+ }>) => void) => void) => void): void;
20
+ subscribe<K extends T['type']>(id: string, type: K, callback: (msg: Extract<T, {
21
+ type: K;
22
+ }>) => void): void;
23
+ subscribeAll(id: string, callback: (msg: T) => void): void;
24
+ publish(msg: T): void;
25
+ unsubscribe(id: string): void;
26
+ }
27
+ //# sourceMappingURL=siggn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"siggn.d.ts","sourceRoot":"","sources":["../../src/siggn.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAgB,MAAM,YAAY,CAAC;AAEpD,qBAAa,KAAK,CAAC,CAAC,SAAS,GAAG;IAC9B,OAAO,CAAC,aAAa,CAA8C;IACnE,OAAO,CAAC,yBAAyB,CAAmC;;IAMpE,WAAW,CAAC,CAAC,SAAS,GAAG;IAIzB,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG;QAChB,SAAS,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAC7B,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;YAAE,IAAI,EAAE,CAAC,CAAA;SAAE,CAAC,KAAK,IAAI,KAC7C,IAAI,CAAC;QACV,WAAW,EAAE,MAAM,IAAI,CAAC;QACxB,aAAa,EAAE,CACb,KAAK,EAAE,CACL,SAAS,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAC7B,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;YAAE,IAAI,EAAE,CAAC,CAAA;SAAE,CAAC,KAAK,IAAI,KAC7C,IAAI,KACN,IAAI,KACN,IAAI,CAAC;QACV,YAAY,EAAE,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,KAAK,IAAI,CAAC;KACpD;IAiBD,aAAa,CACX,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,CACL,SAAS,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAC7B,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;QAAE,IAAI,EAAE,CAAC,CAAA;KAAE,CAAC,KAAK,IAAI,KAC7C,IAAI,KACN,IAAI;IAKX,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAC3B,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;QAAE,IAAI,EAAE,CAAC,CAAA;KAAE,CAAC,KAAK,IAAI;IASlD,YAAY,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI;IAInD,OAAO,CAAC,GAAG,EAAE,CAAC;IAcd,WAAW,CAAC,EAAE,EAAE,MAAM;CAUvB"}
@@ -0,0 +1,14 @@
1
+ export type Msg = {
2
+ type: string;
3
+ [key: string]: unknown;
4
+ };
5
+ export type Subscription<T extends Msg, K extends T['type']> = {
6
+ id: string;
7
+ callback: (msg: Extract<T, {
8
+ type: K;
9
+ }>) => void;
10
+ };
11
+ export type SubscriptionMap<T extends Msg> = {
12
+ [K in T['type']]: Array<Subscription<T, K>>;
13
+ };
14
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,GAAG,GAAG;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,IAAI;IAC7D,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;QAAE,IAAI,EAAE,CAAC,CAAA;KAAE,CAAC,KAAK,IAAI,CAAC;CAClD,CAAC;AAEF,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,GAAG,IAAI;KAC1C,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;CAC5C,CAAC"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@siggn/core",
3
- "version": "0.0.1",
4
- "description": "A lightweight event driven pub/sub system",
3
+ "version": "0.0.4",
4
+ "description": "A lightweight message bus system for Typescript",
5
5
  "keywords": [
6
- "pub",
7
- "sub",
8
- "lightweight",
9
- "signals"
6
+ "pub/sub",
7
+ "message",
8
+ "event",
9
+ "bus"
10
10
  ],
11
11
  "publishConfig": {
12
12
  "@siggn:registry": "https://registry.npmjs.org/",
@@ -18,26 +18,35 @@
18
18
  },
19
19
  "repository": {
20
20
  "type": "git",
21
- "url": "git+https://github.com/Guiguerreiro39/siggn.git"
21
+ "url": "git+https://github.com/Guiguerreiro39/siggn.git/",
22
+ "directory": "packages/core"
22
23
  },
23
- "license": "ISC",
24
- "author": "Guilherme Guerreiro",
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "license": "MIT",
28
+ "author": "Guilherme Guerreiro (https://guilhermegr.com)",
25
29
  "type": "module",
26
- "main": "index.ts",
27
- "scripts": {
28
- "test": "exit 0"
29
- },
30
- "dependencies": {
31
- "bun-types": "^1.3.0",
32
- "csstype": "^3.1.3",
33
- "typescript": "^5.9.3",
34
- "undici-types": "^7.14.0"
35
- },
30
+ "main": "dist/index.cjs.js",
31
+ "types": "./dist/index.d.ts",
32
+ "module": "./dist/index.es.js",
36
33
  "devDependencies": {
37
- "@types/bun": "latest"
34
+ "typescript": "^5.9.3",
35
+ "vite": "^7.1.12",
36
+ "vite-plugin-dts": "^4.5.4",
37
+ "vitest": "^3.2.4"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "typescript": "^5"
41
41
  },
42
- "module": "index.ts"
43
- }
42
+ "scripts": {
43
+ "dev": "vitest",
44
+ "test": "vitest run",
45
+ "build": "vite build",
46
+ "ci": "pnpm run build && pnpm run check-format && pnpm run test",
47
+ "format": "prettier --write .",
48
+ "check-format": "prettier --check .",
49
+ "version": "changeset version",
50
+ "release": "changeset publish"
51
+ }
52
+ }
@@ -1,33 +0,0 @@
1
- name: Node.js Package
2
-
3
- on:
4
- release:
5
- types: [created]
6
-
7
- jobs:
8
- build:
9
- runs-on: ubuntu-latest
10
- steps:
11
- - uses: actions/checkout@v5
12
- - uses: actions/setup-node@v4
13
- with:
14
- node-version: 20
15
- - run: npm ci
16
- - run: npm test
17
-
18
- publish-gpr:
19
- needs: build
20
- runs-on: ubuntu-latest
21
- permissions:
22
- packages: write
23
- contents: read
24
- steps:
25
- - uses: actions/checkout@v5
26
- - uses: actions/setup-node@v4
27
- with:
28
- node-version: 20
29
- registry-url: https://npm.pkg.github.com/
30
- - run: npm ci
31
- - run: npm publish
32
- env:
33
- NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
package/bun.lock DELETED
@@ -1,29 +0,0 @@
1
- {
2
- "lockfileVersion": 1,
3
- "workspaces": {
4
- "": {
5
- "name": "siggn",
6
- "devDependencies": {
7
- "@types/bun": "latest",
8
- },
9
- "peerDependencies": {
10
- "typescript": "^5",
11
- },
12
- },
13
- },
14
- "packages": {
15
- "@types/bun": ["@types/bun@1.3.0", "", { "dependencies": { "bun-types": "1.3.0" } }, "sha512-+lAGCYjXjip2qY375xX/scJeVRmZ5cY0wyHYyCYxNcdEXrQ4AOe3gACgd4iQ8ksOslJtW4VNxBJ8llUwc3a6AA=="],
16
-
17
- "@types/node": ["@types/node@24.8.1", "", { "dependencies": { "undici-types": "~7.14.0" } }, "sha512-alv65KGRadQVfVcG69MuB4IzdYVpRwMG/mq8KWOaoOdyY617P5ivaDiMCGOFDWD2sAn5Q0mR3mRtUOgm99hL9Q=="],
18
-
19
- "@types/react": ["@types/react@19.2.2", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA=="],
20
-
21
- "bun-types": ["bun-types@1.3.0", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-u8X0thhx+yJ0KmkxuEo9HAtdfgCBaM/aI9K90VQcQioAmkVp3SG3FkwWGibUFz3WdXAdcsqOcbU40lK7tbHdkQ=="],
22
-
23
- "csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
24
-
25
- "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
26
-
27
- "undici-types": ["undici-types@7.14.0", "", {}, "sha512-QQiYxHuyZ9gQUIrmPo3IA+hUl4KYk8uSA7cHrcKd/l3p1OTpZcM0Tbp9x7FAtXdAYhlasd60ncPpgu6ihG6TOA=="],
28
- }
29
- }
package/index.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./siggn";
@@ -1,111 +0,0 @@
1
- ---
2
- description: Use Bun instead of Node.js, npm, pnpm, or vite.
3
- globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx, package.json"
4
- alwaysApply: false
5
- ---
6
-
7
- Default to using Bun instead of Node.js.
8
-
9
- - Use `bun <file>` instead of `node <file>` or `ts-node <file>`
10
- - Use `bun test` instead of `jest` or `vitest`
11
- - Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
12
- - Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
13
- - Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
14
- - Bun automatically loads .env, so don't use dotenv.
15
-
16
- ## APIs
17
-
18
- - `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
19
- - `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
20
- - `Bun.redis` for Redis. Don't use `ioredis`.
21
- - `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
22
- - `WebSocket` is built-in. Don't use `ws`.
23
- - Prefer `Bun.file` over `node:fs`'s readFile/writeFile
24
- - Bun.$`ls` instead of execa.
25
-
26
- ## Testing
27
-
28
- Use `bun test` to run tests.
29
-
30
- ```ts#index.test.ts
31
- import { test, expect } from "bun:test";
32
-
33
- test("hello world", () => {
34
- expect(1).toBe(1);
35
- });
36
- ```
37
-
38
- ## Frontend
39
-
40
- Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
41
-
42
- Server:
43
-
44
- ```ts#index.ts
45
- import index from "./index.html"
46
-
47
- Bun.serve({
48
- routes: {
49
- "/": index,
50
- "/api/users/:id": {
51
- GET: (req) => {
52
- return new Response(JSON.stringify({ id: req.params.id }));
53
- },
54
- },
55
- },
56
- // optional websocket support
57
- websocket: {
58
- open: (ws) => {
59
- ws.send("Hello, world!");
60
- },
61
- message: (ws, message) => {
62
- ws.send(message);
63
- },
64
- close: (ws) => {
65
- // handle close
66
- }
67
- },
68
- development: {
69
- hmr: true,
70
- console: true,
71
- }
72
- })
73
- ```
74
-
75
- HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
76
-
77
- ```html#index.html
78
- <html>
79
- <body>
80
- <h1>Hello, world!</h1>
81
- <script type="module" src="./frontend.tsx"></script>
82
- </body>
83
- </html>
84
- ```
85
-
86
- With the following `frontend.tsx`:
87
-
88
- ```tsx#frontend.tsx
89
- import React from "react";
90
-
91
- // import .css files directly and it works
92
- import './index.css';
93
-
94
- import { createRoot } from "react-dom/client";
95
-
96
- const root = createRoot(document.body);
97
-
98
- export default function Frontend() {
99
- return <h1>Hello, world!</h1>;
100
- }
101
-
102
- root.render(<Frontend />);
103
- ```
104
-
105
- Then, run index.ts
106
-
107
- ```sh
108
- bun --hot ./index.ts
109
- ```
110
-
111
- For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.
package/siggn.ts DELETED
@@ -1,32 +0,0 @@
1
- type Msg = {
2
- type: string
3
- [key: string]: unknown
4
- }
5
-
6
- export class Siggn <T extends Msg> {
7
- private subscriptions: Map<T['type'], Map<string, Function>>
8
-
9
- constructor() {
10
- this.subscriptions = new Map();
11
- }
12
-
13
- subscribe(id: string, type: T['type'], callback: (msg: T) => void) {
14
- if (!this.subscriptions.has(type)) {
15
- this.subscriptions.set(type, new Map());
16
- }
17
-
18
- this.subscriptions.get(type)?.set(id, callback);
19
- }
20
-
21
- emit(msg: T) {
22
- this.subscriptions.get(msg.type)?.forEach((callback) => {
23
- callback(msg);
24
- });
25
- }
26
-
27
- unsubscribe(id: string) {
28
- this.subscriptions.forEach((sub) => {
29
- sub.delete(id);
30
- });
31
- }
32
- }
package/test.ts DELETED
@@ -1,35 +0,0 @@
1
- import { Siggn } from "./siggn";
2
-
3
- type Msg = {
4
- type: 'increment_count',
5
- value: number
6
- } | {
7
- type: 'decrement_count',
8
- value: number
9
- }
10
-
11
- const siggn = new Siggn<Msg>();
12
-
13
- let count = 0
14
-
15
- siggn.subscribe('1', 'increment_count', (msg) => {
16
- count += msg.value
17
- })
18
-
19
- siggn.subscribe('2', 'decrement_count', (msg) => {
20
- count -= msg.value
21
- })
22
-
23
- function incrementCount(r: typeof siggn) {
24
- r.emit({ type: 'increment_count', value: 4 })
25
- }
26
-
27
- function decrementCount(r: typeof siggn) {
28
- r.emit({ type: 'decrement_count', value: 2 })
29
- }
30
-
31
- incrementCount(siggn)
32
- console.log(count)
33
-
34
- decrementCount(siggn)
35
- console.log(count)
package/tsconfig.json DELETED
@@ -1,29 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- // Environment setup & latest features
4
- "lib": ["ESNext"],
5
- "target": "ESNext",
6
- "module": "Preserve",
7
- "moduleDetection": "force",
8
- "jsx": "react-jsx",
9
- "allowJs": true,
10
-
11
- // Bundler mode
12
- "moduleResolution": "bundler",
13
- "allowImportingTsExtensions": true,
14
- "verbatimModuleSyntax": true,
15
- "noEmit": true,
16
-
17
- // Best practices
18
- "strict": true,
19
- "skipLibCheck": true,
20
- "noFallthroughCasesInSwitch": true,
21
- "noUncheckedIndexedAccess": true,
22
- "noImplicitOverride": true,
23
-
24
- // Some stricter flags (disabled by default)
25
- "noUnusedLocals": false,
26
- "noUnusedParameters": false,
27
- "noPropertyAccessFromIndexSignature": false
28
- }
29
- }