MCPcopy
hub / github.com/statelyai/xstate / evaluateGuard

Function evaluateGuard

packages/core/src/guards.ts:337–395  ·  view source on GitHub ↗
(
  guard: UnknownGuard | UnknownInlineGuard,
  context: TContext,
  event: TExpressionEvent,
  snapshot: AnyMachineSnapshot
)

Source from the content-addressed store, hash-verified

335
336// TODO: throw on cycles (depth check should be enough)
337export function evaluateGuard<
338 TContext extends MachineContext,
339 TExpressionEvent extends EventObject
340>(
341 guard: UnknownGuard | UnknownInlineGuard,
342 context: TContext,
343 event: TExpressionEvent,
344 snapshot: AnyMachineSnapshot
345): boolean {
346 const { machine } = snapshot;
347 const isInline = typeof guard === 'function';
348
349 const resolved = isInline
350 ? guard
351 : machine.implementations.guards[
352 typeof guard === 'string' ? guard : guard.type
353 ];
354
355 if (!isInline && !resolved) {
356 throw new Error(
357 `Guard '${
358 typeof guard === 'string' ? guard : guard.type
359 }' is not implemented.'.`
360 );
361 }
362
363 if (typeof resolved !== 'function') {
364 return evaluateGuard(resolved!, context, event, snapshot);
365 }
366
367 const guardArgs = {
368 context,
369 event
370 };
371
372 const guardParams =
373 isInline || typeof guard === 'string'
374 ? undefined
375 : 'params' in guard
376 ? typeof guard.params === 'function'
377 ? guard.params({ context, event })
378 : guard.params
379 : undefined;
380
381 if (!('check' in resolved)) {
382 // the existing type of `.guards` assumes non-nullable `TExpressionGuard`
383 // inline guards expect `TExpressionGuard` to be set to `undefined`
384 // it's fine to cast this here, our logic makes sure that we call those 2 "variants" correctly
385 return resolved(guardArgs, guardParams as never);
386 }
387
388 const builtinGuard = resolved as unknown as BuiltinGuard;
389
390 return builtinGuard.check(
391 snapshot,
392 guardArgs,
393 resolved // this holds all params
394 );

Callers 6

nextMethod · 0.90
resolveEnqueueActionsFunction · 0.90
checkNotFunction · 0.85
checkAndFunction · 0.85
checkOrFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected