@codeinkit/dom-trigger 0.0.0-stage → 0.2.0-alpha.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.
@@ -0,0 +1,405 @@
1
+ import { resolveFlowModules } from './modules.js';
2
+ import { DEFAULT_PREFIX, assertEventName, getDocument } from './names.js';
3
+ const CONCURRENCY = ['drop', 'latest', 'queue', 'parallel'];
4
+ function toMatcher(selector, what) {
5
+ if (typeof selector === 'string')
6
+ return (flowId) => flowId.indexOf(selector) === 0;
7
+ if (typeof selector === 'function')
8
+ return (flowId) => !!selector(flowId);
9
+ if (Array.isArray(selector) && selector.every((id) => typeof id === 'string')) {
10
+ const ids = new Set(selector);
11
+ return (flowId) => ids.has(flowId);
12
+ }
13
+ throw new TypeError(`dom-trigger: ${what} must be a flow id prefix, an array of flow ids or a function`);
14
+ }
15
+ function abortError(message) {
16
+ return Object.assign(new Error(message), { name: 'AbortError', code: 'ABORT_ERR' });
17
+ }
18
+ let runCounter = 0;
19
+ function defaultRunId() {
20
+ const c = globalThis.crypto;
21
+ if (c && typeof c.randomUUID === 'function')
22
+ return c.randomUUID();
23
+ runCounter += 1;
24
+ return `${Date.now().toString(36)}-${runCounter.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
25
+ }
26
+ function defaultRoute() {
27
+ const location = globalThis.location;
28
+ return location ? location.pathname : undefined;
29
+ }
30
+ function defaultOnError(error, info) {
31
+ console.error(`[dom-trigger] ${info.status}: flow "${info.flowId}" on "${info.event}"`, error);
32
+ }
33
+ function isSchemaLike(value) {
34
+ const schema = value;
35
+ return !!schema && (typeof schema.safeParse === 'function' || typeof schema.parse === 'function');
36
+ }
37
+ function validate(schema, value) {
38
+ var _a;
39
+ try {
40
+ if (typeof schema.safeParse !== 'function')
41
+ return { ok: true, data: schema.parse(value) };
42
+ const result = schema.safeParse(value);
43
+ return result.success ? { ok: true, data: result.data } : { ok: false, error: (_a = result.error) !== null && _a !== void 0 ? _a : new Error('invalid input') };
44
+ }
45
+ catch (error) {
46
+ return { ok: false, error };
47
+ }
48
+ }
49
+ /** the valid dom triggers of a `triggers` list. Other trigger types are ignored, a bad dom trigger throws */
50
+ function parseTriggers(flowId, triggers, input) {
51
+ if (typeof flowId !== 'string' || flowId === '')
52
+ throw new TypeError('dom-trigger: flowId must be a non-empty string');
53
+ if (!Array.isArray(triggers))
54
+ throw new TypeError(`dom-trigger: triggers of flow "${flowId}" must be an array`);
55
+ const parsed = [];
56
+ for (const trigger of triggers) {
57
+ if (!trigger || trigger.type !== 'dom')
58
+ continue;
59
+ const { event, concurrency = 'drop' } = trigger;
60
+ assertEventName(event);
61
+ if (CONCURRENCY.indexOf(concurrency) === -1) {
62
+ throw new TypeError(`dom-trigger: invalid concurrency ${JSON.stringify(concurrency)} for "${event}" of flow "${flowId}", expected one of ${CONCURRENCY.join(', ')}`);
63
+ }
64
+ if (parsed.some((p) => p.event === event)) {
65
+ throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
66
+ }
67
+ parsed.push({ event, concurrency });
68
+ }
69
+ if (parsed.length > 0 && input !== undefined && !isSchemaLike(input)) {
70
+ throw new TypeError(`dom-trigger: input of flow "${flowId}" must have a safeParse() or a parse() method`);
71
+ }
72
+ return parsed;
73
+ }
74
+ export class DomTrigger {
75
+ constructor(flows, options = {}) {
76
+ var _a;
77
+ /** event name => the flows that listen to it */
78
+ this.entries = new Map();
79
+ /** active runs by runId */
80
+ this.runs = new Map();
81
+ this.statusListeners = new Set();
82
+ /** flows registered with `scoped`, by flow id */
83
+ this.scopedFlows = new Map();
84
+ /** the scopes that are acquired right now */
85
+ this.holds = new Set();
86
+ /**
87
+ * start listening: one listener per event type on the target. Returns `stop`.
88
+ * Without a target (SSR, no document) nothing happens. Calling it twice does not subscribe twice.
89
+ */
90
+ this.start = () => {
91
+ var _a;
92
+ if (this.target)
93
+ return this.stop;
94
+ const target = (_a = this.options.target) !== null && _a !== void 0 ? _a : getDocument();
95
+ if (!target || typeof target.addEventListener !== 'function')
96
+ return this.stop;
97
+ this.target = target;
98
+ this.listeners = new AbortController();
99
+ for (const event of this.entries.keys())
100
+ this.listen(event);
101
+ return this.stop;
102
+ };
103
+ /** remove every listener and abort every running or queued run. `start()` works again afterwards */
104
+ this.stop = () => {
105
+ const { target, listeners } = this;
106
+ this.target = undefined;
107
+ this.listeners = undefined;
108
+ if (target && listeners) {
109
+ listeners.abort();
110
+ // for targets that do not know the `signal` option of addEventListener
111
+ for (const event of this.entries.keys())
112
+ target.removeEventListener(this.prefix + event, this.onEvent);
113
+ }
114
+ for (const list of [...this.entries.values()]) {
115
+ list.forEach((entry) => this.cancelRuns(entry, 'dom-trigger stopped'));
116
+ }
117
+ };
118
+ this.onEvent = (event) => {
119
+ const entries = this.entries.get(event.type.slice(this.prefix.length));
120
+ if (!this.target || !entries || entries.length === 0)
121
+ return;
122
+ // tells the dispatcher that somebody handled it: `dispatchEvent` returns false
123
+ event.preventDefault();
124
+ const detail = event.detail;
125
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
126
+ const target = path[0] || event.target;
127
+ for (const entry of [...entries])
128
+ this.handle(entry, detail, target);
129
+ };
130
+ if (!flows || typeof flows.execute !== 'function') {
131
+ throw new TypeError('dom-trigger: flows must have an execute() method');
132
+ }
133
+ this.flows = flows;
134
+ this.options = options;
135
+ this.prefix = (_a = options.prefix) !== null && _a !== void 0 ? _a : DEFAULT_PREFIX;
136
+ }
137
+ /**
138
+ * add the dom triggers of an already registered flow. Returns the event names it now listens to.
139
+ * With `{ scoped: true }` it only listens while a `scope()` that selects it is held.
140
+ */
141
+ register(flowId, triggers, opts = {}) {
142
+ const parsed = parseTriggers(flowId, triggers, opts.input);
143
+ this.assertNew(flowId, parsed);
144
+ if (!opts.scoped)
145
+ return this.add(flowId, parsed, opts.input);
146
+ return this.addScoped(flowId, parsed, opts.input, this.holdsOf(flowId));
147
+ }
148
+ /**
149
+ * register the dom triggers of every flow module of an eager glob:
150
+ * `registerModules(import.meta.glob('./flows/**\/*.ts', { eager: true }), { base: './flows', registerFlows: true })`.
151
+ * Flow ids are computed exactly like `flows.registerModules` does. Nothing is registered when a module is invalid.
152
+ * `scoped: true` registers all of them as scoped, a selector (prefix, flow ids or predicate) only the flows
153
+ * it selects: those listen only while a `scope()` holds them, and have `scoped: true` in the result.
154
+ */
155
+ registerModules(modules, opts = {}) {
156
+ const { scoped } = opts;
157
+ const isScoped = scoped === undefined || typeof scoped === 'boolean' ? () => scoped === true : toMatcher(scoped, 'the scoped option');
158
+ const seen = new Set();
159
+ const plan = resolveFlowModules(modules, opts.base).map(({ flowId, module }) => {
160
+ const parsed = parseTriggers(flowId, module.triggers === undefined ? [] : module.triggers, module.input);
161
+ this.assertNew(flowId, parsed, seen);
162
+ return {
163
+ flowId,
164
+ parsed,
165
+ input: parsed.length > 0 ? module.input : undefined,
166
+ // user predicates run here, before anything is registered, so a throwing one registers nothing
167
+ holds: parsed.length > 0 && isScoped(flowId) ? this.holdsOf(flowId) : undefined,
168
+ };
169
+ });
170
+ if (opts.registerFlows && typeof this.flows.registerModules === 'function') {
171
+ this.flows.registerModules(modules, opts.base === undefined ? {} : { base: opts.base });
172
+ }
173
+ return plan.map(({ flowId, parsed, input, holds }) => holds ? { flowId, events: this.addScoped(flowId, parsed, input, holds), scoped: true } : { flowId, events: this.add(flowId, parsed, input) });
174
+ }
175
+ /** remove the triggers of a flow (scoped ones too), abort its running and queued runs, drop the listeners nobody needs any more */
176
+ unregister(flowId) {
177
+ this.scopedFlows.delete(flowId);
178
+ this.holds.forEach((hold) => hold.held.delete(flowId));
179
+ this.remove((entry) => entry.flowId === flowId, 'flow unregistered');
180
+ }
181
+ /**
182
+ * hold the scoped flows a selector picks: a flow id prefix (`'booking/'`), an array of flow ids, or a predicate.
183
+ * They listen while at least one scope holds them. Returns the release function (idempotent): the last release
184
+ * of a flow removes its listeners and aborts its running and queued runs (status `cancelled`).
185
+ * Flows that are not scoped are never affected. A scoped flow registered later joins the scopes that select it.
186
+ * Works while stopped too: `start()` attaches the scoped flows that are held at that moment.
187
+ */
188
+ scope(selector) {
189
+ const matches = toMatcher(selector, 'the scope selector');
190
+ const hold = { matches, held: new Set() };
191
+ for (const flowId of this.scopedFlows.keys()) {
192
+ if (matches(flowId))
193
+ hold.held.add(flowId);
194
+ }
195
+ this.holds.add(hold);
196
+ hold.held.forEach((flowId) => this.acquire(flowId));
197
+ return () => {
198
+ if (!this.holds.delete(hold))
199
+ return;
200
+ const held = [...hold.held];
201
+ hold.held.clear();
202
+ held.forEach((flowId) => this.release(flowId));
203
+ };
204
+ }
205
+ /** is a run active (running or queued)? Optionally only of one flow, or of one flow's event */
206
+ isRunning(flowId, event) {
207
+ for (const { entry } of this.runs.values()) {
208
+ if ((flowId === undefined || entry.flowId === flowId) && (event === undefined || entry.event === event))
209
+ return true;
210
+ }
211
+ return false;
212
+ }
213
+ /** the element the event of an active run was dispatched on, null once the run ended */
214
+ getTarget(runId) {
215
+ const run = this.runs.get(runId);
216
+ return run ? run.target : null;
217
+ }
218
+ /** subscribe to the status of every run. Returns the unsubscribe function */
219
+ onStatus(listener) {
220
+ this.statusListeners.add(listener);
221
+ return () => {
222
+ this.statusListeners.delete(listener);
223
+ };
224
+ }
225
+ assertNew(flowId, parsed, seen) {
226
+ for (const { event } of parsed) {
227
+ const key = `${flowId}\n${event}`;
228
+ const scoped = this.scopedFlows.get(flowId);
229
+ const registered = (this.entries.get(event) || []).some((entry) => entry.flowId === flowId) || (!!scoped && scoped.triggers.some((t) => t.event === event));
230
+ if (registered || (seen && seen.has(key))) {
231
+ throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
232
+ }
233
+ if (seen)
234
+ seen.add(key);
235
+ }
236
+ }
237
+ /** the acquired scopes a scoped flow that is about to be registered joins */
238
+ holdsOf(flowId) {
239
+ return [...this.holds].filter((hold) => hold.matches(flowId));
240
+ }
241
+ addScoped(flowId, parsed, input, holds) {
242
+ if (parsed.length === 0)
243
+ return [];
244
+ let flow = this.scopedFlows.get(flowId);
245
+ if (!flow) {
246
+ flow = { triggers: [], holders: 0 };
247
+ this.scopedFlows.set(flowId, flow);
248
+ // a known scoped flow is already held by every scope that selects it
249
+ for (const hold of holds) {
250
+ if (!this.holds.has(hold) || hold.held.has(flowId))
251
+ continue;
252
+ hold.held.add(flowId);
253
+ flow.holders += 1;
254
+ }
255
+ }
256
+ flow.triggers.push(...parsed.map((p) => ({ ...p, input })));
257
+ if (flow.holders > 0)
258
+ this.add(flowId, parsed, input, true);
259
+ return parsed.map((p) => p.event);
260
+ }
261
+ acquire(flowId) {
262
+ const flow = this.scopedFlows.get(flowId);
263
+ if (!flow)
264
+ return;
265
+ flow.holders += 1;
266
+ if (flow.holders === 1)
267
+ flow.triggers.forEach((t) => this.add(flowId, [t], t.input, true));
268
+ }
269
+ release(flowId) {
270
+ const flow = this.scopedFlows.get(flowId);
271
+ if (!flow)
272
+ return;
273
+ flow.holders -= 1;
274
+ if (flow.holders === 0)
275
+ this.remove((entry) => entry.scoped && entry.flowId === flowId, 'flow scope released');
276
+ }
277
+ /** drop the matching entries, the listeners nobody needs any more, and abort their runs */
278
+ remove(match, message) {
279
+ for (const [event, list] of [...this.entries]) {
280
+ const removed = list.filter(match);
281
+ if (removed.length === 0)
282
+ continue;
283
+ const kept = list.filter((entry) => !match(entry));
284
+ if (kept.length > 0) {
285
+ this.entries.set(event, kept);
286
+ }
287
+ else {
288
+ this.entries.delete(event);
289
+ if (this.target)
290
+ this.target.removeEventListener(this.prefix + event, this.onEvent);
291
+ }
292
+ removed.forEach((entry) => this.cancelRuns(entry, message));
293
+ }
294
+ }
295
+ add(flowId, parsed, input, scoped = false) {
296
+ for (const { event, concurrency } of parsed) {
297
+ const entry = { flowId, event, concurrency, input, scoped, runs: new Set(), queue: [] };
298
+ const list = this.entries.get(event);
299
+ if (list) {
300
+ list.push(entry);
301
+ }
302
+ else {
303
+ this.entries.set(event, [entry]);
304
+ this.listen(event);
305
+ }
306
+ }
307
+ return parsed.map((p) => p.event);
308
+ }
309
+ listen(event) {
310
+ if (this.target && this.listeners) {
311
+ this.target.addEventListener(this.prefix + event, this.onEvent, { signal: this.listeners.signal });
312
+ }
313
+ }
314
+ handle(entry, rawDetail, target) {
315
+ const { flowId, event } = entry;
316
+ let runId = '';
317
+ try {
318
+ runId = (this.options.runId || defaultRunId)();
319
+ let detail = rawDetail;
320
+ if (entry.input) {
321
+ const result = validate(entry.input, detail);
322
+ if (!result.ok)
323
+ return this.report({ status: 'invalid', flowId, event, runId, error: result.error });
324
+ detail = result.data;
325
+ }
326
+ if (entry.concurrency === 'drop' && entry.runs.size > 0) {
327
+ return this.report({ status: 'dropped', flowId, event, runId });
328
+ }
329
+ const route = (this.options.route || defaultRoute)();
330
+ const data = { event, detail, runId, source: { flowId, route } };
331
+ const run = { runId, entry, data, target, controller: new AbortController(), started: false };
332
+ if (entry.concurrency === 'latest')
333
+ this.cancelRuns(entry, 'superseded by a newer event');
334
+ entry.runs.add(run);
335
+ this.runs.set(runId, run);
336
+ if (entry.concurrency === 'queue' && entry.runs.size > 1)
337
+ entry.queue.push(run);
338
+ else
339
+ this.launch(run);
340
+ }
341
+ catch (error) {
342
+ // a throwing runId() or route() option
343
+ this.report({ status: 'error', flowId, event, runId, error });
344
+ }
345
+ }
346
+ launch(run) {
347
+ const { entry, runId } = run;
348
+ let result;
349
+ run.started = true;
350
+ this.report({ status: 'running', flowId: entry.flowId, event: entry.event, runId });
351
+ try {
352
+ const scope = (this.options.scope ? this.options.scope() : undefined) || {};
353
+ result = Promise.resolve(this.flows.execute(entry.flowId, run.data, scope, { signal: run.controller.signal, runId }));
354
+ }
355
+ catch (error) {
356
+ result = Promise.reject(error);
357
+ }
358
+ // `settle` never throws, so this chain never rejects
359
+ result.then((output) => this.settle(run, 'done', output), (error) => this.settle(run, 'error', error));
360
+ }
361
+ /** end a run once. A run that was cancelled is already settled, whatever its flow does later is ignored */
362
+ settle(run, status, value) {
363
+ if (this.runs.get(run.runId) !== run)
364
+ return;
365
+ const { entry, runId } = run;
366
+ const { flowId, event } = entry;
367
+ this.runs.delete(runId);
368
+ entry.runs.delete(run);
369
+ this.report(status === 'done' ? { status, flowId, event, runId, output: value } : { status, flowId, event, runId, error: value });
370
+ if (entry.concurrency === 'queue' && run.started) {
371
+ const next = entry.queue.shift();
372
+ if (next)
373
+ this.launch(next);
374
+ }
375
+ }
376
+ cancelRuns(entry, message) {
377
+ const reason = abortError(message);
378
+ const runs = [...entry.runs];
379
+ entry.queue.length = 0;
380
+ for (const run of runs) {
381
+ run.controller.abort(reason);
382
+ this.settle(run, 'cancelled', reason);
383
+ }
384
+ }
385
+ /** tell the status listeners, and `onError` for 'error' and 'invalid'. Never throws */
386
+ report(status) {
387
+ for (const listener of [...this.statusListeners]) {
388
+ try {
389
+ listener(status);
390
+ }
391
+ catch (e) {
392
+ // a status listener must never break the trigger
393
+ }
394
+ }
395
+ if (status.status !== 'error' && status.status !== 'invalid')
396
+ return;
397
+ try {
398
+ const { flowId, event, runId } = status;
399
+ (this.options.onError || defaultOnError)(status.error, { status: status.status, flowId, event, runId });
400
+ }
401
+ catch (e) {
402
+ // neither must onError
403
+ }
404
+ }
405
+ }
@@ -0,0 +1,44 @@
1
+ import { DEFAULT_PREFIX, assertEventName, getDocument } from './names.js';
2
+ /** the CustomEvent constructor of the target's own realm (iframes), else the global one, else none (SSR) */
3
+ function customEventCtor(target) {
4
+ var _a;
5
+ const t = target;
6
+ const view = (t.ownerDocument ? t.ownerDocument.defaultView : t.defaultView) || (t.window === t ? t : undefined);
7
+ const ctor = (_a = view === null || view === void 0 ? void 0 : view.CustomEvent) !== null && _a !== void 0 ? _a : globalThis.CustomEvent;
8
+ return typeof ctor === 'function' ? ctor : undefined;
9
+ }
10
+ /** true when a DomTrigger handled the event (it called `preventDefault()`) */
11
+ function dispatch(target, prefix, name, detail) {
12
+ assertEventName(name);
13
+ const Ctor = target && customEventCtor(target);
14
+ if (!target || !Ctor)
15
+ return false;
16
+ return !target.dispatchEvent(new Ctor(prefix + name, { detail, bubbles: true, composed: true, cancelable: true }));
17
+ }
18
+ export function createEmitter(opts = {}) {
19
+ var _a;
20
+ const prefix = (_a = opts.prefix) !== null && _a !== void 0 ? _a : DEFAULT_PREFIX;
21
+ return {
22
+ emit: (target, name, detail) => dispatch(target, prefix, name, detail),
23
+ emitOnDocument: (name, detail) => dispatch(getDocument(), prefix, name, detail),
24
+ listen(target, name, fn) {
25
+ assertEventName(name);
26
+ const type = prefix + name;
27
+ const listener = (event) => fn(event.detail, event);
28
+ target.addEventListener(type, listener);
29
+ return () => target.removeEventListener(type, listener);
30
+ },
31
+ };
32
+ }
33
+ /**
34
+ * A port for `new Flows({ ports: { dom: createDomPort() } })`, so UI actions can announce what
35
+ * happened: `unsafe.dom.emit('booking.created', { id })`. Dispatches on `target` (default: the
36
+ * document, resolved on every emit). The target lives in the closure, so freezing the port is safe.
37
+ */
38
+ export function createDomPort(opts = {}) {
39
+ var _a;
40
+ const prefix = (_a = opts.prefix) !== null && _a !== void 0 ? _a : DEFAULT_PREFIX;
41
+ return {
42
+ emit: (name, detail) => { var _a; return dispatch((_a = opts.target) !== null && _a !== void 0 ? _a : getDocument(), prefix, name, detail); },
43
+ };
44
+ }
@@ -0,0 +1,4 @@
1
+ export { DomTrigger } from './dom-trigger.js';
2
+ export { createEmitter, createDomPort } from './emitter.js';
3
+ export { resolveFlowModules } from './modules.js';
4
+ export { EVENT_NAME_RE, DEFAULT_PREFIX, isEventName } from './names.js';
@@ -0,0 +1,45 @@
1
+ /** './flows/' | 'flows/' | './flows' => 'flows' */
2
+ function normalizeModulePath(p) {
3
+ return p.replace(/^(\.\/)+/, '').replace(/\/+$/, '');
4
+ }
5
+ function commonDirectory(keys) {
6
+ let common = null;
7
+ for (const key of keys) {
8
+ const dirs = key.split('/').slice(0, -1);
9
+ if (common === null) {
10
+ common = dirs;
11
+ continue;
12
+ }
13
+ let n = 0;
14
+ while (n < common.length && n < dirs.length && common[n] === dirs[n])
15
+ n++;
16
+ common = common.slice(0, n);
17
+ }
18
+ return common ? common.join('/') : '';
19
+ }
20
+ /**
21
+ * The flow modules of an eager `import.meta.glob` object with their flow ids.
22
+ * Must stay the same algorithm as `Flows#registerModules` of @codeinkit/flows 4.0.0-alpha.1
23
+ * (test/modules.test.ts has the parity test): modules without an array `default` are skipped.
24
+ */
25
+ export function resolveFlowModules(modules, base) {
26
+ const keys = Object.keys(modules);
27
+ for (const key of keys) {
28
+ if (typeof modules[key] === 'function') {
29
+ throw new TypeError(`registerModules: "${key}" is a loader function, not a module. Use import.meta.glob(pattern, { eager: true })`);
30
+ }
31
+ }
32
+ const normalized = keys.map(normalizeModulePath);
33
+ const baseDir = base !== undefined ? normalizeModulePath(base) : commonDirectory(normalized);
34
+ const prefix = baseDir === '' ? '' : `${baseDir}/`;
35
+ const resolved = [];
36
+ keys.forEach((key, index) => {
37
+ const mod = modules[key];
38
+ if (!mod || !Array.isArray(mod.default))
39
+ return;
40
+ const filePath = normalized[index];
41
+ const relativeFilePath = filePath.indexOf(prefix) === 0 ? filePath.slice(prefix.length) : filePath;
42
+ resolved.push({ flowId: relativeFilePath.split('.')[0], module: mod });
43
+ });
44
+ return resolved;
45
+ }
@@ -0,0 +1,16 @@
1
+ /** `domain.verb`: lowercase segments separated by dots, at least two of them */
2
+ export const EVENT_NAME_RE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
3
+ /** the DOM event type is `prefix + name`, e.g. `flows:booking.submit` */
4
+ export const DEFAULT_PREFIX = 'flows:';
5
+ export function isEventName(name) {
6
+ return typeof name === 'string' && EVENT_NAME_RE.test(name);
7
+ }
8
+ export function assertEventName(name) {
9
+ if (!isEventName(name)) {
10
+ throw new TypeError(`dom-trigger: invalid event name ${JSON.stringify(name)}, expected "domain.verb" (${EVENT_NAME_RE})`);
11
+ }
12
+ }
13
+ /** `globalThis.document`, undefined on the server. Never read at import time */
14
+ export function getDocument() {
15
+ return typeof document === 'undefined' ? undefined : document;
16
+ }
@@ -0,0 +1 @@
1
+ {"type":"module","sideEffects":false}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,77 @@
1
+ import type { DomTriggerOptions, FlowSelector, FlowsLike, RegisterModulesOptions, RegisterOptions, RunStatus, TriggerDef } from './types.js';
2
+ export declare class DomTrigger {
3
+ private readonly flows;
4
+ private readonly options;
5
+ private readonly prefix;
6
+ /** event name => the flows that listen to it */
7
+ private readonly entries;
8
+ /** active runs by runId */
9
+ private readonly runs;
10
+ private readonly statusListeners;
11
+ /** flows registered with `scoped`, by flow id */
12
+ private readonly scopedFlows;
13
+ /** the scopes that are acquired right now */
14
+ private readonly holds;
15
+ /** set while started */
16
+ private target;
17
+ private listeners;
18
+ constructor(flows: FlowsLike, options?: DomTriggerOptions);
19
+ /**
20
+ * add the dom triggers of an already registered flow. Returns the event names it now listens to.
21
+ * With `{ scoped: true }` it only listens while a `scope()` that selects it is held.
22
+ */
23
+ register(flowId: string, triggers: ReadonlyArray<TriggerDef | unknown>, opts?: RegisterOptions): string[];
24
+ /**
25
+ * register the dom triggers of every flow module of an eager glob:
26
+ * `registerModules(import.meta.glob('./flows/**\/*.ts', { eager: true }), { base: './flows', registerFlows: true })`.
27
+ * Flow ids are computed exactly like `flows.registerModules` does. Nothing is registered when a module is invalid.
28
+ * `scoped: true` registers all of them as scoped, a selector (prefix, flow ids or predicate) only the flows
29
+ * it selects: those listen only while a `scope()` holds them, and have `scoped: true` in the result.
30
+ */
31
+ registerModules(modules: Record<string, unknown>, opts?: RegisterModulesOptions): Array<{
32
+ flowId: string;
33
+ events: string[];
34
+ scoped?: boolean;
35
+ }>;
36
+ /** remove the triggers of a flow (scoped ones too), abort its running and queued runs, drop the listeners nobody needs any more */
37
+ unregister(flowId: string): void;
38
+ /**
39
+ * hold the scoped flows a selector picks: a flow id prefix (`'booking/'`), an array of flow ids, or a predicate.
40
+ * They listen while at least one scope holds them. Returns the release function (idempotent): the last release
41
+ * of a flow removes its listeners and aborts its running and queued runs (status `cancelled`).
42
+ * Flows that are not scoped are never affected. A scoped flow registered later joins the scopes that select it.
43
+ * Works while stopped too: `start()` attaches the scoped flows that are held at that moment.
44
+ */
45
+ scope(selector: FlowSelector): () => void;
46
+ /**
47
+ * start listening: one listener per event type on the target. Returns `stop`.
48
+ * Without a target (SSR, no document) nothing happens. Calling it twice does not subscribe twice.
49
+ */
50
+ readonly start: () => (() => void);
51
+ /** remove every listener and abort every running or queued run. `start()` works again afterwards */
52
+ readonly stop: () => void;
53
+ /** is a run active (running or queued)? Optionally only of one flow, or of one flow's event */
54
+ isRunning(flowId?: string, event?: string): boolean;
55
+ /** the element the event of an active run was dispatched on, null once the run ended */
56
+ getTarget(runId: string): EventTarget | null;
57
+ /** subscribe to the status of every run. Returns the unsubscribe function */
58
+ onStatus(listener: (status: RunStatus) => void): () => void;
59
+ private assertNew;
60
+ /** the acquired scopes a scoped flow that is about to be registered joins */
61
+ private holdsOf;
62
+ private addScoped;
63
+ private acquire;
64
+ private release;
65
+ /** drop the matching entries, the listeners nobody needs any more, and abort their runs */
66
+ private remove;
67
+ private add;
68
+ private listen;
69
+ private readonly onEvent;
70
+ private handle;
71
+ private launch;
72
+ /** end a run once. A run that was cancelled is already settled, whatever its flow does later is ignored */
73
+ private settle;
74
+ private cancelRuns;
75
+ /** tell the status listeners, and `onError` for 'error' and 'invalid'. Never throws */
76
+ private report;
77
+ }
@@ -0,0 +1,24 @@
1
+ import type { EventMap, EventMapLike } from './types.js';
2
+ export interface Emitter<M extends EventMapLike> {
3
+ /** dispatch `prefix + name` on `target`, bubbling up to the document. True when a DomTrigger handled it */
4
+ emit<K extends keyof M & string>(target: EventTarget, name: K, detail: M[K]): boolean;
5
+ /** same on the document. False, without throwing, when there is no document (SSR) */
6
+ emitOnDocument<K extends keyof M & string>(name: K, detail: M[K]): boolean;
7
+ /** listen to an announcement on `target`. Returns the teardown */
8
+ listen<K extends keyof M & string>(target: EventTarget, name: K, fn: (detail: M[K], event: CustomEvent<M[K]>) => void): () => void;
9
+ }
10
+ export declare function createEmitter<M extends EventMapLike = EventMap>(opts?: {
11
+ prefix?: string;
12
+ }): Emitter<M>;
13
+ export interface DomPort<M extends EventMapLike> {
14
+ emit<K extends keyof M & string>(name: K, detail: M[K]): boolean;
15
+ }
16
+ /**
17
+ * A port for `new Flows({ ports: { dom: createDomPort() } })`, so UI actions can announce what
18
+ * happened: `unsafe.dom.emit('booking.created', { id })`. Dispatches on `target` (default: the
19
+ * document, resolved on every emit). The target lives in the closure, so freezing the port is safe.
20
+ */
21
+ export declare function createDomPort<M extends EventMapLike = EventMap>(opts?: {
22
+ target?: EventTarget;
23
+ prefix?: string;
24
+ }): DomPort<M>;
@@ -0,0 +1,7 @@
1
+ export { DomTrigger } from './dom-trigger.js';
2
+ export { createEmitter, createDomPort } from './emitter.js';
3
+ export type { Emitter, DomPort } from './emitter.js';
4
+ export { resolveFlowModules } from './modules.js';
5
+ export type { ResolvedFlowModule } from './modules.js';
6
+ export { EVENT_NAME_RE, DEFAULT_PREFIX, isEventName } from './names.js';
7
+ export type { Concurrency, DomEventMap, DomTriggerData, DomTriggerOptions, EventMap, EventMapLike, ExecuteOptions, FlowSelector, FlowsLike, RegisterModulesOptions, RegisterOptions, RunInfo, RunStatus, RunStatusName, SchemaLike, TriggerDef, } from './types.js';
@@ -0,0 +1,10 @@
1
+ export interface ResolvedFlowModule {
2
+ flowId: string;
3
+ module: Record<string, unknown>;
4
+ }
5
+ /**
6
+ * The flow modules of an eager `import.meta.glob` object with their flow ids.
7
+ * Must stay the same algorithm as `Flows#registerModules` of @codeinkit/flows 4.0.0-alpha.1
8
+ * (test/modules.test.ts has the parity test): modules without an array `default` are skipped.
9
+ */
10
+ export declare function resolveFlowModules(modules: Record<string, unknown>, base?: string): ResolvedFlowModule[];
@@ -0,0 +1,8 @@
1
+ /** `domain.verb`: lowercase segments separated by dots, at least two of them */
2
+ export declare const EVENT_NAME_RE: RegExp;
3
+ /** the DOM event type is `prefix + name`, e.g. `flows:booking.submit` */
4
+ export declare const DEFAULT_PREFIX = "flows:";
5
+ export declare function isEventName(name: unknown): name is string;
6
+ export declare function assertEventName(name: unknown): asserts name is string;
7
+ /** `globalThis.document`, undefined on the server. Never read at import time */
8
+ export declare function getDocument(): Document | undefined;