Server: Phase 2 (REVIEW not respected yet)

This commit is contained in:
Thomas Karner committed 2026-09-21 11:24:43 +02:00
1 parent 5d16ded553
commit 142b47674d
4271 files changed
+1203269

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Tanner Linsley
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
+182
View File
@@ -0,0 +1,182 @@
//#region src/alien.ts
const NONE = 0;
const MUTABLE = 1;
const WATCHING = 2;
const RECURSED_CHECK = 4;
const RECURSED = 8;
const DIRTY = 16;
const PENDING = 32;
/* @__NO_SIDE_EFFECTS__ */
function createReactiveSystem({ update, notify, unwatched }) {
return {
link,
unlink,
propagate,
checkDirty,
shallowPropagate
};
function link(dep, sub, version) {
const prevDep = sub.depsTail;
if (prevDep !== void 0 && prevDep.dep === dep) return;
const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
if (nextDep !== void 0 && nextDep.dep === dep) {
nextDep.version = version;
sub.depsTail = nextDep;
return;
}
const prevSub = dep.subsTail;
if (prevSub !== void 0 && prevSub.version === version && prevSub.sub === sub) return;
const newLink = sub.depsTail = dep.subsTail = {
version,
dep,
sub,
prevDep,
nextDep,
prevSub,
nextSub: void 0
};
if (nextDep !== void 0) nextDep.prevDep = newLink;
if (prevDep !== void 0) prevDep.nextDep = newLink;
else sub.deps = newLink;
if (prevSub !== void 0) prevSub.nextSub = newLink;
else dep.subs = newLink;
}
function unlink(link, sub = link.sub) {
const dep = link.dep;
const prevDep = link.prevDep;
const nextDep = link.nextDep;
const nextSub = link.nextSub;
const prevSub = link.prevSub;
if (nextDep !== void 0) nextDep.prevDep = prevDep;
else sub.depsTail = prevDep;
if (prevDep !== void 0) prevDep.nextDep = nextDep;
else sub.deps = nextDep;
if (nextSub !== void 0) nextSub.prevSub = prevSub;
else dep.subsTail = prevSub;
if (prevSub !== void 0) prevSub.nextSub = nextSub;
else if ((dep.subs = nextSub) === void 0) unwatched(dep);
return nextDep;
}
function propagate(link) {
let next = link.nextSub;
let stack;
top: do {
const sub = link.sub;
let flags = sub.flags;
if (!(flags & 60)) sub.flags = flags | 32;
else if (!(flags & (4 | 8))) flags = 0;
else if (!(flags & 4)) sub.flags = flags & ~8 | 32;
else if (!(flags & (16 | 32)) && isValidLink(link, sub)) {
sub.flags = flags | (8 | 32);
flags &= 1;
} else flags = 0;
if (flags & 2) notify(sub);
if (flags & 1) {
const subSubs = sub.subs;
if (subSubs !== void 0) {
const nextSub = (link = subSubs).nextSub;
if (nextSub !== void 0) {
stack = {
value: next,
prev: stack
};
next = nextSub;
}
continue;
}
}
if ((link = next) !== void 0) {
next = link.nextSub;
continue;
}
while (stack !== void 0) {
link = stack.value;
stack = stack.prev;
if (link !== void 0) {
next = link.nextSub;
continue top;
}
}
break;
} while (true);
}
function checkDirty(link, sub) {
let stack;
let checkDepth = 0;
let dirty = false;
top: do {
const dep = link.dep;
const flags = dep.flags;
if (sub.flags & 16) dirty = true;
else if ((flags & (1 | 16)) === (1 | 16)) {
if (update(dep)) {
const subs = dep.subs;
if (subs.nextSub !== void 0) shallowPropagate(subs);
dirty = true;
}
} else if ((flags & (1 | 32)) === (1 | 32)) {
if (link.nextSub !== void 0 || link.prevSub !== void 0) stack = {
value: link,
prev: stack
};
link = dep.deps;
sub = dep;
++checkDepth;
continue;
}
if (!dirty) {
const nextDep = link.nextDep;
if (nextDep !== void 0) {
link = nextDep;
continue;
}
}
while (checkDepth--) {
const firstSub = sub.subs;
const hasMultipleSubs = firstSub.nextSub !== void 0;
if (hasMultipleSubs) {
link = stack.value;
stack = stack.prev;
} else link = firstSub;
if (dirty) {
if (update(sub)) {
if (hasMultipleSubs) shallowPropagate(firstSub);
sub = link.sub;
continue;
}
dirty = false;
} else sub.flags &= ~32;
sub = link.sub;
const nextDep = link.nextDep;
if (nextDep !== void 0) {
link = nextDep;
continue top;
}
}
return dirty;
} while (true);
}
function shallowPropagate(link) {
do {
const sub = link.sub;
const flags = sub.flags;
if ((flags & (32 | 16)) === 32) {
sub.flags = flags | 16;
if ((flags & (2 | 4)) === 2) notify(sub);
}
} while ((link = link.nextSub) !== void 0);
}
function isValidLink(checkLink, sub) {
let link = sub.depsTail;
while (link !== void 0) {
if (link === checkLink) return true;
link = link.prevDep;
}
return false;
}
}
//#endregion
exports.createReactiveSystem = createReactiveSystem;
//# sourceMappingURL=alien.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"alien.cjs","names":[],"sources":["../src/alien.ts"],"sourcesContent":["/* eslint-disable */\n// Adapted from Alien Signals\n// https://github.com/stackblitz/alien-signals/\n\nexport interface ReactiveNode {\n deps?: Link\n depsTail?: Link\n subs?: Link\n subsTail?: Link\n flags: ReactiveFlags\n}\n\nexport interface Link {\n version: number\n dep: ReactiveNode\n sub: ReactiveNode\n prevSub: Link | undefined\n nextSub: Link | undefined\n prevDep: Link | undefined\n nextDep: Link | undefined\n}\n\ninterface Stack<T> {\n value: T\n prev: Stack<T> | undefined\n}\n\nexport type ReactiveFlags = number\n\nexport const NONE = 0\nexport const MUTABLE = 1\nexport const WATCHING = 2\nexport const RECURSED_CHECK = 4\nexport const RECURSED = 8\nexport const DIRTY = 16\nexport const PENDING = 32\n/*@__NO_SIDE_EFFECTS__*/\nexport function createReactiveSystem({\n update,\n notify,\n unwatched,\n}: {\n update(sub: ReactiveNode): boolean\n notify(sub: ReactiveNode): void\n unwatched(sub: ReactiveNode): void\n}) {\n return {\n link,\n unlink,\n propagate,\n checkDirty,\n shallowPropagate,\n }\n\n function link(dep: ReactiveNode, sub: ReactiveNode, version: number): void {\n const prevDep = sub.depsTail\n if (prevDep !== undefined && prevDep.dep === dep) {\n return\n }\n const nextDep = prevDep !== undefined ? prevDep.nextDep : sub.deps\n if (nextDep !== undefined && nextDep.dep === dep) {\n nextDep.version = version\n sub.depsTail = nextDep\n return\n }\n const prevSub = dep.subsTail\n if (\n prevSub !== undefined &&\n prevSub.version === version &&\n prevSub.sub === sub\n ) {\n return\n }\n const newLink =\n (sub.depsTail =\n dep.subsTail =\n {\n version,\n dep,\n sub,\n prevDep,\n nextDep,\n prevSub,\n nextSub: undefined,\n })\n if (nextDep !== undefined) {\n nextDep.prevDep = newLink\n }\n if (prevDep !== undefined) {\n prevDep.nextDep = newLink\n } else {\n sub.deps = newLink\n }\n if (prevSub !== undefined) {\n prevSub.nextSub = newLink\n } else {\n dep.subs = newLink\n }\n }\n\n function unlink(link: Link, sub = link.sub): Link | undefined {\n const dep = link.dep\n const prevDep = link.prevDep\n const nextDep = link.nextDep\n const nextSub = link.nextSub\n const prevSub = link.prevSub\n if (nextDep !== undefined) {\n nextDep.prevDep = prevDep\n } else {\n sub.depsTail = prevDep\n }\n if (prevDep !== undefined) {\n prevDep.nextDep = nextDep\n } else {\n sub.deps = nextDep\n }\n if (nextSub !== undefined) {\n nextSub.prevSub = prevSub\n } else {\n dep.subsTail = prevSub\n }\n if (prevSub !== undefined) {\n prevSub.nextSub = nextSub\n } else if ((dep.subs = nextSub) === undefined) {\n unwatched(dep)\n }\n return nextDep\n }\n\n function propagate(link: Link): void {\n let next = link.nextSub\n let stack: Stack<Link | undefined> | undefined\n\n top: do {\n const sub = link.sub\n let flags = sub.flags\n\n if (!(flags & (RECURSED_CHECK | RECURSED | DIRTY | PENDING))) {\n sub.flags = flags | PENDING\n } else if (!(flags & (RECURSED_CHECK | RECURSED))) {\n flags = NONE\n } else if (!(flags & RECURSED_CHECK)) {\n sub.flags = (flags & ~RECURSED) | PENDING\n } else if (!(flags & (DIRTY | PENDING)) && isValidLink(link, sub)) {\n sub.flags = flags | (RECURSED | PENDING)\n flags &= MUTABLE\n } else {\n flags = NONE\n }\n\n if (flags & WATCHING) {\n notify(sub)\n }\n\n if (flags & MUTABLE) {\n const subSubs = sub.subs\n if (subSubs !== undefined) {\n const nextSub = (link = subSubs).nextSub\n if (nextSub !== undefined) {\n stack = { value: next, prev: stack }\n next = nextSub\n }\n continue\n }\n }\n\n if ((link = next!) !== undefined) {\n next = link.nextSub\n continue\n }\n\n while (stack !== undefined) {\n link = stack.value!\n stack = stack.prev\n if (link !== undefined) {\n next = link.nextSub\n continue top\n }\n }\n\n break\n } while (true)\n }\n\n function checkDirty(link: Link, sub: ReactiveNode): boolean {\n let stack: Stack<Link> | undefined\n let checkDepth = 0\n let dirty = false\n\n top: do {\n const dep = link.dep\n const flags = dep.flags\n\n if (sub.flags & DIRTY) {\n dirty = true\n } else if ((flags & (MUTABLE | DIRTY)) === (MUTABLE | DIRTY)) {\n if (update(dep)) {\n const subs = dep.subs!\n if (subs.nextSub !== undefined) {\n shallowPropagate(subs)\n }\n dirty = true\n }\n Line truncated
+21
View File
@@ -0,0 +1,21 @@
//#region src/alien.d.ts
interface ReactiveNode {
deps?: Link;
depsTail?: Link;
subs?: Link;
subsTail?: Link;
flags: ReactiveFlags;
}
interface Link {
version: number;
dep: ReactiveNode;
sub: ReactiveNode;
prevSub: Link | undefined;
nextSub: Link | undefined;
prevDep: Link | undefined;
nextDep: Link | undefined;
}
type ReactiveFlags = number;
//#endregion
export { ReactiveNode };
//# sourceMappingURL=alien.d.cts.map
+21
View File
@@ -0,0 +1,21 @@
//#region src/alien.d.ts
interface ReactiveNode {
deps?: Link;
depsTail?: Link;
subs?: Link;
subsTail?: Link;
flags: ReactiveFlags;
}
interface Link {
version: number;
dep: ReactiveNode;
sub: ReactiveNode;
prevSub: Link | undefined;
nextSub: Link | undefined;
prevDep: Link | undefined;
nextDep: Link | undefined;
}
type ReactiveFlags = number;
//#endregion
export { ReactiveNode };
//# sourceMappingURL=alien.d.ts.map
+181
View File
@@ -0,0 +1,181 @@
//#region src/alien.ts
const NONE = 0;
const MUTABLE = 1;
const WATCHING = 2;
const RECURSED_CHECK = 4;
const RECURSED = 8;
const DIRTY = 16;
const PENDING = 32;
/* @__NO_SIDE_EFFECTS__ */
function createReactiveSystem({ update, notify, unwatched }) {
return {
link,
unlink,
propagate,
checkDirty,
shallowPropagate
};
function link(dep, sub, version) {
const prevDep = sub.depsTail;
if (prevDep !== void 0 && prevDep.dep === dep) return;
const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
if (nextDep !== void 0 && nextDep.dep === dep) {
nextDep.version = version;
sub.depsTail = nextDep;
return;
}
const prevSub = dep.subsTail;
if (prevSub !== void 0 && prevSub.version === version && prevSub.sub === sub) return;
const newLink = sub.depsTail = dep.subsTail = {
version,
dep,
sub,
prevDep,
nextDep,
prevSub,
nextSub: void 0
};
if (nextDep !== void 0) nextDep.prevDep = newLink;
if (prevDep !== void 0) prevDep.nextDep = newLink;
else sub.deps = newLink;
if (prevSub !== void 0) prevSub.nextSub = newLink;
else dep.subs = newLink;
}
function unlink(link, sub = link.sub) {
const dep = link.dep;
const prevDep = link.prevDep;
const nextDep = link.nextDep;
const nextSub = link.nextSub;
const prevSub = link.prevSub;
if (nextDep !== void 0) nextDep.prevDep = prevDep;
else sub.depsTail = prevDep;
if (prevDep !== void 0) prevDep.nextDep = nextDep;
else sub.deps = nextDep;
if (nextSub !== void 0) nextSub.prevSub = prevSub;
else dep.subsTail = prevSub;
if (prevSub !== void 0) prevSub.nextSub = nextSub;
else if ((dep.subs = nextSub) === void 0) unwatched(dep);
return nextDep;
}
function propagate(link) {
let next = link.nextSub;
let stack;
top: do {
const sub = link.sub;
let flags = sub.flags;
if (!(flags & 60)) sub.flags = flags | 32;
else if (!(flags & (4 | 8))) flags = 0;
else if (!(flags & 4)) sub.flags = flags & ~8 | 32;
else if (!(flags & (16 | 32)) && isValidLink(link, sub)) {
sub.flags = flags | (8 | 32);
flags &= 1;
} else flags = 0;
if (flags & 2) notify(sub);
if (flags & 1) {
const subSubs = sub.subs;
if (subSubs !== void 0) {
const nextSub = (link = subSubs).nextSub;
if (nextSub !== void 0) {
stack = {
value: next,
prev: stack
};
next = nextSub;
}
continue;
}
}
if ((link = next) !== void 0) {
next = link.nextSub;
continue;
}
while (stack !== void 0) {
link = stack.value;
stack = stack.prev;
if (link !== void 0) {
next = link.nextSub;
continue top;
}
}
break;
} while (true);
}
function checkDirty(link, sub) {
let stack;
let checkDepth = 0;
let dirty = false;
top: do {
const dep = link.dep;
const flags = dep.flags;
if (sub.flags & 16) dirty = true;
else if ((flags & (1 | 16)) === (1 | 16)) {
if (update(dep)) {
const subs = dep.subs;
if (subs.nextSub !== void 0) shallowPropagate(subs);
dirty = true;
}
} else if ((flags & (1 | 32)) === (1 | 32)) {
if (link.nextSub !== void 0 || link.prevSub !== void 0) stack = {
value: link,
prev: stack
};
link = dep.deps;
sub = dep;
++checkDepth;
continue;
}
if (!dirty) {
const nextDep = link.nextDep;
if (nextDep !== void 0) {
link = nextDep;
continue;
}
}
while (checkDepth--) {
const firstSub = sub.subs;
const hasMultipleSubs = firstSub.nextSub !== void 0;
if (hasMultipleSubs) {
link = stack.value;
stack = stack.prev;
} else link = firstSub;
if (dirty) {
if (update(sub)) {
if (hasMultipleSubs) shallowPropagate(firstSub);
sub = link.sub;
continue;
}
dirty = false;
} else sub.flags &= ~32;
sub = link.sub;
const nextDep = link.nextDep;
if (nextDep !== void 0) {
link = nextDep;
continue top;
}
}
return dirty;
} while (true);
}
function shallowPropagate(link) {
do {
const sub = link.sub;
const flags = sub.flags;
if ((flags & (32 | 16)) === 32) {
sub.flags = flags | 16;
if ((flags & (2 | 4)) === 2) notify(sub);
}
} while ((link = link.nextSub) !== void 0);
}
function isValidLink(checkLink, sub) {
let link = sub.depsTail;
while (link !== void 0) {
if (link === checkLink) return true;
link = link.prevDep;
}
return false;
}
}
//#endregion
export { createReactiveSystem };
//# sourceMappingURL=alien.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"alien.js","names":[],"sources":["../src/alien.ts"],"sourcesContent":["/* eslint-disable */\n// Adapted from Alien Signals\n// https://github.com/stackblitz/alien-signals/\n\nexport interface ReactiveNode {\n deps?: Link\n depsTail?: Link\n subs?: Link\n subsTail?: Link\n flags: ReactiveFlags\n}\n\nexport interface Link {\n version: number\n dep: ReactiveNode\n sub: ReactiveNode\n prevSub: Link | undefined\n nextSub: Link | undefined\n prevDep: Link | undefined\n nextDep: Link | undefined\n}\n\ninterface Stack<T> {\n value: T\n prev: Stack<T> | undefined\n}\n\nexport type ReactiveFlags = number\n\nexport const NONE = 0\nexport const MUTABLE = 1\nexport const WATCHING = 2\nexport const RECURSED_CHECK = 4\nexport const RECURSED = 8\nexport const DIRTY = 16\nexport const PENDING = 32\n/*@__NO_SIDE_EFFECTS__*/\nexport function createReactiveSystem({\n update,\n notify,\n unwatched,\n}: {\n update(sub: ReactiveNode): boolean\n notify(sub: ReactiveNode): void\n unwatched(sub: ReactiveNode): void\n}) {\n return {\n link,\n unlink,\n propagate,\n checkDirty,\n shallowPropagate,\n }\n\n function link(dep: ReactiveNode, sub: ReactiveNode, version: number): void {\n const prevDep = sub.depsTail\n if (prevDep !== undefined && prevDep.dep === dep) {\n return\n }\n const nextDep = prevDep !== undefined ? prevDep.nextDep : sub.deps\n if (nextDep !== undefined && nextDep.dep === dep) {\n nextDep.version = version\n sub.depsTail = nextDep\n return\n }\n const prevSub = dep.subsTail\n if (\n prevSub !== undefined &&\n prevSub.version === version &&\n prevSub.sub === sub\n ) {\n return\n }\n const newLink =\n (sub.depsTail =\n dep.subsTail =\n {\n version,\n dep,\n sub,\n prevDep,\n nextDep,\n prevSub,\n nextSub: undefined,\n })\n if (nextDep !== undefined) {\n nextDep.prevDep = newLink\n }\n if (prevDep !== undefined) {\n prevDep.nextDep = newLink\n } else {\n sub.deps = newLink\n }\n if (prevSub !== undefined) {\n prevSub.nextSub = newLink\n } else {\n dep.subs = newLink\n }\n }\n\n function unlink(link: Link, sub = link.sub): Link | undefined {\n const dep = link.dep\n const prevDep = link.prevDep\n const nextDep = link.nextDep\n const nextSub = link.nextSub\n const prevSub = link.prevSub\n if (nextDep !== undefined) {\n nextDep.prevDep = prevDep\n } else {\n sub.depsTail = prevDep\n }\n if (prevDep !== undefined) {\n prevDep.nextDep = nextDep\n } else {\n sub.deps = nextDep\n }\n if (nextSub !== undefined) {\n nextSub.prevSub = prevSub\n } else {\n dep.subsTail = prevSub\n }\n if (prevSub !== undefined) {\n prevSub.nextSub = nextSub\n } else if ((dep.subs = nextSub) === undefined) {\n unwatched(dep)\n }\n return nextDep\n }\n\n function propagate(link: Link): void {\n let next = link.nextSub\n let stack: Stack<Link | undefined> | undefined\n\n top: do {\n const sub = link.sub\n let flags = sub.flags\n\n if (!(flags & (RECURSED_CHECK | RECURSED | DIRTY | PENDING))) {\n sub.flags = flags | PENDING\n } else if (!(flags & (RECURSED_CHECK | RECURSED))) {\n flags = NONE\n } else if (!(flags & RECURSED_CHECK)) {\n sub.flags = (flags & ~RECURSED) | PENDING\n } else if (!(flags & (DIRTY | PENDING)) && isValidLink(link, sub)) {\n sub.flags = flags | (RECURSED | PENDING)\n flags &= MUTABLE\n } else {\n flags = NONE\n }\n\n if (flags & WATCHING) {\n notify(sub)\n }\n\n if (flags & MUTABLE) {\n const subSubs = sub.subs\n if (subSubs !== undefined) {\n const nextSub = (link = subSubs).nextSub\n if (nextSub !== undefined) {\n stack = { value: next, prev: stack }\n next = nextSub\n }\n continue\n }\n }\n\n if ((link = next!) !== undefined) {\n next = link.nextSub\n continue\n }\n\n while (stack !== undefined) {\n link = stack.value!\n stack = stack.prev\n if (link !== undefined) {\n next = link.nextSub\n continue top\n }\n }\n\n break\n } while (true)\n }\n\n function checkDirty(link: Link, sub: ReactiveNode): boolean {\n let stack: Stack<Link> | undefined\n let checkDepth = 0\n let dirty = false\n\n top: do {\n const dep = link.dep\n const flags = dep.flags\n\n if (sub.flags & DIRTY) {\n dirty = true\n } else if ((flags & (MUTABLE | DIRTY)) === (MUTABLE | DIRTY)) {\n if (update(dep)) {\n const subs = dep.subs!\n if (subs.nextSub !== undefined) {\n shallowPropagate(subs)\n }\n dirty = true\n }\n Line truncated
+210
View File
@@ -0,0 +1,210 @@
const require_alien = require('./alien.cjs');
//#region src/atom.ts
function toObserver(nextHandler, errorHandler, completionHandler) {
const isObserver = typeof nextHandler === "object";
const self = isObserver ? nextHandler : void 0;
return {
next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
};
}
const queuedEffects = [];
let cycle = 0;
const { link, unlink, propagate, checkDirty, shallowPropagate } = /* @__PURE__ */ require_alien.createReactiveSystem({
update(atom) {
return atom._update();
},
notify(effect) {
queuedEffects[queuedEffectsLength++] = effect;
effect.flags &= ~2;
},
unwatched(atom) {
if (atom.depsTail !== void 0) {
atom.depsTail = void 0;
atom.flags = 1 | 16;
purgeDeps(atom);
}
}
});
let notifyIndex = 0;
let queuedEffectsLength = 0;
let activeSub;
let batchDepth = 0;
function batch(fn) {
try {
++batchDepth;
fn();
} finally {
if (!--batchDepth) flush();
}
}
function purgeDeps(sub) {
const depsTail = sub.depsTail;
let dep = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
while (dep !== void 0) dep = unlink(dep, sub);
}
function flush() {
if (batchDepth > 0) return;
while (notifyIndex < queuedEffectsLength) {
const effect = queuedEffects[notifyIndex];
queuedEffects[notifyIndex++] = void 0;
effect.notify();
}
notifyIndex = 0;
queuedEffectsLength = 0;
}
function createAsyncAtom(getValue, options) {
const ref = {};
const atom = createAtom(() => {
getValue().then((data) => {
const internalAtom = ref.current;
if (internalAtom._update({
status: "done",
data
})) {
const subs = internalAtom.subs;
if (subs !== void 0) {
propagate(subs);
shallowPropagate(subs);
flush();
}
}
}, (error) => {
const internalAtom = ref.current;
if (internalAtom._update({
status: "error",
error
})) {
const subs = internalAtom.subs;
if (subs !== void 0) {
propagate(subs);
shallowPropagate(subs);
flush();
}
}
});
return { status: "pending" };
}, options);
ref.current = atom;
return atom;
}
function createAtom(valueOrFn, options) {
const isComputed = typeof valueOrFn === "function";
const getter = valueOrFn;
const atom = {
_snapshot: isComputed ? void 0 : valueOrFn,
subs: void 0,
subsTail: void 0,
deps: void 0,
depsTail: void 0,
flags: isComputed ? 0 : 1,
get() {
if (activeSub !== void 0) link(atom, activeSub, cycle);
return atom._snapshot;
},
subscribe(observerOrFn) {
const obs = toObserver(observerOrFn);
const observed = { current: false };
const e = effect(() => {
atom.get();
if (!observed.current) observed.current = true;
else obs.next?.(atom._snapshot);
});
return { unsubscribe: () => {
e.stop();
} };
},
_update(getValue) {
const prevSub = activeSub;
const compare = options?.compare ?? Object.is;
if (isComputed) {
activeSub = atom;
++cycle;
atom.depsTail = void 0;
} else if (getValue === void 0) return false;
if (isComputed) atom.flags = 1 | 4;
try {
const oldValue = atom._snapshot;
const newValue = typeof getValue === "function" ? getValue(oldValue) : getValue === void 0 && isComputed ? getter(oldValue) : getValue;
if (oldValue === void 0 || !compare(oldValue, newValue)) {
atom._snapshot = newValue;
return true;
}
return false;
} finally {
activeSub = prevSub;
if (isComputed) atom.flags &= ~4;
purgeDeps(atom);
}
}
};
if (isComputed) {
atom.flags = 1 | 16;
atom.get = function() {
const flags = atom.flags;
if (flags & 16 || flags & 32 && checkDirty(atom.deps, atom)) {
if (atom._update()) {
const subs = atom.subs;
if (subs !== void 0) shallowPropagate(subs);
}
} else if (flags & 32) atom.flags = flags & ~32;
if (activeSub !== void 0) link(atom, activeSub, cycle);
return atom._snapshot;
};
} else atom.set = function(valueOrFn) {
if (atom._update(valueOrFn)) {
const subs = atom.subs;
if (subs !== void 0) {
propagate(subs);
shallowPropagate(subs);
flush();
}
}
};
return atom;
}
function effect(fn) {
const run = () => {
const prevSub = activeSub;
activeSub = effectObj;
++cycle;
effectObj.depsTail = void 0;
effectObj.flags = 2 | 4;
try {
return fn();
} finally {
activeSub = prevSub;
effectObj.flags &= ~4;
purgeDeps(effectObj);
}
};
const effectObj = {
deps: void 0,
depsTail: void 0,
subs: void 0,
subsTail: void 0,
flags: 2 | 4,
notify() {
const flags = this.flags;
if (flags & 16 || flags & 32 && checkDirty(this.deps, this)) run();
else this.flags = 2;
},
stop() {
this.flags = 0;
this.depsTail = void 0;
purgeDeps(this);
}
};
run();
return effectObj;
}
//#endregion
exports.batch = batch;
exports.createAsyncAtom = createAsyncAtom;
exports.createAtom = createAtom;
exports.flush = flush;
exports.toObserver = toObserver;
//# sourceMappingURL=atom.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"atom.cjs","names":[],"sources":["../src/atom.ts"],"sourcesContent":["import {\n DIRTY,\n MUTABLE,\n NONE,\n PENDING,\n RECURSED_CHECK,\n WATCHING,\n createReactiveSystem,\n} from './alien'\n\nimport type { ReactiveNode } from './alien'\nimport type {\n Atom,\n AtomOptions,\n Observer,\n ReadonlyAtom,\n Subscription,\n} from './types'\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void,\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object'\n const self = isObserver ? nextHandler : undefined\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self,\n ),\n }\n}\n\ninterface InternalAtom<T> extends ReactiveNode {\n _snapshot: T\n _update: (getValue?: T | ((snapshot: T) => T)) => boolean\n get: () => T\n subscribe: (observerOrFn: Observer<T> | ((value: T) => void)) => Subscription\n}\n\nconst queuedEffects: Array<Effect | undefined> = []\nlet cycle = 0\nconst { link, unlink, propagate, checkDirty, shallowPropagate } =\n createReactiveSystem({\n update(atom: InternalAtom<any>): boolean {\n return atom._update()\n },\n // eslint-disable-next-line no-shadow\n notify(effect: Effect): void {\n queuedEffects[queuedEffectsLength++] = effect\n effect.flags &= ~WATCHING\n },\n unwatched(atom: InternalAtom<any>): void {\n if (atom.depsTail !== undefined) {\n atom.depsTail = undefined\n atom.flags = MUTABLE | DIRTY\n purgeDeps(atom)\n }\n },\n })\n\nlet notifyIndex = 0\nlet queuedEffectsLength = 0\nlet activeSub: ReactiveNode | undefined\nlet batchDepth = 0\n\nexport function batch(fn: () => void) {\n try {\n ++batchDepth\n fn()\n } finally {\n if (!--batchDepth) {\n flush()\n }\n }\n}\n\nfunction purgeDeps(sub: ReactiveNode) {\n const depsTail = sub.depsTail\n let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps\n while (dep !== undefined) {\n dep = unlink(dep, sub)\n }\n}\n\nexport function flush(): void {\n if (batchDepth > 0) {\n return\n }\n while (notifyIndex < queuedEffectsLength) {\n // eslint-disable-next-line no-shadow\n const effect = queuedEffects[notifyIndex]!\n queuedEffects[notifyIndex++] = undefined\n effect.notify()\n }\n notifyIndex = 0\n queuedEffectsLength = 0\n}\n\ntype AsyncAtomState<TData, TError = unknown> =\n | { status: 'pending' }\n | { status: 'done'; data: TData }\n | { status: 'error'; error: TError }\n\nexport function createAsyncAtom<T>(\n getValue: () => Promise<T>,\n options?: AtomOptions<AsyncAtomState<T>>,\n): ReadonlyAtom<AsyncAtomState<T>> {\n const ref: { current?: InternalAtom<AsyncAtomState<T>> } = {}\n const atom = createAtom<AsyncAtomState<T>>(() => {\n getValue().then(\n (data) => {\n const internalAtom = ref.current!\n if (internalAtom._update({ status: 'done', data })) {\n const subs = internalAtom.subs\n if (subs !== undefined) {\n propagate(subs)\n shallowPropagate(subs)\n flush()\n }\n }\n },\n (error) => {\n const internalAtom = ref.current!\n if (internalAtom._update({ status: 'error', error })) {\n const subs = internalAtom.subs\n if (subs !== undefined) {\n propagate(subs)\n shallowPropagate(subs)\n flush()\n }\n }\n },\n )\n\n return { status: 'pending' }\n }, options)\n ref.current = atom as unknown as InternalAtom<AsyncAtomState<T>>\n\n return atom\n}\n\nexport function createAtom<T>(\n getValue: (prev?: NoInfer<T>) => T,\n options?: AtomOptions<T>,\n): ReadonlyAtom<T>\nexport function createAtom<T>(\n initialValue: T,\n options?: AtomOptions<T>,\n): Atom<T>\nexport function createAtom<T>(\n valueOrFn: T | ((prev?: T) => T),\n options?: AtomOptions<T>,\n): Atom<T> | ReadonlyAtom<T> {\n const isComputed = typeof valueOrFn === 'function'\n const getter = valueOrFn as (prev?: T) => T\n\n // Create plain object atom\n const atom: InternalAtom<T> = {\n _snapshot: isComputed ? undefined! : valueOrFn,\n\n subs: undefined,\n subsTail: undefined,\n deps: undefined,\n depsTail: undefined,\n flags: isComputed ? NONE : MUTABLE,\n\n get(): T {\n if (activeSub !== undefined) {\n link(atom, activeSub, cycle)\n }\n return atom._snapshot\n },\n\n subscribe(observerOrFn: Observer<T> | ((value: T) => void)) {\n const obs = toObserver(observerOrFn)\n const observed = { current: false }\n const e = effect(() => {\n atom.get()\n if (!observed.current) {\n observed.current = true\n } else {\n obs.next?.(aLine truncated
+21
View File
@@ -0,0 +1,21 @@
import { Atom, AtomOptions, Observer, ReadonlyAtom } from "./types.cjs";
//#region src/atom.d.ts
declare function toObserver<T>(nextHandler?: Observer<T> | ((value: T) => void), errorHandler?: (error: any) => void, completionHandler?: () => void): Observer<T>;
declare function batch(fn: () => void): void;
declare function flush(): void;
type AsyncAtomState<TData, TError = unknown> = {
status: 'pending';
} | {
status: 'done';
data: TData;
} | {
status: 'error';
error: TError;
};
declare function createAsyncAtom<T>(getValue: () => Promise<T>, options?: AtomOptions<AsyncAtomState<T>>): ReadonlyAtom<AsyncAtomState<T>>;
declare function createAtom<T>(getValue: (prev?: NoInfer<T>) => T, options?: AtomOptions<T>): ReadonlyAtom<T>;
declare function createAtom<T>(initialValue: T, options?: AtomOptions<T>): Atom<T>;
//#endregion
export { batch, createAsyncAtom, createAtom, flush, toObserver };
//# sourceMappingURL=atom.d.cts.map
+21
View File
@@ -0,0 +1,21 @@
import { Atom, AtomOptions, Observer, ReadonlyAtom } from "./types.js";
//#region src/atom.d.ts
declare function toObserver<T>(nextHandler?: Observer<T> | ((value: T) => void), errorHandler?: (error: any) => void, completionHandler?: () => void): Observer<T>;
declare function batch(fn: () => void): void;
declare function flush(): void;
type AsyncAtomState<TData, TError = unknown> = {
status: 'pending';
} | {
status: 'done';
data: TData;
} | {
status: 'error';
error: TError;
};
declare function createAsyncAtom<T>(getValue: () => Promise<T>, options?: AtomOptions<AsyncAtomState<T>>): ReadonlyAtom<AsyncAtomState<T>>;
declare function createAtom<T>(getValue: (prev?: NoInfer<T>) => T, options?: AtomOptions<T>): ReadonlyAtom<T>;
declare function createAtom<T>(initialValue: T, options?: AtomOptions<T>): Atom<T>;
//#endregion
export { batch, createAsyncAtom, createAtom, flush, toObserver };
//# sourceMappingURL=atom.d.ts.map
+206
View File
@@ -0,0 +1,206 @@
import { createReactiveSystem } from "./alien.js";
//#region src/atom.ts
function toObserver(nextHandler, errorHandler, completionHandler) {
const isObserver = typeof nextHandler === "object";
const self = isObserver ? nextHandler : void 0;
return {
next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
};
}
const queuedEffects = [];
let cycle = 0;
const { link, unlink, propagate, checkDirty, shallowPropagate } = /* @__PURE__ */ createReactiveSystem({
update(atom) {
return atom._update();
},
notify(effect) {
queuedEffects[queuedEffectsLength++] = effect;
effect.flags &= ~2;
},
unwatched(atom) {
if (atom.depsTail !== void 0) {
atom.depsTail = void 0;
atom.flags = 1 | 16;
purgeDeps(atom);
}
}
});
let notifyIndex = 0;
let queuedEffectsLength = 0;
let activeSub;
let batchDepth = 0;
function batch(fn) {
try {
++batchDepth;
fn();
} finally {
if (!--batchDepth) flush();
}
}
function purgeDeps(sub) {
const depsTail = sub.depsTail;
let dep = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
while (dep !== void 0) dep = unlink(dep, sub);
}
function flush() {
if (batchDepth > 0) return;
while (notifyIndex < queuedEffectsLength) {
const effect = queuedEffects[notifyIndex];
queuedEffects[notifyIndex++] = void 0;
effect.notify();
}
notifyIndex = 0;
queuedEffectsLength = 0;
}
function createAsyncAtom(getValue, options) {
const ref = {};
const atom = createAtom(() => {
getValue().then((data) => {
const internalAtom = ref.current;
if (internalAtom._update({
status: "done",
data
})) {
const subs = internalAtom.subs;
if (subs !== void 0) {
propagate(subs);
shallowPropagate(subs);
flush();
}
}
}, (error) => {
const internalAtom = ref.current;
if (internalAtom._update({
status: "error",
error
})) {
const subs = internalAtom.subs;
if (subs !== void 0) {
propagate(subs);
shallowPropagate(subs);
flush();
}
}
});
return { status: "pending" };
}, options);
ref.current = atom;
return atom;
}
function createAtom(valueOrFn, options) {
const isComputed = typeof valueOrFn === "function";
const getter = valueOrFn;
const atom = {
_snapshot: isComputed ? void 0 : valueOrFn,
subs: void 0,
subsTail: void 0,
deps: void 0,
depsTail: void 0,
flags: isComputed ? 0 : 1,
get() {
if (activeSub !== void 0) link(atom, activeSub, cycle);
return atom._snapshot;
},
subscribe(observerOrFn) {
const obs = toObserver(observerOrFn);
const observed = { current: false };
const e = effect(() => {
atom.get();
if (!observed.current) observed.current = true;
else obs.next?.(atom._snapshot);
});
return { unsubscribe: () => {
e.stop();
} };
},
_update(getValue) {
const prevSub = activeSub;
const compare = options?.compare ?? Object.is;
if (isComputed) {
activeSub = atom;
++cycle;
atom.depsTail = void 0;
} else if (getValue === void 0) return false;
if (isComputed) atom.flags = 1 | 4;
try {
const oldValue = atom._snapshot;
const newValue = typeof getValue === "function" ? getValue(oldValue) : getValue === void 0 && isComputed ? getter(oldValue) : getValue;
if (oldValue === void 0 || !compare(oldValue, newValue)) {
atom._snapshot = newValue;
return true;
}
return false;
} finally {
activeSub = prevSub;
if (isComputed) atom.flags &= ~4;
purgeDeps(atom);
}
}
};
if (isComputed) {
atom.flags = 1 | 16;
atom.get = function() {
const flags = atom.flags;
if (flags & 16 || flags & 32 && checkDirty(atom.deps, atom)) {
if (atom._update()) {
const subs = atom.subs;
if (subs !== void 0) shallowPropagate(subs);
}
} else if (flags & 32) atom.flags = flags & ~32;
if (activeSub !== void 0) link(atom, activeSub, cycle);
return atom._snapshot;
};
} else atom.set = function(valueOrFn) {
if (atom._update(valueOrFn)) {
const subs = atom.subs;
if (subs !== void 0) {
propagate(subs);
shallowPropagate(subs);
flush();
}
}
};
return atom;
}
function effect(fn) {
const run = () => {
const prevSub = activeSub;
activeSub = effectObj;
++cycle;
effectObj.depsTail = void 0;
effectObj.flags = 2 | 4;
try {
return fn();
} finally {
activeSub = prevSub;
effectObj.flags &= ~4;
purgeDeps(effectObj);
}
};
const effectObj = {
deps: void 0,
depsTail: void 0,
subs: void 0,
subsTail: void 0,
flags: 2 | 4,
notify() {
const flags = this.flags;
if (flags & 16 || flags & 32 && checkDirty(this.deps, this)) run();
else this.flags = 2;
},
stop() {
this.flags = 0;
this.depsTail = void 0;
purgeDeps(this);
}
};
run();
return effectObj;
}
//#endregion
export { batch, createAsyncAtom, createAtom, flush, toObserver };
//# sourceMappingURL=atom.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"atom.js","names":[],"sources":["../src/atom.ts"],"sourcesContent":["import {\n DIRTY,\n MUTABLE,\n NONE,\n PENDING,\n RECURSED_CHECK,\n WATCHING,\n createReactiveSystem,\n} from './alien'\n\nimport type { ReactiveNode } from './alien'\nimport type {\n Atom,\n AtomOptions,\n Observer,\n ReadonlyAtom,\n Subscription,\n} from './types'\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void,\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object'\n const self = isObserver ? nextHandler : undefined\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self,\n ),\n }\n}\n\ninterface InternalAtom<T> extends ReactiveNode {\n _snapshot: T\n _update: (getValue?: T | ((snapshot: T) => T)) => boolean\n get: () => T\n subscribe: (observerOrFn: Observer<T> | ((value: T) => void)) => Subscription\n}\n\nconst queuedEffects: Array<Effect | undefined> = []\nlet cycle = 0\nconst { link, unlink, propagate, checkDirty, shallowPropagate } =\n createReactiveSystem({\n update(atom: InternalAtom<any>): boolean {\n return atom._update()\n },\n // eslint-disable-next-line no-shadow\n notify(effect: Effect): void {\n queuedEffects[queuedEffectsLength++] = effect\n effect.flags &= ~WATCHING\n },\n unwatched(atom: InternalAtom<any>): void {\n if (atom.depsTail !== undefined) {\n atom.depsTail = undefined\n atom.flags = MUTABLE | DIRTY\n purgeDeps(atom)\n }\n },\n })\n\nlet notifyIndex = 0\nlet queuedEffectsLength = 0\nlet activeSub: ReactiveNode | undefined\nlet batchDepth = 0\n\nexport function batch(fn: () => void) {\n try {\n ++batchDepth\n fn()\n } finally {\n if (!--batchDepth) {\n flush()\n }\n }\n}\n\nfunction purgeDeps(sub: ReactiveNode) {\n const depsTail = sub.depsTail\n let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps\n while (dep !== undefined) {\n dep = unlink(dep, sub)\n }\n}\n\nexport function flush(): void {\n if (batchDepth > 0) {\n return\n }\n while (notifyIndex < queuedEffectsLength) {\n // eslint-disable-next-line no-shadow\n const effect = queuedEffects[notifyIndex]!\n queuedEffects[notifyIndex++] = undefined\n effect.notify()\n }\n notifyIndex = 0\n queuedEffectsLength = 0\n}\n\ntype AsyncAtomState<TData, TError = unknown> =\n | { status: 'pending' }\n | { status: 'done'; data: TData }\n | { status: 'error'; error: TError }\n\nexport function createAsyncAtom<T>(\n getValue: () => Promise<T>,\n options?: AtomOptions<AsyncAtomState<T>>,\n): ReadonlyAtom<AsyncAtomState<T>> {\n const ref: { current?: InternalAtom<AsyncAtomState<T>> } = {}\n const atom = createAtom<AsyncAtomState<T>>(() => {\n getValue().then(\n (data) => {\n const internalAtom = ref.current!\n if (internalAtom._update({ status: 'done', data })) {\n const subs = internalAtom.subs\n if (subs !== undefined) {\n propagate(subs)\n shallowPropagate(subs)\n flush()\n }\n }\n },\n (error) => {\n const internalAtom = ref.current!\n if (internalAtom._update({ status: 'error', error })) {\n const subs = internalAtom.subs\n if (subs !== undefined) {\n propagate(subs)\n shallowPropagate(subs)\n flush()\n }\n }\n },\n )\n\n return { status: 'pending' }\n }, options)\n ref.current = atom as unknown as InternalAtom<AsyncAtomState<T>>\n\n return atom\n}\n\nexport function createAtom<T>(\n getValue: (prev?: NoInfer<T>) => T,\n options?: AtomOptions<T>,\n): ReadonlyAtom<T>\nexport function createAtom<T>(\n initialValue: T,\n options?: AtomOptions<T>,\n): Atom<T>\nexport function createAtom<T>(\n valueOrFn: T | ((prev?: T) => T),\n options?: AtomOptions<T>,\n): Atom<T> | ReadonlyAtom<T> {\n const isComputed = typeof valueOrFn === 'function'\n const getter = valueOrFn as (prev?: T) => T\n\n // Create plain object atom\n const atom: InternalAtom<T> = {\n _snapshot: isComputed ? undefined! : valueOrFn,\n\n subs: undefined,\n subsTail: undefined,\n deps: undefined,\n depsTail: undefined,\n flags: isComputed ? NONE : MUTABLE,\n\n get(): T {\n if (activeSub !== undefined) {\n link(atom, activeSub, cycle)\n }\n return atom._snapshot\n },\n\n subscribe(observerOrFn: Observer<T> | ((value: T) => void)) {\n const obs = toObserver(observerOrFn)\n const observed = { current: false }\n const e = effect(() => {\n atom.get()\n if (!observed.current) {\n observed.current = true\n } else {\n obs.next?.(atLine truncated
+14
View File
@@ -0,0 +1,14 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_atom = require('./atom.cjs');
const require_store = require('./store.cjs');
const require_shallow = require('./shallow.cjs');
exports.ReadonlyStore = require_store.ReadonlyStore;
exports.Store = require_store.Store;
exports.batch = require_atom.batch;
exports.createAsyncAtom = require_atom.createAsyncAtom;
exports.createAtom = require_atom.createAtom;
exports.createStore = require_store.createStore;
exports.flush = require_atom.flush;
exports.shallow = require_shallow.shallow;
exports.toObserver = require_atom.toObserver;
+5
View File
@@ -0,0 +1,5 @@
import { AnyAtom, Atom, AtomOptions, BaseAtom, InternalBaseAtom, InternalReadonlyAtom, InteropSubscribable, Observer, Readable, ReadonlyAtom, Selection, Subscribable, Subscription } from "./types.cjs";
import { batch, createAsyncAtom, createAtom, flush, toObserver } from "./atom.cjs";
import { ReadonlyStore, Store, StoreAction, StoreActionMap, StoreActionsFactory, createStore } from "./store.cjs";
import { shallow } from "./shallow.cjs";
export { AnyAtom, Atom, AtomOptions, BaseAtom, InternalBaseAtom, InternalReadonlyAtom, InteropSubscribable, Observer, Readable, ReadonlyAtom, ReadonlyStore, Selection, Store, StoreAction, StoreActionMap, StoreActionsFactory, Subscribable, Subscription, batch, createAsyncAtom, createAtom, createStore, flush, shallow, toObserver };
+5
View File
@@ -0,0 +1,5 @@
import { AnyAtom, Atom, AtomOptions, BaseAtom, InternalBaseAtom, InternalReadonlyAtom, InteropSubscribable, Observer, Readable, ReadonlyAtom, Selection, Subscribable, Subscription } from "./types.js";
import { batch, createAsyncAtom, createAtom, flush, toObserver } from "./atom.js";
import { ReadonlyStore, Store, StoreAction, StoreActionMap, StoreActionsFactory, createStore } from "./store.js";
import { shallow } from "./shallow.js";
export { AnyAtom, Atom, AtomOptions, BaseAtom, InternalBaseAtom, InternalReadonlyAtom, InteropSubscribable, Observer, Readable, ReadonlyAtom, ReadonlyStore, Selection, Store, StoreAction, StoreActionMap, StoreActionsFactory, Subscribable, Subscription, batch, createAsyncAtom, createAtom, createStore, flush, shallow, toObserver };
+5
View File
@@ -0,0 +1,5 @@
import { batch, createAsyncAtom, createAtom, flush, toObserver } from "./atom.js";
import { ReadonlyStore, Store, createStore } from "./store.js";
import { shallow } from "./shallow.js";
export { ReadonlyStore, Store, batch, createAsyncAtom, createAtom, createStore, flush, shallow, toObserver };
+31
View File
@@ -0,0 +1,31 @@
//#region src/shallow.ts
function shallow(objA, objB) {
if (Object.is(objA, objB)) return true;
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) return false;
if (objA instanceof Map && objB instanceof Map) {
if (objA.size !== objB.size) return false;
for (const [k, v] of objA) if (!objB.has(k) || !Object.is(v, objB.get(k))) return false;
return true;
}
if (objA instanceof Set && objB instanceof Set) {
if (objA.size !== objB.size) return false;
for (const v of objA) if (!objB.has(v)) return false;
return true;
}
if (objA instanceof Date && objB instanceof Date) {
if (objA.getTime() !== objB.getTime()) return false;
return true;
}
const keysA = getOwnKeys(objA);
if (keysA.length !== getOwnKeys(objB).length) return false;
for (let i = 0; i < keysA.length; i++) if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) return false;
return true;
}
function getOwnKeys(obj) {
return Object.keys(obj).concat(Object.getOwnPropertySymbols(obj));
}
//#endregion
exports.shallow = shallow;
//# sourceMappingURL=shallow.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"shallow.cjs","names":[],"sources":["../src/shallow.ts"],"sourcesContent":["export function shallow<T>(objA: T, objB: T) {\n if (Object.is(objA, objB)) {\n return true\n }\n\n if (\n typeof objA !== 'object' ||\n objA === null ||\n typeof objB !== 'object' ||\n objB === null\n ) {\n return false\n }\n\n if (objA instanceof Map && objB instanceof Map) {\n if (objA.size !== objB.size) return false\n for (const [k, v] of objA) {\n if (!objB.has(k) || !Object.is(v, objB.get(k))) return false\n }\n return true\n }\n\n if (objA instanceof Set && objB instanceof Set) {\n if (objA.size !== objB.size) return false\n for (const v of objA) {\n if (!objB.has(v)) return false\n }\n return true\n }\n\n if (objA instanceof Date && objB instanceof Date) {\n if (objA.getTime() !== objB.getTime()) return false\n return true\n }\n\n const keysA = getOwnKeys(objA)\n if (keysA.length !== getOwnKeys(objB).length) {\n return false\n }\n\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < keysA.length; i++) {\n if (\n !Object.prototype.hasOwnProperty.call(objB, keysA[i] as string) ||\n !Object.is(objA[keysA[i] as keyof T], objB[keysA[i] as keyof T])\n ) {\n return false\n }\n }\n return true\n}\n\nfunction getOwnKeys(obj: object): Array<string | symbol> {\n return (Object.keys(obj) as Array<string | symbol>).concat(\n Object.getOwnPropertySymbols(obj),\n )\n}\n"],"mappings":";;AAAA,SAAgB,QAAW,MAAS,MAAS;AAC3C,KAAI,OAAO,GAAG,MAAM,KAAK,CACvB,QAAO;AAGT,KACE,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,SAAS,YAChB,SAAS,KAET,QAAO;AAGT,KAAI,gBAAgB,OAAO,gBAAgB,KAAK;AAC9C,MAAI,KAAK,SAAS,KAAK,KAAM,QAAO;AACpC,OAAK,MAAM,CAAC,GAAG,MAAM,KACnB,KAAI,CAAC,KAAK,IAAI,EAAE,IAAI,CAAC,OAAO,GAAG,GAAG,KAAK,IAAI,EAAE,CAAC,CAAE,QAAO;AAEzD,SAAO;;AAGT,KAAI,gBAAgB,OAAO,gBAAgB,KAAK;AAC9C,MAAI,KAAK,SAAS,KAAK,KAAM,QAAO;AACpC,OAAK,MAAM,KAAK,KACd,KAAI,CAAC,KAAK,IAAI,EAAE,CAAE,QAAO;AAE3B,SAAO;;AAGT,KAAI,gBAAgB,QAAQ,gBAAgB,MAAM;AAChD,MAAI,KAAK,SAAS,KAAK,KAAK,SAAS,CAAE,QAAO;AAC9C,SAAO;;CAGT,MAAM,QAAQ,WAAW,KAAK;AAC9B,KAAI,MAAM,WAAW,WAAW,KAAK,CAAC,OACpC,QAAO;AAIT,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,IAChC,KACE,CAAC,OAAO,UAAU,eAAe,KAAK,MAAM,MAAM,GAAa,IAC/D,CAAC,OAAO,GAAG,KAAK,MAAM,KAAgB,KAAK,MAAM,IAAe,CAEhE,QAAO;AAGX,QAAO;;AAGT,SAAS,WAAW,KAAqC;AACvD,QAAQ,OAAO,KAAK,IAAI,CAA4B,OAClD,OAAO,sBAAsB,IAAI,CAClC"}
+5
View File
@@ -0,0 +1,5 @@
//#region src/shallow.d.ts
declare function shallow<T>(objA: T, objB: T): boolean;
//#endregion
export { shallow };
//# sourceMappingURL=shallow.d.cts.map
+5
View File
@@ -0,0 +1,5 @@
//#region src/shallow.d.ts
declare function shallow<T>(objA: T, objB: T): boolean;
//#endregion
export { shallow };
//# sourceMappingURL=shallow.d.ts.map
+30
View File
@@ -0,0 +1,30 @@
//#region src/shallow.ts
function shallow(objA, objB) {
if (Object.is(objA, objB)) return true;
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) return false;
if (objA instanceof Map && objB instanceof Map) {
if (objA.size !== objB.size) return false;
for (const [k, v] of objA) if (!objB.has(k) || !Object.is(v, objB.get(k))) return false;
return true;
}
if (objA instanceof Set && objB instanceof Set) {
if (objA.size !== objB.size) return false;
for (const v of objA) if (!objB.has(v)) return false;
return true;
}
if (objA instanceof Date && objB instanceof Date) {
if (objA.getTime() !== objB.getTime()) return false;
return true;
}
const keysA = getOwnKeys(objA);
if (keysA.length !== getOwnKeys(objB).length) return false;
for (let i = 0; i < keysA.length; i++) if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) return false;
return true;
}
function getOwnKeys(obj) {
return Object.keys(obj).concat(Object.getOwnPropertySymbols(obj));
}
//#endregion
export { shallow };
//# sourceMappingURL=shallow.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"shallow.js","names":[],"sources":["../src/shallow.ts"],"sourcesContent":["export function shallow<T>(objA: T, objB: T) {\n if (Object.is(objA, objB)) {\n return true\n }\n\n if (\n typeof objA !== 'object' ||\n objA === null ||\n typeof objB !== 'object' ||\n objB === null\n ) {\n return false\n }\n\n if (objA instanceof Map && objB instanceof Map) {\n if (objA.size !== objB.size) return false\n for (const [k, v] of objA) {\n if (!objB.has(k) || !Object.is(v, objB.get(k))) return false\n }\n return true\n }\n\n if (objA instanceof Set && objB instanceof Set) {\n if (objA.size !== objB.size) return false\n for (const v of objA) {\n if (!objB.has(v)) return false\n }\n return true\n }\n\n if (objA instanceof Date && objB instanceof Date) {\n if (objA.getTime() !== objB.getTime()) return false\n return true\n }\n\n const keysA = getOwnKeys(objA)\n if (keysA.length !== getOwnKeys(objB).length) {\n return false\n }\n\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < keysA.length; i++) {\n if (\n !Object.prototype.hasOwnProperty.call(objB, keysA[i] as string) ||\n !Object.is(objA[keysA[i] as keyof T], objB[keysA[i] as keyof T])\n ) {\n return false\n }\n }\n return true\n}\n\nfunction getOwnKeys(obj: object): Array<string | symbol> {\n return (Object.keys(obj) as Array<string | symbol>).concat(\n Object.getOwnPropertySymbols(obj),\n )\n}\n"],"mappings":";AAAA,SAAgB,QAAW,MAAS,MAAS;AAC3C,KAAI,OAAO,GAAG,MAAM,KAAK,CACvB,QAAO;AAGT,KACE,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,SAAS,YAChB,SAAS,KAET,QAAO;AAGT,KAAI,gBAAgB,OAAO,gBAAgB,KAAK;AAC9C,MAAI,KAAK,SAAS,KAAK,KAAM,QAAO;AACpC,OAAK,MAAM,CAAC,GAAG,MAAM,KACnB,KAAI,CAAC,KAAK,IAAI,EAAE,IAAI,CAAC,OAAO,GAAG,GAAG,KAAK,IAAI,EAAE,CAAC,CAAE,QAAO;AAEzD,SAAO;;AAGT,KAAI,gBAAgB,OAAO,gBAAgB,KAAK;AAC9C,MAAI,KAAK,SAAS,KAAK,KAAM,QAAO;AACpC,OAAK,MAAM,KAAK,KACd,KAAI,CAAC,KAAK,IAAI,EAAE,CAAE,QAAO;AAE3B,SAAO;;AAGT,KAAI,gBAAgB,QAAQ,gBAAgB,MAAM;AAChD,MAAI,KAAK,SAAS,KAAK,KAAK,SAAS,CAAE,QAAO;AAC9C,SAAO;;CAGT,MAAM,QAAQ,WAAW,KAAK;AAC9B,KAAI,MAAM,WAAW,WAAW,KAAK,CAAC,OACpC,QAAO;AAIT,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,IAChC,KACE,CAAC,OAAO,UAAU,eAAe,KAAK,MAAM,MAAM,GAAa,IAC/D,CAAC,OAAO,GAAG,KAAK,MAAM,KAAgB,KAAK,MAAM,IAAe,CAEhE,QAAO;AAGX,QAAO;;AAGT,SAAS,WAAW,KAAqC;AACvD,QAAQ,OAAO,KAAK,IAAI,CAA4B,OAClD,OAAO,sBAAsB,IAAI,CAClC"}
+49
View File
@@ -0,0 +1,49 @@
const require_atom = require('./atom.cjs');
//#region src/store.ts
var Store = class {
constructor(valueOrFn, actionsFactory) {
this.atom = require_atom.createAtom(valueOrFn);
this.get = this.get.bind(this);
this.setState = this.setState.bind(this);
this.subscribe = this.subscribe.bind(this);
if (actionsFactory) this.actions = actionsFactory(this);
}
setState(updater) {
this.atom.set(updater);
}
get state() {
return this.atom.get();
}
get() {
return this.state;
}
subscribe(observerOrFn) {
return this.atom.subscribe(require_atom.toObserver(observerOrFn));
}
};
var ReadonlyStore = class {
constructor(valueOrFn) {
this.atom = require_atom.createAtom(valueOrFn);
}
get state() {
return this.atom.get();
}
get() {
return this.state;
}
subscribe(observerOrFn) {
return this.atom.subscribe(require_atom.toObserver(observerOrFn));
}
};
function createStore(valueOrFn, actions) {
if (typeof valueOrFn === "function") return new ReadonlyStore(valueOrFn);
if (actions) return new Store(valueOrFn, actions);
return new Store(valueOrFn);
}
//#endregion
exports.ReadonlyStore = ReadonlyStore;
exports.Store = Store;
exports.createStore = createStore;
//# sourceMappingURL=store.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"store.cjs","names":["createAtom","toObserver"],"sources":["../src/store.ts"],"sourcesContent":["import { createAtom, toObserver } from './atom'\nimport type { Atom, Observer, Subscription } from './types'\n\nexport type StoreAction = (...args: Array<any>) => any\n\nexport type StoreActionMap = Record<string, StoreAction>\n\nexport type StoreActionsFactory<T, TActions extends StoreActionMap> = (store: {\n setState: Store<T>['setState']\n get: Store<T>['get']\n}) => TActions\n\ntype NonFunction<T> = T extends (...args: Array<any>) => any ? never : T\n\nexport class Store<T, TActions extends StoreActionMap = never> {\n private atom: Atom<T>\n public readonly actions!: TActions\n constructor(getValue: (prev?: NoInfer<T>) => T)\n constructor(initialValue: T)\n constructor(\n initialValue: NonFunction<T>,\n actionsFactory: StoreActionsFactory<T, TActions>,\n )\n constructor(\n valueOrFn: T | ((prev?: T) => T),\n actionsFactory?: StoreActionsFactory<T, TActions>,\n ) {\n // createAtom has overloads that return ReadonlyAtom<T> for functions and Atom<T> for values\n // Store always needs Atom<T> for setState, so we assert the return type\n this.atom = createAtom(\n valueOrFn as T | ((prev?: NoInfer<T>) => T),\n ) as Atom<T>\n\n // bind for safe destructuring\n this.get = this.get.bind(this)\n this.setState = this.setState.bind(this)\n this.subscribe = this.subscribe.bind(this)\n\n if (actionsFactory) {\n this.actions = actionsFactory(this)\n }\n }\n public setState(updater: (prev: T) => T) {\n this.atom.set(updater)\n }\n public get state() {\n return this.atom.get()\n }\n public get() {\n return this.state\n }\n public subscribe(\n observerOrFn: Observer<T> | ((value: T) => void),\n ): Subscription {\n return this.atom.subscribe(toObserver(observerOrFn))\n }\n}\n\nexport class ReadonlyStore<T> implements Omit<\n Store<T>,\n 'setState' | 'actions'\n> {\n private atom: Atom<T>\n constructor(getValue: (prev?: NoInfer<T>) => T)\n constructor(initialValue: T)\n constructor(valueOrFn: T | ((prev?: T) => T)) {\n // createAtom has overloads that return ReadonlyAtom<T> for functions and Atom<T> for values\n // Store always needs Atom<T> for setState, so we assert the return type\n this.atom = createAtom(\n valueOrFn as T | ((prev?: NoInfer<T>) => T),\n ) as Atom<T>\n }\n public get state() {\n return this.atom.get()\n }\n public get() {\n return this.state\n }\n public subscribe(\n observerOrFn: Observer<T> | ((value: T) => void),\n ): Subscription {\n return this.atom.subscribe(toObserver(observerOrFn))\n }\n}\n\nexport function createStore<T>(\n getValue: (prev?: NoInfer<T>) => T,\n): ReadonlyStore<T>\nexport function createStore<T>(initialValue: T): Store<T>\nexport function createStore<T, TActions extends StoreActionMap>(\n initialValue: NonFunction<T>,\n actions: StoreActionsFactory<T, TActions>,\n): Store<T, TActions>\nexport function createStore<T, TActions extends StoreActionMap>(\n valueOrFn: T | ((prev?: T) => T),\n actions?: StoreActionsFactory<T, TActions>,\n): Store<T, TActions> | Store<T> | ReadonlyStore<T> {\n if (typeof valueOrFn === 'function') {\n return new ReadonlyStore(valueOrFn as (prev?: NoInfer<T>) => T)\n }\n if (actions) {\n return new Store(valueOrFn as NonFunction<T>, actions)\n }\n return new Store(valueOrFn)\n}\n"],"mappings":";;;AAcA,IAAa,QAAb,MAA+D;CAS7D,YACE,WACA,gBACA;AAGA,OAAK,OAAOA,wBACV,UACD;AAGD,OAAK,MAAM,KAAK,IAAI,KAAK,KAAK;AAC9B,OAAK,WAAW,KAAK,SAAS,KAAK,KAAK;AACxC,OAAK,YAAY,KAAK,UAAU,KAAK,KAAK;AAE1C,MAAI,eACF,MAAK,UAAU,eAAe,KAAK;;CAGvC,AAAO,SAAS,SAAyB;AACvC,OAAK,KAAK,IAAI,QAAQ;;CAExB,IAAW,QAAQ;AACjB,SAAO,KAAK,KAAK,KAAK;;CAExB,AAAO,MAAM;AACX,SAAO,KAAK;;CAEd,AAAO,UACL,cACc;AACd,SAAO,KAAK,KAAK,UAAUC,wBAAW,aAAa,CAAC;;;AAIxD,IAAa,gBAAb,MAGE;CAIA,YAAY,WAAkC;AAG5C,OAAK,OAAOD,wBACV,UACD;;CAEH,IAAW,QAAQ;AACjB,SAAO,KAAK,KAAK,KAAK;;CAExB,AAAO,MAAM;AACX,SAAO,KAAK;;CAEd,AAAO,UACL,cACc;AACd,SAAO,KAAK,KAAK,UAAUC,wBAAW,aAAa,CAAC;;;AAYxD,SAAgB,YACd,WACA,SACkD;AAClD,KAAI,OAAO,cAAc,WACvB,QAAO,IAAI,cAAc,UAAsC;AAEjE,KAAI,QACF,QAAO,IAAI,MAAM,WAA6B,QAAQ;AAExD,QAAO,IAAI,MAAM,UAAU"}
+35
View File
@@ -0,0 +1,35 @@
import { Observer, Subscription } from "./types.cjs";
//#region src/store.d.ts
type StoreAction = (...args: Array<any>) => any;
type StoreActionMap = Record<string, StoreAction>;
type StoreActionsFactory<T, TActions extends StoreActionMap> = (store: {
setState: Store<T>['setState'];
get: Store<T>['get'];
}) => TActions;
type NonFunction<T> = T extends ((...args: Array<any>) => any) ? never : T;
declare class Store<T, TActions extends StoreActionMap = never> {
private atom;
readonly actions: TActions;
constructor(getValue: (prev?: NoInfer<T>) => T);
constructor(initialValue: T);
constructor(initialValue: NonFunction<T>, actionsFactory: StoreActionsFactory<T, TActions>);
setState(updater: (prev: T) => T): void;
get state(): T;
get(): T;
subscribe(observerOrFn: Observer<T> | ((value: T) => void)): Subscription;
}
declare class ReadonlyStore<T> implements Omit<Store<T>, 'setState' | 'actions'> {
private atom;
constructor(getValue: (prev?: NoInfer<T>) => T);
constructor(initialValue: T);
get state(): T;
get(): T;
subscribe(observerOrFn: Observer<T> | ((value: T) => void)): Subscription;
}
declare function createStore<T>(getValue: (prev?: NoInfer<T>) => T): ReadonlyStore<T>;
declare function createStore<T>(initialValue: T): Store<T>;
declare function createStore<T, TActions extends StoreActionMap>(initialValue: NonFunction<T>, actions: StoreActionsFactory<T, TActions>): Store<T, TActions>;
//#endregion
export { ReadonlyStore, Store, StoreAction, StoreActionMap, StoreActionsFactory, createStore };
//# sourceMappingURL=store.d.cts.map
+35
View File
@@ -0,0 +1,35 @@
import { Observer, Subscription } from "./types.js";
//#region src/store.d.ts
type StoreAction = (...args: Array<any>) => any;
type StoreActionMap = Record<string, StoreAction>;
type StoreActionsFactory<T, TActions extends StoreActionMap> = (store: {
setState: Store<T>['setState'];
get: Store<T>['get'];
}) => TActions;
type NonFunction<T> = T extends ((...args: Array<any>) => any) ? never : T;
declare class Store<T, TActions extends StoreActionMap = never> {
private atom;
readonly actions: TActions;
constructor(getValue: (prev?: NoInfer<T>) => T);
constructor(initialValue: T);
constructor(initialValue: NonFunction<T>, actionsFactory: StoreActionsFactory<T, TActions>);
setState(updater: (prev: T) => T): void;
get state(): T;
get(): T;
subscribe(observerOrFn: Observer<T> | ((value: T) => void)): Subscription;
}
declare class ReadonlyStore<T> implements Omit<Store<T>, 'setState' | 'actions'> {
private atom;
constructor(getValue: (prev?: NoInfer<T>) => T);
constructor(initialValue: T);
get state(): T;
get(): T;
subscribe(observerOrFn: Observer<T> | ((value: T) => void)): Subscription;
}
declare function createStore<T>(getValue: (prev?: NoInfer<T>) => T): ReadonlyStore<T>;
declare function createStore<T>(initialValue: T): Store<T>;
declare function createStore<T, TActions extends StoreActionMap>(initialValue: NonFunction<T>, actions: StoreActionsFactory<T, TActions>): Store<T, TActions>;
//#endregion
export { ReadonlyStore, Store, StoreAction, StoreActionMap, StoreActionsFactory, createStore };
//# sourceMappingURL=store.d.ts.map
+47
View File
@@ -0,0 +1,47 @@
import { createAtom, toObserver } from "./atom.js";
//#region src/store.ts
var Store = class {
constructor(valueOrFn, actionsFactory) {
this.atom = createAtom(valueOrFn);
this.get = this.get.bind(this);
this.setState = this.setState.bind(this);
this.subscribe = this.subscribe.bind(this);
if (actionsFactory) this.actions = actionsFactory(this);
}
setState(updater) {
this.atom.set(updater);
}
get state() {
return this.atom.get();
}
get() {
return this.state;
}
subscribe(observerOrFn) {
return this.atom.subscribe(toObserver(observerOrFn));
}
};
var ReadonlyStore = class {
constructor(valueOrFn) {
this.atom = createAtom(valueOrFn);
}
get state() {
return this.atom.get();
}
get() {
return this.state;
}
subscribe(observerOrFn) {
return this.atom.subscribe(toObserver(observerOrFn));
}
};
function createStore(valueOrFn, actions) {
if (typeof valueOrFn === "function") return new ReadonlyStore(valueOrFn);
if (actions) return new Store(valueOrFn, actions);
return new Store(valueOrFn);
}
//#endregion
export { ReadonlyStore, Store, createStore };
//# sourceMappingURL=store.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"store.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["import { createAtom, toObserver } from './atom'\nimport type { Atom, Observer, Subscription } from './types'\n\nexport type StoreAction = (...args: Array<any>) => any\n\nexport type StoreActionMap = Record<string, StoreAction>\n\nexport type StoreActionsFactory<T, TActions extends StoreActionMap> = (store: {\n setState: Store<T>['setState']\n get: Store<T>['get']\n}) => TActions\n\ntype NonFunction<T> = T extends (...args: Array<any>) => any ? never : T\n\nexport class Store<T, TActions extends StoreActionMap = never> {\n private atom: Atom<T>\n public readonly actions!: TActions\n constructor(getValue: (prev?: NoInfer<T>) => T)\n constructor(initialValue: T)\n constructor(\n initialValue: NonFunction<T>,\n actionsFactory: StoreActionsFactory<T, TActions>,\n )\n constructor(\n valueOrFn: T | ((prev?: T) => T),\n actionsFactory?: StoreActionsFactory<T, TActions>,\n ) {\n // createAtom has overloads that return ReadonlyAtom<T> for functions and Atom<T> for values\n // Store always needs Atom<T> for setState, so we assert the return type\n this.atom = createAtom(\n valueOrFn as T | ((prev?: NoInfer<T>) => T),\n ) as Atom<T>\n\n // bind for safe destructuring\n this.get = this.get.bind(this)\n this.setState = this.setState.bind(this)\n this.subscribe = this.subscribe.bind(this)\n\n if (actionsFactory) {\n this.actions = actionsFactory(this)\n }\n }\n public setState(updater: (prev: T) => T) {\n this.atom.set(updater)\n }\n public get state() {\n return this.atom.get()\n }\n public get() {\n return this.state\n }\n public subscribe(\n observerOrFn: Observer<T> | ((value: T) => void),\n ): Subscription {\n return this.atom.subscribe(toObserver(observerOrFn))\n }\n}\n\nexport class ReadonlyStore<T> implements Omit<\n Store<T>,\n 'setState' | 'actions'\n> {\n private atom: Atom<T>\n constructor(getValue: (prev?: NoInfer<T>) => T)\n constructor(initialValue: T)\n constructor(valueOrFn: T | ((prev?: T) => T)) {\n // createAtom has overloads that return ReadonlyAtom<T> for functions and Atom<T> for values\n // Store always needs Atom<T> for setState, so we assert the return type\n this.atom = createAtom(\n valueOrFn as T | ((prev?: NoInfer<T>) => T),\n ) as Atom<T>\n }\n public get state() {\n return this.atom.get()\n }\n public get() {\n return this.state\n }\n public subscribe(\n observerOrFn: Observer<T> | ((value: T) => void),\n ): Subscription {\n return this.atom.subscribe(toObserver(observerOrFn))\n }\n}\n\nexport function createStore<T>(\n getValue: (prev?: NoInfer<T>) => T,\n): ReadonlyStore<T>\nexport function createStore<T>(initialValue: T): Store<T>\nexport function createStore<T, TActions extends StoreActionMap>(\n initialValue: NonFunction<T>,\n actions: StoreActionsFactory<T, TActions>,\n): Store<T, TActions>\nexport function createStore<T, TActions extends StoreActionMap>(\n valueOrFn: T | ((prev?: T) => T),\n actions?: StoreActionsFactory<T, TActions>,\n): Store<T, TActions> | Store<T> | ReadonlyStore<T> {\n if (typeof valueOrFn === 'function') {\n return new ReadonlyStore(valueOrFn as (prev?: NoInfer<T>) => T)\n }\n if (actions) {\n return new Store(valueOrFn as NonFunction<T>, actions)\n }\n return new Store(valueOrFn)\n}\n"],"mappings":";;;AAcA,IAAa,QAAb,MAA+D;CAS7D,YACE,WACA,gBACA;AAGA,OAAK,OAAO,WACV,UACD;AAGD,OAAK,MAAM,KAAK,IAAI,KAAK,KAAK;AAC9B,OAAK,WAAW,KAAK,SAAS,KAAK,KAAK;AACxC,OAAK,YAAY,KAAK,UAAU,KAAK,KAAK;AAE1C,MAAI,eACF,MAAK,UAAU,eAAe,KAAK;;CAGvC,AAAO,SAAS,SAAyB;AACvC,OAAK,KAAK,IAAI,QAAQ;;CAExB,IAAW,QAAQ;AACjB,SAAO,KAAK,KAAK,KAAK;;CAExB,AAAO,MAAM;AACX,SAAO,KAAK;;CAEd,AAAO,UACL,cACc;AACd,SAAO,KAAK,KAAK,UAAU,WAAW,aAAa,CAAC;;;AAIxD,IAAa,gBAAb,MAGE;CAIA,YAAY,WAAkC;AAG5C,OAAK,OAAO,WACV,UACD;;CAEH,IAAW,QAAQ;AACjB,SAAO,KAAK,KAAK,KAAK;;CAExB,AAAO,MAAM;AACX,SAAO,KAAK;;CAEd,AAAO,UACL,cACc;AACd,SAAO,KAAK,KAAK,UAAU,WAAW,aAAa,CAAC;;;AAYxD,SAAgB,YACd,WACA,SACkD;AAClD,KAAI,OAAO,cAAc,WACvB,QAAO,IAAI,cAAc,UAAsC;AAEjE,KAAI,QACF,QAAO,IAAI,MAAM,WAA6B,QAAQ;AAExD,QAAO,IAAI,MAAM,UAAU"}
+52
View File
@@ -0,0 +1,52 @@
import { ReactiveNode } from "./alien.cjs";
//#region src/types.d.ts
type Selection<TSelected> = Readable<TSelected>;
interface InteropSubscribable<T> {
subscribe: (observer: Observer<T>) => Subscription;
}
type Observer<T> = {
next?: (value: T) => void;
error?: (err: unknown) => void;
complete?: () => void;
};
interface Subscription {
unsubscribe: () => void;
}
interface Subscribable<T> extends InteropSubscribable<T> {
subscribe: ((observer: Observer<T>) => Subscription) & ((next: (value: T) => void, error?: (error: any) => void, complete?: () => void) => Subscription);
}
interface Readable<T> extends Subscribable<T> {
get: () => T;
}
interface BaseAtom<T> extends Subscribable<T>, Readable<T> {}
interface InternalBaseAtom<T> extends Subscribable<T>, Readable<T> {
/** @internal */
_snapshot: T;
/** @internal */
_update: (getValue?: T | ((snapshot: T) => T)) => boolean;
}
interface Atom<T> extends BaseAtom<T> {
/** Sets the value of the atom using a function. */
set: ((fn: (prevVal: T) => T) => void) & ((value: T) => void);
}
interface AtomOptions<T> {
compare?: (prev: T, next: T) => boolean;
}
type AnyAtom = BaseAtom<any>;
interface InternalReadonlyAtom<T> extends InternalBaseAtom<T>, ReactiveNode {}
/**
* An atom that is read-only and cannot be set.
*
* @example
*
* ```ts
* const atom = createAtom(() => 42);
* // @ts-expect-error - Cannot set a readonly atom
* atom.set(43);
* ```
*/
interface ReadonlyAtom<T> extends BaseAtom<T> {}
//#endregion
export { AnyAtom, Atom, AtomOptions, BaseAtom, InternalBaseAtom, InternalReadonlyAtom, InteropSubscribable, Observer, Readable, ReadonlyAtom, Selection, Subscribable, Subscription };
//# sourceMappingURL=types.d.cts.map
+52
View File
@@ -0,0 +1,52 @@
import { ReactiveNode } from "./alien.js";
//#region src/types.d.ts
type Selection<TSelected> = Readable<TSelected>;
interface InteropSubscribable<T> {
subscribe: (observer: Observer<T>) => Subscription;
}
type Observer<T> = {
next?: (value: T) => void;
error?: (err: unknown) => void;
complete?: () => void;
};
interface Subscription {
unsubscribe: () => void;
}
interface Subscribable<T> extends InteropSubscribable<T> {
subscribe: ((observer: Observer<T>) => Subscription) & ((next: (value: T) => void, error?: (error: any) => void, complete?: () => void) => Subscription);
}
interface Readable<T> extends Subscribable<T> {
get: () => T;
}
interface BaseAtom<T> extends Subscribable<T>, Readable<T> {}
interface InternalBaseAtom<T> extends Subscribable<T>, Readable<T> {
/** @internal */
_snapshot: T;
/** @internal */
_update: (getValue?: T | ((snapshot: T) => T)) => boolean;
}
interface Atom<T> extends BaseAtom<T> {
/** Sets the value of the atom using a function. */
set: ((fn: (prevVal: T) => T) => void) & ((value: T) => void);
}
interface AtomOptions<T> {
compare?: (prev: T, next: T) => boolean;
}
type AnyAtom = BaseAtom<any>;
interface InternalReadonlyAtom<T> extends InternalBaseAtom<T>, ReactiveNode {}
/**
* An atom that is read-only and cannot be set.
*
* @example
*
* ```ts
* const atom = createAtom(() => 42);
* // @ts-expect-error - Cannot set a readonly atom
* atom.set(43);
* ```
*/
interface ReadonlyAtom<T> extends BaseAtom<T> {}
//#endregion
export { AnyAtom, Atom, AtomOptions, BaseAtom, InternalBaseAtom, InternalReadonlyAtom, InteropSubscribable, Observer, Readable, ReadonlyAtom, Selection, Subscribable, Subscription };
//# sourceMappingURL=types.d.ts.map
+57
View File
@@ -0,0 +1,57 @@
{
"name": "@tanstack/store",
"version": "0.11.1",
"description": "Framework agnostic type-safe store w/ reactive framework adapters",
"author": "Tanner Linsley",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/TanStack/store.git",
"directory": "packages/store"
},
"homepage": "https://tanstack.com/store",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"keywords": [
"store",
"typescript"
],
"type": "module",
"types": "./dist/index.d.cts",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./package.json": "./package.json"
},
"sideEffects": false,
"files": [
"dist",
"src"
],
"devDependencies": {
"@angular/core": "^21.2.8",
"@preact/signals": "^2.9.0",
"solid-js": "^1.9.12",
"vue": "^3.5.32"
},
"scripts": {
"clean": "premove ./dist ./coverage",
"test:eslint": "eslint ./src ./tests",
"test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"",
"test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js",
"test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js",
"test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js",
"test:types:ts59": "tsc",
"test:lib": "vitest",
"test:bench": "vitest bench",
"test:lib:dev": "pnpm run test:lib --watch",
"test:build": "publint --strict",
"build": "tsdown --tsconfig tsconfig.build.json"
}
}
+278
View File
@@ -0,0 +1,278 @@
/* eslint-disable */
// Adapted from Alien Signals
// https://github.com/stackblitz/alien-signals/
export interface ReactiveNode {
deps?: Link
depsTail?: Link
subs?: Link
subsTail?: Link
flags: ReactiveFlags
}
export interface Link {
version: number
dep: ReactiveNode
sub: ReactiveNode
prevSub: Link | undefined
nextSub: Link | undefined
prevDep: Link | undefined
nextDep: Link | undefined
}
interface Stack<T> {
value: T
prev: Stack<T> | undefined
}
export type ReactiveFlags = number
export const NONE = 0
export const MUTABLE = 1
export const WATCHING = 2
export const RECURSED_CHECK = 4
export const RECURSED = 8
export const DIRTY = 16
export const PENDING = 32
/*@__NO_SIDE_EFFECTS__*/
export function createReactiveSystem({
update,
notify,
unwatched,
}: {
update(sub: ReactiveNode): boolean
notify(sub: ReactiveNode): void
unwatched(sub: ReactiveNode): void
}) {
return {
link,
unlink,
propagate,
checkDirty,
shallowPropagate,
}
function link(dep: ReactiveNode, sub: ReactiveNode, version: number): void {
const prevDep = sub.depsTail
if (prevDep !== undefined && prevDep.dep === dep) {
return
}
const nextDep = prevDep !== undefined ? prevDep.nextDep : sub.deps
if (nextDep !== undefined && nextDep.dep === dep) {
nextDep.version = version
sub.depsTail = nextDep
return
}
const prevSub = dep.subsTail
if (
prevSub !== undefined &&
prevSub.version === version &&
prevSub.sub === sub
) {
return
}
const newLink =
(sub.depsTail =
dep.subsTail =
{
version,
dep,
sub,
prevDep,
nextDep,
prevSub,
nextSub: undefined,
})
if (nextDep !== undefined) {
nextDep.prevDep = newLink
}
if (prevDep !== undefined) {
prevDep.nextDep = newLink
} else {
sub.deps = newLink
}
if (prevSub !== undefined) {
prevSub.nextSub = newLink
} else {
dep.subs = newLink
}
}
function unlink(link: Link, sub = link.sub): Link | undefined {
const dep = link.dep
const prevDep = link.prevDep
const nextDep = link.nextDep
const nextSub = link.nextSub
const prevSub = link.prevSub
if (nextDep !== undefined) {
nextDep.prevDep = prevDep
} else {
sub.depsTail = prevDep
}
if (prevDep !== undefined) {
prevDep.nextDep = nextDep
} else {
sub.deps = nextDep
}
if (nextSub !== undefined) {
nextSub.prevSub = prevSub
} else {
dep.subsTail = prevSub
}
if (prevSub !== undefined) {
prevSub.nextSub = nextSub
} else if ((dep.subs = nextSub) === undefined) {
unwatched(dep)
}
return nextDep
}
function propagate(link: Link): void {
let next = link.nextSub
let stack: Stack<Link | undefined> | undefined
top: do {
const sub = link.sub
let flags = sub.flags
if (!(flags & (RECURSED_CHECK | RECURSED | DIRTY | PENDING))) {
sub.flags = flags | PENDING
} else if (!(flags & (RECURSED_CHECK | RECURSED))) {
flags = NONE
} else if (!(flags & RECURSED_CHECK)) {
sub.flags = (flags & ~RECURSED) | PENDING
} else if (!(flags & (DIRTY | PENDING)) && isValidLink(link, sub)) {
sub.flags = flags | (RECURSED | PENDING)
flags &= MUTABLE
} else {
flags = NONE
}
if (flags & WATCHING) {
notify(sub)
}
if (flags & MUTABLE) {
const subSubs = sub.subs
if (subSubs !== undefined) {
const nextSub = (link = subSubs).nextSub
if (nextSub !== undefined) {
stack = { value: next, prev: stack }
next = nextSub
}
continue
}
}
if ((link = next!) !== undefined) {
next = link.nextSub
continue
}
while (stack !== undefined) {
link = stack.value!
stack = stack.prev
if (link !== undefined) {
next = link.nextSub
continue top
}
}
break
} while (true)
}
function checkDirty(link: Link, sub: ReactiveNode): boolean {
let stack: Stack<Link> | undefined
let checkDepth = 0
let dirty = false
top: do {
const dep = link.dep
const flags = dep.flags
if (sub.flags & DIRTY) {
dirty = true
} else if ((flags & (MUTABLE | DIRTY)) === (MUTABLE | DIRTY)) {
if (update(dep)) {
const subs = dep.subs!
if (subs.nextSub !== undefined) {
shallowPropagate(subs)
}
dirty = true
}
} else if ((flags & (MUTABLE | PENDING)) === (MUTABLE | PENDING)) {
if (link.nextSub !== undefined || link.prevSub !== undefined) {
stack = { value: link, prev: stack }
}
link = dep.deps!
sub = dep
++checkDepth
continue
}
if (!dirty) {
const nextDep = link.nextDep
if (nextDep !== undefined) {
link = nextDep
continue
}
}
while (checkDepth--) {
const firstSub = sub.subs!
const hasMultipleSubs = firstSub.nextSub !== undefined
if (hasMultipleSubs) {
link = stack!.value
stack = stack!.prev
} else {
link = firstSub
}
if (dirty) {
if (update(sub)) {
if (hasMultipleSubs) {
shallowPropagate(firstSub)
}
sub = link.sub
continue
}
dirty = false
} else {
sub.flags &= ~PENDING
}
sub = link.sub
const nextDep = link.nextDep
if (nextDep !== undefined) {
link = nextDep
continue top
}
}
return dirty
} while (true)
}
function shallowPropagate(link: Link): void {
do {
const sub = link.sub
const flags = sub.flags
if ((flags & (PENDING | DIRTY)) === PENDING) {
sub.flags = flags | DIRTY
if ((flags & (WATCHING | RECURSED_CHECK)) === WATCHING) {
notify(sub)
}
}
} while ((link = link.nextSub!) !== undefined)
}
function isValidLink(checkLink: Link, sub: ReactiveNode): boolean {
let link = sub.depsTail
while (link !== undefined) {
if (link === checkLink) {
return true
}
link = link.prevDep
}
return false
}
}
+318
View File
@@ -0,0 +1,318 @@
import {
DIRTY,
MUTABLE,
NONE,
PENDING,
RECURSED_CHECK,
WATCHING,
createReactiveSystem,
} from './alien'
import type { ReactiveNode } from './alien'
import type {
Atom,
AtomOptions,
Observer,
ReadonlyAtom,
Subscription,
} from './types'
export function toObserver<T>(
nextHandler?: Observer<T> | ((value: T) => void),
errorHandler?: (error: any) => void,
completionHandler?: () => void,
): Observer<T> {
const isObserver = typeof nextHandler === 'object'
const self = isObserver ? nextHandler : undefined
return {
next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(
self,
),
}
}
interface InternalAtom<T> extends ReactiveNode {
_snapshot: T
_update: (getValue?: T | ((snapshot: T) => T)) => boolean
get: () => T
subscribe: (observerOrFn: Observer<T> | ((value: T) => void)) => Subscription
}
const queuedEffects: Array<Effect | undefined> = []
let cycle = 0
const { link, unlink, propagate, checkDirty, shallowPropagate } =
createReactiveSystem({
update(atom: InternalAtom<any>): boolean {
return atom._update()
},
// eslint-disable-next-line no-shadow
notify(effect: Effect): void {
queuedEffects[queuedEffectsLength++] = effect
effect.flags &= ~WATCHING
},
unwatched(atom: InternalAtom<any>): void {
if (atom.depsTail !== undefined) {
atom.depsTail = undefined
atom.flags = MUTABLE | DIRTY
purgeDeps(atom)
}
},
})
let notifyIndex = 0
let queuedEffectsLength = 0
let activeSub: ReactiveNode | undefined
let batchDepth = 0
export function batch(fn: () => void) {
try {
++batchDepth
fn()
} finally {
if (!--batchDepth) {
flush()
}
}
}
function purgeDeps(sub: ReactiveNode) {
const depsTail = sub.depsTail
let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps
while (dep !== undefined) {
dep = unlink(dep, sub)
}
}
export function flush(): void {
if (batchDepth > 0) {
return
}
while (notifyIndex < queuedEffectsLength) {
// eslint-disable-next-line no-shadow
const effect = queuedEffects[notifyIndex]!
queuedEffects[notifyIndex++] = undefined
effect.notify()
}
notifyIndex = 0
queuedEffectsLength = 0
}
type AsyncAtomState<TData, TError = unknown> =
| { status: 'pending' }
| { status: 'done'; data: TData }
| { status: 'error'; error: TError }
export function createAsyncAtom<T>(
getValue: () => Promise<T>,
options?: AtomOptions<AsyncAtomState<T>>,
): ReadonlyAtom<AsyncAtomState<T>> {
const ref: { current?: InternalAtom<AsyncAtomState<T>> } = {}
const atom = createAtom<AsyncAtomState<T>>(() => {
getValue().then(
(data) => {
const internalAtom = ref.current!
if (internalAtom._update({ status: 'done', data })) {
const subs = internalAtom.subs
if (subs !== undefined) {
propagate(subs)
shallowPropagate(subs)
flush()
}
}
},
(error) => {
const internalAtom = ref.current!
if (internalAtom._update({ status: 'error', error })) {
const subs = internalAtom.subs
if (subs !== undefined) {
propagate(subs)
shallowPropagate(subs)
flush()
}
}
},
)
return { status: 'pending' }
}, options)
ref.current = atom as unknown as InternalAtom<AsyncAtomState<T>>
return atom
}
export function createAtom<T>(
getValue: (prev?: NoInfer<T>) => T,
options?: AtomOptions<T>,
): ReadonlyAtom<T>
export function createAtom<T>(
initialValue: T,
options?: AtomOptions<T>,
): Atom<T>
export function createAtom<T>(
valueOrFn: T | ((prev?: T) => T),
options?: AtomOptions<T>,
): Atom<T> | ReadonlyAtom<T> {
const isComputed = typeof valueOrFn === 'function'
const getter = valueOrFn as (prev?: T) => T
// Create plain object atom
const atom: InternalAtom<T> = {
_snapshot: isComputed ? undefined! : valueOrFn,
subs: undefined,
subsTail: undefined,
deps: undefined,
depsTail: undefined,
flags: isComputed ? NONE : MUTABLE,
get(): T {
if (activeSub !== undefined) {
link(atom, activeSub, cycle)
}
return atom._snapshot
},
subscribe(observerOrFn: Observer<T> | ((value: T) => void)) {
const obs = toObserver(observerOrFn)
const observed = { current: false }
const e = effect(() => {
atom.get()
if (!observed.current) {
observed.current = true
} else {
obs.next?.(atom._snapshot)
}
})
return {
unsubscribe: () => {
e.stop()
},
}
},
_update(getValue?: T | ((snapshot: T) => T)): boolean {
const prevSub = activeSub
const compare = options?.compare ?? Object.is
if (isComputed) {
activeSub = atom
++cycle
atom.depsTail = undefined
} else if (getValue === undefined) {
// Mutable atoms can be marked dirty by the reactive graph, but they should
// never be recomputed without an explicit value/updater.
return false
}
if (isComputed) {
atom.flags = MUTABLE | RECURSED_CHECK
}
try {
const oldValue = atom._snapshot
const newValue =
typeof getValue === 'function'
? (getValue as (snapshot: T) => T)(oldValue)
: getValue === undefined && isComputed
? getter(oldValue)
: getValue!
if (oldValue === undefined || !compare(oldValue, newValue)) {
atom._snapshot = newValue
return true
}
return false
} finally {
activeSub = prevSub
if (isComputed) {
atom.flags &= ~RECURSED_CHECK
}
purgeDeps(atom)
}
},
}
if (isComputed) {
atom.flags = MUTABLE | DIRTY
atom.get = function (): T {
const flags = atom.flags
if (flags & DIRTY || (flags & PENDING && checkDirty(atom.deps!, atom))) {
if (atom._update()) {
const subs = atom.subs
if (subs !== undefined) {
shallowPropagate(subs)
}
}
} else if (flags & PENDING) {
atom.flags = flags & ~PENDING
}
if (activeSub !== undefined) {
link(atom, activeSub, cycle)
}
return atom._snapshot
}
} else {
;(atom as unknown as Atom<T>).set = function (
// eslint-disable-next-line no-shadow
valueOrFn: T | ((prev: T) => T),
): void {
if (atom._update(valueOrFn)) {
const subs = atom.subs
if (subs !== undefined) {
propagate(subs)
shallowPropagate(subs)
flush()
}
}
}
}
return atom as unknown as Atom<T> | ReadonlyAtom<T>
}
interface Effect extends ReactiveNode {
notify: () => void
stop: () => void
}
function effect<T>(fn: () => T): Effect {
const run = (): T => {
const prevSub = activeSub
activeSub = effectObj
++cycle
effectObj.depsTail = undefined
effectObj.flags = WATCHING | RECURSED_CHECK
try {
return fn()
} finally {
activeSub = prevSub
effectObj.flags &= ~RECURSED_CHECK
purgeDeps(effectObj)
}
}
const effectObj: Effect = {
deps: undefined,
depsTail: undefined,
subs: undefined,
subsTail: undefined,
flags: WATCHING | RECURSED_CHECK,
notify(): void {
const flags = this.flags
if (flags & DIRTY || (flags & PENDING && checkDirty(this.deps!, this))) {
run()
} else {
this.flags = WATCHING
}
},
stop(): void {
this.flags = NONE
this.depsTail = undefined
purgeDeps(this)
},
}
run()
return effectObj
}
+4
View File
@@ -0,0 +1,4 @@
export * from './types'
export * from './atom'
export * from './store'
export * from './shallow'
+57
View File
@@ -0,0 +1,57 @@
export function shallow<T>(objA: T, objB: T) {
if (Object.is(objA, objB)) {
return true
}
if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false
}
if (objA instanceof Map && objB instanceof Map) {
if (objA.size !== objB.size) return false
for (const [k, v] of objA) {
if (!objB.has(k) || !Object.is(v, objB.get(k))) return false
}
return true
}
if (objA instanceof Set && objB instanceof Set) {
if (objA.size !== objB.size) return false
for (const v of objA) {
if (!objB.has(v)) return false
}
return true
}
if (objA instanceof Date && objB instanceof Date) {
if (objA.getTime() !== objB.getTime()) return false
return true
}
const keysA = getOwnKeys(objA)
if (keysA.length !== getOwnKeys(objB).length) {
return false
}
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < keysA.length; i++) {
if (
!Object.prototype.hasOwnProperty.call(objB, keysA[i] as string) ||
!Object.is(objA[keysA[i] as keyof T], objB[keysA[i] as keyof T])
) {
return false
}
}
return true
}
function getOwnKeys(obj: object): Array<string | symbol> {
return (Object.keys(obj) as Array<string | symbol>).concat(
Object.getOwnPropertySymbols(obj),
)
}
+367
View File
@@ -0,0 +1,367 @@
/* eslint-disable */
// Adapted from Alien Signals
// https://github.com/stackblitz/alien-signals/
import {
DIRTY,
MUTABLE,
NONE,
PENDING,
RECURSED,
RECURSED_CHECK,
WATCHING,
createReactiveSystem,
} from './alien'
import type { ReactiveNode } from './alien'
export { createReactiveSystem } from './alien'
export type { Link, ReactiveFlags, ReactiveNode } from './alien'
interface EffectNode extends ReactiveNode {
fn(): void
}
interface ComputedNode<T = any> extends ReactiveNode {
value: T | undefined
getter: (previousValue?: T) => T
}
interface SignalNode<T = any> extends ReactiveNode {
currentValue: T
pendingValue: T
}
let cycle = 0
let batchDepth = 0
let notifyIndex = 0
let queuedLength = 0
let activeSub: ReactiveNode | undefined
const queued: (EffectNode | undefined)[] = []
const { link, unlink, propagate, checkDirty, shallowPropagate } =
/* @__PURE__ */ createReactiveSystem({
update(node: SignalNode | ComputedNode): boolean {
if (node.depsTail !== undefined) {
return updateComputed(node as ComputedNode)
} else {
return updateSignal(node as SignalNode)
}
},
notify(effect: EffectNode) {
let insertIndex = queuedLength
let firstInsertedIndex = insertIndex
do {
queued[insertIndex++] = effect
effect.flags &= ~WATCHING
effect = effect.subs?.sub as EffectNode
if (effect === undefined || !(effect.flags & WATCHING)) {
break
}
} while (true)
queuedLength = insertIndex
while (firstInsertedIndex < --insertIndex) {
const left = queued[firstInsertedIndex]
queued[firstInsertedIndex++] = queued[insertIndex]
queued[insertIndex] = left
}
},
unwatched(node) {
if (!(node.flags & MUTABLE)) {
effectScopeOper.call(node)
} else if (node.depsTail !== undefined) {
node.depsTail = undefined
node.flags = MUTABLE | DIRTY
purgeDeps(node)
}
},
})
export function getActiveSub(): ReactiveNode | undefined {
return activeSub
}
export function setActiveSub(sub?: ReactiveNode) {
const prevSub = activeSub
activeSub = sub
return prevSub
}
export function getBatchDepth(): number {
return batchDepth
}
export function startBatch() {
++batchDepth
}
export function endBatch() {
if (!--batchDepth) {
flush()
}
}
export function isSignal(fn: () => void): boolean {
return fn.name === 'bound ' + signalOper.name
}
export function isComputed(fn: () => void): boolean {
return fn.name === 'bound ' + computedOper.name
}
export function isEffect(fn: () => void): boolean {
return fn.name === 'bound ' + effectOper.name
}
export function isEffectScope(fn: () => void): boolean {
return fn.name === 'bound ' + effectScopeOper.name
}
export function signal<T>(): {
(): T | undefined
(value: T | undefined): void
}
export function signal<T>(initialValue: T): {
(): T
(value: T): void
}
export function signal<T>(initialValue?: T): {
(): T | undefined
(value: T | undefined): void
} {
return signalOper.bind({
currentValue: initialValue,
pendingValue: initialValue,
subs: undefined,
subsTail: undefined,
flags: MUTABLE,
}) as () => T | undefined
}
export function computed<T>(getter: (previousValue?: T) => T): () => T {
return computedOper.bind({
value: undefined,
subs: undefined,
subsTail: undefined,
deps: undefined,
depsTail: undefined,
flags: NONE,
getter: getter as (previousValue?: unknown) => unknown,
}) as () => T
}
export function effect(fn: () => void): () => void {
const e: EffectNode = {
fn,
subs: undefined,
subsTail: undefined,
deps: undefined,
depsTail: undefined,
flags: WATCHING | RECURSED_CHECK,
}
const prevSub = setActiveSub(e)
if (prevSub !== undefined) {
link(e, prevSub, 0)
}
try {
e.fn()
} finally {
activeSub = prevSub
e.flags &= ~RECURSED_CHECK
}
return effectOper.bind(e)
}
export function effectScope(fn: () => void): () => void {
const e: ReactiveNode = {
deps: undefined,
depsTail: undefined,
subs: undefined,
subsTail: undefined,
flags: NONE,
}
const prevSub = setActiveSub(e)
if (prevSub !== undefined) {
link(e, prevSub, 0)
}
try {
fn()
} finally {
activeSub = prevSub
}
return effectScopeOper.bind(e)
}
export function trigger(fn: () => void) {
const sub: ReactiveNode = {
deps: undefined,
depsTail: undefined,
flags: WATCHING,
}
const prevSub = setActiveSub(sub)
try {
fn()
} finally {
activeSub = prevSub
let link = sub.deps
while (link !== undefined) {
const dep = link.dep
link = unlink(link, sub)
const subs = dep.subs
if (subs !== undefined) {
sub.flags = NONE
propagate(subs)
shallowPropagate(subs)
}
}
if (!batchDepth) {
flush()
}
}
}
function updateComputed(c: ComputedNode): boolean {
++cycle
c.depsTail = undefined
c.flags = MUTABLE | RECURSED_CHECK
const prevSub = setActiveSub(c)
try {
const oldValue = c.value
return oldValue !== (c.value = c.getter(oldValue))
} finally {
activeSub = prevSub
c.flags &= ~RECURSED_CHECK
purgeDeps(c)
}
}
function updateSignal(s: SignalNode): boolean {
s.flags = MUTABLE
return s.currentValue !== (s.currentValue = s.pendingValue)
}
function run(e: EffectNode): void {
const flags = e.flags
if (flags & DIRTY || (flags & PENDING && checkDirty(e.deps!, e))) {
++cycle
e.depsTail = undefined
e.flags = WATCHING | RECURSED_CHECK
const prevSub = setActiveSub(e)
try {
;(e as EffectNode).fn()
} finally {
activeSub = prevSub
e.flags &= ~RECURSED_CHECK
purgeDeps(e)
}
} else {
e.flags = WATCHING
}
}
function flush(): void {
try {
while (notifyIndex < queuedLength) {
const effect = queued[notifyIndex]!
queued[notifyIndex++] = undefined
run(effect)
}
} finally {
while (notifyIndex < queuedLength) {
const effect = queued[notifyIndex]!
queued[notifyIndex++] = undefined
effect.flags |= WATCHING | RECURSED
}
notifyIndex = 0
queuedLength = 0
}
}
function computedOper<T>(this: ComputedNode<T>): T {
const flags = this.flags
if (
flags & DIRTY ||
(flags & PENDING &&
(checkDirty(this.deps!, this) ||
((this.flags = flags & ~PENDING), false)))
) {
if (updateComputed(this)) {
const subs = this.subs
if (subs !== undefined) {
shallowPropagate(subs)
}
}
} else if (!flags) {
this.flags = MUTABLE | RECURSED_CHECK
const prevSub = setActiveSub(this)
try {
this.value = this.getter()
} finally {
activeSub = prevSub
this.flags &= ~RECURSED_CHECK
}
}
const sub = activeSub
if (sub !== undefined) {
link(this, sub, cycle)
}
return this.value!
}
function signalOper<T>(this: SignalNode<T>, ...value: [T]): T | void {
if (value.length) {
if (this.pendingValue !== (this.pendingValue = value[0])) {
this.flags = MUTABLE | DIRTY
const subs = this.subs
if (subs !== undefined) {
propagate(subs)
if (!batchDepth) {
flush()
}
}
}
} else {
if (this.flags & DIRTY) {
if (updateSignal(this)) {
const subs = this.subs
if (subs !== undefined) {
shallowPropagate(subs)
}
}
}
let sub = activeSub
while (sub !== undefined) {
if (sub.flags & (MUTABLE | WATCHING)) {
link(this, sub, cycle)
break
}
sub = sub.subs?.sub
}
return this.currentValue
}
}
function effectOper(this: EffectNode): void {
effectScopeOper.call(this)
}
function effectScopeOper(this: ReactiveNode): void {
this.depsTail = undefined
this.flags = NONE
purgeDeps(this)
const sub = this.subs
if (sub !== undefined) {
unlink(sub)
}
}
function purgeDeps(sub: ReactiveNode) {
const depsTail = sub.depsTail
let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps
while (dep !== undefined) {
dep = unlink(dep, sub)
}
}
+105
View File
@@ -0,0 +1,105 @@
import { createAtom, toObserver } from './atom'
import type { Atom, Observer, Subscription } from './types'
export type StoreAction = (...args: Array<any>) => any
export type StoreActionMap = Record<string, StoreAction>
export type StoreActionsFactory<T, TActions extends StoreActionMap> = (store: {
setState: Store<T>['setState']
get: Store<T>['get']
}) => TActions
type NonFunction<T> = T extends (...args: Array<any>) => any ? never : T
export class Store<T, TActions extends StoreActionMap = never> {
private atom: Atom<T>
public readonly actions!: TActions
constructor(getValue: (prev?: NoInfer<T>) => T)
constructor(initialValue: T)
constructor(
initialValue: NonFunction<T>,
actionsFactory: StoreActionsFactory<T, TActions>,
)
constructor(
valueOrFn: T | ((prev?: T) => T),
actionsFactory?: StoreActionsFactory<T, TActions>,
) {
// createAtom has overloads that return ReadonlyAtom<T> for functions and Atom<T> for values
// Store always needs Atom<T> for setState, so we assert the return type
this.atom = createAtom(
valueOrFn as T | ((prev?: NoInfer<T>) => T),
) as Atom<T>
// bind for safe destructuring
this.get = this.get.bind(this)
this.setState = this.setState.bind(this)
this.subscribe = this.subscribe.bind(this)
if (actionsFactory) {
this.actions = actionsFactory(this)
}
}
public setState(updater: (prev: T) => T) {
this.atom.set(updater)
}
public get state() {
return this.atom.get()
}
public get() {
return this.state
}
public subscribe(
observerOrFn: Observer<T> | ((value: T) => void),
): Subscription {
return this.atom.subscribe(toObserver(observerOrFn))
}
}
export class ReadonlyStore<T> implements Omit<
Store<T>,
'setState' | 'actions'
> {
private atom: Atom<T>
constructor(getValue: (prev?: NoInfer<T>) => T)
constructor(initialValue: T)
constructor(valueOrFn: T | ((prev?: T) => T)) {
// createAtom has overloads that return ReadonlyAtom<T> for functions and Atom<T> for values
// Store always needs Atom<T> for setState, so we assert the return type
this.atom = createAtom(
valueOrFn as T | ((prev?: NoInfer<T>) => T),
) as Atom<T>
}
public get state() {
return this.atom.get()
}
public get() {
return this.state
}
public subscribe(
observerOrFn: Observer<T> | ((value: T) => void),
): Subscription {
return this.atom.subscribe(toObserver(observerOrFn))
}
}
export function createStore<T>(
getValue: (prev?: NoInfer<T>) => T,
): ReadonlyStore<T>
export function createStore<T>(initialValue: T): Store<T>
export function createStore<T, TActions extends StoreActionMap>(
initialValue: NonFunction<T>,
actions: StoreActionsFactory<T, TActions>,
): Store<T, TActions>
export function createStore<T, TActions extends StoreActionMap>(
valueOrFn: T | ((prev?: T) => T),
actions?: StoreActionsFactory<T, TActions>,
): Store<T, TActions> | Store<T> | ReadonlyStore<T> {
if (typeof valueOrFn === 'function') {
return new ReadonlyStore(valueOrFn as (prev?: NoInfer<T>) => T)
}
if (actions) {
return new Store(valueOrFn as NonFunction<T>, actions)
}
return new Store(valueOrFn)
}
+67
View File
@@ -0,0 +1,67 @@
import type { ReactiveNode } from './alien'
export type Selection<TSelected> = Readable<TSelected>
export interface InteropSubscribable<T> {
subscribe: (observer: Observer<T>) => Subscription
}
// Based on RxJS types
export type Observer<T> = {
next?: (value: T) => void
error?: (err: unknown) => void
complete?: () => void
}
export interface Subscription {
unsubscribe: () => void
}
export interface Subscribable<T> extends InteropSubscribable<T> {
subscribe: ((observer: Observer<T>) => Subscription) &
((
next: (value: T) => void,
error?: (error: any) => void,
complete?: () => void,
) => Subscription)
}
export interface Readable<T> extends Subscribable<T> {
get: () => T
}
export interface BaseAtom<T> extends Subscribable<T>, Readable<T> {}
export interface InternalBaseAtom<T> extends Subscribable<T>, Readable<T> {
/** @internal */
_snapshot: T
/** @internal */
_update: (getValue?: T | ((snapshot: T) => T)) => boolean
}
export interface Atom<T> extends BaseAtom<T> {
/** Sets the value of the atom using a function. */
set: ((fn: (prevVal: T) => T) => void) & ((value: T) => void)
}
export interface AtomOptions<T> {
compare?: (prev: T, next: T) => boolean
}
export type AnyAtom = BaseAtom<any>
export interface InternalReadonlyAtom<T>
extends InternalBaseAtom<T>, ReactiveNode {}
/**
* An atom that is read-only and cannot be set.
*
* @example
*
* ```ts
* const atom = createAtom(() => 42);
* // @ts-expect-error - Cannot set a readonly atom
* atom.set(43);
* ```
*/
export interface ReadonlyAtom<T> extends BaseAtom<T> {}