Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 215x 215x 37x 37x 215x 72x 72x 136x 136x 72x 72x 106x 215x 48x 48x 48x 48x 48x 48x 48x 48x 9x 9x 9x 9x 9x 9x 9x 9x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 81x 4x 4x 4x 4x 4x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 81x 213x 3x 3x 213x 64x 64x 64x 213x 48x 48x 48x 213x 7x 1x 1x 6x 6x 6x 168x 89x 89x 89x 2x 2x 2x 213x 213x 213x 213x 71x 71x 81x 2x 2x 2x 2x 2x 2x 2x 69x 81x 81x 108x 2x 2x 108x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 81x 81x 81x 81x 81x 81x 81x 81x 81x 48x 1x 1x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 48x 2x 2x 2x 2x 2x 48x 48x 48x 48x 24x 24x 23x 47x 32x 32x 32x 1x 1x 1x 32x 48x 47x 2x 2x 47x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 409x 409x 409x 275x 407x 61x 61x 5x 5x 5x 5x 5x 61x 61x 214x 81x 81x 81x 81x 81x 81x 81x 81x 81x 113x 2x 2x 111x 111x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 82x 78x 78x 4x 4x 4x 4x 4x 4x 4x 82x 82x 82x 82x 82x 4x 4x 88x 88x 67x 67x 67x 67x 67x 67x 67x 270x 206x 206x 64x 64x 270x 7x 7x 7x 63x 270x 1x 1x 270x 64x 64x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 37x 4x 4x 4x 4x 4x 4x 4x 33x 33x 33x 37x 24x 24x 24x 33x 33x 33x 16x 16x 15x 15x 11x 11x 15x 33x 67x 67x 67x 67x 67x 67x 67x 67x 67x 3x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 1x 1x 6x 3x 5x 5x 67x 67x 67x 67x 67x 67x 67x 67x 326x 326x 326x 19x 19x 19x 19x 19x 19x 326x 326x 326x 234x 234x 234x 326x 233x 233x 67x 67x 67x 67x 67x 67x 67x 67x 67x 5x 5x 5x 5x 5x 5x 67x 67x 2x 2x 2x 2x 67x 67x 1x 1x 1x 1x 1x 1x 67x 67x 67x 67x 4x 4x 67x 67x 69x 56x 56x 13x 67x 67x 67x 67x 81x 48x 48x 48x 48x 48x 48x 48x 36x 36x 48x 48x 48x 48x 48x 48x 48x 48x 48x 20x 19x 19x 19x 19x 19x 20x 20x | /**
* @file bridge.js
* @description The Avenx-JS Bridge factory.
*
* A Bridge is a module-scoped, reactive unit of shared state and behaviour.
* Components reach a bridge by importing it, which is what makes the
* connection statically visible to the compiler:
*
* // src/bridges/auth.bridge.js
* import { bridge } from 'avenx-core/runtime';
*
* export default bridge({
* state: { user: null },
* get isLoggedIn() { return this.user !== null; },
* login(user) {
* this.user = user;
* this.emit('login', user);
* },
* });
*
* // any component
* import auth from '../bridges/auth.bridge.js';
* <p>{{ auth.user?.name }}</p>
*
* Two facades are built over one reactive state object:
*
* - `this` inside actions, getters and setup() can read *and* write state,
* and can emit events.
* - the exported instance can read state, call actions and subscribe with
* `on()`, but cannot assign state and cannot emit.
*
* The split is lexical rather than temporal, so it survives `await` inside an
* async action, and it gives every mutation a single traceable origin.
*/
import { StateFactory } from '../reactive/createState.js';
import { pushWatcher, popWatcher } from '../reactive/watcher.js';
import { onScopeDispose, runInScope } from '../reactive/scope.js';
import { AvenxError, AvenxErrorCodes, formatMessage } from './AvenxError.js';
import { logger } from './AvenxLogger.js';
import { tracer } from '../trace/tracer.js';
import { TraceNodeType } from '../trace/schema.js';
import { traceDerived } from '../trace/derived.js';
import { journal } from '../reactive/journal.js';
import { atomicOptions } from './atomic.js';
/**
* Marks a value as an Avenx bridge instance.
* @type {symbol}
*/
export const IS_BRIDGE = Symbol.for('avenx.bridge');
/**
* Internal channel used by the compiler to label a bridge. A symbol keeps it
* out of the member namespace that templates and `ownKeys` see.
* @type {symbol}
*/
const SET_NAME = Symbol.for('avenx.bridge.setName');
/**
* Definition keys that the Bridge API owns and a definition may not redeclare.
* @type {string[]}
*/
const RESERVED_KEYS = ['on', 'emit', '$dispose', '$name'];
/**
* Keys of the consumer-facing instance that are not bridge state.
* @type {Set<string>}
*/
const INSTANCE_API_KEYS = new Set(['on', '$dispose', '$name']);
const stateFactory = new StateFactory();
/**
* Deep-copies plain objects and arrays so a bridge never mutates the literal
* that was passed to `bridge()`. Everything else (class instances, Dates,
* functions, Maps) is intentionally shared by reference: those values are not
* made reactive either, so copying them would only be surprising.
* @param {any} value - The value to copy.
* @returns {any} A copy for plain containers, or the original value.
*/
function cloneInitial(value) {
if (Array.isArray(value)) {
return value.map(cloneInitial);
}
if (value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
const copy = {};
for (const key of Object.keys(value)) {
copy[key] = cloneInitial(value[key]);
}
return copy;
}
return value;
}
/**
* Runs a function outside of any reactive watcher, so reads performed inside it
* are not attributed to whichever render happened to trigger it.
* @template T
* @param {function(): T} fn - The function to run untracked.
* @returns {T} Whatever `fn` returned.
*/
function untracked(fn) {
pushWatcher(null);
try {
return fn();
} finally {
popWatcher();
}
}
/**
* Creates a Bridge: a reactive unit of shared state and behaviour that
* components consume by importing it.
* @param {object} definition - The bridge definition.
* @param {object} [definition.state] - Initial shared state. Reactive, read-only for consumers.
* @param {Function} [definition.setup] - Lazy initializer run on first use. May return a cleanup function.
* @returns {object} The bridge instance to export from the module.
*/
export function bridge(definition) {
if (definition === null || typeof definition !== 'object' || Array.isArray(definition)) {
throw new AvenxError(
AvenxErrorCodes.BRIDGE_INVALID_DEFINITION,
definition === null ? 'null' : Array.isArray(definition) ? 'an array' : typeof definition,
);
}
const descriptors = Object.getOwnPropertyDescriptors(definition);
/**
* Getter name to getter implementation.
* @type {Map<string, Function>}
*/
const getters = new Map();
/**
* Action name to raw implementation.
* @type {Map<string, Function>}
*/
const rawActions = new Map();
/** @type {Function|null} */
let setupFn = null;
for (const [key, descriptor] of Object.entries(descriptors)) {
if (RESERVED_KEYS.includes(key)) {
throw new AvenxError(AvenxErrorCodes.BRIDGE_RESERVED_KEY, key, RESERVED_KEYS.join(', '));
}
if (key === 'state') {
if (descriptor.get) {
throw new AvenxError(AvenxErrorCodes.BRIDGE_RESERVED_KEY, 'state', 'state must be a plain object, not a getter');
}
continue;
}
if (descriptor.get) {
getters.set(key, descriptor.get);
continue;
}
if (key === 'setup') {
if (typeof descriptor.value !== 'function') {
throw new AvenxError(AvenxErrorCodes.BRIDGE_INVALID_MEMBER, 'setup', typeof descriptor.value, 'setup');
}
setupFn = descriptor.value;
continue;
}
if (typeof descriptor.value === 'function') {
rawActions.set(key, descriptor.value);
continue;
}
throw new AvenxError(
AvenxErrorCodes.BRIDGE_INVALID_MEMBER,
key,
descriptor.value === null ? 'null' : typeof descriptor.value,
key,
);
}
const initialState = definition.state;
if (initialState !== undefined && (initialState === null || typeof initialState !== 'object' || Array.isArray(initialState))) {
throw new AvenxError(
AvenxErrorCodes.BRIDGE_INVALID_MEMBER,
'state',
initialState === null ? 'null' : Array.isArray(initialState) ? 'array' : typeof initialState,
'state',
);
}
const stateKeys = initialState ? Object.keys(initialState) : [];
for (const key of stateKeys) {
if (getters.has(key) || rawActions.has(key)) {
throw new AvenxError(AvenxErrorCodes.BRIDGE_RESERVED_KEY, key, 'state keys must not collide with actions or getters');
}
}
/**
* Debug label; set by the compiler through defineBridgeName().
* @type {string}
*/
let name = 'bridge';
/** @type {Map<string, Set<Function>>} */
const listeners = new Map();
/**
* Cleanup returned by setup().
* @type {Function|null}
*/
let cleanupFn = null;
/** @type {boolean} */
let initialized = false;
/** @type {boolean} */
let initializing = false;
/**
* The reactive state proxy.
* @type {object}
*/
const state = stateFactory.create(cloneInitial(initialState) || {});
/**
* Broadcasts an event to every listener. Available on `this` inside the
* bridge only: consumers observe events, they do not fabricate them.
* @param {string} event - The event name.
* @param {any} [payload] - The value handed to each listener.
*/
const emit = (event, payload) => {
if (typeof event !== 'string' || event.length === 0) {
throw new AvenxError(AvenxErrorCodes.BRIDGE_INVALID_EVENT, `emitted by "${name}"`, typeof event, typeof payload);
}
const handlers = listeners.get(event);
// Recorded before the no-listener shortcut below: an emit that nobody was
// subscribed to is exactly the kind of thing a developer opens a trace to
// discover, so it is worth a node even though it does nothing.
//
// An emit opens a scope rather than recording a leaf, so whatever the
// listeners go on to write belongs under the event that notified them
// rather than under whichever action happened to be running.
const emitToken = tracer.on
? tracer.enter(TraceNodeType.BRIDGE_EMIT, {
bridge: name,
event,
listeners: handlers ? handlers.size : 0,
payload: tracer.sink.capture(payload, `${name}.${event}`),
})
: -1;
try {
if (!handlers || handlers.size === 0) {
return;
}
// Copy: a listener may unsubscribe itself or others while running.
for (const handler of [...handlers]) {
try {
handler(payload);
} catch (error) {
// One faulty listener must not stop the others.
logger.error(formatMessage(AvenxErrorCodes.BRIDGE_LISTENER_ERROR, name, event, error));
}
}
} finally {
if (emitToken >= 0) {
tracer.leave(emitToken);
}
}
};
/**
* Stable bound action identities.
* @type {Map<string, Function>}
*/
const boundActions = new Map();
/**
* Resolves a member on the write-capable facade.
* @param {string|symbol} key - The member name.
* @returns {any} The resolved value.
*/
const readSelf = (key) => {
if (key === 'emit') return emit;
if (typeof key !== 'string') return undefined;
if (boundActions.has(key)) return boundActions.get(key);
const getter = getters.get(key);
if (getter) {
const value = getter.call(self);
if (tracer.on) {
// A bridge getter has no cache of its own, so this runs on every read.
// traceDerived records it only when the answer changed, which is the
// only form in which a derived value explains anything.
traceDerived(self, { name: key, kind: 'getter', owner: name }, value);
}
return value;
}
return state[key];
};
/**
* The write-capable facade bound to `this` inside actions, getters and setup.
* @type {object}
*/
const self = new Proxy(Object.create(null), {
get: (_target, key) => readSelf(key),
set: (_target, key, value) => {
if (typeof key === 'string' && (getters.has(key) || boundActions.has(key) || key === 'emit')) {
throw new AvenxError(AvenxErrorCodes.BRIDGE_RESERVED_KEY, key, 'actions and getters are not assignable');
}
state[key] = value;
return true;
},
has: (_target, key) => key === 'emit' || getters.has(key) || boundActions.has(key) || key in state,
deleteProperty: (_target, key) => {
delete state[key];
return true;
},
ownKeys: () => [...new Set([...Object.keys(state), ...getters.keys()])],
getOwnPropertyDescriptor: (_target, key) => {
if (typeof key !== 'string' || !(getters.has(key) || key in state)) {
return undefined;
}
return { enumerable: true, configurable: true, writable: true, value: readSelf(key) };
},
});
for (const [key, fn] of rawActions) {
// Declared with atomic(), so every write this action makes is journaled
// and undone if it fails. Resolved once, here, so an action that is not
// atomic does not pay a closure for the branch on every call.
const transaction = atomicOptions(fn);
const spec = transaction ? { owner: name, name: key, onConflict: transaction.onConflict } : null;
/**
* Invokes the action, inside a transaction when it was declared atomic.
* @param {any[]} args - The call arguments.
* @returns {any} Whatever the action returned.
*/
const runner = spec ? (args) => journal.run(spec, () => fn.apply(self, args)) : (args) => fn.apply(self, args);
boundActions.set(key, (...args) => {
if (!tracer.on) {
return runner(args);
}
// A bridge is the only place shared state may be written, so a bridge
// action is the single traceable origin of every mutation it makes.
// Opening a node here is what lets a trace read
// "cart.addQty(id, 1) -> write cart.items.2.qty".
const token = tracer.enter(TraceNodeType.BRIDGE_ACTION, {
bridge: name,
name: key,
args: args.length > 0 ? tracer.sink.capture(args, `${name}.${key}.args`) : undefined,
});
try {
return runner(args);
} finally {
tracer.leave(token);
}
});
}
/**
* Runs setup() on first use. Detached from the caller's reactive watcher and
* disposal scope: a bridge belongs to the module, not to whichever component
* happened to touch it first.
*/
const ensureInitialized = () => {
if (initialized || initializing) {
return;
}
initializing = true;
try {
if (setupFn) {
const cleanup = runInScope(null, () => untracked(() => setupFn.call(self)));
cleanupFn = typeof cleanup === 'function' ? cleanup : null;
}
initialized = true;
} catch (error) {
initialized = true;
throw new AvenxError(AvenxErrorCodes.BRIDGE_SETUP_FAILED, name, error && error.message ? error.message : error);
} finally {
initializing = false;
}
};
/**
* Subscribes to a bridge event.
*
* When called while a component's disposal scope is active — that is, from a
* lifecycle hook or an event handler — the subscription is released
* automatically on unmount. The returned function unsubscribes early.
* @param {string} event - The event name to listen for.
* @param {Function} handler - Invoked with the emitted payload.
* @returns {Function} Unsubscribe function. Safe to call more than once.
*/
const on = (event, handler) => {
if (typeof event !== 'string' || event.length === 0 || typeof handler !== 'function') {
throw new AvenxError(
AvenxErrorCodes.BRIDGE_INVALID_EVENT,
`subscription on "${name}"`,
typeof event,
typeof handler,
);
}
ensureInitialized();
let handlers = listeners.get(event);
if (!handlers) {
handlers = new Set();
listeners.set(event, handlers);
}
handlers.add(handler);
return onScopeDispose(() => {
const current = listeners.get(event);
if (current) {
current.delete(handler);
if (current.size === 0) {
listeners.delete(event);
}
}
});
};
/**
* Releases everything the bridge holds: the cleanup returned by setup(), all
* event listeners, and any state changes. The bridge stays usable — the next
* access re-runs setup() with the original state. This makes bridges safe to
* reuse across tests and across hot reloads.
*/
const $dispose = () => {
if (cleanupFn) {
const cleanup = cleanupFn;
cleanupFn = null;
try {
untracked(() => cleanup());
} catch (error) {
logger.error(formatMessage(AvenxErrorCodes.BRIDGE_SETUP_FAILED, name, error && error.message ? error.message : error));
}
}
listeners.clear();
initialized = false;
// Reset in place rather than building a fresh reactive object. A new object
// would strand every watcher that already tracked the old one — consumers
// would silently stop updating — and it would hide the reset from anyone
// currently rendering. Writing through the existing proxy keeps identity
// stable and notifies dependents that the state reverted.
const defaults = cloneInitial(initialState) || {};
for (const key of Object.keys(state)) {
if (!Object.prototype.hasOwnProperty.call(defaults, key)) {
delete state[key];
}
}
for (const [key, value] of Object.entries(defaults)) {
state[key] = value;
}
};
/**
* Resolves a member on the consumer-facing instance.
* @param {string|symbol} key - The member name.
* @returns {any} The resolved value.
*/
const readInstance = (key) => {
if (key === IS_BRIDGE) return true;
if (key === '$name') return name;
if (key === SET_NAME) {
return (bridgeName) => {
if (typeof bridgeName === 'string' && bridgeName.length > 0) {
name = bridgeName;
}
};
}
if (typeof key !== 'string') return undefined;
if (key === 'on') return on;
if (key === '$dispose') return $dispose;
// Emission is the bridge's own capability: consumers observe events, they
// never fabricate them. Keeping `emit` off the instance is what makes the
// direction of a bridge unambiguous.
if (key === 'emit') return undefined;
ensureInitialized();
return readSelf(key);
};
/**
* The consumer-facing bridge instance.
* @type {object}
*/
const instance = new Proxy(Object.create(null), {
get: (_target, key) => readInstance(key),
set: (_target, key) => {
throw new AvenxError(
AvenxErrorCodes.BRIDGE_READONLY_STATE,
name,
String(key),
`${name}.someAction(value)`,
);
},
has: (_target, key) =>
key === IS_BRIDGE ||
INSTANCE_API_KEYS.has(key) ||
getters.has(key) ||
boundActions.has(key) ||
key in state,
deleteProperty: (_target, key) => {
throw new AvenxError(
AvenxErrorCodes.BRIDGE_READONLY_STATE,
name,
String(key),
`${name}.someAction(value)`,
);
},
// Spreading or serialising a bridge yields a snapshot of its data, not its
// API surface: {...auth} and JSON.stringify(auth) both give state.
ownKeys: () => {
ensureInitialized();
return [...new Set([...Object.keys(state), ...getters.keys()])];
},
getOwnPropertyDescriptor: (_target, key) => {
if (typeof key !== 'string' || !(getters.has(key) || key in state)) {
return undefined;
}
return { enumerable: true, configurable: true, writable: false, value: readInstance(key) };
},
});
return instance;
}
/**
* Reports whether a value is a bridge instance created by {@link bridge}.
* @param {any} value - The value to test.
* @returns {boolean} True when the value is a bridge instance.
*/
export function isBridge(value) {
return !!(value && (typeof value === 'object' || typeof value === 'function') && value[IS_BRIDGE] === true);
}
/**
* Assigns a bridge its diagnostic name. Emitted by the compiler alongside each
* bridge definition so error messages and devtools can identify it.
* @param {string} name - The bridge name, derived from its file name.
* @param {object} instance - The bridge instance.
* @returns {object} The same instance, for convenient chaining.
*/
export function defineBridgeName(name, instance) {
if (isBridge(instance)) {
const setName = instance[SET_NAME];
if (typeof setName === 'function') {
setName(name);
}
}
return instance;
}
|