posipaki 0.3.2 → 0.3.3

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "posipaki",
4
- "version": "0.3.2",
4
+ "version": "0.3.3",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "scripts": {
@@ -10,7 +10,8 @@
10
10
  "files": [
11
11
  "dist/*js",
12
12
  "dist/*map",
13
- "dist/*d.ts"
13
+ "dist/*d.ts",
14
+ "src/*ts"
14
15
  ],
15
16
  "devDependencies": {
16
17
  "typescript": "^4.4.3"
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ import Process, { spawn, Message, ProcessCtx, ProcessFn } from './process.js';
2
+ import { runDispatch } from './util.js';
3
+
4
+ export { Process, spawn, runDispatch, Message, ProcessCtx, ProcessFn }
package/src/process.ts ADDED
@@ -0,0 +1,144 @@
1
+ import { watchExit, Waiter, defer, makeWaiter } from './util.js';
2
+
3
+ export type Message = {
4
+ type: string;
5
+ };
6
+ type ExitMessage = {
7
+ type: 'EXIT';
8
+ pid: Symbol;
9
+ };
10
+
11
+ type ProcessGenerator<ProcessState> = Generator<ProcessState | null, void, Message>;
12
+ type Fork<ChildArgs, ChildState> = (fn : ProcessFn<ChildArgs, ChildState>, pname : string) => (args: ChildArgs) => Process<ChildArgs, ChildState>;
13
+
14
+
15
+ export type ProcessFn<Args, State> = (ctx: ProcessCtx, args: Args) => ProcessGenerator<State>;
16
+ type ProcessMessageCb = (msg: Message | ExitMessage) => void;
17
+
18
+ export type ProcessCtx = {
19
+ pname: string,
20
+ fork: Fork<unknown, unknown>,
21
+ send: (msg: Message) => void,
22
+ toParent: ProcessMessageCb,
23
+ };
24
+
25
+ type NotifyFn = () => void;
26
+ type UnsubscibeFn = () => void;
27
+
28
+ export function spawn<Args, State>(fn: ProcessFn<Args, State>, pname: string, toParent?: ProcessMessageCb) {
29
+ return (args: Args): Process<Args, State> => {
30
+ const process = new Process(fn, pname, toParent);
31
+ process.start(args);
32
+ return process;
33
+ };
34
+ }
35
+ const noop = ()=> null;
36
+
37
+ class Process<Args, State> {
38
+ pgenerator: ProcessFn<Args, State>;
39
+ pname: string;
40
+ toParent: ProcessMessageCb;
41
+ id: Symbol;
42
+ state: State | null;
43
+
44
+ private current: ProcessGenerator<State> | null;
45
+ private buffer: Array<Message>;
46
+ private children: Array<Process<unknown, unknown>>;
47
+ private subscribers: Array<NotifyFn>;
48
+ private exitWaiter: Waiter;
49
+
50
+ constructor(fn: ProcessFn<Args, State>, pname: string, toParent: ProcessMessageCb | undefined) {
51
+ this.pgenerator = fn;
52
+ this.pname = pname;
53
+ this.toParent = toParent || noop;
54
+ this.id = Symbol(pname);
55
+
56
+
57
+ this.current = null;
58
+ this.state = null;
59
+ this.buffer = [];
60
+
61
+ this.children = [];
62
+ this.subscribers = [];
63
+ this.exitWaiter = makeWaiter();
64
+ }
65
+
66
+ start(arg0: Args) {
67
+ const ctx: ProcessCtx = {
68
+ pname: this.pname,
69
+ fork: this.fork.bind(this),
70
+ send: this.send.bind(this),
71
+ toParent: this.toParent,
72
+ };
73
+ const task = watchExit<Args, State>(this)(ctx, arg0);
74
+ this.current = task;
75
+ let ret = task.next();
76
+ this.state = ret.value || null;
77
+ this._tick(task.next());
78
+ }
79
+
80
+ fork<ChildArgs, ChildState> (fn : ProcessFn<ChildArgs, ChildState>, pname : string) {
81
+ return (args: ChildArgs) => {
82
+ const child = new Process(fn, pname, this.fromChild.bind(this));
83
+ this.children.push(child as Process<unknown, unknown>);
84
+ child.start(args);
85
+ return child;
86
+ }
87
+ }
88
+
89
+ _tick (ret: IteratorResult<State | null, void> | null) {
90
+ if (!this.current) {
91
+ return;
92
+ }
93
+
94
+ let msg: Message | undefined;
95
+ while(msg = this.buffer.shift()) {
96
+ this._tick(this.current.next(msg));
97
+ }
98
+ this.notify();
99
+ if (ret && ret.done) {
100
+ this.exitWaiter.resolve();
101
+ }
102
+ }
103
+
104
+ toAllChildren(msg: Message) {
105
+ this.children.forEach(p => p.send(msg));
106
+ }
107
+
108
+ send(msg: Message) {
109
+ this.buffer.push(msg);
110
+ defer(()=> this._tick(null));
111
+ }
112
+
113
+ notify() {
114
+ this.subscribers.forEach((f) => f());
115
+ }
116
+
117
+ get isListenedTo() {
118
+ return this.subscribers.length > 0;
119
+ }
120
+
121
+ subscribe(f: NotifyFn) {
122
+ this.subscribers.push(f);
123
+ return () => {
124
+ const idx = this.subscribers.indexOf(f);
125
+ if (idx < 0) {
126
+ return;
127
+ }
128
+ this.subscribers.splice(idx, 1);
129
+ }
130
+ }
131
+
132
+ wait() {
133
+ return this.exitWaiter.promise;
134
+ }
135
+
136
+ fromChild(msg: Message | ExitMessage) {
137
+ if (msg.type === 'EXIT') {
138
+ this.children = this.children.filter(p=> p.id !== (msg as ExitMessage).pid);
139
+ }
140
+ this.send(msg);
141
+ }
142
+ }
143
+
144
+ export default Process;
package/src/util.ts ADDED
@@ -0,0 +1,54 @@
1
+ import type Process from './process';
2
+ import type { ProcessCtx, Message } from './process';
3
+
4
+ function debugLog(level: boolean, ...args: Array<unknown>) {
5
+ if (level) {
6
+ console.log(...args);
7
+ }
8
+ }
9
+
10
+ type ReducerClosure = (msg: Message) => void;
11
+ type ReadyFn = () => boolean;
12
+ type NotifyFn = () => void;
13
+
14
+ function* runDispatch(name: string, fn : ReducerClosure, readyFn: ReadyFn = ()=> false, debugLevel = false) : Generator<null, void, Message> {
15
+ let msg: Message;
16
+ while(!readyFn()) {
17
+ msg = yield null;
18
+ debugLog(debugLevel, 'msg', name, ' <- ', msg);
19
+ fn(msg);
20
+ }
21
+ }
22
+
23
+ function watchExit<Args, State>(process: Process<Args, State>) {
24
+ return function* (ctx: ProcessCtx, arg0: Args) {
25
+ yield* process.pgenerator(ctx, arg0);
26
+ process.toAllChildren({ type: 'STOP' });
27
+ process.toParent({ type: 'EXIT', pid: process.id});
28
+ }
29
+ }
30
+
31
+ type DeferCb = () => void;
32
+ type Defer = (fn: DeferCb) => void;
33
+ type WindowGlobal = {
34
+ setImmediate?: Defer
35
+ };
36
+
37
+ function defer(fn: DeferCb) {
38
+ const g = globalThis as WindowGlobal;
39
+ const setDefer = (g.setImmediate || requestIdleCallback) as Defer;
40
+ setDefer(fn);
41
+ }
42
+ export type Waiter = {
43
+ promise: Promise<void>;
44
+ resolve: NotifyFn;
45
+ };
46
+ function makeWaiter() : Waiter {
47
+ let resolve: unknown;
48
+ let promise = new Promise<void>(_resolve => {
49
+ resolve = _resolve;
50
+ });
51
+ return {promise, resolve: resolve as NotifyFn};
52
+ }
53
+
54
+ export { runDispatch, watchExit, defer, makeWaiter };
package/src/xfetch.ts ADDED
@@ -0,0 +1,83 @@
1
+ import { runDispatch } from './util.js';
2
+ import type { ProcessCtx, Message } from './process';
3
+
4
+ function isJsonHelper(res : Response) {
5
+ const ct = res.headers.get('content-type');
6
+ return ct === 'application/json';
7
+ }
8
+
9
+ export type FetchState<T> = {
10
+ code: 'pending' | 'loading' | 'aborted' | 'failed' | 'ok',
11
+ data: T | null,
12
+ text: string | null,
13
+ };
14
+ export type FetchArgs = {
15
+ url: URL,
16
+ };
17
+ type FetchMessage<T> = {
18
+ type: string,
19
+ data?: T | null,
20
+ text?: string | null,
21
+ };
22
+
23
+ type FetchGenerator<T> = Generator<FetchState<T> | null, void, Message>;
24
+
25
+ function* xfetch<Type>({ pname, toParent, send } : ProcessCtx, { url } : FetchArgs) : FetchGenerator<Type> {
26
+ const state: FetchState<Type> = { code: 'pending', data: null, text: null };
27
+ yield state;
28
+
29
+ const controller = new AbortController();
30
+ const signal = controller.signal;
31
+
32
+ const toSelf = (msg: unknown) => send(msg as Message);
33
+
34
+ (async function do_request() {
35
+ try {
36
+ toSelf({ type: 'LOADING'});
37
+ const res: Response = await fetch(url.href, { signal });
38
+ if (isJsonHelper(res)) {
39
+ const data = await res.json();
40
+ toSelf({ type: 'OK', data });
41
+ } else {
42
+ const text = await res.text();
43
+ toSelf({ type: 'OK', text });
44
+ }
45
+ } catch (e) {
46
+ const isAborted = (e instanceof DOMException && e.name === 'AbortError');
47
+ if (isAborted) {
48
+ toSelf({ type: 'ABORTED', pname });
49
+ } else {
50
+ //console.log('e', e);
51
+ toSelf({ type: 'ERROR', pname });
52
+ }
53
+ }
54
+ })();
55
+
56
+ const isDone = ()=> !(state.code === 'pending' || state.code === 'loading')
57
+
58
+ yield* runDispatch(pname, (msg : FetchMessage<Type>)=> {
59
+ if (msg.type === 'STOP') {
60
+ controller.abort();
61
+ }
62
+ if (msg.type === 'ABORTED') {
63
+ toParent(msg);
64
+ state.code = 'aborted';
65
+ }
66
+ if (msg.type === 'ERROR') {
67
+ toParent(msg);
68
+ state.code = 'failed';
69
+ }
70
+ if (msg.type === 'LOADING') {
71
+ state.code = 'loading';
72
+ }
73
+
74
+ if (msg.type === 'OK') {
75
+ toParent(msg);
76
+ state.code = 'ok';
77
+ state.data = msg.data || null;
78
+ state.text = msg.text || null;
79
+ }
80
+ }, isDone, true);
81
+ }
82
+
83
+ export { xfetch };