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