```ts
export function topologicalSort(nodes: readonly string[], edges: readonly (readonly [string, string])[]): string[] {
  const graph = new Map<string, Set<string>>();
  for (const [from, to] of edges) {
    if (!graph.has(from)) graph.set(from, new Set());
    if (!graph.has(to)) graph.set(to, new Set());
    graph.get(from)?.add(to);
  }
  
  const inDegree = new Map<string, number>();
  for (const node of nodes) inDegree.set(node, 0);

  for (const [from] of edges) {
    if (inDegree.has(from)) inDegree.set(from, inDegree.get(from)! + 1);
  }

  const queue: string[] = [];
  for (const [node, degree] of inDegree.entries()) {
    if (degree === 0 && nodes.includes(node)) queue.push(node);
  }

  const sortedNodes: string[] = [];
  while (queue.length > 0) {
    const node = queue.shift()!;
    if (!nodes.includes(node)) throw new Error('Invalid edge involving non-existing node');
    sortedNodes.push(node);

    for (const neighbor of graph.get(node) || []) {
      inDegree.set(neighbor, inDegree.get(neighbor)! - 1);
      if (inDegree.get(neighbor) === 0) queue.push(neighbor);
    }
  }

  if (sortedNodes.length !== nodes.length) throw new Error('Cycle detected');

  return sortedNodes;
}
```