@biglogic/rgs 3.0.1 → 3.2.0

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.
Files changed (44) hide show
  1. package/README.md +14 -0
  2. package/advanced.js +1 -1
  3. package/index.js +1 -1
  4. package/package.json +26 -28
  5. package/rgs-extension.vsix +0 -0
  6. package/examples/README.md +0 -41
  7. package/examples/async-data-fetch/UserLoader.d.ts +0 -12
  8. package/examples/async-data-fetch/UserLoader.ts +0 -30
  9. package/examples/basic-counter/CounterComponent.d.ts +0 -2
  10. package/examples/basic-counter/CounterComponent.tsx +0 -22
  11. package/examples/basic-counter/CounterStore.d.ts +0 -7
  12. package/examples/basic-counter/CounterStore.ts +0 -25
  13. package/examples/big-data-indexeddb/BigDataStore.d.ts +0 -10
  14. package/examples/big-data-indexeddb/BigDataStore.ts +0 -60
  15. package/examples/global-theme/ThemeManager.d.ts +0 -7
  16. package/examples/global-theme/ThemeManager.ts +0 -32
  17. package/examples/hybrid-cloud-sync/HybridStore.d.ts +0 -19
  18. package/examples/hybrid-cloud-sync/HybridStore.ts +0 -78
  19. package/examples/persistent-cart/CartStore.d.ts +0 -13
  20. package/examples/persistent-cart/CartStore.ts +0 -41
  21. package/examples/rbac-dashboard/DashboardStore.d.ts +0 -47
  22. package/examples/rbac-dashboard/DashboardStore.ts +0 -46
  23. package/examples/secure-auth/AuthStore.d.ts +0 -14
  24. package/examples/secure-auth/AuthStore.ts +0 -36
  25. package/examples/security-best-practices/SecurityStore.d.ts +0 -22
  26. package/examples/security-best-practices/SecurityStore.ts +0 -75
  27. package/examples/stress-tests/StressStore.d.ts +0 -41
  28. package/examples/stress-tests/StressStore.ts +0 -61
  29. package/examples/super-easy/EasyStore.d.ts +0 -44
  30. package/examples/super-easy/EasyStore.ts +0 -61
  31. package/examples/undo-redo-editor/EditorStore.d.ts +0 -9
  32. package/examples/undo-redo-editor/EditorStore.ts +0 -28
  33. package/markdown/SUMMARY.md +0 -59
  34. package/markdown/api.md +0 -381
  35. package/markdown/chapters/01-philosophy.md +0 -54
  36. package/markdown/chapters/02-getting-started.md +0 -68
  37. package/markdown/chapters/03-the-magnetar-way.md +0 -69
  38. package/markdown/chapters/04-persistence-and-safety.md +0 -125
  39. package/markdown/chapters/05-plugin-sdk.md +0 -290
  40. package/markdown/chapters/05-plugins-and-extensibility.md +0 -190
  41. package/markdown/chapters/06-case-studies.md +0 -69
  42. package/markdown/chapters/07-faq.md +0 -53
  43. package/markdown/chapters/08-migration-guide.md +0 -253
  44. package/markdown/chapters/09-security-architecture.md +0 -40
