@pixel-pulse/cache-brain 1.0.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.
- package/LICENSE +8 -0
- package/README.md +169 -0
- package/dist/index.d.mts +99 -0
- package/dist/index.d.ts +99 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/dist/types.d.mts +29 -0
- package/dist/types.d.ts +29 -0
- package/dist/types.js +1 -0
- package/dist/types.mjs +0 -0
- package/package.json +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
Copyright © 2026 Lin Htet Aung (Liam)
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
5
|
+
|
|
6
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
7
|
+
|
|
8
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<img src="https://cache-brain.netlify.app/og-image.jpeg" width="100%" alt="Cache Brain - Smart Caching Engine"/>
|
|
3
|
+
|
|
4
|
+
<br/>
|
|
5
|
+
|
|
6
|
+
[](https://www.npmjs.com/package/@pixel-pulse/cache-brain)
|
|
7
|
+
[](https://opensource.org/licenses/MIT)
|
|
8
|
+
|
|
9
|
+
<h3>Next-Generation Caching Engine for Vanilla.js</h3>
|
|
10
|
+
|
|
11
|
+
<p>
|
|
12
|
+
<a href="https://cache-brain.netlify.app/"><b>Cache Brain</b></a> •
|
|
13
|
+
<a href="https://cache-brain.netlify.app/doc"><b>Documentation</b></a> •
|
|
14
|
+
<a href="https://cache-brain.netlify.app/doc/playground/core"><b>Server Lab</b></a> •
|
|
15
|
+
<a href="https://cache-brain.netlify.app/doc/playground/hook"><b>Client Lab</b></a> •
|
|
16
|
+
<a href="https://github.com/LinnHtetAungSE"><b>GitHub</b></a>
|
|
17
|
+
</p>
|
|
18
|
+
</div>
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
**The high-performance caching engine for modern web apps.** Zero-config server caching with real-time client synchronization.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## ✨ Features
|
|
27
|
+
|
|
28
|
+
- **Atomic Pulse Engine:** Unified API supporting `swr`, `cache-first`, `network-first` and `no-cache` strategies with a single function call.
|
|
29
|
+
- **Visual Diagnostics:** Real-time DevTools to track **TTL**, **Registry Hits**, and **Deduplication** events as they happen.
|
|
30
|
+
- **Event Bridge:** Reactive synchronization ensuring that when data updates in one component, the entire UI stays in sync.
|
|
31
|
+
- **App Router Native:** Deeply optimized for Next.js Server Components, Actions, and high-performance client hydration.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## ⚠️ Beta Version Notice
|
|
36
|
+
|
|
37
|
+
This project is currently in **v1.0.0-beta**. We are actively refining the **Registry Pulse** logic and synchronization performance.
|
|
38
|
+
|
|
39
|
+
- Please report any bugs via GitHub Issues.
|
|
40
|
+
- Expect breaking changes until version **1.2.0**.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## ⚡️ Overview
|
|
45
|
+
|
|
46
|
+
Cache Brain is designed to be the "connective tissue" between your data source and your UI. It provides a lightweight, framework-agnostic core that handles deduplication, expiration, and revalidation logic, ensuring your app stays fast and your data stays fresh.
|
|
47
|
+
|
|
48
|
+
- **🚀 Performance-First:** Optimized lookup speeds for high-frequency data access.
|
|
49
|
+
- **🛡 Deduplication:** Prevents "cache stampede" by collapsing multiple identical requests.
|
|
50
|
+
- **🛠 Framework Agnostic:** Pure TypeScript logic that runs in Browser, Node.js, or Edge.
|
|
51
|
+
- **🔄 Smart Invalidation:** Time-based (TTL) and manual cache purging.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 📦 Installation
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
npm add @pixel-pulse/cache-brain
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## 🍦 Vanilla JS Usage
|
|
62
|
+
|
|
63
|
+
Cache Brain is framework-agnostic at its core. You can use it in any JavaScript environment.
|
|
64
|
+
|
|
65
|
+
1. **Initialize the Client**
|
|
66
|
+
|
|
67
|
+
Configure your global caching strategy once at the entry point of your application.
|
|
68
|
+
|
|
69
|
+
```JavaScript
|
|
70
|
+
import { CacheBrainClient } from "@pixel-pulse/cache-brain";
|
|
71
|
+
|
|
72
|
+
new CacheBrainClient({
|
|
73
|
+
defaultTTL: 1000 * 60 * 5, // 5 minutes
|
|
74
|
+
revalidateOnFocus: true, // Refresh data when window gains focus
|
|
75
|
+
debug: false
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
2. **Fetch with smartCache**
|
|
80
|
+
|
|
81
|
+
Wrap your data fetching logic with `smartCache`. It automatically handles the cache lookup, fetching, and storage.
|
|
82
|
+
|
|
83
|
+
```JavaScript
|
|
84
|
+
import { smartCache } from "@pixel-pulse/cache-brain";
|
|
85
|
+
|
|
86
|
+
async function getPosts() {
|
|
87
|
+
return await smartCache(['posts', 'latest'], async () => {
|
|
88
|
+
const response = await fetch('[https://api.example.com/posts](https://api.example.com/posts)');
|
|
89
|
+
return response.json();
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Subsequent calls return cached data instantly!
|
|
94
|
+
const posts = await getPosts();
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### ⚙️ Configuration & Schema
|
|
98
|
+
|
|
99
|
+
The core engine uses `CacheOptions` to determine how specific data is handled and stores them as a `CacheEntry`.
|
|
100
|
+
|
|
101
|
+
#### Cache Options
|
|
102
|
+
|
|
103
|
+
| Property | Type | Description | Default |
|
|
104
|
+
| :-------- | :-------- | :--------------------------------------------------------------------------- | :------- |
|
|
105
|
+
| `ttl` | `number` | Time-to-live in milliseconds. Defines how long the data remains "Fresh". | `300000` |
|
|
106
|
+
| `label` | `string` | A human-readable identifier for easier debugging in **DevTools**. | `Key` |
|
|
107
|
+
| `persist` | `boolean` | If true, the entry survives page refreshes (via `localStorage`/`IndexedDB`). | `false` |
|
|
108
|
+
|
|
109
|
+
#### Internal Entry Schema
|
|
110
|
+
|
|
111
|
+
| Key | Description |
|
|
112
|
+
| :------------- | :---------------------------------------------------------------------------- |
|
|
113
|
+
| `key` | A unique array of strings identifying the resource (e.g., `['user', '123']`). |
|
|
114
|
+
| `data` | The actual payload returned by your fetcher function. |
|
|
115
|
+
| `expiry` | The absolute timestamp (ms) when the data becomes stale. |
|
|
116
|
+
| `lastAccessed` | Timestamp used by the engine for LRU (Least Recently Used) cleanup logic. |
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## 🧩 Framework Extensions
|
|
121
|
+
|
|
122
|
+
Need reactivity? Install the specific package for your stack:
|
|
123
|
+
|
|
124
|
+
- **React / Next.js:** [@pixel-pulse/cache-brain-react](https://www.npmjs.com/package/@pixel-pulse/cache-brain-react)
|
|
125
|
+
- **Vue / Nuxt 3:** [@pixel-pulse/cache-brain-vue](https://www.npmjs.com/package/@pixel-pulse/cache-brain-vue)
|
|
126
|
+
- **React / Next.js Debugger:** [@pixel-pulse/cache-brain-react-devtools](https://www.npmjs.com/package/@pixel-pulse/cache-brain-react-devtools)
|
|
127
|
+
- **Vue / Nuxt.js Debugger:** [@pixel-pulse/cache-brain-vue-devtools](https://www.npmjs.com/package/@pixel-pulse/cache-brain-vue-devtools)
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
### 🛡 License
|
|
131
|
+
|
|
132
|
+
<details>
|
|
133
|
+
<summary>Distributed under the <b>MIT License</b>. Click to view full license.</summary>
|
|
134
|
+
<br />
|
|
135
|
+
|
|
136
|
+
```text
|
|
137
|
+
MIT License
|
|
138
|
+
|
|
139
|
+
Copyright (c) Lin Htet Aung | 2026 Pixel Pulse Tech
|
|
140
|
+
|
|
141
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
142
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
143
|
+
in the Software without restriction, including without limitation the rights
|
|
144
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
145
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
146
|
+
furnished to do so, subject to the following conditions:
|
|
147
|
+
|
|
148
|
+
The above copyright notice and this permission notice shall be included in all
|
|
149
|
+
copies or substantial portions of the Software.
|
|
150
|
+
|
|
151
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
152
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
153
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
154
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
155
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
156
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
157
|
+
SOFTWARE.
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
</details>
|
|
161
|
+
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
<p align="center">
|
|
165
|
+
<br />
|
|
166
|
+
<b>Engineered by Pixel Pulse Tech</b><br />
|
|
167
|
+
<sub>Redefining state management for 2026.</sub>
|
|
168
|
+
</p>
|
|
169
|
+
```
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { CacheEntry, SmartCacheOptions } from './types.mjs';
|
|
2
|
+
|
|
3
|
+
interface CacheOptions {
|
|
4
|
+
ttl?: number;
|
|
5
|
+
persist?: boolean;
|
|
6
|
+
label?: string;
|
|
7
|
+
}
|
|
8
|
+
type DataListener = (data: CacheEntry<any>[]) => void;
|
|
9
|
+
type RevalidateListener = (queryKey?: string[]) => void;
|
|
10
|
+
declare class CacheEngine {
|
|
11
|
+
#private;
|
|
12
|
+
private static instance;
|
|
13
|
+
private constructor();
|
|
14
|
+
/**
|
|
15
|
+
* Singleton Access
|
|
16
|
+
*/
|
|
17
|
+
static getInstance(): CacheEngine;
|
|
18
|
+
/**
|
|
19
|
+
* Configuration Bridge
|
|
20
|
+
* Called by CacheBrainClient constructor to sync main.ts settings
|
|
21
|
+
*/
|
|
22
|
+
setConfig(options: {
|
|
23
|
+
defaultTTL?: number;
|
|
24
|
+
}): void;
|
|
25
|
+
private startCleanupCycle;
|
|
26
|
+
private rehydrate;
|
|
27
|
+
private saveToDisk;
|
|
28
|
+
getValues(): CacheEntry<any>[];
|
|
29
|
+
notify(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Core State Mutation
|
|
32
|
+
*/
|
|
33
|
+
set(key: any, data: any, options?: CacheOptions): void;
|
|
34
|
+
get(key: any): any;
|
|
35
|
+
remove(key: any): void;
|
|
36
|
+
/**
|
|
37
|
+
* Observability
|
|
38
|
+
*/
|
|
39
|
+
subscribe(fn: DataListener): () => void;
|
|
40
|
+
onRevalidate(fn: RevalidateListener): () => void;
|
|
41
|
+
triggerRevalidation(queryKey?: string | string[]): void;
|
|
42
|
+
clear(): void;
|
|
43
|
+
destroy(): void;
|
|
44
|
+
}
|
|
45
|
+
declare const cacheEngine: CacheEngine;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Universal Cache Logic: Coordinates the Engine and the Network
|
|
49
|
+
*/
|
|
50
|
+
declare function smartCache<T = any>(key: string | any[], fetcher: () => Promise<T>, options?: SmartCacheOptions): Promise<T>;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* EMIT UPDATE
|
|
54
|
+
* ✅ Pass the data directly into the function so we don't
|
|
55
|
+
* need to import the engine here.
|
|
56
|
+
*/
|
|
57
|
+
declare const emitUpdate: (data?: any[]) => void;
|
|
58
|
+
|
|
59
|
+
declare const normalizeKey: (key: any) => string;
|
|
60
|
+
|
|
61
|
+
interface CacheBrainClientOptions {
|
|
62
|
+
revalidateOnFocus?: boolean;
|
|
63
|
+
revalidateOnReconnect?: boolean;
|
|
64
|
+
defaultTTL?: number;
|
|
65
|
+
}
|
|
66
|
+
declare class CacheBrainClient {
|
|
67
|
+
private options;
|
|
68
|
+
constructor(options?: CacheBrainClientOptions);
|
|
69
|
+
private setupEventListeners;
|
|
70
|
+
/**
|
|
71
|
+
* Triggers a revalidation (pulse) for active hooks.
|
|
72
|
+
* If no key is provided, it triggers a global pulse.
|
|
73
|
+
*/
|
|
74
|
+
revalidate(queryKey?: string | string[]): void;
|
|
75
|
+
/**
|
|
76
|
+
* Manually updates the cache.
|
|
77
|
+
*/
|
|
78
|
+
setCacheData(queryKey: any[], data: any, options?: CacheOptions): void;
|
|
79
|
+
/**
|
|
80
|
+
* Permanently removes a key or clears the entire brain from memory.
|
|
81
|
+
*/
|
|
82
|
+
invalidate(queryKey?: any[] | string): void;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* GLOBAL TYPE DEFINITION
|
|
87
|
+
* Updated to __CB_DEVTOOLS__ to match the new "Cache Brain" branding.
|
|
88
|
+
*/
|
|
89
|
+
declare global {
|
|
90
|
+
interface Window {
|
|
91
|
+
__CB_DEVTOOLS__?: {
|
|
92
|
+
getCache: () => any[];
|
|
93
|
+
subscribe: (cb: (data: any[]) => void) => () => void;
|
|
94
|
+
revalidate: (queryKey?: string[]) => void;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export { CacheBrainClient, cacheEngine, emitUpdate, normalizeKey, smartCache };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { CacheEntry, SmartCacheOptions } from './types.js';
|
|
2
|
+
|
|
3
|
+
interface CacheOptions {
|
|
4
|
+
ttl?: number;
|
|
5
|
+
persist?: boolean;
|
|
6
|
+
label?: string;
|
|
7
|
+
}
|
|
8
|
+
type DataListener = (data: CacheEntry<any>[]) => void;
|
|
9
|
+
type RevalidateListener = (queryKey?: string[]) => void;
|
|
10
|
+
declare class CacheEngine {
|
|
11
|
+
#private;
|
|
12
|
+
private static instance;
|
|
13
|
+
private constructor();
|
|
14
|
+
/**
|
|
15
|
+
* Singleton Access
|
|
16
|
+
*/
|
|
17
|
+
static getInstance(): CacheEngine;
|
|
18
|
+
/**
|
|
19
|
+
* Configuration Bridge
|
|
20
|
+
* Called by CacheBrainClient constructor to sync main.ts settings
|
|
21
|
+
*/
|
|
22
|
+
setConfig(options: {
|
|
23
|
+
defaultTTL?: number;
|
|
24
|
+
}): void;
|
|
25
|
+
private startCleanupCycle;
|
|
26
|
+
private rehydrate;
|
|
27
|
+
private saveToDisk;
|
|
28
|
+
getValues(): CacheEntry<any>[];
|
|
29
|
+
notify(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Core State Mutation
|
|
32
|
+
*/
|
|
33
|
+
set(key: any, data: any, options?: CacheOptions): void;
|
|
34
|
+
get(key: any): any;
|
|
35
|
+
remove(key: any): void;
|
|
36
|
+
/**
|
|
37
|
+
* Observability
|
|
38
|
+
*/
|
|
39
|
+
subscribe(fn: DataListener): () => void;
|
|
40
|
+
onRevalidate(fn: RevalidateListener): () => void;
|
|
41
|
+
triggerRevalidation(queryKey?: string | string[]): void;
|
|
42
|
+
clear(): void;
|
|
43
|
+
destroy(): void;
|
|
44
|
+
}
|
|
45
|
+
declare const cacheEngine: CacheEngine;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Universal Cache Logic: Coordinates the Engine and the Network
|
|
49
|
+
*/
|
|
50
|
+
declare function smartCache<T = any>(key: string | any[], fetcher: () => Promise<T>, options?: SmartCacheOptions): Promise<T>;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* EMIT UPDATE
|
|
54
|
+
* ✅ Pass the data directly into the function so we don't
|
|
55
|
+
* need to import the engine here.
|
|
56
|
+
*/
|
|
57
|
+
declare const emitUpdate: (data?: any[]) => void;
|
|
58
|
+
|
|
59
|
+
declare const normalizeKey: (key: any) => string;
|
|
60
|
+
|
|
61
|
+
interface CacheBrainClientOptions {
|
|
62
|
+
revalidateOnFocus?: boolean;
|
|
63
|
+
revalidateOnReconnect?: boolean;
|
|
64
|
+
defaultTTL?: number;
|
|
65
|
+
}
|
|
66
|
+
declare class CacheBrainClient {
|
|
67
|
+
private options;
|
|
68
|
+
constructor(options?: CacheBrainClientOptions);
|
|
69
|
+
private setupEventListeners;
|
|
70
|
+
/**
|
|
71
|
+
* Triggers a revalidation (pulse) for active hooks.
|
|
72
|
+
* If no key is provided, it triggers a global pulse.
|
|
73
|
+
*/
|
|
74
|
+
revalidate(queryKey?: string | string[]): void;
|
|
75
|
+
/**
|
|
76
|
+
* Manually updates the cache.
|
|
77
|
+
*/
|
|
78
|
+
setCacheData(queryKey: any[], data: any, options?: CacheOptions): void;
|
|
79
|
+
/**
|
|
80
|
+
* Permanently removes a key or clears the entire brain from memory.
|
|
81
|
+
*/
|
|
82
|
+
invalidate(queryKey?: any[] | string): void;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* GLOBAL TYPE DEFINITION
|
|
87
|
+
* Updated to __CB_DEVTOOLS__ to match the new "Cache Brain" branding.
|
|
88
|
+
*/
|
|
89
|
+
declare global {
|
|
90
|
+
interface Window {
|
|
91
|
+
__CB_DEVTOOLS__?: {
|
|
92
|
+
getCache: () => any[];
|
|
93
|
+
subscribe: (cb: (data: any[]) => void) => () => void;
|
|
94
|
+
revalidate: (queryKey?: string[]) => void;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export { CacheBrainClient, cacheEngine, emitUpdate, normalizeKey, smartCache };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var m=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var S=(t,e)=>{for(var n in e)m(t,n,{get:e[n],enumerable:!0})},D=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of L(e))!x.call(t,a)&&a!==n&&m(t,a,{get:()=>e[a],enumerable:!(i=O(e,a))||i.enumerable});return t};var _=t=>D(m({},"__esModule",{value:!0}),t);var A={};S(A,{CacheBrainClient:()=>p,cacheEngine:()=>r,emitUpdate:()=>d,normalizeKey:()=>c,smartCache:()=>C});module.exports=_(A);var v=Symbol.for("ncb.cache"),w=Symbol.for("ncb.inflight");globalThis[v]||(globalThis[v]=new Map);globalThis[w]||(globalThis[w]=new Map);var s=globalThis[v],f=globalThis[w];var c=t=>Array.isArray(t)?t.map(e=>String(e)).join(":").replace(/:+/g,":"):String(t);var g="cb_cache_snapshot";var R="cb-devtools-update",d=(t=[])=>{typeof window>"u"||window.dispatchEvent(new CustomEvent(R,{detail:t}))};var b=class t{static instance;#t=new Set;#n=new Set;#a={defaultTTL:300*1e3};#r=300*1e3;#i=!1;#e=null;constructor(){this.startCleanupCycle()}static getInstance(){return t.instance||(t.instance=new t,t.instance.rehydrate()),t.instance}setConfig(e){e.defaultTTL!==void 0&&(this.#a.defaultTTL=e.defaultTTL)}startCleanupCycle(){typeof window>"u"||this.#e||(this.#e=setInterval(()=>{let e=!1,n=Date.now();s.forEach((i,a)=>{let o=n>i.expiry,l=n-i.lastAccessed>this.#r;o&&l&&(s.delete(a),e=!0)}),e&&(this.saveToDisk(),this.notify())},3e4))}rehydrate(){if(!(typeof window>"u"))try{let e=localStorage.getItem(g);if(!e)return;let n=JSON.parse(e);s.clear(),Object.keys(n).forEach(i=>{let a=n[i];if(!a||!a.key)return;let o=c(a.key);Date.now()<a.expiry+this.#r&&s.set(o,a)}),this.notify()}catch(e){console.warn("CB: Rehydration failed",e)}}saveToDisk(){if(!(typeof window>"u"))try{let e=Array.from(s.entries()).filter(([i,a])=>a.persist!==!1),n=Object.fromEntries(e);localStorage.setItem(g,JSON.stringify(n))}catch(e){console.warn("CB: Persistence failed",e)}}getValues(){return s?Array.from(s.values()):[]}notify(){if(!this.#i){this.#i=!0;try{let e=this.getValues();this.#t.forEach(n=>n(e)),d()}finally{this.#i=!1}}}set(e,n,i={}){let a=c(e),o=i.ttl??this.#a.defaultTTL,l=i.persist??!0,u={key:Array.isArray(e)?e:[String(e)],data:n,expiry:Date.now()+o,ttl:o,lastAccessed:Date.now(),persist:l};s.set(a,u),l&&this.saveToDisk(),this.notify()}get(e){let n=c(e),i=s.get(n);if(i)return i.lastAccessed=Date.now(),i.data}remove(e){s.delete(c(e)),this.saveToDisk(),this.notify()}subscribe(e){return this.#t.add(e),e(this.getValues()),()=>{this.#t.delete(e)}}onRevalidate(e){return this.#n.add(e),()=>{this.#n.delete(e)}}triggerRevalidation(e){let n=e?Array.isArray(e)?e:[e]:void 0;Array.from(this.#n).forEach(i=>i(n))}clear(){s.clear(),typeof window<"u"&&localStorage.removeItem(g),this.notify()}destroy(){this.#e&&(clearInterval(this.#e),this.#e=null)}},r=b.getInstance();async function C(t,e,n){let i=c(t),{ttl:a,strategy:o="cache-first",dedupe:l=!0,persist:u}=n||{};if(l&&f.has(i))return f.get(i);let E=(async()=>{try{let h=r.get(t);if(o==="cache-first"&&h!==void 0)return h;if(o==="network-first")try{let y=await e();return r.set(t,y,{ttl:a,persist:u}),y}catch(y){if(h!==void 0)return h;throw y}if(o==="no-cache")return await e();let T=await e();return r.set(t,T,{ttl:a,persist:u}),T}finally{l&&f.delete(i)}})();return l&&f.set(i,E),E}var I=3e5,p=class{options;constructor(e={}){this.options={revalidateOnFocus:e.revalidateOnFocus??!0,revalidateOnReconnect:e.revalidateOnReconnect??!0,defaultTTL:e.defaultTTL??I},r.setConfig(this.options),typeof window<"u"&&this.setupEventListeners()}setupEventListeners(){window.addEventListener("focus",()=>{this.options.revalidateOnFocus&&this.revalidate()}),window.addEventListener("online",()=>{this.options.revalidateOnReconnect&&this.revalidate()})}revalidate(e){let n=typeof e=="string"?[e]:e;r.triggerRevalidation(n),d()}setCacheData(e,n,i){let a={ttl:i?.ttl??this.options.defaultTTL,...i};r.set(e,n,a),d()}invalidate(e){let n=typeof e=="string"?[e]:e;n?r.remove(n):r.clear(),d()}},Z=new p;typeof window<"u"&&(window.__CB_DEVTOOLS__={getCache:()=>r.getValues(),revalidate:t=>{r.triggerRevalidation(t)},subscribe:t=>r.subscribe(t)});0&&(module.exports={CacheBrainClient,cacheEngine,emitUpdate,normalizeKey,smartCache});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var m=Symbol.for("ncb.cache"),v=Symbol.for("ncb.inflight");globalThis[m]||(globalThis[m]=new Map);globalThis[v]||(globalThis[v]=new Map);var s=globalThis[m],f=globalThis[v];var l=i=>Array.isArray(i)?i.map(e=>String(e)).join(":").replace(/:+/g,":"):String(i);var y="cb_cache_snapshot";var T="cb-devtools-update",d=(i=[])=>{typeof window>"u"||window.dispatchEvent(new CustomEvent(T,{detail:i}))};var w=class i{static instance;#t=new Set;#n=new Set;#a={defaultTTL:300*1e3};#r=300*1e3;#i=!1;#e=null;constructor(){this.startCleanupCycle()}static getInstance(){return i.instance||(i.instance=new i,i.instance.rehydrate()),i.instance}setConfig(e){e.defaultTTL!==void 0&&(this.#a.defaultTTL=e.defaultTTL)}startCleanupCycle(){typeof window>"u"||this.#e||(this.#e=setInterval(()=>{let e=!1,t=Date.now();s.forEach((n,a)=>{let o=t>n.expiry,c=t-n.lastAccessed>this.#r;o&&c&&(s.delete(a),e=!0)}),e&&(this.saveToDisk(),this.notify())},3e4))}rehydrate(){if(!(typeof window>"u"))try{let e=localStorage.getItem(y);if(!e)return;let t=JSON.parse(e);s.clear(),Object.keys(t).forEach(n=>{let a=t[n];if(!a||!a.key)return;let o=l(a.key);Date.now()<a.expiry+this.#r&&s.set(o,a)}),this.notify()}catch(e){console.warn("CB: Rehydration failed",e)}}saveToDisk(){if(!(typeof window>"u"))try{let e=Array.from(s.entries()).filter(([n,a])=>a.persist!==!1),t=Object.fromEntries(e);localStorage.setItem(y,JSON.stringify(t))}catch(e){console.warn("CB: Persistence failed",e)}}getValues(){return s?Array.from(s.values()):[]}notify(){if(!this.#i){this.#i=!0;try{let e=this.getValues();this.#t.forEach(t=>t(e)),d()}finally{this.#i=!1}}}set(e,t,n={}){let a=l(e),o=n.ttl??this.#a.defaultTTL,c=n.persist??!0,p={key:Array.isArray(e)?e:[String(e)],data:t,expiry:Date.now()+o,ttl:o,lastAccessed:Date.now(),persist:c};s.set(a,p),c&&this.saveToDisk(),this.notify()}get(e){let t=l(e),n=s.get(t);if(n)return n.lastAccessed=Date.now(),n.data}remove(e){s.delete(l(e)),this.saveToDisk(),this.notify()}subscribe(e){return this.#t.add(e),e(this.getValues()),()=>{this.#t.delete(e)}}onRevalidate(e){return this.#n.add(e),()=>{this.#n.delete(e)}}triggerRevalidation(e){let t=e?Array.isArray(e)?e:[e]:void 0;Array.from(this.#n).forEach(n=>n(t))}clear(){s.clear(),typeof window<"u"&&localStorage.removeItem(y),this.notify()}destroy(){this.#e&&(clearInterval(this.#e),this.#e=null)}},r=w.getInstance();async function C(i,e,t){let n=l(i),{ttl:a,strategy:o="cache-first",dedupe:c=!0,persist:p}=t||{};if(c&&f.has(n))return f.get(n);let b=(async()=>{try{let u=r.get(i);if(o==="cache-first"&&u!==void 0)return u;if(o==="network-first")try{let h=await e();return r.set(i,h,{ttl:a,persist:p}),h}catch(h){if(u!==void 0)return u;throw h}if(o==="no-cache")return await e();let E=await e();return r.set(i,E,{ttl:a,persist:p}),E}finally{c&&f.delete(n)}})();return c&&f.set(n,b),b}var O=3e5,g=class{options;constructor(e={}){this.options={revalidateOnFocus:e.revalidateOnFocus??!0,revalidateOnReconnect:e.revalidateOnReconnect??!0,defaultTTL:e.defaultTTL??O},r.setConfig(this.options),typeof window<"u"&&this.setupEventListeners()}setupEventListeners(){window.addEventListener("focus",()=>{this.options.revalidateOnFocus&&this.revalidate()}),window.addEventListener("online",()=>{this.options.revalidateOnReconnect&&this.revalidate()})}revalidate(e){let t=typeof e=="string"?[e]:e;r.triggerRevalidation(t),d()}setCacheData(e,t,n){let a={ttl:n?.ttl??this.options.defaultTTL,...n};r.set(e,t,a),d()}invalidate(e){let t=typeof e=="string"?[e]:e;t?r.remove(t):r.clear(),d()}},U=new g;typeof window<"u"&&(window.__CB_DEVTOOLS__={getCache:()=>r.getValues(),revalidate:i=>{r.triggerRevalidation(i)},subscribe:i=>r.subscribe(i)});export{g as CacheBrainClient,r as cacheEngine,d as emitUpdate,l as normalizeKey,C as smartCache};
|
package/dist/types.d.mts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
interface CacheOptions {
|
|
2
|
+
ttl: number;
|
|
3
|
+
label?: string;
|
|
4
|
+
persist?: boolean;
|
|
5
|
+
}
|
|
6
|
+
interface CacheEntry<T> {
|
|
7
|
+
key: string[];
|
|
8
|
+
data: T;
|
|
9
|
+
expiry: number;
|
|
10
|
+
ttl: number;
|
|
11
|
+
lastAccessed: number;
|
|
12
|
+
persist?: boolean;
|
|
13
|
+
}
|
|
14
|
+
interface WatcherOptions {
|
|
15
|
+
revalidateOnFocus?: boolean;
|
|
16
|
+
revalidateOnReconnect?: boolean;
|
|
17
|
+
staleTime?: number;
|
|
18
|
+
refetchInterval?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Strategy = "cache-first" | "network-first" | "swr" | "no-cache";
|
|
22
|
+
type SmartCacheOptions = {
|
|
23
|
+
strategy?: Strategy;
|
|
24
|
+
ttl?: number;
|
|
25
|
+
dedupe?: boolean;
|
|
26
|
+
persist?: boolean;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export type { CacheEntry, CacheOptions, SmartCacheOptions, Strategy, WatcherOptions };
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
interface CacheOptions {
|
|
2
|
+
ttl: number;
|
|
3
|
+
label?: string;
|
|
4
|
+
persist?: boolean;
|
|
5
|
+
}
|
|
6
|
+
interface CacheEntry<T> {
|
|
7
|
+
key: string[];
|
|
8
|
+
data: T;
|
|
9
|
+
expiry: number;
|
|
10
|
+
ttl: number;
|
|
11
|
+
lastAccessed: number;
|
|
12
|
+
persist?: boolean;
|
|
13
|
+
}
|
|
14
|
+
interface WatcherOptions {
|
|
15
|
+
revalidateOnFocus?: boolean;
|
|
16
|
+
revalidateOnReconnect?: boolean;
|
|
17
|
+
staleTime?: number;
|
|
18
|
+
refetchInterval?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Strategy = "cache-first" | "network-first" | "swr" | "no-cache";
|
|
22
|
+
type SmartCacheOptions = {
|
|
23
|
+
strategy?: Strategy;
|
|
24
|
+
ttl?: number;
|
|
25
|
+
dedupe?: boolean;
|
|
26
|
+
persist?: boolean;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export type { CacheEntry, CacheOptions, SmartCacheOptions, Strategy, WatcherOptions };
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var o=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var h=(t,e,a,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let p of y(e))!s.call(t,p)&&p!==a&&o(t,p,{get:()=>e[p],enumerable:!(r=c(e,p))||r.enumerable});return t};var m=t=>h(o({},"__esModule",{value:!0}),t);var f={};module.exports=m(f);
|
package/dist/types.mjs
ADDED
|
File without changes
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pixel-pulse/cache-brain",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Universal caching engine for Next.js with React 18 hook and Nuxt.js with Vue 3 support.",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./types": {
|
|
15
|
+
"types": "./dist/types.d.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"keywords": [
|
|
22
|
+
"nextjs",
|
|
23
|
+
"cache",
|
|
24
|
+
"smart-cache",
|
|
25
|
+
"swr",
|
|
26
|
+
"vanilla-js",
|
|
27
|
+
"pixel-pulse"
|
|
28
|
+
],
|
|
29
|
+
"author": "Lin Htet Aung (Liam) (https://github.com/LinnHtetAungSE)",
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"react": ">=18.0.0",
|
|
33
|
+
"react-dom": ">=18.0.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/node": "^20.19.39",
|
|
37
|
+
"@types/react": "^18.3.1",
|
|
38
|
+
"@types/react-dom": "^18.3.1",
|
|
39
|
+
"react": "18.3.1",
|
|
40
|
+
"react-dom": "18.3.1",
|
|
41
|
+
"tsup": "^8.0.0",
|
|
42
|
+
"typescript": "^6.0.2"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "tsup",
|
|
46
|
+
"dev": "tsup --watch"
|
|
47
|
+
}
|
|
48
|
+
}
|