# Validate connections

Use connection validation when your editor needs typed wires, per-port capacity limits, or a directed graph that stays acyclic. Declare the ports in specs, let the engine enforce their anatomy and data types, and add a validator for your domain rules.

This page starts from the project in your [JavaScript](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start), or [Qwik quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start). Keep its entry files, configuration, and stylesheet imports. The examples below add a shared module and a view; render that view from your existing app or route.

## Connection validation

The sample draws A → B → C, with blue number ports, a purple string input, and a destination labelled Restricted. Number-to-string connections are refused by the declared types. C's input accepts at most two wires; the initial B → C wire occupies one slot. A custom rule refuses connections to Restricted with a reason.

1. Use the packages installed by your quick start. If you add this to another project, install the matching binding and its Grafloria peers:

   JavaScript:
   ```bash
   npm install @grafloria/element @grafloria/renderer @grafloria/engine
   ```
   React:
   ```bash
   npm install @grafloria/react @grafloria/element @grafloria/renderer @grafloria/engine
   ```
   Vue:
   ```bash
   npm install @grafloria/vue @grafloria/element @grafloria/renderer @grafloria/engine
   ```
   Angular:
   ```bash
   npm install @grafloria/angular @grafloria/element @grafloria/renderer @grafloria/engine
   ```
   Qwik:
   ```bash
   npm install -D @grafloria/qwik @grafloria/element @grafloria/renderer @grafloria/engine
   ```

2. Add the shared data and rules in `src/connections.ts` (Angular: `src/app/connections.ts`). [`NodeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-nodespec) holds each node's [`PortSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-portspec); [`EdgeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-edgespec) pins the initial wires to their handles.

   Register data types through [`portTypeRegistry`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-ports#porttyperegistry-constant), the process-wide [`PortTypeRegistry`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-ports#porttyperegistry-class). Its `registerAll()` gives the glyphs their colors. Equal type names are compatible even without `compatibleWith`; that list permits additional, directional conversions. An untyped port or `'*'` accepts either data type.

   [`registerConnectionValidator`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#registerconnectionvalidator) accepts the renderer's [`ConnectionValidator`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-types#connectionvalidator): one candidate containing both nodes, nullable ports, and an optional `link` during reconnection. Return `true` to allow, `false` to refuse without a message, or a reason string to refuse with a message. Every registered validator must pass.

   ```ts title="src/connections.ts"
   import { portTypeRegistry } from '@grafloria/engine';
   import type { DiagramModel } from '@grafloria/engine';
   import { registerConnectionValidator } from '@grafloria/renderer';
   import type {
     ConnectionValidator, DiagramInstance, EdgeSpec, NodeSpec,
   } from '@grafloria/renderer';

   export function registerDataTypes(): void {
     portTypeRegistry.registerAll([
       { name: 'number', color: '#2563eb' },
       { name: 'string', color: '#9333ea' },
     ]);
   }

   export const nodes: NodeSpec[] = [
     ...['a', 'b', 'c'].map((id, index): NodeSpec => ({
       id, label: id.toUpperCase(),
       position: { x: 60 + index * 220, y: 100 },
       size: { width: 140, height: 70 },
       ports: [
         { id: `${id}.in`, side: 'left', type: 'input', dataType: 'number',
           ...(id === 'c' ? { maxConnections: 2 } : {}) },
         { id: `${id}.out`, side: 'right', type: 'output', dataType: 'number' },
       ],
     })),
     { id: 'text', label: 'String input',
       position: { x: 500, y: 260 }, size: { width: 140, height: 70 },
       ports: [{ id: 'text.in', side: 'left', type: 'input', dataType: 'string' }] },
     { id: 'restricted', label: 'Restricted',
       position: { x: 280, y: 260 }, size: { width: 140, height: 70 },
       ports: [{ id: 'restricted.in', side: 'left', type: 'input', dataType: 'number' }] },
   ];

   export const edges: EdgeSpec[] = [
     { id: 'ab', source: 'a', target: 'b', sourceHandle: 'a.out', targetHandle: 'b.in' },
     { id: 'bc', source: 'b', target: 'c', sourceHandle: 'b.out', targetHandle: 'c.in' },
   ];

   export function reaches(
     model: DiagramModel, fromId: string, toId: string, excludedLinkId?: string,
   ): boolean {
     const seen = new Set<string>();
     const stack = [fromId];
     while (stack.length) {
       const current = stack.pop()!;
       if (current === toId) return true;
       if (seen.has(current)) continue;
       seen.add(current);
       for (const link of model.getLinks()) {
         if (link.id === excludedLinkId) continue;
         const source = model.getNodeByPortId(link.sourcePortId)?.id;
         const target = model.getNodeByPortId(link.targetPortId)?.id;
         if (source === current && target) stack.push(target);
       }
     }
     return false;
   }

   export function attachRules(
     instance: Pick<DiagramInstance, 'getModel' | 'getEngine'>,
     report: (message: string) => void,
   ): () => void {
     const model = instance.getModel();
     const engine = instance.getEngine();
     const restricted: ConnectionValidator = ({ sourceNode, targetNode }) => {
       if (model.getNode(sourceNode.id) !== sourceNode) return true;
       return targetNode.id === 'restricted' ? 'This destination is restricted.' : true;
     };
     const noCycles: ConnectionValidator = ({ sourceNode, targetNode, link }) => {
       if (model.getNode(sourceNode.id) !== sourceNode) return true;
       return reaches(model, targetNode.id, sourceNode.id, link?.id)
         ? 'This connection would create a cycle.' : true;
     };
     const removeRestricted = registerConnectionValidator(restricted);
     const removeCycles = registerConnectionValidator(noCycles);
     const names = [
       'connection:start', 'connection:update', 'connection:port-enter',
       'connection:port-leave', 'connection:complete', 'connection:cancel',
     ];
     const listeners = names.map(name => {
       const listener = (): void => {
         const reason = engine.getConnectionStateManager().getState().rejectionMessage;
         report(`${name}${reason ? `: ${reason}` : ''}`);
       };
       engine.on(name, listener);
       return () => engine.off(name, listener);
     });
     return () => {
       removeRestricted();
       removeCycles();
       listeners.forEach(remove => remove());
     };
   }
   ```

   The [`DiagramModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-diagrammodel) query uses the current links, not the original edge array. The identity check scopes each process-global validator to this model.