@@ -1,69 +0,0 @@
1
- # 🛒 Chapter 6: Case Studies - Real Strategies
2
-
3
- In this chapter, we put theory aside and see how RGS solves the problems that keep you up at night (or at least frustrated in the office).
4
-
5
- ---
6
-
7
- ## 🍎 Case 1: High-Performance E-commerce
8
-
9
- **The Problem**: A shopping cart with 50 items, complex sidebar filters, and a product list that must update without "jumping" the whole page.
10
-
11
- **The RGS Strategy**:
12
-
13
- 1. **Atomic Filters**: Don't save the entire filters object. Use separate keys (`category`, `priceRange`, `search`). This way, if the user only changes the price, the search bar doesn't re-render.
14
- 2. **Persistent Cart**: Use `gstate` with a `cart` namespace.
15
- 3. **Computed State for Totals**:
16
-
17
- ```javascript
18
- cartStore.compute('totalAmount', ['items'], (s) =>
19
- s.items.reduce((acc, curr) => acc + curr.price, 0)
20
- );
21
- ```
22
-
23
- **Why do this?** Because the component displaying the total price updates *only* when the `items` array changes, not when the user's name or shipping address changes. **Zero waste.**
24
-
25
- ---
26
-
27
- ## 📊 Case 2: Real-time Dashboard (Sockets/Events)
28
-
29
- **The Problem**: You receive thousands of updates via WebSocket (e.g., crypto prices or server notifications), and React can't keep up.
30
-
31
- **The RGS Strategy**:
32
-
33
- 1. **Atomic Transactions**: In RGS, you can group updates.
34
-
35
- ```javascript
36
- socket.on('bulk_update', (data) => {
37
- store.transaction(() => {
38
- data.forEach(item => store.set(`price_${item.id}`, item.price));
39
- });
40
- });
41
- ```
42
-
43
- **Why do this?** Instead of triggering 100 React updates, the `transaction` triggers **only one** at the end. Your dashboard's performance will go from "tractor" to "Ferrari".
44
-
45
- ---
46
-
47
- ## 🏦 Case 3: Multi-Step Forms (User Onboarding)
48
-
49
- **The Problem**: A signup form with 5 steps. If the user hits "Back" or refreshes the page, they lose everything.
50
-
51
- **The RGS Strategy**:
52
-
53
- 1. Use a dedicated `gstate` called `onboarding`.
54
- 2. Enable `persist: true`.
55
- 3. At each step, just call `set('step1', values)`.
56
- **Why do this?** Because you don't have to manage manual saving logic. When the user returns, the fields are already populated. At the very end (Step 5), call `store.destroy()` to clean up. Clean and elegant.
57
-
58
- ---
59
-
60
- ## 🛡️ Message for Advanced Architects
61
-
62
- *"But I could do all this with a custom cache and an event bus..."*
63
- Sure you could. You could also walk to work instead of driving. But RGS is the car: it's tested, it handles edge cases (closed tabs, full storage, corrupted types), and it lets you focus on **business logic**, not infrastructure.
64
-
65
- Stop reinventing the wheel. Use RGS.
66
-
67
- ---
68
-
69
- **Next step:** [FAQ: For the Skeptics and the Curious](07-faq.md)
@@ -1,53 +0,0 @@
1
- # ❓ Chapter 7: FAQ - Architectural Insights
2
-
3
- This section provides technical context for the design decisions behind RGS (Argis) - React Globo State.
4
-
5
- ## 1. "Why integrate Security and GDPR into the State layer?"
6
-
7
- **The Rationale:** In enterprise environments, ensuring that every data access is authorized is critical. By integrating **RBAC** and **Auditing** directly into the store instance, we provide a "Secure-by-Default" architecture. This prevents common oversights where developers might forget to apply permission checks in custom middleware or component logic.
8
-
9
- ## 2. "How does RGS compare to the React Context API?"
10
-
11
- **The Technical Difference:** Context is a dependency injection tool. When values change, React often triggers broad re-renders across the consumer tree. RGS uses a **Surgical Subscription** model. Only components observing a specific key are notified of changes, ensuring optimal performance even in data-heavy applications.
12
-
13
- ## 3. "Is there a performance overhead for Safety Features?"
14
-
15
- **The Trade-off:** Capabilities like deep freezing (immutability) and sanitization do introduce a small computational cost (typically 1-2ms). We believe this is a worthwhile investment to prevent accidental state mutations and security vulnerabilities. For performance-critical scenarios (like high-frequency animations), these features can be selectively disabled.
16
-
17
- ## 4. "How is Type Safety handled with string keys?"
18
-
19
- **The Approach:** String keys provide the flexibility needed for dynamic and runtime-generated state namespaces. For developers requiring strict type safety, RGS offers the `gstate` factory and `GStatePlugins` augmentation, allowing you to define a fully typed interface for your store and its plugins.
20
-
21
- ## 5. "What logic dictates the use of 'Ghost Stores'?"
22
-
23
- **Operational Resilience:** Many applications experience race conditions during hydration or initialization. Instead of allowing the application to crash due to an uninitialized reference, RGS returns a protective Proxy. This Proxy logs a developer warning while providing a safe fallback, ensuring the user interface remains functional while the developer addresses the initialization sequence.
24
-
25
- ## 6. "Is it compatible with modern React patterns (SSR/Next.js)?"
26
-
27
- **Yes.** RGS is built on top of `useSyncExternalStore` and is fully compatible with Concurrent Rendering and Server-Side Rendering (SSR). It works seamlessly with Next.js, Remix, and other modern frameworks without hydration mismatch issues.
28
-
29
- ## 7. "Where do the best practices and improvements come from?"
30
-
31
- **The Process:** All improvements and best practices are based on:
32
-
33
- - **Official React Documentation** - useSyncExternalStore for SSR, hooks rules, React 18/19 features
34
- - **TypeScript Best Practices** - Type safety patterns, generics, strict mode
35
- - **Security Standards** - OWASP for XSS prevention, AES-256-GCM encryption, RBAC patterns
36
- - **Community Libraries** - Patterns from Zustand, Redux, Jotai for plugin architecture
37
- - **Enterprise Patterns** - Error handling, multi-store isolation, GDPR compliance
38
-
39
- Key fixes (like security isolation per-store, Immer optional loading) come from common issues in similar libraries.
40
-
41
- ---
42
-
43
- ## 🛑 Best Practices: Maximizing Reliability
44
-
45
- 1. **State Granularity**: Use RGS for global, persistent, or secured data. For transient UI state (like toggle transitions), standard `useState` is more appropriate.
46
- 2. **Namespace Management**: Always define a unique namespace for your store to prevent data collisions in shared domain environments.
47
- 3. **Rule Validation**: Ensure your RBAC rules are tested against your expected key patterns to maintain a robust security posture.
48
-
49
- ---
50
-
51
- ## 👋 Conclusion
52
-
53
- RGS is designed for teams that prioritize long-term maintainability and system stability. By handling the complexities of security and persistence at the architectural level, we allow developers to focus on building features with confidence.
@@ -1,253 +0,0 @@
1
- # 🔄 Migration Guide
2
-
3
- ## Upgrading from Previous Versions
4
-
5
- ### Security: `secure` → `encoded`
6
-
7
- **IMPORTANT:** The `secure` option has been deprecated in favor of `encoded` to clarify that it only applies **base64 encoding**, not encryption.
8
-
9
- #### ❌ Old Code (Deprecated)
10
-
11
- ```typescript
12
- store.set('apiKey', 'secret123', {
13
- persist: true,
14
- secure: true // ⚠️ DEPRECATED: This is NOT encryption!
15
- })
16
- ```
17
-
18
- #### ✅ New Code (Recommended)
19
-
20
- ```typescript
21
- store.set('apiKey', 'secret123', {
22
- persist: true,
23
- encoded: true // ✅ Clear: This is base64 encoding
24
- })
25
- ```
26
-
27
- #### Backward Compatibility
28
-
29
- Your old code will **still work**, but you'll see a deprecation warning in TypeScript:
30
-
31
- ```typescript
32
- /** @deprecated Use 'encoded' instead. 'secure' only applies base64 encoding, not encryption. */
33
- secure?: boolean
34
- ```
35
-
36
- #### Why This Change?
37
-
38
- Base64 encoding is **NOT encryption**. It's trivial to decode:
39
-
40
- ```javascript
41
- // Anyone can decode base64
42
- const encoded = btoa(JSON.stringify({ secret: 'password123' }))
43
- const decoded = JSON.parse(atob(encoded)) // { secret: 'password123' }
44
- ```
45
-
46
- **For real security**, use proper encryption libraries like:
47
-
48
- - `crypto-js` (AES encryption)
49
- - `tweetnacl` (NaCl encryption)
50
- - Web Crypto API (`crypto.subtle`)
51
-
52
- ---
53
-
54
- ### Error Handling: `onError` Callback
55
-
56
- **NEW:** You can now catch and handle errors from plugins, hydration, and other operations.
57
-
58
- #### Example: Custom Error Logging
59
-
60
- ```typescript
61
- import { initState, useStore } from '@biglogic/rgs'
62
-
63
- const store = initState({
64
- namespace: 'myapp',
65
- onError: (error, context) => {
66
- // Send to your error tracking service
67
- console.error(`[gState Error] ${context.operation}:`, error)
68
-
69
- if (context.operation === 'hydration') {
70
- // Handle corrupted localStorage
71
- localStorage.clear()
72
- alert('Storage corrupted, resetting...')
73
- }
74
-
75
- if (context.operation.startsWith('plugin:')) {
76
- // Handle plugin crashes
77
- Sentry.captureException(error, { tags: { plugin: context.operation } })
78
- }
79
- }
80
- })
81
- ```
82
-
83
- #### Error Context
84
-
85
- ```typescript
86
- interface ErrorContext {
87
- operation: string // 'hydration', 'plugin:name:hook', 'set'
88
- key?: string // State key (if applicable)
89
- }
90
- ```
91
-
92
- ---
93
-
94
- ### Performance: `maxObjectSize` Warning
95
-
96
- **NEW:** Get warned when storing objects larger than a configurable limit (default: 5MB).
97
-
98
- #### Example: Custom Size Limit
99
-
100
- ```typescript
101
- import { createStore } from '@biglogic/rgs'
102
-
103
- const store = createStore({
104
- maxObjectSize: 10 * 1024 * 1024, // 10MB limit
105
- onError: (error, context) => {
106
- if (context.operation === 'set') {
107
- console.warn(`Large object detected in key: ${context.key}`)
108
- }
109
- }
110
- })
111
-
112
- // This will trigger a warning if > 10MB
113
- store.set('bigData', hugeArray)
114
- ```
115
-
116
- #### Disable Size Checking
117
-
118
- ```typescript
119
- const store = createStore({
120
- maxObjectSize: 0 // Disable size warnings
121
- })
122
- ```
123
-
124
- ---
125
-
126
- ## Upgrading to Latest Version (The Enterprise Update)
127
-
128
- **IMPORTANT:** This release introduces a fundamental shift towards **Multi-Store Isolation**. Security rules and GDPR consents are now instance-bound rather than global.
129
-
130
- ### 1. Security: Global → Instance-Specific
131
-
132
- In previous versions, security rules were shared globally. Now, each store instance maintains its own rules for better isolation in micro-frontend environments.
133
-
134
- #### ❌ Deprecated Global Methods
135
-
136
- ```typescript
137
- import { addAccessRule, recordConsent } from '@biglogic/rgs'
138
-
139
- // ⚠️ DEPRECATED: These affect the 'default' store only and are less isolated
140
- addAccessRule('user_*', ['read', 'write'])
141
- ```
142
-
143
- #### ✅ Recommended Instance Methods
144
-
145
- ```typescript
146
- const store = createStore({ namespace: 'my-isolated-app' })
147
-
148
- // ✅ Use the instance methods
149
- store.addAccessRule('user_*', ['read', 'write'])
150
- store.recordConsent('user123', 'marketing', true)
151
- ```
152
-
153
- ### 2. Operational Resilience: Ghost Stores
154
-
155
- **NEW:** If you access a store that hasn't finished its initialization (e.g., during slow hydration), RGS now returns a **Ghost Store Proxy**.
156
-
157
- - **Behavior:** It prevents application crashes by providing a safe fallback.
158
- - **Developer Warning:** It logs a detailed warning in the console so you can fix the initialization sequence.
159
-
160
- ### 3. Performance: Regex Caching
161
-
162
- **NEW:** Permission checks now use an internal **Regex Cache** per instance.
163
-
164
- - **Why?** Avoids the overhead of re-compiling regex strings on every `.get()` or `.set()` call.
165
- - **Impact:** Significant performance boost for applications with high-frequency state updates and complex RBAC rules.
166
-
167
- ### 4. Advanced Plugin Typing
168
-
169
- **NEW:** Introducing `GStatePlugins` for Module Augmentation.
170
-
171
- - You can now define types for your custom plugins to get full IDE autocomplete.
172
-
173
- ---
174
-
175
- ## v2.9.5: The Architecture & Safety Update (2026-02-16)
176
-
177
- This release focuses on improving developer ergonomics, security visibility, and complex dependency handling.
178
-
179
- ### 1. Nested Computed Dependencies
180
- **NEW:** Computed values can now re-trigger based on other computed values.
181
-
182
- ```typescript
183
- store.compute('tax', (get) => (get<number>('subtotal') || 0) * 0.2)
184
- store.compute('total', (get) => (get<number>('subtotal') || 0) + (get<number>('tax') || 0))
185
- ```
186
-
187
- ### 2. Direct Store Access: `getStore()`
188
- **NEW:** A top-level utility to retrieve the default store without React hooks.
189
-
190
- ```typescript
191
- import { getStore } from '@biglogic/rgs'
192
-
193
- export const toggleTheme = () => {
194
- const store = getStore()
195
- if (store) store.set('mode', 'dark')
196
- }
197
- ```
198
-
199
- ### 3. Exposed Metadata: `namespace` and `userId`
200
- **NEW:** Store instances now expose their identifying properties as read-only getters.
201
-
202
- ```typescript
203
- const store = createStore({ namespace: 'auth-vault', userId: 'user-001' })
204
- console.log(store.namespace) // 'auth-vault'
205
- console.log(store.userId) // 'user-001'
206
- ```
207
-
208
- ### 4. High-Volume & Hybrid Sync (Plugins)
209
- **NEW:** Support for GB-scale storage and Remote Cloud Backups.
210
-
211
- - **IndexedDB Plugin**: Replaces localStorage for massive browser datasets.
212
- - **Cloud Sync Plugin**: Differential synchronization to MongoDB, Firebase, or any SQL backend.
213
-
214
- ```typescript
215
- // Example: Manual Cloud Sync
216
- const result = await store.plugins.cloudSync.sync()
217
- console.log('Stats:', store.plugins.cloudSync.getStats())
218
- ```
219
-
220
- ---
221
-
222
- ## Breaking Changes
223
-
224
- ### 🔒 Security Isolation
225
-
226
- If you relied on `addAccessRule()` from the global export to affect a `createStore()` instance, you must now call `store.addAccessRule()` on that specific instance.
227
-
228
- ---
229
-
230
- ## Recommended Actions
231
-
232
- ### 1. Migrate Security Calls to Store Instances
233
-
234
- **Priority:** High (if using multiple stores)
235
-
236
- **Effort:** Low
237
-
238
- ### 2. Implement `GStatePlugins` for Custom Plugins
239
-
240
- **Priority:** Medium (Developer Experience)
241
-
242
- **Effort:** Low
243
-
244
- ---
245
-
246
- ## Need Help?
247
-
248
- - **Issues:** [GitHub Issues](https://github.com/dpassariello/rgs/issues)
249
- - **Docs:** [Galaxy Documentation](../SUMMARY.md)
250
-
251
- ---
252
-
253
- ## Last updated: 2026-02-16
@@ -1,40 +0,0 @@
1
- # Security Architecture & Hardening
2
-
3
- ## Overview
4
- React Globo State (RGS) is designed with a "Security-First" philosophy. Our architecture ensures that global state is not only reactive but protected against common web vulnerabilities and unauthorized access.
5
-
6
- ## 1. Data Sanitization (XSS Defense)
7
- The `sanitizeValue` utility provides a robust baseline defense by stripping malicious content from strings and objects before they enter the store.
8
-
9
- - **Scheme Blocking**: Specifically blocks `javascript:`, `vbscript:`, and `data:text/html` schemes.
10
- - **Tag Removal**: Automatically removes dangerous HTML tags such as `<script>`, `<iframe>`, `<form>`, and `<meta>`.
11
- - **Entity Removal**: Strips HTML entities (`&#...;`) to prevent obfuscation-based bypasses.
12
-
13
- ## 2. Advanced Deep Cloning
14
- To ensure state immutability and prevent unintended side effects, RGS uses an intelligent cloning engine:
15
- - **Native structuredClone**: Leverages the browser's native API for maximum performance.
16
- - **Support for Collections**: Extends cloning capabilities to `Map` and `Set` objects.
17
- - **Circular Reference Protection**: Uses `WeakMap` to handle complex nested structures safely.
18
-
19
- ## 3. Cryptography (AES-256-GCM)
20
- The security module uses the Web Crypto API to provide high-performance, authenticated encryption:
21
- - **AES-GCM**: Provides both confidentiality and integrity verification.
22
- - **GCM (Galois/Counter Mode)**: Ensures that data has not been tampered with during storage.
23
-
24
- ## 4. RBAC (Role-Based Access Control)
25
- RGS supports fine-grained access rules:
26
- - **Fail-Closed Design**: Access is denied by default if any rules are defined.
27
- - **Regex Caching**: Store instances cache compiled regular expressions for ultra-fast permission checks.
28
-
29
- ## 5. Security Best Practices
30
- For real-world implementations, refer to the `examples/security-best-practices` directory, which covers:
31
- - **Encryption Key Management**: Using `generateEncryptionKey()` for secure key generation.
32
- - **Audit Logging**: Tracking all store modifications for compliance.
33
- - **GDPR Compliance**: Managing user consent and data export/deletion.
34
-
35
- ## Summary of 2.9.5 Enhancements
36
- - Robust regex patterns for `sanitizeValue`.
37
- - Recursive sanitization for plain objects.
38
- - `Map` and `Set` support in `deepClone`.
39
- - **Exposed Metadata**: Store instances now expose read-only `namespace` and `userId`.
40
- - **Direct Store Access**: Added `getStore()` utility for non-React contexts.