@clagradi/effect-runtime 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,180 @@
1
+ # effect-runtime
2
+
3
+ `@clagradi/effect-runtime` is a tiny React 18+ primitive that makes async effects safer than raw `useEffect`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i @clagradi/effect-runtime
9
+ ```
10
+
11
+ ## API
12
+
13
+ ```ts
14
+ export function useEvent<T extends (...args: any[]) => any>(fn: T): T;
15
+
16
+ type EffectTaskScope = {
17
+ signal: AbortSignal;
18
+ runId: number;
19
+ isActive(): boolean;
20
+ commit(fn: () => void): void;
21
+ onCleanup(fn: () => void): void;
22
+ };
23
+
24
+ type EffectTask =
25
+ (scope: EffectTaskScope) =>
26
+ void | (() => void) | Promise<void | (() => void)>;
27
+
28
+ export function useEffectTask(
29
+ task: EffectTask,
30
+ deps: any[],
31
+ options?: { layout?: boolean; onError?: (err: unknown) => void; debugName?: string }
32
+ ): void;
33
+ ```
34
+
35
+ ## Quickstart
36
+
37
+ ### Example 1: fetch with `signal` + anti-race `commit`
38
+
39
+ ```tsx
40
+ import { useState } from 'react';
41
+ import { useEffectTask } from '@clagradi/effect-runtime';
42
+
43
+ export function UserCard({ userId }: { userId: string }) {
44
+ const [name, setName] = useState('loading...');
45
+
46
+ useEffectTask(
47
+ async ({ signal, commit }) => {
48
+ const response = await fetch(`/api/users/${userId}`, { signal });
49
+ const user = (await response.json()) as { name: string };
50
+
51
+ commit(() => {
52
+ setName(user.name);
53
+ });
54
+ },
55
+ [userId]
56
+ );
57
+
58
+ return <div>{name}</div>;
59
+ }
60
+ ```
61
+
62
+ ### Example 2: interval with `useEvent`
63
+
64
+ ```tsx
65
+ import { useState } from 'react';
66
+ import { useEffectTask, useEvent } from '@clagradi/effect-runtime';
67
+
68
+ export function Counter() {
69
+ const [count, setCount] = useState(0);
70
+ const onTick = useEvent(() => setCount((value) => value + 1));
71
+
72
+ useEffectTask(({ onCleanup }) => {
73
+ const handle = setInterval(() => onTick(), 1000);
74
+ onCleanup(() => clearInterval(handle));
75
+ }, []);
76
+
77
+ return <span>{count}</span>;
78
+ }
79
+ ```
80
+
81
+ ### Example 3: subscription with `onCleanup`
82
+
83
+ ```tsx
84
+ import { useEffectTask } from '@clagradi/effect-runtime';
85
+
86
+ type Subscription = { unsubscribe: () => void };
87
+ declare function subscribeToRoom(roomId: string, cb: (msg: string) => void): Subscription;
88
+
89
+ export function RoomFeed({ roomId }: { roomId: string }) {
90
+ useEffectTask(({ onCleanup }) => {
91
+ const sub = subscribeToRoom(roomId, (msg) => {
92
+ console.log(msg);
93
+ });
94
+
95
+ onCleanup(() => sub.unsubscribe());
96
+ }, [roomId]);
97
+
98
+ return null;
99
+ }
100
+ ```
101
+
102
+ ## Why better than useEffect
103
+
104
+ - Per-run `AbortController` (auto-abort on rerun/unmount)
105
+ - `commit()` anti-race guard for stale async completions
106
+ - Multiple cleanups with LIFO execution via `onCleanup()`
107
+ - Late async cleanup is never lost (executes immediately if resolved after dispose)
108
+ - `useEvent` gives stable identity + latest closure
109
+
110
+ ## Caveats
111
+
112
+ - This is not a data-fetching cache layer (not React Query/SWR).
113
+ - No SSR orchestration/caching features.
114
+
115
+ ## Release checklist
116
+
117
+ 1. Run package checks:
118
+
119
+ ```bash
120
+ npm run typecheck
121
+ npm run test
122
+ npm run build
123
+ ```
124
+
125
+ 2. Create a package tarball:
126
+
127
+ ```bash
128
+ npm pack
129
+ ```
130
+
131
+ 3. Install locally in a separate app (use either method):
132
+
133
+ ```bash
134
+ # from repo folder path
135
+ npm i /absolute/path/to/UseEffectState
136
+
137
+ # from generated tarball
138
+ npm i /absolute/path/to/UseEffectState/clagradi-effect-runtime-0.1.0.tgz
139
+ ```
140
+
141
+ 4. Verify in the consumer app:
142
+
143
+ - `import { useEffectTask, useEvent } from '@clagradi/effect-runtime'` resolves.
144
+ - TypeScript picks up package types from `dist/index.d.ts` (run `npm run typecheck`).
145
+
146
+ ## Publishing to npm
147
+
148
+ 1. Check package name availability:
149
+
150
+ ```bash
151
+ npm view @clagradi/effect-runtime
152
+ # 404 => available
153
+ ```
154
+
155
+ 2. Login:
156
+
157
+ ```bash
158
+ npm login
159
+ ```
160
+
161
+ 3. Publish the package:
162
+
163
+ ```bash
164
+ npm publish --access public
165
+ ```
166
+
167
+ Scoped packages default to private. Always pass `--access public` for public releases.
168
+
169
+ 4. Versioning:
170
+
171
+ ```bash
172
+ npm version patch # or minor / major
173
+ git push
174
+ git push --tags
175
+ ```
176
+
177
+ 5. Tag/release strategy:
178
+
179
+ - CI publish runs when pushing a tag matching `v*` (for example `v0.1.0`) or when a GitHub Release is published.
180
+ - The publish workflow uses `npm publish --provenance --access public` with `NODE_AUTH_TOKEN=${{ secrets.NPM_TOKEN }}`.
package/dist/index.cjs ADDED
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ useEffectTask: () => useEffectTask,
24
+ useEvent: () => useEvent
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/useEvent.ts
29
+ var import_react = require("react");
30
+ function useEvent(fn) {
31
+ const fnRef = (0, import_react.useRef)(fn);
32
+ fnRef.current = fn;
33
+ const stableFn = (0, import_react.useCallback)((...args) => {
34
+ return fnRef.current(...args);
35
+ }, []);
36
+ return stableFn;
37
+ }
38
+
39
+ // src/useEffectTask.ts
40
+ var import_react2 = require("react");
41
+ function isPromise(value) {
42
+ return typeof value?.then === "function";
43
+ }
44
+ function isAbortError(error) {
45
+ return error instanceof DOMException && (error.name === "AbortError" || error.code === DOMException.ABORT_ERR);
46
+ }
47
+ function reportError(error, signal, options) {
48
+ if (signal.aborted || isAbortError(error)) {
49
+ return;
50
+ }
51
+ if (options?.onError) {
52
+ options.onError(error);
53
+ return;
54
+ }
55
+ const runtime = globalThis;
56
+ if (runtime.process?.env?.NODE_ENV !== "production") {
57
+ console.error(
58
+ `[useEffectTask${options?.debugName ? `:${options.debugName}` : ""}]`,
59
+ error
60
+ );
61
+ }
62
+ }
63
+ function useEffectTask(task, deps, options) {
64
+ const runIdRef = (0, import_react2.useRef)(0);
65
+ const latestTask = useEvent(task);
66
+ const selectedEffect = options?.layout ? import_react2.useLayoutEffect : import_react2.useEffect;
67
+ selectedEffect(() => {
68
+ const runId = ++runIdRef.current;
69
+ const controller = new AbortController();
70
+ const cleanupStack = [];
71
+ let taskCleanup;
72
+ let disposed = false;
73
+ const isActive = () => {
74
+ return !controller.signal.aborted && runIdRef.current === runId && !disposed;
75
+ };
76
+ const runCleanup = (cleanup) => {
77
+ if (!cleanup) {
78
+ return;
79
+ }
80
+ try {
81
+ cleanup();
82
+ } catch (error) {
83
+ reportError(error, controller.signal, options);
84
+ }
85
+ };
86
+ const dispose = () => {
87
+ if (disposed) {
88
+ return;
89
+ }
90
+ disposed = true;
91
+ controller.abort();
92
+ for (let index = cleanupStack.length - 1; index >= 0; index -= 1) {
93
+ runCleanup(cleanupStack[index]);
94
+ }
95
+ cleanupStack.length = 0;
96
+ runCleanup(taskCleanup);
97
+ taskCleanup = void 0;
98
+ };
99
+ const scope = {
100
+ signal: controller.signal,
101
+ runId,
102
+ isActive,
103
+ commit: (fn) => {
104
+ if (!isActive()) {
105
+ return;
106
+ }
107
+ fn();
108
+ },
109
+ onCleanup: (fn) => {
110
+ if (disposed) {
111
+ runCleanup(fn);
112
+ return;
113
+ }
114
+ cleanupStack.push(fn);
115
+ }
116
+ };
117
+ try {
118
+ const output = latestTask(scope);
119
+ if (isPromise(output)) {
120
+ output.then((resolvedCleanup) => {
121
+ if (typeof resolvedCleanup !== "function") {
122
+ return;
123
+ }
124
+ if (disposed || !isActive()) {
125
+ runCleanup(resolvedCleanup);
126
+ return;
127
+ }
128
+ taskCleanup = resolvedCleanup;
129
+ }).catch((error) => {
130
+ reportError(error, controller.signal, options);
131
+ });
132
+ } else if (typeof output === "function") {
133
+ taskCleanup = output;
134
+ }
135
+ } catch (error) {
136
+ reportError(error, controller.signal, options);
137
+ }
138
+ return dispose;
139
+ }, deps);
140
+ }
141
+ // Annotate the CommonJS export names for ESM import in node:
142
+ 0 && (module.exports = {
143
+ useEffectTask,
144
+ useEvent
145
+ });
@@ -0,0 +1,19 @@
1
+ declare function useEvent<T extends (...args: any[]) => any>(fn: T): T;
2
+
3
+ type EffectTaskCleanup = () => void;
4
+ interface EffectTaskScope {
5
+ signal: AbortSignal;
6
+ runId: number;
7
+ isActive: () => boolean;
8
+ commit: (fn: () => void) => void;
9
+ onCleanup: (fn: EffectTaskCleanup) => void;
10
+ }
11
+ interface UseEffectTaskOptions {
12
+ layout?: boolean;
13
+ onError?: (err: unknown) => void;
14
+ debugName?: string;
15
+ }
16
+ type EffectTask = (scope: EffectTaskScope) => void | EffectTaskCleanup | Promise<void | EffectTaskCleanup>;
17
+ declare function useEffectTask(task: EffectTask, deps: any[], options?: UseEffectTaskOptions): void;
18
+
19
+ export { type EffectTask, type EffectTaskCleanup, type EffectTaskScope, type UseEffectTaskOptions, useEffectTask, useEvent };
@@ -0,0 +1,19 @@
1
+ declare function useEvent<T extends (...args: any[]) => any>(fn: T): T;
2
+
3
+ type EffectTaskCleanup = () => void;
4
+ interface EffectTaskScope {
5
+ signal: AbortSignal;
6
+ runId: number;
7
+ isActive: () => boolean;
8
+ commit: (fn: () => void) => void;
9
+ onCleanup: (fn: EffectTaskCleanup) => void;
10
+ }
11
+ interface UseEffectTaskOptions {
12
+ layout?: boolean;
13
+ onError?: (err: unknown) => void;
14
+ debugName?: string;
15
+ }
16
+ type EffectTask = (scope: EffectTaskScope) => void | EffectTaskCleanup | Promise<void | EffectTaskCleanup>;
17
+ declare function useEffectTask(task: EffectTask, deps: any[], options?: UseEffectTaskOptions): void;
18
+
19
+ export { type EffectTask, type EffectTaskCleanup, type EffectTaskScope, type UseEffectTaskOptions, useEffectTask, useEvent };
package/dist/index.js ADDED
@@ -0,0 +1,117 @@
1
+ // src/useEvent.ts
2
+ import { useCallback, useRef } from "react";
3
+ function useEvent(fn) {
4
+ const fnRef = useRef(fn);
5
+ fnRef.current = fn;
6
+ const stableFn = useCallback((...args) => {
7
+ return fnRef.current(...args);
8
+ }, []);
9
+ return stableFn;
10
+ }
11
+
12
+ // src/useEffectTask.ts
13
+ import { useEffect, useLayoutEffect, useRef as useRef2 } from "react";
14
+ function isPromise(value) {
15
+ return typeof value?.then === "function";
16
+ }
17
+ function isAbortError(error) {
18
+ return error instanceof DOMException && (error.name === "AbortError" || error.code === DOMException.ABORT_ERR);
19
+ }
20
+ function reportError(error, signal, options) {
21
+ if (signal.aborted || isAbortError(error)) {
22
+ return;
23
+ }
24
+ if (options?.onError) {
25
+ options.onError(error);
26
+ return;
27
+ }
28
+ const runtime = globalThis;
29
+ if (runtime.process?.env?.NODE_ENV !== "production") {
30
+ console.error(
31
+ `[useEffectTask${options?.debugName ? `:${options.debugName}` : ""}]`,
32
+ error
33
+ );
34
+ }
35
+ }
36
+ function useEffectTask(task, deps, options) {
37
+ const runIdRef = useRef2(0);
38
+ const latestTask = useEvent(task);
39
+ const selectedEffect = options?.layout ? useLayoutEffect : useEffect;
40
+ selectedEffect(() => {
41
+ const runId = ++runIdRef.current;
42
+ const controller = new AbortController();
43
+ const cleanupStack = [];
44
+ let taskCleanup;
45
+ let disposed = false;
46
+ const isActive = () => {
47
+ return !controller.signal.aborted && runIdRef.current === runId && !disposed;
48
+ };
49
+ const runCleanup = (cleanup) => {
50
+ if (!cleanup) {
51
+ return;
52
+ }
53
+ try {
54
+ cleanup();
55
+ } catch (error) {
56
+ reportError(error, controller.signal, options);
57
+ }
58
+ };
59
+ const dispose = () => {
60
+ if (disposed) {
61
+ return;
62
+ }
63
+ disposed = true;
64
+ controller.abort();
65
+ for (let index = cleanupStack.length - 1; index >= 0; index -= 1) {
66
+ runCleanup(cleanupStack[index]);
67
+ }
68
+ cleanupStack.length = 0;
69
+ runCleanup(taskCleanup);
70
+ taskCleanup = void 0;
71
+ };
72
+ const scope = {
73
+ signal: controller.signal,
74
+ runId,
75
+ isActive,
76
+ commit: (fn) => {
77
+ if (!isActive()) {
78
+ return;
79
+ }
80
+ fn();
81
+ },
82
+ onCleanup: (fn) => {
83
+ if (disposed) {
84
+ runCleanup(fn);
85
+ return;
86
+ }
87
+ cleanupStack.push(fn);
88
+ }
89
+ };
90
+ try {
91
+ const output = latestTask(scope);
92
+ if (isPromise(output)) {
93
+ output.then((resolvedCleanup) => {
94
+ if (typeof resolvedCleanup !== "function") {
95
+ return;
96
+ }
97
+ if (disposed || !isActive()) {
98
+ runCleanup(resolvedCleanup);
99
+ return;
100
+ }
101
+ taskCleanup = resolvedCleanup;
102
+ }).catch((error) => {
103
+ reportError(error, controller.signal, options);
104
+ });
105
+ } else if (typeof output === "function") {
106
+ taskCleanup = output;
107
+ }
108
+ } catch (error) {
109
+ reportError(error, controller.signal, options);
110
+ }
111
+ return dispose;
112
+ }, deps);
113
+ }
114
+ export {
115
+ useEffectTask,
116
+ useEvent
117
+ };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@clagradi/effect-runtime",
3
+ "version": "0.1.0",
4
+ "description": "Better async effect primitive for React 18+",
5
+ "license": "MIT",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": ["dist"],
17
+ "sideEffects": false,
18
+ "scripts": {
19
+ "build": "tsup",
20
+ "test": "vitest run",
21
+ "test:watch": "vitest",
22
+ "typecheck": "tsc --noEmit",
23
+ "prepublishOnly": "npm run typecheck && npm run test && npm run build"
24
+ },
25
+ "peerDependencies": {
26
+ "react": ">=18"
27
+ },
28
+ "devDependencies": {
29
+ "@testing-library/react": "^16.1.0",
30
+ "@types/node": "^22.13.10",
31
+ "@types/react": "^18.3.18",
32
+ "@types/react-dom": "^18.3.5",
33
+ "jsdom": "^25.0.1",
34
+ "react": "^18.3.1",
35
+ "react-dom": "^18.3.1",
36
+ "tsup": "^8.3.5",
37
+ "typescript": "^5.7.2",
38
+ "vitest": "^2.1.8"
39
+ }
40
+ }