3. Mount the view and keep the returned cleanup until unmount. [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) gives you the live model and engine. These views keep a bounded event log; they do not replace it with a timer or a click-only counter.

   Add `attachRules()` and the connection log to the mounted view; see [Edit nodes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/edit-nodes) for the framework mounting and state-binding patterns.

   :::code-group
   ```ts title="JavaScript"
   // src/main.ts — retain the quick start's stylesheet imports.
   import { render } from '@grafloria/element';
   import { attachRules, edges, nodes, registerDataTypes } from './connections';
   import { connectForward } from './connect-forward';
   import { auditLinks } from './audit-links';

   const app = document.querySelector<HTMLElement>('#app')!;
   const close = document.createElement('button');
   close.textContent = 'Close diagram';
   const log = document.createElement('pre');
   log.textContent = 'Drag a port to begin.';
   const host = document.createElement('div');
   host.style.height = '420px';
   app.append(close, log, host);
   registerDataTypes();
   const instance = render({ nodes, edges }, host, {
     interaction: { portVisibility: 'always' },
   });
   const messages: string[] = [];
   const report = (message: string): void => {
     messages.push(message);
     log.textContent = messages.slice(-8).join('\n');
   };
   const removeRules = attachRules(instance, report);
   const removeConnect = instance.on('connect', ({ link }) => report(`connect: ${link.id}`));
   const forward = document.createElement('button');
   forward.textContent = 'Connect A to C';
   const audit = document.createElement('button');
   audit.textContent = 'Audit links';
   app.insertBefore(forward, host);
   app.insertBefore(audit, host);
   forward.addEventListener('click', () => {
     report(connectForward(instance) ? 'Forward connection accepted.' : 'Forward connection refused.');
   });
   audit.addEventListener('click', () => {
     report(JSON.stringify(auditLinks(instance), null, 2));
   });
   close.addEventListener('click', () => {
     removeConnect();
     removeRules();
     instance.dispose();
     host.remove();
     close.disabled = true;
     forward.disabled = true;
     audit.disabled = true;
   });
   ```
   ```tsx title="React"
   // src/ConnectionView.tsx
   import { useEffect, useRef, useState } from 'react';
   import { GrafloriaFlow } from '@grafloria/react';
   import type { DiagramInstance } from '@grafloria/renderer';
   import { attachRules, edges, nodes, registerDataTypes } from './connections';

   export default function ConnectionView() {
     const [ready, setReady] = useState(false);
     const [messages, setMessages] = useState<string[]>([]);
     const cleanup = useRef<(() => void) | null>(null);
     const report = (message: string): void => {
       setMessages(previous => [...previous, message].slice(-8));
     };
     useEffect(() => {
       registerDataTypes();
       setReady(true);
       return () => { cleanup.current?.(); cleanup.current = null; };
     }, []);
     const onInit = (instance: DiagramInstance): void => {
       cleanup.current?.();
       cleanup.current = attachRules(instance, report);
     };
     return <section>
       <pre>{messages.join('\n') || 'Drag a port to begin.'}</pre>
       <div style={{ height: 420 }}>
         {ready && <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
           interaction={{ portVisibility: 'always' }} onInit={onInit}
           onConnect={({ link }) => report(`connect: ${link.id}`)} />}
       </div>
     </section>;
   }
   ```
   ```vue title="Vue"
   <!-- src/ConnectionView.vue -->
   <script setup lang="ts">
   import { onBeforeUnmount, ref } from 'vue';
   import { GrafloriaFlow } from '@grafloria/vue';
   import type { LinkModel } from '@grafloria/engine';
   import type { DiagramInstance } from '@grafloria/renderer';
   import { attachRules, edges, nodes, registerDataTypes } from './connections';

   registerDataTypes();
   const messages = ref<string[]>([]);
   let cleanup: (() => void) | undefined;
   function report(message: string): void {
     messages.value = [...messages.value, message].slice(-8);
   }
   function onInit(instance: DiagramInstance): void {
     cleanup?.();
     cleanup = attachRules(instance, report);
   }
   function onConnect(event: { link: LinkModel }): void {
     report(`connect: ${event.link.id}`);
   }
   onBeforeUnmount(() => cleanup?.());
   </script>
   <template>
     <section>
       <pre>{{ messages.join('\n') || 'Drag a port to begin.' }}</pre>
       <div style="height:420px">
         <GrafloriaFlow :default-nodes="nodes" :default-edges="edges"
           :interaction="{ portVisibility: 'always' }"
           @init="onInit" @connect="onConnect" />
       </div>
     </section>
   </template>
   ```
   ```ts title="Angular"
   // src/app/connection-view.component.ts
   import { Component, DestroyRef, inject, signal } from '@angular/core';
   import { DiagramCanvasComponent } from '@grafloria/angular';
   import type { GrafloriaCanvasInstance } from '@grafloria/angular';
   import { PortVisibilityStrategy } from '@grafloria/engine';
   import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
   import { attachRules, edges, nodes, registerDataTypes } from './connections';

   @Component({
     selector: 'app-connection-view',
     imports: [DiagramCanvasComponent],
     template: `
       <pre>{{ messages().join('\n') || 'Drag a port to begin.' }}</pre>
       <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
         (ready)="onReady($event)" style="display:block;height:420px" />
     `,
   })
   export class ConnectionViewComponent {
     readonly nodes = signal<NodeSpec[]>(nodes);
     readonly edges = signal<EdgeSpec[]>(edges);
     readonly messages = signal<string[]>([]);
     private cleanup: (() => void) | undefined;
     private removeConnect: (() => void) | undefined;

     constructor() {
       registerDataTypes();
       inject(DestroyRef).onDestroy(() => {
         this.removeConnect?.();
         this.cleanup?.();
       });
     }
     onReady(instance: GrafloriaCanvasInstance): void {
       instance.getEngine().setInteractionConfig({ portVisibility: PortVisibilityStrategy.ALWAYS });
       this.removeConnect?.();
       this.cleanup?.();
       this.cleanup = attachRules(instance, message => this.report(message));
       this.removeConnect = instance.on('connect', ({ link }) => this.report(`connect: ${link.id}`));
     }
     private report(message: string): void {
       this.messages.update(previous => [...previous, message].slice(-8));
     }
   }
   ```
   ```tsx title="Qwik"
   // src/ConnectionView.qwik.tsx
   import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
   import type { NoSerialize } from '@builder.io/qwik';
   import { GrafloriaFlow } from '@grafloria/qwik';
   import { attachRules, edges, nodes, registerDataTypes } from './connections';

   export default component$(() => {
     const ready = useSignal(false);
     const messages = useSignal<string[]>([]);
     const removeRules = useSignal<NoSerialize<() => void>>();
     useVisibleTask$(({ cleanup }) => {
       registerDataTypes();
       ready.value = true;
       cleanup(() => removeRules.value?.());
     });
     return <section>
       <pre>{messages.value.join('\n') || 'Drag a port to begin.'}</pre>
       <div style={{ height: '420px' }}>
         {ready.value && <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
           interaction={{ portVisibility: 'always' }}
           onInit$={instance => {
             removeRules.value?.();
             removeRules.value = noSerialize(attachRules(instance, (message: string) => {
               messages.value = [...messages.value, message].slice(-8);
             }));
           }}
           onConnect$={({ link }) => {
             messages.value = [...messages.value, `connect: ${link.id}`].slice(-8);
           }} />}
       </div>
     </section>;
   });
   ```
   :::

   Render the exported Qwik view from your existing route. Angular sets visibility with [`PortVisibilityStrategy`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-config#portvisibilitystrategy): `ALWAYS` draws ports continuously, `ON_HOVER` reveals them on hover, and `HIDDEN` hides idle ports.

   The JavaScript view starts with the chain and three controls above the canvas.

   ![A → B → C above Restricted and String input, with Close diagram, Connect A to C, and Audit links controls.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/620bbf608474ee0864ffe8acd37c8f62.png)

   The React view starts with the drag prompt above the same typed graph.

   ![React's initial A → B → C chain, blue number ports, and purple String input port.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/d7177b981549ada31dbe7d1aa7f1cd97.png)

   The Vue view shows the same initial graph and prompt. The Angular view starts with the chain and both additional destinations.

4. Press A's right port, drag to C's left port, and release. A → C fills C's remaining slot. A further wire to that input is refused. Try the String input and Restricted destinations: neither attempt creates a wire. The log records the refused drag and its reason during `connection:update`.

Compare the running [Typed ports](https://grafloria.com/demos/ports/typed-ports.html), [Connection limit](https://grafloria.com/demos/nodes/connection-limit.html), and [port validation](https://grafloria.com/demos/ports/connection-validation.html) demos. The [interaction validation demo](https://grafloria.com/demos/interaction/validation.html) shows validation in the connection gesture.

### Options that matter

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `PortSpec.type` | `'input' \| 'output' \| 'bi'` | `'bi'` | Sets direction. Two inputs or two outputs cannot attach to one another; a `bi` port can pair with either. |
| `PortSpec.dataType` | `string` | Unset | Gives the port a named data-flow type and registered color. |
| `PortSpec.maxConnections` | `number` | Unlimited | Caps the total wires attached to this port. |
| `PortSpec.gating.fromMaxLinks` | `number \| null` | Unlimited | Caps outgoing wires. |
| `PortSpec.gating.toMaxLinks` | `number \| null` | Unlimited | Caps incoming wires. |
| `PortSpec.gating.isConnectableStart` / `isConnectableEnd` | `boolean` | `true` | Separately disables starting or receiving a wire. |
| `PortSpec.gating.allowSelfLink` | `boolean` | `false` | Permits same-node links when both endpoints allow them. |
| `PortSpec.gating.allowDuplicateLinks` | `boolean` | `true` | Set to `false` to refuse a second link between the same ports, including the reverse direction. |
| `PortSpec.gating.allowedTypes` | `string[]` | No restriction | Restricts the data-type or system-type identities that may attach. |
| `interaction.portVisibility` | `'always' \| 'on-hover' \| 'never' \| 'hidden'` | `'on-hover'` | `always` draws ports continuously; `on-hover` reveals them on node hover or as connection targets; `never` and `hidden` draw only highlighted or valid target ports. |

For port positioning, glyphs, labels, groups, and attachment spots, use [Arrange ports and connect](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/ports-and-connection-gestures).

For a node's connection-group identity, `setConnectionGroup(group)` stores the group string, tracks the change, and emits `connection-group:changed`; `getConnectionGroup()` returns that string, or `undefined` when no group is assigned. These are methods on the live node, not port-group layout settings.

## Preventing cycles

1. Keep the `noCycles` validator in `attachRules()` above. It follows directed links from the proposed target to the proposed source. If that path already exists, adding the new edge closes a loop.
2. In any of the mounted views, drag C's right port to A's left port. The validator returns `This connection would create a cycle.` and the model retains A → B → C without a back edge.
3. Try A → C instead while C has capacity. That forward edge is allowed. Moving the boxes does not change reachability.

This cycle guard applies to new-wire connection gestures. Endpoint reconnection checks endpoint identity, direction, and connection groups separately. See the [Preventing cycles demo](https://grafloria.com/demos/interaction/preventing-cycles.html) for a longer chain of new-wire attempts.

### Connect from your own control

To exercise the same rendered instance from a button, use its [`InteractionController`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-interactioncontroller). Add this module and wire it into the JavaScript view below; do not create a separate controller or model.

```ts title="src/connect-forward.ts"
import type { DiagramInstance } from '@grafloria/renderer';

export function connectForward(instance: DiagramInstance): boolean {
  const model = instance.getModel();
  const source = model.getNode('a');
  const target = model.getNode('c');
  const sourcePort = source?.getPort('a.out');
  const targetPort = target?.getPort('c.in');
  if (!source || !target || !sourcePort || !targetPort) return false;
  const engine = instance.getEngine();
  const start = sourcePort.getAbsolutePosition(source.getBoundingBox());
  const end = targetPort.getAbsolutePosition(target.getBoundingBox());
  instance.interaction.startConnection(sourcePort, start.x, start.y, engine);
  instance.interaction.handleMouseMove(end.x, end.y, engine);
  instance.interaction.handleConnectionDrag(end.x, end.y, engine);
  return instance.interaction.completeConnection(engine);
}
```

The JavaScript view above imports this module and binds its Connect A to C button to `connectForward()`. Add the audit module below too before running that view.

`completeConnection()` returns a boolean for acceptance; the engine creates and routes the actual link asynchronously. Use the view's `connect` callback or subscription to react to the created [`LinkModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-linkmodel), rather than querying for it immediately after the call.

## Connection events

1. Keep the lifecycle listeners in the runnable `attachRules()` sample. These six events belong to the engine, so subscribe through `getEngine().on()` and remove each listener with `off()`.
2. Drag from A's output over an input, move away, and release on a valid input. The log records start, updates, target transitions, and completion.
3. Begin another drag and press Escape, or release over empty canvas. The log records cancellation rather than completion; no wire is added.

| Event | What the reader gets |
| --- | --- |
| `connection:start` | The source port, start point, and valid target port IDs. |
| `connection:update` | The current point and target, validity, rejection reason, and readable `rejectionMessage`. |
| `connection:port-enter` | The newly entered port and its validity and rejection information. |
| `connection:port-leave` | The port the pointer left. |
| `connection:complete` | The accepted source and target ports and their IDs. |
| `connection:cancel` | The source of an abandoned or refused drag. |

Completion and cancellation split the drag's end by outcome. The component's `onConnect`, `@connect`, or `onConnect$` callback reports the created link; Angular's instance subscription serves the same purpose because the canvas has no corresponding output. The lower-level lifecycle listeners report the gesture before that link notification. Watch the [Connection events demo](https://grafloria.com/demos/interaction/connection-events.html) to see the stream while dragging.

## Validate existing links

Drag validators decide whether to offer a connection. A [`ValidationEngine`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-validation#validationengine) rule instead audits existing entities and returns a [`ValidationResult`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-types-interfaces-s-v#validationresult) containing `valid`, `errors`, and `warnings`.

Use a separate [`TypeRegistry`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-validation#typeregistry) and validation engine when you need an additional audit policy without changing the canvas's editing policy. The following module audits links in the mounted model; its typed rule returns an error for a same-node edge.

```ts title="src/audit-links.ts"
import { TypeRegistry, ValidationEngine } from '@grafloria/engine';
import type { LinkModel, ValidationResult, ValidationRule } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';

export function auditLinks(instance: DiagramInstance): ValidationResult[] {
  const registry = new TypeRegistry();
  const validator = new ValidationEngine(registry);
  const noSelfLoops: ValidationRule<LinkModel> = link => {
    const sameNode = instance.getModel().getNodeByPortId(link.sourcePortId)
      === instance.getModel().getNodeByPortId(link.targetPortId);
    return {
      valid: !sameNode,
      errors: sameNode ? [{
        path: `link.${link.id}`, message: 'A link must join different nodes.',
        code: 'SELF_LOOP', severity: 'error',
      }] : [],
      warnings: [],
    };
  };
  validator.addRule('link', noSelfLoops);
  const model = instance.getModel();
  return model.getLinks().map(link => validator.validateLink(link, model));
}
```

The JavaScript view's Audit links button prints each current link's audit result; it does not add or remove wires.

`addRule()` accepts `diagram`, `node`, `port`, and `link` as its entity categories. This audit uses `link` because it inspects endpoints. The engine's [`ConnectionValidator`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-state#connectionvalidator) is a different type: it takes two [`PortModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-portmodel) arguments and returns a boolean or reason string, not a `ValidationResult`.

For built-in audits, use the canvas's [`DiagramEngine`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-engine#diagramengine):

| Method | Scope and result |
| --- | --- |
| `validateDiagram(options)` | Audits the loaded diagram and returns errors and warnings. |
| `validate()` | Audits the diagram with default options; with no diagram, returns a valid empty result. |
| `validateNode(nodeId, options)` | Audits one node. |
| `validateLink(linkId, options)` | Audits one link against the loaded diagram. |
| `validatePort(portId, nodeId, options)` | Audits a port in its owning node. |
| `validateLayout(groupId, options)` | Audits a group's layout configuration. |
| `registerNodeType(definition)` | Registers a node validation definition, not an HTML renderer. |
| `registerPortType(definition)` | Registers a system port definition; use `portTypeRegistry` for data-flow colors and compatibility. |
| `registerLinkType(definition)` | Registers a link validation definition. |
| `registerGroupType(definition)` | Registers a group validation definition. |
| `enableRealTimeValidation()` / `disableRealTimeValidation()` | Switches the validation engine's real-time flag. |
| `isRealTimeValidationEnabled()` | Reads that flag. |

## Pitfalls

- Connection validators are process-global. Keep each disposer and call it on unmount, as these samples do; otherwise the rule can remain after navigation or affect another canvas. [`clearConnectionValidators`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#clearconnectionvalidators) clears every registered rule: use it only when you intend a clean registry, not when closing one of several views.
- [`isValidConnection`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#isvalidconnection) evaluates registered host validators, not the built-in anatomy and data-type rules. With no registered host validators it returns `{ valid: true }`. Use the real connection gesture to test the combined policy.
- For a custom node's rendered content, use [Customize rendering contracts](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/custom-rendering), not the validation type registry. For host sizing, see [Nest containers and lanes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/nest-containers).

### Check and clear host rules

Use this JavaScript entry in a single-canvas project, retaining the quick start's stylesheet imports. Check Restricted policy reports the host validator's refusal without creating a wire. Clear host rules removes the custom destination and cycle rules; the declared port rules still apply. Do not clear the registry when another canvas needs its validators.

```ts title="src/main.ts"
import './style.css';
import { render } from '@grafloria/element';
import { clearConnectionValidators, isValidConnection } from '@grafloria/renderer';
import { attachRules, edges, nodes, registerDataTypes } from './connections';

const app = document.querySelector<HTMLElement>('#app')!;
const check = document.createElement('button');
check.textContent = 'Check Restricted policy';
const clear = document.createElement('button');
clear.textContent = 'Clear host rules';
const close = document.createElement('button');
close.textContent = 'Close diagram';
const log = document.createElement('pre');
const host = document.createElement('div');
host.style.height = '420px';
app.append(check, clear, close, log, host);
registerDataTypes();
const instance = render({ nodes, edges }, host, {
  interaction: { portVisibility: 'always' },
});
const removeRules = attachRules(instance, message => { log.textContent = message; });
check.addEventListener('click', () => {
  const model = instance.getModel();
  const sourceNode = model.getNode('a');
  const targetNode = model.getNode('restricted');
  if (!sourceNode || !targetNode) return;
  const result = isValidConnection({
    sourceNode, targetNode,
    sourcePort: sourceNode.getPort('a.out') ?? null,
    targetPort: targetNode.getPort('restricted.in') ?? null,
  });
  log.textContent = result.valid ? 'Host rules allow this candidate.'
    : result.reason ?? 'Host rules refuse this candidate.';
});
clear.addEventListener('click', () => {
  clearConnectionValidators();
  log.textContent = 'Host rules cleared. Check the policy again.';
});
close.addEventListener('click', () => {
  removeRules();
  instance.dispose();
  host.remove();
  check.disabled = clear.disabled = close.disabled = true;
});
```

## Related

- [Arrange ports and connect](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/ports-and-connection-gestures) — position and label the ports that expose these rules.
- [Commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history) — make edits from your own UI undoable.
- [Models and the document](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/model-and-document) — query the live graph rather than stale spec arrays.
