* Renders a snapshot of the module with declarations in dependency order and roots in input order. * * **Gotchas** * * Missing definitions and eager dependency cycles throw. Adding declarations later can change import * aliases, so render the complete module again after further change
(roots: ReadonlyArray<Fragment> = [])
| 613 | * aliases, so render the complete module again after further changes. |
| 614 | */ |
| 615 | finalize(roots: ReadonlyArray<Fragment> = []): { |
| 616 | readonly names: ReadonlyMap<Binding, string> |
| 617 | readonly declarations: ReadonlyArray<{ readonly binding: Binding; readonly fragments: ReadonlyArray<string> }> |
| 618 | readonly roots: ReadonlyArray<string> |
| 619 | readonly imports: ReadonlyArray<string> |
| 620 | readonly body: ReadonlyArray<string> |
| 621 | } { |
| 622 | const visiting = new Set<Binding>() |
| 623 | const visited = new Set<Binding>() |
| 624 | const ordered: Array<Declaration> = [] |
| 625 | const visit = (binding: Binding): void => { |
| 626 | if (visited.has(binding) || hasProperty(binding, "import")) return |
| 627 | if (visiting.has(binding)) throw new Error(`Cyclic initialization dependency: ${binding.preferredName}`) |
| 628 | const declaration = this.#declarations.get(binding) |
| 629 | if (declaration === undefined) throw new Error(`Missing definition: ${binding.preferredName}`) |
| 630 | visiting.add(binding) |
| 631 | for (const dependency of declaration.dependencies) visit(dependency) |
| 632 | visiting.delete(binding) |
| 633 | visited.add(binding) |
| 634 | ordered.push(declaration) |
| 635 | } |
| 636 | for (const binding of this.#declarations.keys()) visit(binding) |
| 637 | |
| 638 | const names = new Map(this.#bindings) |
| 639 | const imports = new Map<string, UsedImport>() |
| 640 | const render = this.#renderer(names, imports) |
| 641 | const output = { |
| 642 | names, |
| 643 | declarations: ordered.map(({ binding, fragments }) => ({ binding, fragments: fragments.map(render) })), |
| 644 | roots: roots.map(render), |
| 645 | body: this.#body.map(render) |
| 646 | } |
| 647 | const orderedImports: Array<string | UsedImport> = [] |
| 648 | for (const entry of this.#importOrder) { |
| 649 | if (typeof entry === "string") { |
| 650 | orderedImports.push(entry) |
| 651 | } else { |
| 652 | const key = importKey(entry.import) |
| 653 | const used = imports.get(key) |
| 654 | if (used !== undefined && (!used.runtime || !entry.import.typeOnly)) { |
| 655 | orderedImports.push(used) |
| 656 | imports.delete(key) |
| 657 | } |
| 658 | } |
| 659 | } |
| 660 | return { ...output, imports: printImports([...orderedImports, ...imports.values()]) } |
| 661 | } |
| 662 | |
| 663 | /** |
| 664 | * Prints a module's imports, ordered declarations, and appended source as TypeScript. |
no test coverage detected