Docs

Search documentation

Shared docs and current release

Loading search…

日本語

@shumoku/core · 0.6.1

TypeScript API

128 public functions generated from TypeScript and TSDoc.

absenceImpliesRetraction True when absence in a snapshot should be treated as evidence (retract / mark stale). False when the snapshot 's absence is meaningless because the node was deliberately not asked. This is the *critical* anti-footgun call codex flagged: if we post-filter excluded nodes out of a NetBox snapshot whose status is `ok` (= absence trusted), the resolver would happily interpret the missing entry as "NetBox says it 's gone". We never want that. addHttpWarning Add HTTP warning to connection result if URL uses insecure HTTP addressKey An address as a key: its host part, so `10.0.0.1/24` and `10.0.0.1` are one. applyGraphEdits Writes the edits made to a drawn graph back into the model it was drawn from. `drawn` is the graph as it was before the edits and `edited` as it is after; only what differs between them is written. The configuration keeps what the graph cannot say, such as a node's software or the host a VM runs on, and a field the graph draws from another (a product's name, a link's speed) is kept as written until that field is edited. The drawing of an edited element is replaced, as the graph says all of it. A graph carries nothing of the observation record, so none is written. Without an edit, the model itself is returned. applyThemeToCSS Apply theme to CSS variables asEntityId Trust-boundary cast — DB reads, registry mint, wire-format parse. Use ONLY at: mint, DB row reads, HTTP param boundaries, and tests. If you find yourself casting mid-logic, fix the signature above you instead. attachmentKey Stable merge / suppression key for an attachment. `access` is keyed per protocol (SNMP and SSH are distinct slots); `metrics-binding` is keyed per metrics source (two metrics sources can each bind one element — but ONE binding per (source, element) is the invariant; extend with a role segment if per-metric-role binding is ever needed, don't overload the slot); every other kind keys by its `kind`. The resolver merges attachments by this key (the first contribution in the ordering wins per key) and the human suppresses by it (`suppressedAttachments`). One definition so merge and suppression never disagree on what "the same attachment slot" means. bindingInterfaceName The best name to hand the plugin for an interface binding. Identity (`ifName`) is the durable key; `interfaceName` is the migration / label fallback. The poll-time resolution layer may refine this against the source's live interface list, but a name is always derivable here. buildAlertTitle Display title: `"<alertname> - <host>"`, or just the name when no host. buildIdentity Build the `Identity` a hosts or metrics source reports for a host or an interface from raw parts, dropping empty values. Returns `undefined` when nothing identifying was supplied. For a topology node's own attributes use `deviceAttributes`. cableConnectorForStandard Derive the cable-end connector from the link's effective standard. The model no longer stores `cable.connector` explicitly — call this from display / validation code that needs the connector value. cableGradesForStandard Cable grades available given the link's standard. Returns an empty array when grade isn't a meaningful axis (DAC / AOC) — the UI hides the third select in that case. cableVariantsForPlug Cable variants for a plug — all standards reachable through that cage form factor, ordered by speed. For RJ45 this includes 10M / 100M / 1G / 2.5G / 5G / 10G; for SFP+ it includes SR / LR / CR / AOC. checkNetwork Every issue in a written network, all at once: someone who writes from an example needs the whole list, not the first mistake. An empty list means the network can be read. classifyIcon Classify a raw icon string into inline-SVG vs URL. Inline content starts with `<` (either a bare `<path .../>` fragment or a full `<svg>...</svg>` block). Anything else is treated as a URL, including `data:` URIs. classifyStandardGroup No summary. combineLinkPresentation Compose an independent connection; style does not change endpoints or physical data. combineNetworkDocument Compose an independent graph for existing layout, renderer and editor consumers. This checks the presentation boundary, not the entire topology schema. combineNodePresentation Compose an independent runtime node without changing stored payloads. combineSubgraphPresentation Compose an independent group with its display override. computeEffectivePolicy No summary. contrastRatio The WCAG contrast ratio of two colours. createTheme Create custom theme defaultCableGrade Default grade for a freshly-picked standard. Used when the user picks/changes the cable medium and we want the third select to land on a sensible value rather than empty. defaultStandardForCages Propose a sensible default standard given the cages on both ends. deriveMapping Derive a legacy `MetricsMapping` from the bindings in an observation record, keyed by the drawn graph's element ids (the record is keyed by the same ids). - Node host binding → `mapping.nodes[node.id]`. - Link interface binding lives on a port's record; we attribute it to the link whose endpoint references that port, keyed `link.id || link-${i}` to match the rest of the server (server.ts / topologies.ts). Pure; never mutates the input. deriveStructure The structure a written network implies. A network is the `config` of a read model (`readNetworkModel(yaml).config`); the result refers to it by its written ids. deviceAttributes A node's device attributes from raw parts: empty values dropped, `chassisId` and `mac` in the canonical MAC spelling where they are MACs. Spread the result onto the node the plugin returns. deviceKeysOfIdentity A hosts / metrics source's `Identity` as the keys a node is recognized by. diagramTitle Everything a node or link says, one fact a line: what a title (tooltip) shows in full. drawingArcs How each vertex of a polyline is rounded, given the radius asked for at each (0 at the ends). The arc is tangent to both runs, so a vertex turning through θ takes `r·tan(θ/2)` off each, at most half of either run; where that does not fit, the radius is reduced to fit. A vertex that is not rounded (an end, no radius, a run of no length, no turn) has no arc. This is the one place a drawn corner is worked out; the renderer writes the arcs out and the layout samples them. drawingBoundary Where the network meets what lies beyond it, as ids the structure can measure from. The drawing layer's own choice comes first; else the external or cloud nodes and the routing domains that links reach, what the input itself says is outside; else the structure's candidates (where the physical meets the virtual). A part of the network that none of these reaches gets its own guess (`upstreamOf`), so it still has an up and a down. drawNetwork Draws a model as a scene: `layoutNetwork`, keeping the coordinates. drawnInPlace A node as its card is drawn inside what it runs on: without the facts about where it runs (`about: 'hosting'`), which the box or frame round it already says. The node keeps them for details and tooltips; only the card leaves them out. effectiveLinkStandard No summary. effectivePlugCage Resolve the effective plug cage for an endpoint with the canonical priority: explicit `plug.cage` > module's required cage > port.connectors[0] (only when the port has a single connector — multi-connector combo ports require an explicit choice on the link side). Returns undefined when none are known. effectivePolicyForNode Convenience: compute the effective discovery policy for a node of a drawn graph, whose attachments are in the observation record beside it. Walks the graph's subgraphs once into a lookup map, joining each with its record, then delegates to `computeEffectivePolicy`. The resolver, the scheduler, and the API "GET effective policy for this node" surface all need the same answer; they call this helper. endpointModule No summary. endpointPlugCage No summary. endpointStandard No summary. extractHost Host from the common label dialects, in priority order. filterAlertLabels Drop Alertmanager-internal labels (`__name__`, other `__…`). fittingLineTone The tone that tells the most lines apart over these backgrounds: of the lightnesses at which every hue is seen, the one that leaves the most chroma. For writing a theme's `lineTone`. flattenObject Flatten an arbitrary upstream record into `DiscoveredMetric[]` for the plugin "All metrics" passthrough panel. This is the generic dumper every `HostsCapable` plugin should use instead of hand-enumerating fields (which is how zabbix ended up coercing every value to a number and dropping categorical attributes). Walk the object: - object children join into the metric name with `_` (`{ a: { b: 1 } }` with prefix `p` → `p_a_b`), - array-of-primitives emits a `<name>_count`, - array-of-objects emits a `<name>_count` then expands each element with a `<key>_index` label, - null / undefined / empty-string / non-finite leaves are skipped as noise. Lifted verbatim (behavior-preserving) from the aruba-instant-on plugin, which had the only correct generic implementation. formatReachMeters Format a meters value for UI display (1000+ → km). fromNetworkGraph Splits a drawn graph back into a model: the inverse of `toNetworkGraph` for what the configuration can say. A node drawn for a segment becomes the segment again. A graph carries nothing of the observation record, so none comes back. getDeviceIcon Get SVG icon content for a device type getNodeId Helper to get node ID from endpoint. Kept as a tiny accessor so callers read intent ("the link's source node") rather than reaching into shape. getStandardSpec No summary. getThemeFromCSS Get theme from CSS variables groupCableVariants Group cable variants by `cableKind` for sectioned `<optgroup>` rendering. groupStandards Group a list of `StandardOption`s by their `group` for sectioned dropdowns. hasAlertsCapability No summary. hasAutoscanCapability No summary. hasConfigOptions Duck-type: can this plugin supply dynamic candidates for `optionsSource` fields? hasConnectionInfo Duck-type: does this plugin expose derived, display-only connection info? hasHostsCapability No summary. hasMetricsCapability No summary. hasNativeApi Duck-type check: does this plugin expose a native-API passthrough? Intentionally not bound to a `DataSourceCapability` literal — this is a developer-only escape hatch, not a product feature, so it stays off the advertised capability list. hasTopologyCapability No summary. hostingOf What is drawn inside what. A guest goes in with what it runs on unless it names another place; one that names the place its host stands in still goes in, as a source such as NetBox gives each VM its site. A guest's guest (a container on a VM) goes in the outermost host's box. hueOf A colour's OKLCH hue, in degrees. interfaceMatchScore Score how well two normalized interface names match (0–1): same canonical prefix, then port numbers compared right-to-left (rightmost = most specific). interfaceNamesMatch Whether two interface names denote the same physical port. Same canonical prefix with aligning numbers (score ≥ 0.5), OR — for cross-vocabulary cases like TTDB's speed-code `hg` vs Juniper `et-` where prefixes differ but the port number is identical — the full number sequence matches. isExcluded True when the node should NOT be auto-touched by the scheduler or by any source's discovery pass — convenience predicate that hides the mode comparison from callers that just need a yes/no answer. isPluggableConnector No summary. isPoeCapableConnector No summary. isSecretProp A field is a write-only secret if it declares `secret: true`. `format: 'password'` is honoured too so external plugins that predate the flag keep working; new schemas should set `secret: true`. issuesForTarget Filter issues whose target points at a specific field. Used by the UI. keyHash Stable string form of a key for use as a Map key. labelText A label line as drawn: the bold and line-break markup a label may carry is not text. layoutDrawing Lays a network out as a scene: where each box stands and how each line runs. `network` is the configuration as written, `structure` what follows from it and the boundary points, and `metrics` every length the drawing may use. Every discrete choice is made from relations and indices before any coordinate, one stage after another, and the coordinates are solved once for each axis at the end: the ranks (`ranksOf`) from the flows, the left-to-right order of every rank (`layersOf`), the free space cut into corridors (`corridorsOf`), each line's way through them (`routesOf`), the order of the lines in each corridor (`tracksOf`), what the ports and corridors ask of the sizes (`needsOf`), and the coordinates (`placeAll`). No stage reads a length to decide, so a font that measures a little differently moves things a little and changes nothing else. layoutNetwork Lays a model out: the one entry from what is written (and what the layers add) to where each box stands and how each line runs, with the arrangement that was solved into those places. The model is the truth; both are its projection, made fresh each time. The order a person put siblings in (`drawing.order`) is read here, so every caller, the Editor and the Server alike, draws the same model the same way. lineColorCapacity The most colours a tone can tell apart. lineColors `count` colours of a tone, as `#rrggbb`: hues evenly spaced from the tone's, at the least chroma that keeps them told apart. `undefined` when the tone has no room for that many. linkSpeedBps The nominal speed of a link (bits/sec): what its ends' standards name, else the `speedBps` the link carries for a link that no standard describes. linkTitle No summary. mapAlertmanagerSeverity No summary. mapWithConcurrency Run `fn` over `items` with at most `limit` calls in flight at once, preserving input order in the result array. Replaces the two failure modes the audit found: unbounded `Promise.all` fan-out (network-scan would open hundreds of SNMP sockets at once) and fully sequential `await`-in-a-loop polling (zabbix walked hosts one by one). A rejected `fn` rejects the whole call (like `Promise.all`); a caller wanting partial results should catch inside `fn`. mediumFromGrade Derive the cable medium kind from a `CableGrade`. Twisted-pair categories map to twisted-pair, OM3/4/5 → multi-mode fiber, OS1/2 → single-mode fiber, DAC and AOC are their own mediums. mediumFromStandard Derive the cable medium implied by an Ethernet standard. Resolves the standard via `STANDARD_SPECS` and maps `cableKind` + `fiberMode` onto the unified `CableMedium` enum. mergeTheme Merge theme with overrides metricsBindingOf The metrics-binding attachment on an element, if any. When `activeSourceIds` is given, only a binding whose `sourceId` is active counts — so a binding left behind by a detached/removed metrics source stops driving the mapping. missingCapabilityMethods Declared capabilities whose required method is missing on a constructed instance, formatted `"cap → method()"`. Empty array = compliant. Unknown (open) capabilities are skipped. The registry calls this once at first instantiate (decision 7) to catch a plugin that advertises a capability it doesn't actually implement (C6). newId Generate a fresh unique ID for the given entity kind. Collision probability for 10-char nanoid is negligible for editor-scale workloads (~trillions of IDs before 1% collision chance). nodeContentScale The safe central rectangle inside each nonrectangular outline. nodeIdentityKeys A node's identity keys in priority order; the first match wins during cluster lookup, and the caller binds every key to the cluster after a match so a later contribution that carries only a weaker key still collapses onto it. nodeIdentityQuality Coarse identity quality, shown in the UI to warn which elements may detach from their metrics across reboots. Node: `stable` with a chassisId and an address or sysName, `weak` with any one of them, `unbound` with none. Port: `stable` with a name and a mac or ifIndex, `weak` with one key, `unbound` with none. normalizeInterfaceName Normalize an interface name to `{ prefix, numbers, sub }`. The numeric part is split on `/`, `-`, or `:` so TTDB's dash form ("hg-0-0-0" → [0,0,0]) lines up with the slash form ("hg/0/0/0" → [0,0,0]). normalizeMacKey Canonical spelling for a MAC-shaped key: lowercase, colon-separated. Sources disagree on how to write the same wire address. Huawei NCE returns `50-04-01-01-D5-50` in its device list and `CC:D8:1F:9F:D4:AB` in its LLDP table; an SNMP walk of the very same switch yields `cc:d8:1f:9f:d4:ab`; Cisco gear writes `ccd8.1f9f.d4ab`. Keys are matched as exact strings, so without one canonical spelling a device arrives as two entities that never merge — the failure is silent, which is what makes it worth normalizing here rather than in each plugin. Anything that is not twelve hex digits once separators are stripped is returned untouched: `chassisId` is only sometimes a MAC (LLDP also permits interface names and network addresses) and must survive as written. normalizePortConnector No summary. oklchToHex An OKLCH colour as `#rrggbb`. paperSizeToPixels Convert paper size to pixels at given DPI parseAlertmanagerAlerts Parse an Alertmanager response into core `Alert[]`, applying the standard active/timeRange and minSeverity filters. - Active alerts are always kept; resolved alerts are dropped when `activeOnly`, otherwise dropped once older than `timeRange` (default 1h). - Unparseable `startsAt` falls back to `now`; missing/unparseable `endsAt` yields `undefined` (no bogus epoch-0 end time). parseNetworkPresentation Validate and copy unknown presentation data. plugFromCage Build a cage-only plug — the user picked a form factor without a module yet. plugFromStandard Build a plug from a chosen module standard. The plug carries only the `module` — `cage` is intentionally omitted because it's derivable from `module.standard` via `STANDARD_SPECS[std].cage`. Returns `undefined` if the standard is unknown. plugProfileForStandard Resolve a standard to its plug profile (for prefilling the plug select). plugProfilesForConnectors Plug profiles compatible with the given port connectors. Empty arrays are permissive (return all plugs); multi-connector combo ports return the union of compatible plugs. portIdentityKeys A port's identity keys in priority order. Ports are matched within one node cluster — the same name on another chassis is another port; the caller scopes the lookup. `ifIndex` is last: many agents renumber it across reboots. portIdentityQuality No summary. rateFromBps Writes a rate in bits/sec as the input does, such as `10G` or `100M`. reachForLink Effective reach in meters for a link, accounting for the cable grade. Falls back to the standard's `maxReach_m` when the grade isn't set or isn't in the registry's per-grade table. readNetworkModel Reads a network YAML into a model that holds it as its configuration. A network that cannot be read as written throws a `NetworkInputError` listing every issue in it. resolveIcon Resolve the icon to render for a given spec. Returns the explicit `spec.icon` if any; otherwise the bundled device-type fallback; otherwise null. resolveNetwork Merge the project's configuration with what every source observed into one network of the same shape. All contributions are peers with an ordering between them; the project is first in it. Nodes are clustered by the attributes their configuration writes (`address`, `chassisId`, `sysName`, `mac`: any-key match), by a source's own ids (`observation.vendorIds`) or by a shared registry entity id, regardless of the ordering; ports within a cluster by name, `mac` and `ifIndex`. Then per field the first contribution in the ordering that holds a value wins (`priority desc, capturedAt desc`). Every node, port, group and link gets a `provenance` in the observation record returned beside the model. The merged network keeps a node's project id when the project wrote it, and gives a node only sources found a synthesized `discovered:N` id. Each source's groups, segments, routing domains, connections, redundancy sets and terminations are namespaced by its source id so they never collide. See `apps/server/docs/design/topology-source-priority-merge.md`. sampleNetworkModel The sample with its drawing layer. sanitizeIconSvg No summary. sanitizeIconSvgWith No summary. segmentAddressesOf The addresses each node holds in a network's segments, by node id (a set's shared address is not a node's). separateLinkPresentation Split connection style from facts. Unstyled idless links are preserved. separateNetworkGraph Separate shape, styles and graph settings from facts; physical records are copied unchanged. separateNodePresentation Split a structured-cloneable runtime node into independent storage values. separateSubgraphPresentation Split group style from facts. severityAtLeast True when `severity` is at least as severe as `min`. severityRank Rank of a severity (unknown → `info`). sourceToGraph Draws one contribution on its own: its network and how it would have it drawn. specDeviceType Extract DeviceType from a spec (hardware and compute only). standardsForConnectors Standards available given the connectors on each port. Used by the editor's cascading "Standard" picker so the dropdown only offers links that physically fit. Empty arrays are treated permissively — we'd rather show too many than none. For combo ports (multiple connectors), this returns the union: any standard that fits at least one connector on each side qualifies. Returned as one flat list; group via `option.group` if the UI wants to split into sections. standardSpeedBps The speed (bits/sec) the standards of the plugs name: the slower when the two ends differ (a BiDi link), the only one when one end names it, nothing when neither does. symmetricPlug Produce a symmetric plug spec for a link — both endpoints get the same plug+module. Used by editor flows that default to symmetric links. toneFits Whether every hue of a lightness and chroma is shown by a screen and seen against every background, checked every few degrees. toNetworkGraph Builds the graph that layout and the renderers draw from the configuration and its drawing. Sources are not read: `resolveNetwork` merges them into the configuration first. The observation record is not read either: a drawing carries no identity, provenance or attachments; the Server keeps those beside the graph, by element id. validateAgainstSchema No summary. validateLinkCompatibility Validate a link against its endpoints, ports, and cable. Runs every registered endpoint-level and link-level check; collects all issues the UI / consumers can route to inline markers via `issuesForTarget`. validateTopologyIdentityContract Check whether what a topology plugin discovered satisfies the identity contract. Returns arrays of violating node / port ids. Both arrays empty → contract met. vendorIdsOf A source's own ids for a node, for its observation's `vendorIds`; empty values dropped. writeNetworkModel Writes a model's configuration as the network YAML. Its drawing is not written.