@yalehwang/plantuml-js 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yale Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @yalehwang/plantuml-js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Pure-TypeScript PlantUML **class diagram** renderer (MIT). Renders `.puml`
4
+ class diagrams to SVG with a pluggable layout engine — `elkjs` (pure JS) by
5
+ default, `@viz-js/viz` (WASM Graphviz) as an option.
6
+
7
+ > **Engine status** — `'viz'` is **experimental**. It reaches only a fraction
8
+ > of `'elk'`'s area utilization and still routes a few edges through unrelated
9
+ > nodes on large package diagrams. See [`docs/viz-decision.md`](docs/viz-decision.md)
10
+ > for the measured comparison. Use `'elk'` (the default) for production diagrams.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install @yalehwang/plantuml-js
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```ts
21
+ import { createRenderer } from '@yalehwang/plantuml-js';
22
+
23
+ const renderer = createRenderer({ layout: 'elk' }); // or 'viz' (experimental)
24
+ const { svg, diagramType, warnings } = await renderer.render(`
25
+ @startuml
26
+ class A
27
+ @enduml
28
+ `);
29
+ ```
30
+
31
+ A minimal runnable example (works in Node 18+ and browsers with a bundler):
32
+
33
+ ```js
34
+ import { createRenderer } from '@yalehwang/plantuml-js';
35
+
36
+ const renderer = createRenderer({ layout: 'viz' });
37
+ const { svg } = await renderer.render('@startuml\nclass A\nclass B\n@enduml');
38
+ console.log(svg);
39
+ // <svg xmlns="http://www.w3.org/2000/svg" ...><rect .../></svg>
40
+ ```
41
+
42
+ ## Status
43
+
44
+ - **M1** — scaffolding, class-subset parser, PlantUmlModel IR, elkjs layout,
45
+ SVG emission. `render("@startuml\nclass A\n@enduml")` produces a correct SVG.
46
+ - **M2** — members / relations / generics / package grouping / aliases,
47
+ orthogonal edge routing, text metrics.
48
+ - **M3** — `@viz-js/viz` engine, API polish, npm publish.
49
+
50
+ ## API
51
+
52
+ | Function | Description |
53
+ |---|---|
54
+ | `createRenderer({ layout })` | Build a renderer. `layout` is `'elk'` (default), `'viz'` (experimental), or a custom `LayoutEngine`. |
55
+ | `renderer.render(puml)` | Parse + layout + emit SVG. Returns `{ svg, diagramType, warnings }`. Throws `RenderError` on structurally invalid puml. |
56
+ | `parsePlantUml(puml)` | Parse a puml string into a `PlantUmlModel`. |
57
+ | `checkSyntax(puml)` | Validate without throwing. Returns `{ ok, errors, warnings }` of line-accurate `SyntaxDiagnostic`s. |
58
+ | `explain(puml)` | Explain each line. Returns `LineExplanation[]` (line, kind, explanation). |
59
+ | `renderDot(dot, engine)` | Render a raw DOT string to SVG via `@viz-js/viz`. `engine` is `'dot'` (default), `'neato'`, `'fdp'`, `'sfdp'`, `'circo'`, `'twopi'`, `'osage'`, or `'patchwork'`. |
60
+ | `ElkLayoutEngine` / `VizLayoutEngine` | The two built-in `LayoutEngine` implementations, exported for direct use. |
61
+
62
+ ### Error semantics
63
+
64
+ `createRenderer` fails closed on an unknown layout name (`'elk'`, `'viz'`, or a
65
+ `LayoutEngine` instance only), and `render` throws a `RenderError` whose
66
+ `diagnostics` carry the offending line numbers. `checkSyntax` reports the same
67
+ problems as structured data instead of throwing.
68
+
69
+ ## License
70
+
71
+ MIT
@@ -0,0 +1,286 @@
1
+ # Third-Party Licenses
2
+
3
+ `@yalehwang/plantuml-js` is distributed under the MIT license. This file lists
4
+ third-party software the package depends on, together with the license terms
5
+ under which each is distributed.
6
+
7
+ ## elkjs
8
+
9
+ - **Package**: `elkjs`
10
+ - **Version**: 0.12.0
11
+ - **License**: `EPL-2.0` — SPDX `EPL-2.0 OR GPL-3.0-or-later`. This project
12
+ elects the **EPL-2.0** option (not the GPL-3.0 option).
13
+ - **Copyright**: Copyright (c) the elkjs contributors — Kiel University,
14
+ TypeFox, and others.
15
+ - **Source**: https://github.com/kieler/elkjs
16
+ - **Usage**: standalone npm dependency used for layered graph layout. It is
17
+ installed via npm and is **not** vendored, copied, or modified into this
18
+ package's source; it is distributed unmodified under EPL-2.0.
19
+
20
+ The full EPL-2.0 license text follows.
21
+
22
+ ---
23
+
24
+ # Eclipse Public License - v 2.0
25
+
26
+ THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
27
+ PUBLIC LICENSE (“AGREEMENT”). ANY USE, REPRODUCTION OR DISTRIBUTION OF
28
+ THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
29
+
30
+ ## 1. DEFINITIONS
31
+
32
+ “Contribution” means:
33
+
34
+ - a\) in the case of the initial Contributor, the initial content
35
+ Distributed under this Agreement, and
36
+ - b\) in the case of each subsequent Contributor:
37
+ - i\) changes to the Program, and
38
+ - ii\) additions to the Program;
39
+
40
+ where such changes and/or additions to the Program originate from
41
+ and are Distributed by that particular Contributor. A Contribution
42
+ “originates” from a Contributor if it was added to the Program by
43
+ such Contributor itself or anyone acting on such Contributor's
44
+ behalf. Contributions do not include changes or additions to the
45
+ Program that are not Modified Works.
46
+
47
+ “Contributor” means any person or entity that Distributes the Program.
48
+
49
+ “Licensed Patents” mean patent claims licensable by a Contributor which
50
+ are necessarily infringed by the use or sale of its Contribution alone
51
+ or when combined with the Program.
52
+
53
+ “Program” means the Contributions Distributed in accordance with this
54
+ Agreement.
55
+
56
+ “Recipient” means anyone who receives the Program under this Agreement
57
+ or any Secondary License (as applicable), including Contributors.
58
+
59
+ “Derivative Works” shall mean any work, whether in Source Code or other
60
+ form, that is based on (or derived from) the Program and for which the
61
+ editorial revisions, annotations, elaborations, or other modifications
62
+ represent, as a whole, an original work of authorship.
63
+
64
+ “Modified Works” shall mean any work in Source Code or other form that
65
+ results from an addition to, deletion from, or modification of the
66
+ contents of the Program, including, for purposes of clarity any new file
67
+ in Source Code form that contains any contents of the Program. Modified
68
+ Works shall not include works that contain only declarations,
69
+ interfaces, types, classes, structures, or files of the Program solely
70
+ in each case in order to link to, bind by name, or subclass the Program
71
+ or Modified Works thereof.
72
+
73
+ “Distribute” means the acts of a) distributing or b) making available in
74
+ any manner that enables the transfer of a copy.
75
+
76
+ “Source Code” means the form of a Program preferred for making
77
+ modifications, including but not limited to software source code,
78
+ documentation source, and configuration files.
79
+
80
+ “Secondary License” means either the GNU General Public License, Version
81
+ 2.0, or any later versions of that license, including any exceptions or
82
+ additional permissions as identified by the initial Contributor.
83
+
84
+ ## 2. GRANT OF RIGHTS
85
+
86
+ - a\) Subject to the terms of this Agreement, each Contributor hereby
87
+ grants Recipient a non-exclusive, worldwide, royalty-free copyright
88
+ license to reproduce, prepare Derivative Works of, publicly display,
89
+ publicly perform, Distribute and sublicense the Contribution of such
90
+ Contributor, if any, and such Derivative Works.
91
+ - b\) Subject to the terms of this Agreement, each Contributor hereby
92
+ grants Recipient a non-exclusive, worldwide, royalty-free patent license
93
+ under Licensed Patents to make, use, sell, offer to sell, import and
94
+ otherwise transfer the Contribution of such Contributor, if any, in
95
+ Source Code or other form. This patent license shall apply to the
96
+ combination of the Contribution and the Program if, at the time the
97
+ Contribution is added by the Contributor, such addition of the
98
+ Contribution causes such combination to be covered by the
99
+ Licensed Patents. The patent license shall not apply to any other
100
+ combinations which include the Contribution. No hardware per se is
101
+ licensed hereunder.
102
+ - c\) Recipient understands that although each Contributor grants the
103
+ licenses to its Contributions set forth herein, no assurances are
104
+ provided by any Contributor that the Program does not infringe the
105
+ patent or other intellectual property rights of any other entity. Each
106
+ Contributor disclaims any liability to Recipient for claims brought by
107
+ any other entity based on infringement of intellectual property rights
108
+ or otherwise. As a condition to exercising the rights and licenses
109
+ granted hereunder, each Recipient hereby assumes sole responsibility to
110
+ secure any other intellectual property rights needed, if any. For
111
+ example, if a third party patent license is required to allow Recipient
112
+ to Distribute the Program, it is Recipient's responsibility to acquire
113
+ that license before distributing the Program.
114
+ - d\) Each Contributor represents that to its knowledge it has sufficient
115
+ copyright rights in its Contribution, if any, to grant the copyright
116
+ license set forth in this Agreement.
117
+ - e\) Notwithstanding the terms of any Secondary License, no Contributor
118
+ makes additional grants to any Recipient (other than those set forth in
119
+ this Agreement) as a result of such Recipient's receipt of the Program
120
+ under the terms of a Secondary License (if permitted under the terms of
121
+ Section 3).
122
+
123
+ ## 3. REQUIREMENTS
124
+
125
+ 3.1 If a Contributor Distributes the Program in any form, then:
126
+
127
+ - a\) the Program must also be made available as Source Code, in accordance
128
+ with section 3.2, and the Contributor must accompany the Program with a
129
+ statement that the Source Code for the Program is available under this
130
+ Agreement, and informs Recipients how to obtain it in a reasonable
131
+ manner on or through a medium customarily used for software exchange;
132
+ and
133
+ - b\) the Contributor may Distribute the Program under a license different
134
+ than this Agreement, provided that such license:
135
+ - i\) effectively disclaims on behalf of all other Contributors all
136
+ warranties and conditions, express and implied, including warranties or
137
+ conditions of title and non-infringement, and implied warranties or
138
+ conditions of merchantability and fitness for a particular purpose;
139
+ - ii\) effectively excludes on behalf of all other Contributors all
140
+ liability for damages, including direct, indirect, special, incidental
141
+ and consequential damages, such as lost profits;
142
+ - iii\) does not attempt to limit or alter the recipients' rights in the
143
+ Source Code under section 3.2; and
144
+ - iv\) requires any subsequent distribution of the Program by any party to
145
+ be under a license that satisfies the requirements of this section 3.
146
+
147
+ 3.2 When the Program is Distributed as Source Code:
148
+
149
+ - a\) it must be made available under this Agreement, or if the Program (i)
150
+ is combined with other material in a separate file or files made
151
+ available under a Secondary License, and (ii) the initial Contributor
152
+ attached to the Source Code the notice described in Exhibit A of this
153
+ Agreement, then the Program may be made available under the terms of
154
+ such Secondary Licenses, and
155
+ - b\) a copy of this Agreement must be included with each copy of
156
+ the Program.
157
+
158
+ 3.3 Contributors may not remove or alter any copyright, patent,
159
+ trademark, attribution notices, disclaimers of warranty, or limitations
160
+ of liability (‘notices’) contained within the Program from any copy of
161
+ the Program which they Distribute, provided that Contributors may add
162
+ their own appropriate notices.
163
+
164
+ ## 4. COMMERCIAL DISTRIBUTION
165
+
166
+ Commercial distributors of software may accept certain responsibilities
167
+ with respect to end users, business partners and the like. While this
168
+ license is intended to facilitate the commercial use of the Program, the
169
+ Contributor who includes the Program in a commercial product offering
170
+ should do so in a manner which does not create potential liability for
171
+ other Contributors. Therefore, if a Contributor includes the Program in
172
+ a commercial product offering, such Contributor (“Commercial
173
+ Contributor”) hereby agrees to defend and indemnify every other
174
+ Contributor (“Indemnified Contributor”) against any losses, damages and
175
+ costs (collectively “Losses”) arising from claims, lawsuits and other
176
+ legal actions brought by a third party against the Indemnified
177
+ Contributor to the extent caused by the acts or omissions of such
178
+ Commercial Contributor in connection with its distribution of the
179
+ Program in a commercial product offering. The obligations in this
180
+ section do not apply to any claims or Losses relating to any actual or
181
+ alleged intellectual property infringement. In order to qualify, an
182
+ Indemnified Contributor must: a) promptly notify the Commercial
183
+ Contributor in writing of such claim, and b) allow the Commercial
184
+ Contributor to control, and cooperate with the Commercial Contributor
185
+ in, the defense and any related settlement negotiations. The Indemnified
186
+ Contributor may participate in any such claim at its own expense.
187
+
188
+ For example, a Contributor might include the Program in a commercial
189
+ product offering, Product X. That Contributor is then a Commercial
190
+ Contributor. If that Commercial Contributor then makes performance
191
+ claims, or offers warranties related to Product X, those performance
192
+ claims and warranties are such Commercial Contributor's responsibility
193
+ alone. Under this section, the Commercial Contributor would have to
194
+ defend claims against the other Contributors related to those
195
+ performance claims and warranties, and if a court requires any other
196
+ Contributor to pay any damages as a result, the Commercial Contributor
197
+ must pay those damages.
198
+
199
+ ## 5. NO WARRANTY {#warranty}
200
+
201
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
202
+ PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN “AS IS”
203
+ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
204
+ IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
205
+ TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
206
+ PURPOSE. Each Recipient is solely responsible for determining the
207
+ appropriateness of using and distributing the Program and assumes all
208
+ risks associated with its exercise of rights under this Agreement,
209
+ including but not limited to the risks and costs of program errors,
210
+ compliance with applicable laws, damage to or loss of data, programs or
211
+ equipment, and unavailability or interruption of operations.
212
+
213
+ ## 6. DISCLAIMER OF LIABILITY {#disclaimer}
214
+
215
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
216
+ PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS
217
+ SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
218
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
219
+ PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
220
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
221
+ ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
222
+ EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
223
+ POSSIBILITY OF SUCH DAMAGES.
224
+
225
+ ## 7. GENERAL
226
+
227
+ If any provision of this Agreement is invalid or unenforceable under
228
+ applicable law, it shall not affect the validity or enforceability of
229
+ the remainder of the terms of this Agreement, and without further action
230
+ by the parties hereto, such provision shall be reformed to the minimum
231
+ extent necessary to make such provision valid and enforceable.
232
+
233
+ If Recipient institutes patent litigation against any entity (including
234
+ a cross-claim or counterclaim in a lawsuit) alleging that the Program
235
+ itself (excluding combinations of the Program with other software or
236
+ hardware) infringes such Recipient's patent(s), then such Recipient's
237
+ rights granted under Section 2(b) shall terminate as of the date such
238
+ litigation is filed.
239
+
240
+ All Recipient's rights under this Agreement shall terminate if it fails
241
+ to comply with any of the material terms or conditions of this Agreement
242
+ and does not cure such failure in a reasonable period of time after
243
+ becoming aware of such noncompliance. If all Recipient's rights under
244
+ this Agreement terminate, Recipient agrees to cease use and distribution
245
+ of the Program as soon as reasonably practicable. However, Recipient's
246
+ obligations under this Agreement and any licenses granted by Recipient
247
+ relating to the Program shall continue and survive.
248
+
249
+ Everyone is permitted to copy and distribute copies of this Agreement,
250
+ but in order to avoid inconsistency the Agreement is copyrighted and may
251
+ only be modified in the following manner. The Agreement Steward reserves
252
+ the right to publish new versions (including revisions) of this
253
+ Agreement from time to time. No one other than the Agreement Steward has
254
+ the right to modify this Agreement. The Eclipse Foundation is the
255
+ initial Agreement Steward. The Eclipse Foundation may assign the
256
+ responsibility to serve as the Agreement Steward to a suitable separate
257
+ entity. Each new version of the Agreement will be given a distinguishing
258
+ version number. The Program (including Contributions) may always be
259
+ Distributed subject to the version of the Agreement under which it was
260
+ received. In addition, after a new version of the Agreement is
261
+ published, Contributor may elect to Distribute the Program (including
262
+ its Contributions) under the new version.
263
+
264
+ Except as expressly stated in Sections 2(a) and 2(b) above, Recipient
265
+ receives no rights or licenses to the intellectual property of any
266
+ Contributor under this Agreement, whether expressly, by implication,
267
+ estoppel or otherwise. All rights in the Program not expressly granted
268
+ under this Agreement are reserved. Nothing in this Agreement is intended
269
+ to be enforceable by any entity that is not a Contributor or Recipient.
270
+ No third-party beneficiary rights are created under this Agreement.
271
+
272
+ ## Exhibit A – Form of Secondary Licenses Notice {#exhibit-a}
273
+
274
+ “This Source Code may also be made available under the following
275
+ Secondary Licenses when the conditions for such availability set forth
276
+ in the Eclipse Public License, v. 2.0 are satisfied: GNU General Public License v3.0 or later”
277
+
278
+ > Simply including a copy of this Agreement, including this Exhibit A is
279
+ > not sufficient to license the Source Code under Secondary Licenses.
280
+ >
281
+ > If it is not possible or desirable to put the notice in a particular
282
+ > file, then You may include the notice in a location (such as a LICENSE
283
+ > file in a relevant directory) where a recipient would be likely to
284
+ > look for such a notice.
285
+ >
286
+ > You may add additional accurate notices of copyright ownership.
@@ -0,0 +1,76 @@
1
+ /**
2
+ * ArchGuard neighbourhood-JSON → PlantUML class-diagram bridge.
3
+ *
4
+ * Converts ArchGuard's neighbourhood shape
5
+ * { nodes: [{ id, label, distance }], edges: [{ from, to, relationType }] }
6
+ * into a `@startuml … @enduml` string the renderer consumes. `id` is
7
+ * `<scopeKey>/<relpath>.<EntityName>`; the bridge drops the scopeKey prefix for
8
+ * display and keeps `relpath.EntityName` (with its `/` separators) so the
9
+ * renderer's path-prefix overview (`view: {kind:'overview', depth}`) can group
10
+ * by directory.
11
+ *
12
+ * Aliases are stable (`n<i>` by node index), so a filtered subset still
13
+ * addresses the same node ids. The returned `aliasOf` map (original id →
14
+ * alias) is what the host uses to link a rendered `data-entity-id` back to the
15
+ * source node — the renderer draws that alias as the entity id.
16
+ */
17
+ export interface ArchguardNode {
18
+ id: string;
19
+ label: string;
20
+ distance?: number;
21
+ }
22
+ export interface ArchguardEdge {
23
+ from: string;
24
+ to: string;
25
+ relationType: string;
26
+ }
27
+ export interface ArchguardGraph {
28
+ nodes: ArchguardNode[];
29
+ edges: ArchguardEdge[];
30
+ }
31
+ /**
32
+ * ArchGuard relationType → PlantUML arrow + optional stereotype label.
33
+ *
34
+ * Semantics follow the archguard-aligned decision, NOT the renderer's raw
35
+ * six-way set:
36
+ * - `dependency` → Dependency (`..>`, `<<uses>>`)
37
+ * - `call` → Dependency (`..>`, `<<call>>`) — a call is a use, not a
38
+ * structural Association
39
+ * - `composition` → Aggregation (`o--` hollow diamond) — field-held
40
+ * reference, lifecycle unknown; deliberately NOT Composition `*--`
41
+ * - `aggregation` → Aggregation (`o--`)
42
+ * - `inheritance` → Generalization (`--|>`)
43
+ * - `implementation` → Realization (`..|>`)
44
+ */
45
+ export declare const ARCHGUARD_RELATION_ARROWS: Record<string, {
46
+ arrow: string;
47
+ label?: string;
48
+ }>;
49
+ /** Strip the leading `<scopeKey>/` so only the relpath remains. */
50
+ export declare function pathName(id: string): string;
51
+ /**
52
+ * Display name `relpath.EntityName`, optionally truncated to the last
53
+ * `maxDirSegments` directory segments (front-truncated, tail + entity kept).
54
+ * `maxDirSegments = 0` keeps the full path.
55
+ */
56
+ export declare function displayName(id: string, maxDirSegments?: number): string;
57
+ /** Deterministic alias map: node at index `i` → `n<i>`. */
58
+ export declare function archguardAliasMap(nodes: ArchguardNode[]): Map<string, string>;
59
+ export interface ArchguardBridgeOptions {
60
+ /**
61
+ * Stable alias map. Pass the map built over the *full* graph when rendering a
62
+ * filtered subset, so the subset keeps the original node ids. Defaults to a
63
+ * fresh map over `graph.nodes`.
64
+ */
65
+ aliasOf?: Map<string, string>;
66
+ /** Display-name truncation passed to {@link displayName}. */
67
+ maxDirSegments?: number;
68
+ }
69
+ export interface ArchguardPlantUml {
70
+ /** The generated `@startuml … @enduml` class diagram. */
71
+ puml: string;
72
+ /** original id → alias (`n<i>`); use to map a rendered `data-entity-id` back. */
73
+ aliasOf: Map<string, string>;
74
+ }
75
+ /** Emit a `@startuml … @enduml` class diagram for a (possibly filtered) graph. */
76
+ export declare function archguardToPlantUml(graph: ArchguardGraph, options?: ArchguardBridgeOptions): ArchguardPlantUml;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * ArchGuard neighbourhood-JSON → PlantUML class-diagram bridge.
3
+ *
4
+ * Converts ArchGuard's neighbourhood shape
5
+ * { nodes: [{ id, label, distance }], edges: [{ from, to, relationType }] }
6
+ * into a `@startuml … @enduml` string the renderer consumes. `id` is
7
+ * `<scopeKey>/<relpath>.<EntityName>`; the bridge drops the scopeKey prefix for
8
+ * display and keeps `relpath.EntityName` (with its `/` separators) so the
9
+ * renderer's path-prefix overview (`view: {kind:'overview', depth}`) can group
10
+ * by directory.
11
+ *
12
+ * Aliases are stable (`n<i>` by node index), so a filtered subset still
13
+ * addresses the same node ids. The returned `aliasOf` map (original id →
14
+ * alias) is what the host uses to link a rendered `data-entity-id` back to the
15
+ * source node — the renderer draws that alias as the entity id.
16
+ */
17
+ /**
18
+ * ArchGuard relationType → PlantUML arrow + optional stereotype label.
19
+ *
20
+ * Semantics follow the archguard-aligned decision, NOT the renderer's raw
21
+ * six-way set:
22
+ * - `dependency` → Dependency (`..>`, `<<uses>>`)
23
+ * - `call` → Dependency (`..>`, `<<call>>`) — a call is a use, not a
24
+ * structural Association
25
+ * - `composition` → Aggregation (`o--` hollow diamond) — field-held
26
+ * reference, lifecycle unknown; deliberately NOT Composition `*--`
27
+ * - `aggregation` → Aggregation (`o--`)
28
+ * - `inheritance` → Generalization (`--|>`)
29
+ * - `implementation` → Realization (`..|>`)
30
+ */
31
+ export const ARCHGUARD_RELATION_ARROWS = {
32
+ dependency: { arrow: '..>', label: '<<uses>>' },
33
+ call: { arrow: '..>', label: '<<call>>' },
34
+ composition: { arrow: 'o--' },
35
+ aggregation: { arrow: 'o--' },
36
+ inheritance: { arrow: '--|>' },
37
+ implementation: { arrow: '..|>' },
38
+ };
39
+ /** Strip the leading `<scopeKey>/` so only the relpath remains. */
40
+ export function pathName(id) {
41
+ const slash = id.indexOf('/');
42
+ return slash === -1 ? id : id.slice(slash + 1);
43
+ }
44
+ /**
45
+ * Display name `relpath.EntityName`, optionally truncated to the last
46
+ * `maxDirSegments` directory segments (front-truncated, tail + entity kept).
47
+ * `maxDirSegments = 0` keeps the full path.
48
+ */
49
+ export function displayName(id, maxDirSegments = 0) {
50
+ const rel = pathName(id);
51
+ const dot = rel.lastIndexOf('.');
52
+ const dirs = dot === -1 ? '' : rel.slice(0, dot);
53
+ const entity = dot === -1 ? rel : rel.slice(dot + 1);
54
+ const segments = dirs.split('/').filter(Boolean);
55
+ if (maxDirSegments > 0 && segments.length > maxDirSegments) {
56
+ return [...segments.slice(-maxDirSegments), entity].join('/');
57
+ }
58
+ return rel;
59
+ }
60
+ /** Deterministic alias map: node at index `i` → `n<i>`. */
61
+ export function archguardAliasMap(nodes) {
62
+ const aliasOf = new Map();
63
+ nodes.forEach((node, i) => aliasOf.set(node.id, `n${i}`));
64
+ return aliasOf;
65
+ }
66
+ /** Escape a name for a quoted PlantUML identifier. */
67
+ function sanitizeName(name) {
68
+ return name.replace(/["\r\n\t\\]/g, "'").replace(/\s+/g, ' ').trim();
69
+ }
70
+ /** Assign (and remember) a stable alias for a node. */
71
+ function aliasFor(node, index, aliasOf) {
72
+ const existing = aliasOf.get(node.id);
73
+ if (existing !== undefined)
74
+ return existing;
75
+ let alias = `n${index}`;
76
+ let k = index;
77
+ while ([...aliasOf.values()].includes(alias)) {
78
+ alias = `n${++k}`;
79
+ }
80
+ aliasOf.set(node.id, alias);
81
+ return alias;
82
+ }
83
+ /** Emit a `@startuml … @enduml` class diagram for a (possibly filtered) graph. */
84
+ export function archguardToPlantUml(graph, options = {}) {
85
+ const aliasOf = options.aliasOf ?? archguardAliasMap(graph.nodes);
86
+ const maxDirSegments = options.maxDirSegments ?? 0;
87
+ const lines = ['@startuml'];
88
+ graph.nodes.forEach((node, i) => {
89
+ const alias = aliasFor(node, i, aliasOf);
90
+ lines.push(`class "${sanitizeName(displayName(node.id, maxDirSegments))}" as ${alias}`);
91
+ });
92
+ for (const edge of graph.edges) {
93
+ const source = aliasOf.get(edge.from);
94
+ const target = aliasOf.get(edge.to);
95
+ if (source === undefined || target === undefined)
96
+ continue;
97
+ const mapping = ARCHGUARD_RELATION_ARROWS[edge.relationType] ?? { arrow: '-->' };
98
+ const suffix = mapping.label ? ` : ${mapping.label}` : '';
99
+ lines.push(`${source} ${mapping.arrow} ${target}${suffix}`);
100
+ }
101
+ lines.push('@enduml');
102
+ return { puml: lines.join('\n'), aliasOf };
103
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @yalehwang/plantuml-js — viz-free core (the `./elk` subpath export).
3
+ *
4
+ * Everything a caller needs to parse, transform and render class diagrams with
5
+ * the ELK engine, without pulling in `@viz-js/viz` (which ships a ~1MB WASM).
6
+ * `src/index.ts` is the full build: it re-exports this core and adds the viz
7
+ * engine + `renderDot`.
8
+ */
9
+ import { PlantUmlModel } from './model.js';
10
+ import { parsePlantUml } from './parser.js';
11
+ import { LayoutEngine } from './layout.js';
12
+ import { ElkLayoutEngine } from './layout/elk.js';
13
+ import { renderSvg } from './render/svg.js';
14
+ import { ViewSpec, TransformOptions } from './transform.js';
15
+ export type { PlantUmlModel, PlantUmlEntity, PlantUmlMember, PlantUmlRelation, PlantUmlPackage, EntityKind, RelationType, } from './model.js';
16
+ export type { LayoutEngine, LayoutResult, NodeLayout, EdgeLayout, Point, } from './layout.js';
17
+ export interface RendererOptions {
18
+ /**
19
+ * `'elk'` (default) | a custom `LayoutEngine` instance. `'viz'` is only
20
+ * accepted by the full build (`@yalehwang/plantuml-js`); this core entry
21
+ * fails closed on it.
22
+ */
23
+ layout?: 'elk' | 'viz' | LayoutEngine;
24
+ /** Collapse/expand the diagram before layout (overview, single package, …). */
25
+ view?: ViewSpec;
26
+ /** Extra model transforms applied on top of the view (aggregation, cycles, …). */
27
+ transform?: TransformOptions;
28
+ }
29
+ export interface RenderResult {
30
+ svg: string;
31
+ diagramType: string;
32
+ warnings: string[];
33
+ }
34
+ export interface Renderer {
35
+ render(puml: string): Promise<RenderResult>;
36
+ }
37
+ /** One structured syntax finding produced by {@link checkSyntax}. */
38
+ export interface SyntaxDiagnostic {
39
+ /** 1-based line number in the source. */
40
+ line: number;
41
+ message: string;
42
+ severity: 'error' | 'warning';
43
+ }
44
+ /** Result of {@link checkSyntax}: diagnostics, never a thrown exception. */
45
+ export interface SyntaxCheckResult {
46
+ /** True when no `error`-severity diagnostics were found. */
47
+ ok: boolean;
48
+ errors: SyntaxDiagnostic[];
49
+ warnings: SyntaxDiagnostic[];
50
+ }
51
+ /** Error thrown by {@link createRenderer}'s `render` on structurally invalid puml. */
52
+ export declare class RenderError extends Error {
53
+ readonly diagnostics: SyntaxDiagnostic[];
54
+ constructor(diagnostics: SyntaxDiagnostic[]);
55
+ }
56
+ export declare function createRenderer(options?: RendererOptions): Renderer;
57
+ /**
58
+ * Entity count at or above which the default full-graph render enables hub
59
+ * summarization. Smaller models stay untouched so a hand-authored diagram is
60
+ * drawn exactly as written.
61
+ */
62
+ export declare const FULL_GRAPH_HUB_NODE_THRESHOLD = 40;
63
+ /**
64
+ * Distinct-source in-degree above which a node's incoming edges are summarized
65
+ * into a `usageCount` badge in the default full-graph render. 6 summarizes the
66
+ * archguard package diagram's shared-infrastructure hubs (`src/types`,
67
+ * `src/types/extensions`, `src/core/interfaces`, plus the other nodes with 8+
68
+ * distinct dependents) while leaving ordinary modules drawn edge-by-edge.
69
+ */
70
+ export declare const FULL_GRAPH_HUB_IN_DEGREE_THRESHOLD = 6;
71
+ /**
72
+ * The transform pipeline the renderer applies to a full (unviewed) model by
73
+ * default: aggregate parallel edges, summarize hubs on large graphs, and mark
74
+ * cycle feedback arcs. `overrides` (a caller-supplied `transform` option) wins
75
+ * over the defaults, so `{ hubThreshold: undefined }` re-enables per-edge
76
+ * drawing of the hub's incoming edges.
77
+ */
78
+ export declare function transformFullGraph(model: PlantUmlModel, overrides?: TransformOptions): PlantUmlModel;
79
+ /**
80
+ * Validate a puml string without throwing. Returns structured diagnostics for
81
+ * structurally invalid input (content outside a diagram, unbalanced
82
+ * `@startuml`/`@enduml`, malformed entity declarations), so callers can surface
83
+ * line-accurate messages instead of catching an exception.
84
+ */
85
+ export declare function checkSyntax(puml: string): SyntaxCheckResult;
86
+ /** One per-line explanation produced by {@link explain}. */
87
+ export interface LineExplanation {
88
+ /** 1-based line number. */
89
+ line: number;
90
+ /** The raw source text of the line. */
91
+ text: string;
92
+ kind: 'directive' | 'entity' | 'member' | 'relation' | 'package' | 'comment' | 'blank' | 'unknown';
93
+ /** A human-readable description of what the line means. */
94
+ explanation: string;
95
+ }
96
+ /**
97
+ * Explain a puml string line by line, classifying each line (directive, entity,
98
+ * member, relation, package, comment, blank, or unknown) with a short
99
+ * human-readable description. Purely descriptive — it never mutates or throws.
100
+ */
101
+ export declare function explain(puml: string): LineExplanation[];
102
+ export { parsePlantUml, ElkLayoutEngine, renderSvg };
103
+ export { computeLayoutMetrics } from './layout-metrics.js';
104
+ export type { LayoutMetrics } from './layout-metrics.js';
105
+ export { applyView, transformModel, aggregateRelations, transitiveReduce, summarizeHubs, markCycles, groupByPathPrefix, } from './transform.js';
106
+ export type { ViewSpec, TransformOptions } from './transform.js';
107
+ export { archguardToPlantUml, archguardAliasMap, pathName, displayName, ARCHGUARD_RELATION_ARROWS, } from './archguard.js';
108
+ export type { ArchguardNode, ArchguardEdge, ArchguardGraph, ArchguardBridgeOptions, ArchguardPlantUml, } from './archguard.js';