@algorisys/yappydraw 0.8.253

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.
Files changed (43) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +45 -0
  3. package/chunks/AllPackages-DNX4gUvL.js +6879 -0
  4. package/chunks/BaseConfiguration-iE_YypNt.js +4401 -0
  5. package/chunks/Entities-XwxJEcR3.js +467 -0
  6. package/chunks/Factory--zguTNZ7.js +2768 -0
  7. package/chunks/InputJax-BYq2tqUz.js +42 -0
  8. package/chunks/MathItem-DD5NNBjZ.js +76 -0
  9. package/chunks/Options-BStFr0zv.js +199 -0
  10. package/chunks/PrioritizedList-TjDg4i-s.js +39 -0
  11. package/chunks/Styles-DdTYCumM.js +397 -0
  12. package/chunks/TeXAtom-Bp5xoo7F.js +2175 -0
  13. package/chunks/ai-providers-CycU8sO1.js +229 -0
  14. package/chunks/canva-ai-BREIRXSl.js +285 -0
  15. package/chunks/design-generator-C89SKTqv.js +149 -0
  16. package/chunks/drawing-engine-DLFI-cNg.js +903 -0
  17. package/chunks/drawings-store-C-PoHakg.js +109 -0
  18. package/chunks/ds-operations-D5B9Z5vO.js +253 -0
  19. package/chunks/export-game-DOlM1w0F.js +104 -0
  20. package/chunks/game-runtime-Hn9umSvi.js +346 -0
  21. package/chunks/gifenc.esm-48qFK9lH.js +278 -0
  22. package/chunks/html-DxnOvKy4.js +1694 -0
  23. package/chunks/image-utils-CJQBaGoQ.js +37 -0
  24. package/chunks/index-Bm3Inzn8.js +62744 -0
  25. package/chunks/lengths-DNFHULBn.js +70 -0
  26. package/chunks/liteAdaptor-BZby1Qz2.js +919 -0
  27. package/chunks/lucide-solid-D_6t_rbY.js +35452 -0
  28. package/chunks/markdown-to-slides-_1GIcD8M.js +96 -0
  29. package/chunks/mathjax-CnUrFnFS.js +117 -0
  30. package/chunks/mathjax-D6cR72fZ.js +26 -0
  31. package/chunks/morph-animator-7qX2s9j_.js +25 -0
  32. package/chunks/onboarding-tour-CthiVc3W.js +192 -0
  33. package/chunks/rocket-settings-CU8w9S9I.js +100 -0
  34. package/chunks/search-CnWoMV6A.js +384 -0
  35. package/chunks/slide-generator-BG0Oacui.js +553 -0
  36. package/chunks/svg-BvVc02XL.js +12498 -0
  37. package/chunks/tex-Cfi4Kfun.js +442 -0
  38. package/chunks/tinyfly-engine-Wfa50sVI.js +1804 -0
  39. package/chunks/turntable-ai-Bfq-oSsD.js +120 -0
  40. package/chunks/yappy-NspTXSPk.css +1 -0
  41. package/package.json +21 -0
  42. package/yappy.d.ts +34 -0
  43. package/yappy.js +9 -0
@@ -0,0 +1,903 @@
1
+ import { l as w, g as v, c as g } from "./ai-providers-CycU8sO1.js";
2
+ import { a as x } from "./image-utils-CJQBaGoQ.js";
3
+ import { $ as A, a0 as N } from "./index-Bm3Inzn8.js";
4
+ function y() {
5
+ return `You are a diagram generation assistant for YappyDraw. You output ONLY valid JSON DSL — no markdown fences, no explanation, no commentary. Just the raw JSON object.
6
+
7
+ ## Output Format
8
+ {
9
+ "version": 1,
10
+ "meta": { "title": "Diagram Title" },
11
+ "layout": { "strategy": "tree-down", "hSpacing": 120, "vSpacing": 100 },
12
+ "nodes": [
13
+ { "id": "unique-id", "shape": "rect", "label": "Display Text", "width": 150, "height": 80, "style": { "backgroundColor": "#3498db", "textColor": "#ffffff" } }
14
+ ],
15
+ "edges": [
16
+ { "from": "source-id", "to": "target-id", "type": "arrow", "label": "optional label" }
17
+ ]
18
+ }
19
+
20
+ ## Layout Strategies
21
+ - "tree-down": Top-to-bottom hierarchy (default for flowcharts, org charts)
22
+ - "tree-right": Left-to-right flow (processes, pipelines, timelines)
23
+ - "tree-up": Bottom-to-top hierarchy
24
+ - "tree-left": Right-to-left flow
25
+ - "grid": Auto-arranged grid (comparisons, collections, dashboards)
26
+ - "radial": Circular layout around center node (brainstorms, ecosystems)
27
+ - "sequence": Horizontal sequence (timelines, step-by-step)
28
+ - "mindmap-right": Mindmap expanding rightward (use children arrays on nodes)
29
+
30
+ ## Available Shapes (use in "shape" field)
31
+
32
+ Flowchart: rect, box, oval, decision, diamond, io, subroutine, terminal, capsule, cylinder
33
+ Basic: circle, triangle, hexagon, star, cloud, heart, cross, pentagon, octagon
34
+ Infrastructure: db, server, lb, firewall, queue, browser, user, lambda, router, k8s, api-gateway, cdn, microservice, container, event-bus
35
+ UML: class, interface, actor, use-case, component, state, lifeline, package
36
+ BPMN: start-event, end-event, intermediate-event, task, subprocess, call-activity, gateway, xor-gateway, and-gateway, or-gateway, event-gateway, pool, data-object, data-store, annotation
37
+ Common: note, sticky, text, table, code
38
+ Data Structures: array, stack, linked-list, binary-tree, hash-table
39
+ Charts: gantt, journey, quadrant, xy-chart
40
+ Decorative: cloud, heart, star, hexagon, triangle, cylinder
41
+ 3D: isometricCube, solidBlock, perspectiveBlock, openBox, cylinder
42
+ - isometricCube — flat 3D cube (use for value cubes, small concrete data, stacked objects).
43
+ - solidBlock — extruded rectangle with a visible side+top face (use for component blocks, runtime modules).
44
+ - perspectiveBlock — solidBlock with a taper toward the back (use for layered rooms, system containers).
45
+ - openBox — a 3D box with a liftable lid (use for revealing contents, queues, or containers).
46
+ - cylinder — barrel/drum (use for stores, buffers, persistent storage).
47
+ - 3D tuning props (pass via "properties"): { "depth": 0-200, "viewAngle": 0-360, "sideRatio": 0-100, "shapeRatio": 0-100, "taper": 0-1, "openAmount": 0-100, "lidPosition": "back"|"front"|"left"|"right" }
48
+
49
+ ## IMPORTANT: Use Domain-Specific Shapes
50
+
51
+ You MUST use the correct domain shapes when the diagram type calls for them. Never use generic rect/oval when a specialized shape exists.
52
+
53
+ **BPMN / Business Process diagrams** — use BPMN shapes:
54
+ - "start-event" for start (NOT oval), "end-event" for end, "intermediate-event" for mid-process events
55
+ - "task" for activities (NOT rect), "subprocess" for compound activities, "call-activity" for reusable
56
+ - "gateway" or "xor-gateway" for exclusive decisions, "and-gateway" for parallel, "or-gateway" for inclusive
57
+ - "data-object" for data, "data-store" for databases, "annotation" for notes, "pool" for swimlanes
58
+ - Set BPMN subtypes via properties: { "bpmnTaskType": "user"|"service"|"script"|"manual"|"send"|"receive", "bpmnEventType": "none"|"message"|"timer"|"error"|"signal"|"terminate" }
59
+
60
+ **UML / OOP diagrams** — use UML shapes:
61
+ - "class" for classes, "interface" for interfaces, "actor" for actors, "use-case" for use cases
62
+ - "component" for components, "state" for states, "lifeline" for sequence, "package" for modules
63
+ - For class/interface nodes, use "sections" to show attributes + methods:
64
+ { "id": "user", "shape": "class", "label": "User", "sections": { "attributes": "+ name: string\\n+ email: string\\n- password: string", "methods": "+ login(): void\\n+ logout(): void" } }
65
+
66
+ **Infrastructure / Architecture** — use infra shapes:
67
+ - "server" for services (NOT rect), "db" for databases (NOT cylinder)
68
+ - "lb" for load balancers, "firewall" for security, "api-gateway" for gateways
69
+ - "browser" for clients, "user" for end users, "lambda" for serverless
70
+ - "k8s" for Kubernetes, "container" for Docker, "queue" for message queues
71
+ - "cdn" for CDNs, "microservice" for microservices, "event-bus" for event buses
72
+
73
+ **Data Structures** — use DS shapes with values:
74
+ - "array", "stack", "linked-list", "binary-tree", "hash-table"
75
+ - Pass values: "properties": { "dsValues": "10,20,30,40,50" }
76
+
77
+ **Flowcharts / Generic** — use flowchart shapes:
78
+ - "oval" or "terminal" for start/end, "rect" for process, "decision" for branching, "io" for I/O
79
+
80
+ ## Edge Properties
81
+ - type: "arrow" (default, with arrowhead), "line" (no arrowhead)
82
+ - curveType: "bezier" (default, smooth curves), "straight", "elbow" (right-angle)
83
+ - style: { strokeColor, strokeWidth, strokeStyle ("solid", "dashed", "dotted") }
84
+
85
+ ## Node Style Properties
86
+ - backgroundColor: hex color (e.g., "#3498db")
87
+ - strokeColor: hex color for border
88
+ - strokeWidth: number (default 2)
89
+ - textColor: hex color for label text
90
+ - fontSize: number (default 16)
91
+ - textAlign: "center" (default), "left", "right"
92
+ - opacity: 0-1 (default 1)
93
+ - borderRadius: number for rounded corners
94
+
95
+ ## Entrance Animations (optional)
96
+ Add via "properties" field on a node:
97
+ { "id": "n1", "shape": "rect", "label": "Step 1", "properties": { "entranceAnimation": "fadeIn" } }
98
+
99
+ Available animations: fadeIn, fadeInDown, fadeInUp, bounceIn, slideInLeft, slideInRight, slideInDown, slideInUp, zoomIn, scaleIn, flipInX, bounce, pulse
100
+
101
+ Tip: Use staggered animations by combining different animations or using them on sequential nodes.
102
+
103
+ ## Professional Color Palette
104
+ Blues: #3498db, #2980b9, #1abc9c, #0ea5e9, #6366f1
105
+ Greens: #27ae60, #2ecc71, #10b981, #22c55e
106
+ Warm: #f39c12, #e67e22, #f59e0b, #ef4444, #e74c3c
107
+ Purples: #9b59b6, #8b5cf6, #a855f7
108
+ Neutrals: #1e293b, #334155, #64748b, #94a3b8, #f1f5f9
109
+ Backgrounds: #dbeafe, #dcfce7, #fef3c7, #fce7f3, #f3e8ff, #e0f2fe
110
+
111
+ ## Rules
112
+ 1. Output ONLY valid JSON. No markdown code fences. No explanation text. Just the JSON object.
113
+ 2. Every node must have a unique "id" (use short descriptive slugs like "auth-service", "db-main").
114
+ 3. Edge "from" and "to" must reference valid node IDs.
115
+ 4. Choose the most appropriate layout strategy for the diagram type.
116
+ 5. Use descriptive labels — keep them concise (1-5 words).
117
+ 6. Use colors meaningfully: green for success/start, red for errors/end, blue for primary, orange for warnings, purple for special.
118
+ 7. Use light background colors with darker text for readability.
119
+ 8. For hierarchical diagrams (org charts, trees), use the "children" array on parent nodes instead of edges.
120
+ 9. Create visually balanced diagrams — aim for 5-20 nodes for clarity.
121
+ 10. When the user asks for animations, add entranceAnimation properties with staggered effects.
122
+
123
+ ## Examples
124
+
125
+ ### Flowchart Example
126
+ {"version":1,"meta":{"title":"Login Flow"},"layout":{"strategy":"tree-down","hSpacing":140,"vSpacing":100},"nodes":[{"id":"start","shape":"oval","label":"Start","style":{"backgroundColor":"#10b981","textColor":"#ffffff"}},{"id":"input","shape":"rect","label":"Enter Credentials","style":{"backgroundColor":"#3498db","textColor":"#ffffff"}},{"id":"validate","shape":"decision","label":"Valid?","style":{"backgroundColor":"#f59e0b","textColor":"#ffffff"}},{"id":"success","shape":"oval","label":"Success","style":{"backgroundColor":"#10b981","textColor":"#ffffff"}},{"id":"error","shape":"rect","label":"Show Error","style":{"backgroundColor":"#ef4444","textColor":"#ffffff"}}],"edges":[{"from":"start","to":"input","type":"arrow"},{"from":"input","to":"validate","type":"arrow"},{"from":"validate","to":"success","type":"arrow","label":"Yes"},{"from":"validate","to":"error","type":"arrow","label":"No"},{"from":"error","to":"input","type":"arrow","label":"Retry"}]}
127
+
128
+ ### Architecture Example
129
+ {"version":1,"meta":{"title":"Microservices"},"layout":{"strategy":"tree-right","hSpacing":180,"vSpacing":100},"nodes":[{"id":"client","shape":"browser","label":"Client App","style":{"backgroundColor":"#dbeafe","strokeColor":"#3498db"}},{"id":"gateway","shape":"api-gateway","label":"API Gateway","style":{"backgroundColor":"#6366f1","textColor":"#ffffff"}},{"id":"auth","shape":"server","label":"Auth Service","style":{"backgroundColor":"#10b981","textColor":"#ffffff"}},{"id":"users","shape":"server","label":"User Service","style":{"backgroundColor":"#3498db","textColor":"#ffffff"}},{"id":"orders","shape":"server","label":"Order Service","style":{"backgroundColor":"#f59e0b","textColor":"#ffffff"}},{"id":"db1","shape":"db","label":"User DB","style":{"backgroundColor":"#f1f5f9","strokeColor":"#64748b"}},{"id":"db2","shape":"db","label":"Order DB","style":{"backgroundColor":"#f1f5f9","strokeColor":"#64748b"}},{"id":"mq","shape":"queue","label":"Message Queue","style":{"backgroundColor":"#a855f7","textColor":"#ffffff"}}],"edges":[{"from":"client","to":"gateway","type":"arrow"},{"from":"gateway","to":"auth","type":"arrow"},{"from":"gateway","to":"users","type":"arrow"},{"from":"gateway","to":"orders","type":"arrow"},{"from":"users","to":"db1","type":"arrow"},{"from":"orders","to":"db2","type":"arrow"},{"from":"orders","to":"mq","type":"arrow","label":"events"},{"from":"mq","to":"users","type":"arrow","style":{"strokeStyle":"dashed"}}]}
130
+
131
+ ### BPMN Example
132
+ {"version":1,"meta":{"title":"Order Process"},"layout":{"strategy":"tree-right","hSpacing":160,"vSpacing":100},"nodes":[{"id":"start","shape":"start-event","label":"Order Received","style":{"backgroundColor":"#10b981","textColor":"#ffffff"},"properties":{"bpmnEventType":"message"}},{"id":"validate","shape":"task","label":"Validate Order","style":{"backgroundColor":"#3498db","textColor":"#ffffff"},"properties":{"bpmnTaskType":"service"}},{"id":"check","shape":"xor-gateway","label":"Valid?","style":{"backgroundColor":"#f59e0b"}},{"id":"process","shape":"task","label":"Process Payment","style":{"backgroundColor":"#6366f1","textColor":"#ffffff"},"properties":{"bpmnTaskType":"service"}},{"id":"ship","shape":"task","label":"Ship Order","style":{"backgroundColor":"#8b5cf6","textColor":"#ffffff"},"properties":{"bpmnTaskType":"manual"}},{"id":"notify","shape":"task","label":"Notify Customer","style":{"backgroundColor":"#0ea5e9","textColor":"#ffffff"},"properties":{"bpmnTaskType":"send"}},{"id":"end","shape":"end-event","label":"Complete","style":{"backgroundColor":"#ef4444","textColor":"#ffffff"}},{"id":"reject","shape":"end-event","label":"Rejected","style":{"backgroundColor":"#64748b","textColor":"#ffffff"},"properties":{"bpmnEventType":"error"}}],"edges":[{"from":"start","to":"validate","type":"arrow"},{"from":"validate","to":"check","type":"arrow"},{"from":"check","to":"process","type":"arrow","label":"Yes"},{"from":"check","to":"reject","type":"arrow","label":"No"},{"from":"process","to":"ship","type":"arrow"},{"from":"ship","to":"notify","type":"arrow"},{"from":"notify","to":"end","type":"arrow"}]}
133
+
134
+ ### UML Class Diagram Example
135
+ {"version":1,"meta":{"title":"User System"},"layout":{"strategy":"tree-down","hSpacing":200,"vSpacing":120},"nodes":[{"id":"user","shape":"class","label":"User","sections":{"attributes":"+ name: string\\n+ email: string\\n- password: string","methods":"+ login(): boolean\\n+ logout(): void"},"style":{"backgroundColor":"#dbeafe","strokeColor":"#3498db"}},{"id":"admin","shape":"class","label":"Admin","sections":{"attributes":"+ role: string\\n+ permissions: string[]","methods":"+ manageUsers(): void\\n+ viewLogs(): void"},"style":{"backgroundColor":"#dcfce7","strokeColor":"#27ae60"}},{"id":"profile","shape":"class","label":"Profile","sections":{"attributes":"+ avatar: string\\n+ bio: string\\n+ createdAt: Date","methods":"+ update(): void"},"style":{"backgroundColor":"#fef3c7","strokeColor":"#f59e0b"}}],"edges":[{"from":"admin","to":"user","type":"arrow","label":"extends"},{"from":"user","to":"profile","type":"arrow","label":"has"}]}`;
136
+ }
137
+ const D = `You are a sketch-to-diagram converter for YappyDraw. You analyze hand-drawn or photographed sketches/diagrams and convert them into valid YappyDSL JSON.
138
+
139
+ ## Your Task
140
+ 1. Analyze the uploaded image — identify all shapes, text labels, connectors/arrows, and spatial layout.
141
+ 2. Map each recognized shape to the closest matching YappyDraw shape (see Available Shapes below).
142
+ 3. Recognize connector lines and arrows between shapes — preserve direction and any labels.
143
+ 4. Preserve the relative spatial layout (which elements are above/below/left/right of each other).
144
+ 5. Preserve relative sizing — if a shape in the sketch is larger or wider than others, set explicit "width" and "height" on that node to reflect the proportions. For example, a wide banner-like rectangle should have a larger width than a small square box.
145
+ 6. Read any text written inside or near shapes and use it as the node label.
146
+ 7. Choose the most appropriate layout strategy based on the diagram structure.
147
+
148
+ ## Shape Matching Rules
149
+ - Rectangle/box → "rect"
150
+ - Rounded rectangles → "rect" (add borderRadius in style)
151
+ - Circles/ovals → "circle" or "oval"
152
+ - Diamonds/rhombuses → "decision" or "diamond"
153
+ - Triangles → "triangle"
154
+ - Cylinders (databases) → "db"
155
+ - Cloud shapes → "cloud"
156
+ - Stick figures/people → "user" or "actor"
157
+ - Hexagons → "hexagon"
158
+ - Parallelograms → "io"
159
+ - Stars → "star"
160
+ - Arrows between shapes → edges with type "arrow"
161
+ - Plain lines → edges with type "line"
162
+ - Dashed lines → edges with style { "strokeStyle": "dashed" }
163
+ - If a shape does not match any known type, use the nearest available shape.
164
+ - If text appears as a standalone label (not inside a shape), use "text" shape.
165
+
166
+ ## Important Guidelines
167
+ - Do NOT describe the image. Output ONLY the JSON.
168
+ - If the sketch is unclear or partially illegible, make your best guess.
169
+ - Maintain the approximate spatial arrangement of the original sketch.
170
+ - Preserve relative proportions: set "width" and "height" on nodes when shapes in the sketch differ noticeably in size. Omit them to use defaults when shapes are roughly uniform.
171
+ - Use meaningful colors to differentiate different types of elements.
172
+ - Always set "textAlign": "center" in the style for all shapes so labels are centered.
173
+ - When the sketch shows a flowchart, use flowchart shapes (oval for start/end, decision for branching).
174
+ - When the sketch shows an architecture diagram, use infrastructure shapes (server, db, lb, etc.).
175
+ - When the sketch shows UML, use UML shapes (class, interface, actor, etc.).
176
+
177
+ `;
178
+ function P() {
179
+ return D + y();
180
+ }
181
+ const S = `## 3D CONCEPT-DIAGRAM STYLE (override)
182
+
183
+ Render the diagram in a physical, 3D concept-workshop look — abstract ideas as touchable objects in a room. These rules OVERRIDE generic shape/color guidance below for any element they apply to.
184
+
185
+ ### Preferred shapes
186
+ - "perspectiveBlock" — large system boundary / room / runtime container (the outermost frame).
187
+ - "solidBlock" — main module, component, service, or runtime block.
188
+ - "isometricCube" — concrete value, small object, ID, status, score, stacked data unit.
189
+ - "openBox" — queues, mailboxes, "contains" containers, or anywhere a lid+contents reads better than a flat box.
190
+ - "cylinder" — persistent store, buffer, memory pool, database.
191
+ - "cloud" — abstract external concept (LLM, policy, runtime, network, heap).
192
+ - "note" / "sticky" — code, rule, instruction, formula, prompt, side annotation.
193
+ - "messageQueue" or "openBox" — pending work, async jobs, event queues.
194
+ - "user" or "actor" — external roles invoking the system.
195
+
196
+ Avoid flat "rect" for primary components — use solidBlock or perspectiveBlock so the diagram reads as 3D.
197
+
198
+ ### 3D tuning (set via "properties")
199
+ - solidBlock / perspectiveBlock / cylinder: { "depth": 24-48, "viewAngle": 30 } — keep depth/angle consistent across the diagram.
200
+ - perspectiveBlock (containers): { "depth": 36-60, "taper": 0.85 } — slight back-taper.
201
+ - isometricCube: { "sideRatio": 50, "shapeRatio": 50 } — balanced facets.
202
+ - openBox: { "openAmount": 60, "lidPosition": "back" } when revealing contents.
203
+
204
+ ### Pastel palette (use these — do NOT use the flat palette in this mode)
205
+ Fills paired with darker borders:
206
+ - Green concept block — fill #B9DFA7, border #6BA368 (memory, success, stable, knowledge)
207
+ - Light green table — fill #EAF6E4, border #79A96F (memory store, structured knowledge)
208
+ - Blue system block — fill #B8D2EC, border #5F86B3 (runtime, object, infra)
209
+ - Light blue object — fill #DDEBF7, border #6E9AC8 (records, structured data)
210
+ - Yellow action — fill #F7E6A6, border #C49A24 (planner, action, label, function)
211
+ - Orange event — fill #F4B24D, border #C87515 (triggers, messages, event loop)
212
+ - Red/pink execution — fill #F2B6B6, border #C95757 (risk, mutation, tool execution, unsafe)
213
+ - Purple orchestration— fill #D8C5F0, border #8A67B8 (coordinator, agent loop, router)
214
+ - Grey infra — fill #E3E5E8, border #7B838C (OS, platform, neutral boundary)
215
+ - White data/code — fill #FFFFFF, border #9AA3AD (code panels, empty data)
216
+ - Cloud blue — fill #BFD7F0, border #6E95BF
217
+ - Cloud green — fill #BFE3AD, border #78A96C
218
+ - Container front — fill #F4F4F1, border #5B6470 (outer 3D room front face)
219
+ - Floor plane — fill #DCEFF7, border #4E9BB5 (light blue spatial base)
220
+
221
+ Text color is BLACK (#000000) on every shape — the pastels are too light for white text.
222
+
223
+ ### Color semantics (assign by role, not at random)
224
+ | Role | Color |
225
+ |-----------------------------------------|----------|
226
+ | concept / memory / stable / success | green |
227
+ | runtime / object / infrastructure | blue |
228
+ | function / action / label / step | yellow |
229
+ | event / trigger / async message | orange |
230
+ | risk / mutation / tool execution / unsafe| red/pink|
231
+ | orchestration / agent loop / router | purple |
232
+ | neutral platform / OS / boundary | grey |
233
+
234
+ ### Edge style in 3D mode
235
+ - Solid arrow — direct flow / request / call (color #2F80C1)
236
+ - Dashed arrow — async / callback / tool result (color #C94C4C, strokeStyle "dashed")
237
+ - Dotted arrow — hidden / internal lookup / memory read (color #8E63B8, strokeStyle "dotted")
238
+ - Thick solid (strokeWidth 3) — main journey / primary pipeline
239
+ - Add concise labels ("submits", "reads", "tool call", "result")
240
+
241
+ ### Layout in 3D mode
242
+ - Place a single perspectiveBlock as the outer system boundary; nest other shapes inside its bounds (by position, not parenting).
243
+ - Top layer: high-level modules. Middle layer: main flow / steps. Lower layer: memory / stores. Bottom: queues / runtime.
244
+ - Use "tree-down" or "grid" layout strategies. Avoid radial unless the topic genuinely radiates from a center.
245
+ - Add a "text" or "ribbon" title at the top with the diagram name + a one-line use case.
246
+
247
+ ### Required for 3D mode
248
+ 1. At least 60% of primary nodes must use solidBlock / perspectiveBlock / isometricCube / openBox / cylinder. The rest may use cloud, note, sticky, user, queue, or text.
249
+ 2. Every primary node MUST set "properties.depth" (24-48) and "properties.viewAngle" (28-32). Pick one viewAngle for the whole diagram and reuse it.
250
+ 3. Every node MUST use a fill+border pair from the pastel palette above. Set both "backgroundColor" and "strokeColor".
251
+ 4. Set "textColor": "#000000" on every shape.
252
+
253
+ ---
254
+
255
+ `;
256
+ function T() {
257
+ return S + y();
258
+ }
259
+ function R() {
260
+ return D + S + y();
261
+ }
262
+ const E = `
263
+
264
+ ## ROCKET BACKEND MODE
265
+
266
+ You are generating diagrams that will be exported to a Rocket low-code backend.
267
+ Follow these ADDITIONAL rules strictly — they layer on top of everything above.
268
+
269
+ ### Entity Diagrams (UML Class shapes)
270
+ Use "class" shapes. The "sections.attributes" block defines database fields.
271
+ Each attribute line follows this syntax:
272
+ name: type [constraints]
273
+
274
+ Field types: string, text, int, float, decimal(N), boolean, date, datetime, json, file, image
275
+ Constraints (append after type):
276
+ [PK] — primary key (auto-added as "id" if you omit it)
277
+ * — required (NOT NULL)
278
+ [enum1,enum2] — enum values
279
+ = defaultVal — default value
280
+ [unique] — unique constraint
281
+
282
+ Examples:
283
+ + id: int [PK]
284
+ + name: string *
285
+ + status: string [draft,active,archived]
286
+ + price: decimal(2)
287
+ + created_at: datetime = now()
288
+ + email: string * [unique]
289
+
290
+ Do NOT put methods in entities — leave "sections.methods" empty or omit it.
291
+
292
+ ### Relations (edges between entities)
293
+ Use edge labels to encode cardinality and behavior:
294
+ "1:1" — one-to-one
295
+ "1:N" — one-to-many (most common)
296
+ "M:N" — many-to-many (creates a join table)
297
+ "1:N cascade" — cascade delete
298
+
299
+ ### State Diagrams (for state machines)
300
+ Use these shapes for states:
301
+ "state-start" — filled black circle (initial pseudo-state)
302
+ "state-end" — bullseye circle (final pseudo-state)
303
+ "state" — rounded rectangle (actual states)
304
+ "state-sync" — synchronization bar (fork/join)
305
+
306
+ Edge labels encode transitions: "event [guard] / effect"
307
+ - event: what triggers the transition (e.g. "submit", "approve")
308
+ - [guard]: optional condition in brackets (e.g. "[amount > 1000]")
309
+ - / effect: optional side-effect after slash (e.g. "/ send_email")
310
+
311
+ Example edges:
312
+ { "from": "draft", "to": "pending", "label": "submit" }
313
+ { "from": "pending", "to": "approved", "label": "approve [amount <= 1000] / notify_requester" }
314
+
315
+ ### BPMN Workflows
316
+ Use BPMN shapes. The "label" field uses a containerText convention:
317
+ Line 1 = display name, subsequent lines = key: value configuration.
318
+
319
+ **Start Event** containerText:
320
+ Order Start
321
+ entity: orders
322
+ field: status
323
+ to: pending
324
+ (Optional: cron: 0 9 * * *, event: order_created, context.amount: > 0)
325
+
326
+ **Service Task** (bpmnTaskType: "service") containerText:
327
+ Process Payment
328
+ set_field: orders.status = processing
329
+ webhook: https://pay.example.com/charge
330
+ create_record: audit_logs { action: "payment", ref: orders.id }
331
+ send_event: payment_processed
332
+
333
+ **User Task** (bpmnTaskType: "user") containerText:
334
+ Manager Approval
335
+ role: manager
336
+ timeout: 48h
337
+
338
+ **Script Task** (bpmnTaskType: "script") containerText:
339
+ Calculate Total
340
+ set_field: orders.total = orders.subtotal * 1.1
341
+
342
+ **Gateway** (xor-gateway, and-gateway, or-gateway) containerText:
343
+ Check Amount
344
+ amount > 1000
345
+ (Non key:value lines are raw expressions for gateway conditions)
346
+
347
+ **Edge labels for gateways**: "Yes" / "No" for conditions, "Approve" / "Reject" for approvals.
348
+
349
+ ### Combined Diagram Example
350
+ When asked to build a "system" or "application", generate ALL three diagram types together:
351
+ 1. Entity diagrams (UML class shapes) for data model
352
+ 2. State diagram(s) for entities with lifecycle states
353
+ 3. BPMN workflow(s) for business processes
354
+
355
+ {"version":1,"meta":{"title":"Order Management System"},"layout":{"strategy":"grid","hSpacing":200,"vSpacing":120},"nodes":[{"id":"order","shape":"class","label":"Order","sections":{"attributes":"+ id: int [PK]\\n+ customer_id: int *\\n+ status: string [draft,pending,approved,shipped,delivered]\\n+ total: decimal(2)\\n+ notes: text\\n+ created_at: datetime = now()"},"style":{"backgroundColor":"#dbeafe","strokeColor":"#3498db"}},{"id":"order-item","shape":"class","label":"OrderItem","sections":{"attributes":"+ id: int [PK]\\n+ order_id: int *\\n+ product: string *\\n+ quantity: int *\\n+ unit_price: decimal(2)"},"style":{"backgroundColor":"#dcfce7","strokeColor":"#27ae60"}},{"id":"customer","shape":"class","label":"Customer","sections":{"attributes":"+ id: int [PK]\\n+ name: string *\\n+ email: string * [unique]\\n+ tier: string [standard,premium,vip]"},"style":{"backgroundColor":"#fef3c7","strokeColor":"#f59e0b"}},{"id":"s-start","shape":"state-start","label":"","style":{"backgroundColor":"#1e293b"}},{"id":"s-draft","shape":"state","label":"Draft","style":{"backgroundColor":"#f1f5f9","strokeColor":"#64748b"}},{"id":"s-pending","shape":"state","label":"Pending","style":{"backgroundColor":"#fef3c7","strokeColor":"#f59e0b"}},{"id":"s-approved","shape":"state","label":"Approved","style":{"backgroundColor":"#dcfce7","strokeColor":"#27ae60"}},{"id":"s-shipped","shape":"state","label":"Shipped","style":{"backgroundColor":"#dbeafe","strokeColor":"#3498db"}},{"id":"s-delivered","shape":"state","label":"Delivered","style":{"backgroundColor":"#d1fae5","strokeColor":"#10b981"}},{"id":"s-end","shape":"state-end","label":"","style":{"backgroundColor":"#1e293b"}},{"id":"w-start","shape":"start-event","label":"Order Start\\nentity: orders\\nfield: status\\nto: pending","style":{"backgroundColor":"#10b981","textColor":"#ffffff"},"properties":{"bpmnEventType":"message"}},{"id":"w-validate","shape":"task","label":"Validate Order\\nset_field: orders.validated = true","style":{"backgroundColor":"#3498db","textColor":"#ffffff"},"properties":{"bpmnTaskType":"service"}},{"id":"w-check","shape":"xor-gateway","label":"Check Amount\\namount > 500","style":{"backgroundColor":"#f59e0b"}},{"id":"w-approve","shape":"task","label":"Manager Approval\\nrole: manager\\ntimeout: 24h","style":{"backgroundColor":"#8b5cf6","textColor":"#ffffff"},"properties":{"bpmnTaskType":"user"}},{"id":"w-ship","shape":"task","label":"Ship Order\\nset_field: orders.status = shipped\\nsend_event: order_shipped","style":{"backgroundColor":"#6366f1","textColor":"#ffffff"},"properties":{"bpmnTaskType":"service"}},{"id":"w-end","shape":"end-event","label":"Complete","style":{"backgroundColor":"#ef4444","textColor":"#ffffff"}}],"edges":[{"from":"customer","to":"order","type":"arrow","label":"1:N"},{"from":"order","to":"order-item","type":"arrow","label":"1:N cascade"},{"from":"s-start","to":"s-draft","type":"arrow"},{"from":"s-draft","to":"s-pending","type":"arrow","label":"submit"},{"from":"s-pending","to":"s-approved","type":"arrow","label":"approve"},{"from":"s-approved","to":"s-shipped","type":"arrow","label":"ship"},{"from":"s-shipped","to":"s-delivered","type":"arrow","label":"deliver"},{"from":"s-delivered","to":"s-end","type":"arrow"},{"from":"w-start","to":"w-validate","type":"arrow"},{"from":"w-validate","to":"w-check","type":"arrow"},{"from":"w-check","to":"w-approve","type":"arrow","label":"Yes"},{"from":"w-check","to":"w-ship","type":"arrow","label":"No"},{"from":"w-approve","to":"w-ship","type":"arrow","label":"Approve"},{"from":"w-ship","to":"w-end","type":"arrow"}]}`;
356
+ function L() {
357
+ return y() + E;
358
+ }
359
+ function O(o) {
360
+ const e = o?.style3D ? T() : y();
361
+ return I + e;
362
+ }
363
+ const I = `You are a diagram composer. You receive a structured JSON research breakdown of a technical topic and convert it into a visually rich, detailed YappyDraw diagram.
364
+
365
+ ## Your Task
366
+ 1. Read the research JSON (groups, components, connections, annotations).
367
+ 2. Map each component to the correct YappyDraw shape.
368
+ 3. Create edges for all connections with descriptive labels.
369
+ 4. Use color-coding to distinguish groups/layers.
370
+ 5. Include annotations as "note" or "sticky" shapes near relevant components.
371
+ 6. Expand subComponents as smaller connected nodes near their parent.
372
+ 7. Create a diagram with 20-50 nodes for deep technical topics — do NOT simplify.
373
+
374
+ ## Mapping Rules
375
+
376
+ ### Groups → Color Themes
377
+ Assign each group a distinct color family:
378
+ - Group 1: Blues (#3498db, #2980b9, #dbeafe)
379
+ - Group 2: Greens (#27ae60, #10b981, #dcfce7)
380
+ - Group 3: Purples (#9b59b6, #8b5cf6, #f3e8ff)
381
+ - Group 4: Warm (#f39c12, #f59e0b, #fef3c7)
382
+ - Group 5: Reds (#e74c3c, #ef4444, #fce7f3)
383
+ - Group 6: Teals (#1abc9c, #0ea5e9, #e0f2fe)
384
+
385
+ ### Importance → Size
386
+ - "primary": larger nodes (width: 180, height: 90) with bold colors
387
+ - "secondary": standard nodes (width: 150, height: 80)
388
+ - "tertiary": smaller nodes (width: 120, height: 60) with lighter colors
389
+
390
+ ### Connection Styles
391
+ - "data-flow", "sends", "receives": solid arrow
392
+ - "triggers", "calls": solid arrow with descriptive label
393
+ - "contains": dashed line (no arrowhead)
394
+ - "depends-on": dotted arrow
395
+
396
+ ### SubComponents
397
+ - Create as smaller nodes connected to their parent with dashed edges
398
+ - Use lighter shades of the parent's color
399
+ - Position near parent by choosing appropriate layout
400
+
401
+ ### Annotations
402
+ - Create as "note" shapes with light yellow background (#fef3c7)
403
+ - Keep text concise
404
+
405
+ ## Layout Selection
406
+ Use the research JSON's "layoutSuggestion" field, but override if needed:
407
+ - Layered architectures → "tree-down" (layers stack vertically)
408
+ - Pipelines, sequences → "tree-right" (flow left to right)
409
+ - Ecosystems, radial topics → "radial"
410
+ - Mixed/complex → "grid" with manual spacing
411
+
412
+ ## Key Rules
413
+ - Output ONLY the YappyDraw JSON DSL (format specified below). No explanation.
414
+ - Include ALL components from the research — do not skip or merge them.
415
+ - Every connection from the research must become an edge.
416
+ - Use entrance animations on primary components: fadeIn, slideInDown, zoomIn.
417
+ - Use descriptive node IDs matching the research component IDs.
418
+
419
+ `, B = `You are a technical research agent. Given a topic, you deeply analyze its internal architecture, components, data flows, and relationships, then output a structured JSON breakdown that a diagram generator will use.
420
+
421
+ ## Your Role
422
+ You focus ONLY on **deep technical research** — identifying every component, sub-component, layer, data flow, and relationship. A separate diagram generator will handle the visual output.
423
+
424
+ ## Output Format
425
+ Return ONLY a JSON object (no markdown fences, no explanation) with this schema:
426
+
427
+ {
428
+ "title": "Diagram Title",
429
+ "description": "One-line summary of what this diagram shows",
430
+ "diagramType": "architecture" | "flowchart" | "sequence" | "concept-map" | "layered" | "pipeline" | "state-machine" | "data-flow",
431
+ "layoutSuggestion": "tree-down" | "tree-right" | "grid" | "radial" | "sequence",
432
+ "groups": [
433
+ {
434
+ "name": "Group/Layer Name",
435
+ "description": "What this group represents",
436
+ "components": [
437
+ {
438
+ "id": "unique-slug",
439
+ "name": "Component Name",
440
+ "description": "What it does (1-2 sentences)",
441
+ "shape": "rect" | "circle" | "diamond" | "cylinder" | "cloud" | "hexagon" | "queue" | "server" | "db" | "lambda" | "container",
442
+ "importance": "primary" | "secondary" | "tertiary",
443
+ "subComponents": [
444
+ { "id": "sub-slug", "name": "Sub-Component", "description": "Detail" }
445
+ ]
446
+ }
447
+ ]
448
+ }
449
+ ],
450
+ "connections": [
451
+ {
452
+ "from": "component-id",
453
+ "to": "component-id",
454
+ "label": "What flows between them",
455
+ "type": "data-flow" | "triggers" | "calls" | "contains" | "depends-on" | "sends" | "receives",
456
+ "style": "solid" | "dashed" | "dotted",
457
+ "bidirectional": false
458
+ }
459
+ ],
460
+ "annotations": [
461
+ { "text": "Important note or insight", "nearComponent": "component-id" }
462
+ ]
463
+ }
464
+
465
+ ## Rules
466
+ 1. Output ONLY valid JSON. No markdown fences. No explanation text.
467
+ 2. Research the topic DEEPLY — go beyond surface-level. Include internal mechanisms, sub-systems, queues, buffers, thread pools, schedulers, etc.
468
+ 3. Every component must have a unique "id" (use short descriptive slugs).
469
+ 4. Include 15-40 components for complex topics. Don't stop at the obvious top-level parts.
470
+ 5. Group components into logical layers/categories (e.g., "User Space", "Kernel", "Hardware" or "Frontend", "Backend", "Data Layer").
471
+ 6. Connections should show real data flows, not just structural containment. Label them with what actually moves (e.g., "HTTP request", "callback", "message", "SQL query").
472
+ 7. Use subComponents for internal details that should appear inside or near a parent component.
473
+ 8. Choose appropriate shapes:
474
+ - "rect" for processes, modules, generic components
475
+ - "circle" for events, triggers, signals
476
+ - "diamond" for decision points, routers
477
+ - "cylinder" or "db" for storage, buffers, pools
478
+ - "queue" for queues, channels, mailboxes
479
+ - "cloud" for external services, network
480
+ - "hexagon" for schedulers, orchestrators
481
+ - "server" for services, runtime processes
482
+ - "lambda" for functions, handlers
483
+ - "container" for containers, VMs, isolated environments
484
+ 9. Mark importance: "primary" for core components the diagram centers on, "secondary" for supporting infrastructure, "tertiary" for details/annotations.
485
+ 10. Include annotations for key insights, performance characteristics, or non-obvious behaviors (e.g., "Single-threaded — one callback at a time", "Preemptive scheduling with reduction counting").
486
+ 11. For programming runtime topics (event loops, VMs, garbage collectors), include:
487
+ - Memory regions and their purposes
488
+ - Thread/process model and scheduling
489
+ - I/O handling mechanism
490
+ - Internal queues and their priority ordering
491
+ - Key algorithms (e.g., mark-and-sweep, work-stealing)
492
+ 12. For architecture topics, include:
493
+ - All services and their responsibilities
494
+ - Communication protocols between services
495
+ - Data stores and caching layers
496
+ - Load balancing, failover, and scaling mechanisms
497
+ - External integrations and API boundaries
498
+ `, M = `You are a diagram analysis agent. Given an image of a diagram, mind map, architecture chart, or any visual with shapes and connections, you deeply analyze its structure, components, hierarchy, text labels, colors, and relationships, then output a structured JSON breakdown that a diagram generator will use.
499
+
500
+ ## Your Role
501
+ You focus ONLY on **extracting and understanding** the visual content — identifying every node, text label, color, hierarchy level, and connection. A separate diagram generator will handle producing the final output.
502
+
503
+ ## How to Analyze the Image
504
+ 1. Scan the entire image methodically — top-to-bottom, left-to-right.
505
+ 2. Identify every distinct shape/box/node, no matter how small.
506
+ 3. Read ALL text inside and near shapes carefully — preserve exact wording.
507
+ 4. Note the color/fill of each shape — this often indicates grouping or hierarchy level.
508
+ 5. Trace every line/arrow/connector between shapes — note direction and any labels.
509
+ 6. Identify the hierarchy: which nodes are parents, children, or siblings.
510
+ 7. Group nodes by visual similarity (color, position, level in hierarchy).
511
+
512
+ ## Output Format
513
+ Return ONLY a JSON object (no markdown fences, no explanation) with this schema:
514
+
515
+ {
516
+ "title": "Diagram Title (from image or inferred)",
517
+ "description": "One-line summary of what this diagram shows",
518
+ "diagramType": "architecture" | "flowchart" | "sequence" | "concept-map" | "layered" | "pipeline" | "state-machine" | "data-flow" | "mind-map" | "org-chart",
519
+ "layoutSuggestion": "tree-down" | "tree-right" | "grid" | "radial" | "mindmap-right",
520
+ "groups": [
521
+ {
522
+ "name": "Group/Category Name",
523
+ "description": "What this group represents",
524
+ "color": "dominant color of this group's nodes (e.g. #c0392b, dark-red, navy-blue)",
525
+ "components": [
526
+ {
527
+ "id": "unique-slug",
528
+ "name": "Exact Text Label from Image",
529
+ "description": "Sub-text or annotation if visible, otherwise inferred purpose",
530
+ "shape": "rect" | "circle" | "diamond" | "cylinder" | "cloud" | "hexagon" | "oval" | "capsule",
531
+ "importance": "primary" | "secondary" | "tertiary",
532
+ "observedColor": "#hex or color name from the image",
533
+ "subComponents": [
534
+ { "id": "sub-slug", "name": "Sub-label text", "description": "Detail text if visible" }
535
+ ]
536
+ }
537
+ ]
538
+ }
539
+ ],
540
+ "connections": [
541
+ {
542
+ "from": "component-id",
543
+ "to": "component-id",
544
+ "label": "Label on the connector if any",
545
+ "type": "data-flow" | "triggers" | "calls" | "contains" | "depends-on" | "hierarchy" | "association",
546
+ "style": "solid" | "dashed" | "dotted",
547
+ "bidirectional": false
548
+ }
549
+ ],
550
+ "annotations": [
551
+ { "text": "Any standalone text or legend visible in the image", "nearComponent": "component-id" }
552
+ ]
553
+ }
554
+
555
+ ## Rules
556
+ 1. Output ONLY valid JSON. No markdown fences. No explanation text.
557
+ 2. Extract EVERY node visible in the image — do not skip small or peripheral nodes.
558
+ 3. Read text labels EXACTLY as written. If partially illegible, make your best guess and note uncertainty in the description.
559
+ 4. Every component must have a unique "id" (use short descriptive slugs derived from the label text).
560
+ 5. Group components by visual similarity: same color, same hierarchy level, or spatial proximity.
561
+ 6. Preserve the observed colors — the diagram composer will use these to match the original palette.
562
+ 7. For mind maps and hierarchies, use "hierarchy" connection type from parent to child nodes.
563
+ 8. Mark importance based on visual prominence: larger/central nodes are "primary", mid-level are "secondary", leaf/small nodes are "tertiary".
564
+ 9. If the image contains a title or heading, use it as the "title" field.
565
+ 10. Include any sub-text, tags, or annotations visible below or near a node label in the "description" field.
566
+ 11. For complex diagrams with 15+ nodes, ensure you capture ALL of them — count the nodes in the image and verify your output has the same count.
567
+ 12. Choose appropriate shapes based on what you see: rounded boxes → "capsule", sharp rectangles → "rect", rotated squares → "diamond", circles → "circle", etc.
568
+ `;
569
+ function U(o) {
570
+ let e = "Analyze this diagram image thoroughly. Extract every node, connection, label, and color you can see.";
571
+ return o && (e += `
572
+
573
+ Additional context from the user: ${o}`), e += `
574
+
575
+ Be exhaustive — capture every visible element. Count the nodes to make sure you haven't missed any.`, e;
576
+ }
577
+ function F(o, e) {
578
+ let a = o;
579
+ return a += `
580
+
581
+ Aim for 20-30 components for a thorough breakdown.`, a;
582
+ }
583
+ async function $(o, e, a) {
584
+ return e?.mode === "deep" ? Y(o, e, a) : q(o, e, a);
585
+ }
586
+ async function q(o, e, a) {
587
+ const r = Date.now(), n = w(), t = e?.provider ?? n.activeProvider, p = n.providers[t], i = v(t);
588
+ if (!i)
589
+ return {
590
+ success: !1,
591
+ error: `No API key configured for ${t}. Open AI Settings to add one.`
592
+ };
593
+ const d = e?.model ?? p.model, f = e?.rocketMode ? L() : e?.style3D ? T() : y(), c = e?.rocketMode ? 8192 : 4096;
594
+ a?.("Generating diagram...");
595
+ let s;
596
+ try {
597
+ s = await g({
598
+ provider: t,
599
+ model: d,
600
+ apiKey: i,
601
+ systemPrompt: f,
602
+ userPrompt: o,
603
+ temperature: 0.3,
604
+ maxTokens: c
605
+ });
606
+ } catch (l) {
607
+ return {
608
+ success: !1,
609
+ error: `LLM call failed: ${l.message}`,
610
+ duration: Date.now() - r
611
+ };
612
+ }
613
+ return s.success ? k(s.content, r, e, s.usage) : {
614
+ success: !1,
615
+ error: s.error ?? "Unknown LLM error",
616
+ rawResponse: s.content,
617
+ duration: Date.now() - r
618
+ };
619
+ }
620
+ async function Y(o, e, a) {
621
+ const r = Date.now(), n = w(), t = e?.provider ?? n.activeProvider, p = n.providers[t], i = v(t);
622
+ if (!i)
623
+ return {
624
+ success: !1,
625
+ error: `No API key configured for ${t}. Open AI Settings to add one.`
626
+ };
627
+ const d = e?.model ?? p.model;
628
+ a?.("Researching topic deeply...");
629
+ const f = F(o);
630
+ let c;
631
+ try {
632
+ c = await g({
633
+ provider: t,
634
+ model: d,
635
+ apiKey: i,
636
+ systemPrompt: B,
637
+ userPrompt: f,
638
+ temperature: 0.5,
639
+ maxTokens: 8192
640
+ });
641
+ } catch (u) {
642
+ return {
643
+ success: !1,
644
+ error: `Research agent failed: ${u.message}`,
645
+ duration: Date.now() - r,
646
+ stage: "research"
647
+ };
648
+ }
649
+ if (!c.success)
650
+ return {
651
+ success: !1,
652
+ error: `Research agent failed: ${c.error ?? "Unknown error"}`,
653
+ rawResponse: c.content,
654
+ duration: Date.now() - r,
655
+ stage: "research"
656
+ };
657
+ const s = {
658
+ promptTokens: c.usage?.promptTokens || 0,
659
+ completionTokens: c.usage?.completionTokens || 0
660
+ }, l = C(c.content);
661
+ if (!l)
662
+ return {
663
+ success: !1,
664
+ error: "Research agent returned invalid JSON. Please try again.",
665
+ rawResponse: c.content,
666
+ duration: Date.now() - r,
667
+ stage: "research"
668
+ };
669
+ a?.("Composing detailed diagram...");
670
+ const h = O({ style3D: e?.style3D });
671
+ let m;
672
+ try {
673
+ m = await g({
674
+ provider: t,
675
+ model: d,
676
+ apiKey: i,
677
+ systemPrompt: h,
678
+ userPrompt: l,
679
+ temperature: 0.3,
680
+ maxTokens: 8192
681
+ });
682
+ } catch (u) {
683
+ return {
684
+ success: !1,
685
+ error: `Diagram composer failed: ${u.message}`,
686
+ duration: Date.now() - r,
687
+ stage: "composer"
688
+ };
689
+ }
690
+ return m.success ? (s.promptTokens += m.usage?.promptTokens || 0, s.completionTokens += m.usage?.completionTokens || 0, k(m.content, r, e, s)) : {
691
+ success: !1,
692
+ error: `Diagram composer failed: ${m.error ?? "Unknown error"}`,
693
+ rawResponse: m.content,
694
+ duration: Date.now() - r,
695
+ stage: "composer"
696
+ };
697
+ }
698
+ async function K(o, e, a) {
699
+ return e?.mode === "deep" ? _(o, e, a) : J(o, e, a);
700
+ }
701
+ async function J(o, e, a) {
702
+ const r = Date.now(), n = w(), t = e?.provider ?? n.activeProvider, p = n.providers[t], i = v(t);
703
+ if (!i)
704
+ return {
705
+ success: !1,
706
+ error: `No API key configured for ${t}. Open AI Settings to add one.`
707
+ };
708
+ let d;
709
+ try {
710
+ d = await x(o);
711
+ } catch (h) {
712
+ return {
713
+ success: !1,
714
+ error: `Image processing failed: ${h.message}`,
715
+ duration: Date.now() - r
716
+ };
717
+ }
718
+ const f = e?.model ?? p.model, c = e?.style3D ? R() : P(), s = e?.additionalPrompt ? `Convert this sketch into a YappyDraw diagram. Additional context: ${e.additionalPrompt}` : "Convert this hand-drawn sketch into a YappyDraw diagram. Identify all shapes, text labels, and connections. Output only the JSON.";
719
+ a?.("Generating from sketch...");
720
+ let l;
721
+ try {
722
+ l = await g({
723
+ provider: t,
724
+ model: f,
725
+ apiKey: i,
726
+ systemPrompt: c,
727
+ userPrompt: s,
728
+ images: [{ base64: d.base64, mediaType: d.mediaType }],
729
+ temperature: 0.3,
730
+ maxTokens: 8192
731
+ });
732
+ } catch (h) {
733
+ return {
734
+ success: !1,
735
+ error: `LLM call failed: ${h.message}`,
736
+ duration: Date.now() - r
737
+ };
738
+ }
739
+ return l.success ? k(l.content, r, e, l.usage) : {
740
+ success: !1,
741
+ error: l.error ?? "Unknown LLM error",
742
+ rawResponse: l.content,
743
+ duration: Date.now() - r
744
+ };
745
+ }
746
+ async function _(o, e, a) {
747
+ const r = Date.now(), n = w(), t = e?.provider ?? n.activeProvider, p = n.providers[t], i = v(t);
748
+ if (!i)
749
+ return {
750
+ success: !1,
751
+ error: `No API key configured for ${t}. Open AI Settings to add one.`
752
+ };
753
+ let d;
754
+ try {
755
+ d = await x(o);
756
+ } catch (b) {
757
+ return {
758
+ success: !1,
759
+ error: `Image processing failed: ${b.message}`,
760
+ duration: Date.now() - r
761
+ };
762
+ }
763
+ const f = e?.model ?? p.model;
764
+ a?.("Analyzing image deeply...");
765
+ const c = U(e?.additionalPrompt);
766
+ let s;
767
+ try {
768
+ s = await g({
769
+ provider: t,
770
+ model: f,
771
+ apiKey: i,
772
+ systemPrompt: M,
773
+ userPrompt: c,
774
+ images: [{ base64: d.base64, mediaType: d.mediaType }],
775
+ temperature: 0.5,
776
+ maxTokens: 8192
777
+ });
778
+ } catch (b) {
779
+ return {
780
+ success: !1,
781
+ error: `Vision analysis failed: ${b.message}`,
782
+ duration: Date.now() - r,
783
+ stage: "research"
784
+ };
785
+ }
786
+ if (!s.success)
787
+ return {
788
+ success: !1,
789
+ error: `Vision analysis failed: ${s.error ?? "Unknown error"}`,
790
+ rawResponse: s.content,
791
+ duration: Date.now() - r,
792
+ stage: "research"
793
+ };
794
+ const l = {
795
+ promptTokens: s.usage?.promptTokens || 0,
796
+ completionTokens: s.usage?.completionTokens || 0
797
+ }, h = C(s.content);
798
+ if (!h)
799
+ return {
800
+ success: !1,
801
+ error: "Vision analysis returned invalid JSON — the image may be too complex or unclear. Try adding a description.",
802
+ rawResponse: s.content,
803
+ duration: Date.now() - r,
804
+ stage: "research"
805
+ };
806
+ a?.("Composing detailed diagram...");
807
+ const m = O({ style3D: e?.style3D });
808
+ let u;
809
+ try {
810
+ u = await g({
811
+ provider: t,
812
+ model: f,
813
+ apiKey: i,
814
+ systemPrompt: m,
815
+ userPrompt: h,
816
+ temperature: 0.3,
817
+ maxTokens: 8192
818
+ });
819
+ } catch (b) {
820
+ return {
821
+ success: !1,
822
+ error: `Diagram composer failed: ${b.message}`,
823
+ duration: Date.now() - r,
824
+ stage: "composer"
825
+ };
826
+ }
827
+ return u.success ? (l.promptTokens += u.usage?.promptTokens || 0, l.completionTokens += u.usage?.completionTokens || 0, k(u.content, r, e, l)) : {
828
+ success: !1,
829
+ error: `Diagram composer failed: ${u.error ?? "Unknown error"}`,
830
+ rawResponse: u.content,
831
+ duration: Date.now() - r,
832
+ stage: "composer"
833
+ };
834
+ }
835
+ function k(o, e, a, r) {
836
+ const n = C(o);
837
+ if (!n)
838
+ return {
839
+ success: !1,
840
+ error: "Could not extract valid JSON from LLM response. The AI could not recognize shapes in this image — try a clearer sketch or add a description.",
841
+ rawResponse: o,
842
+ duration: Date.now() - e
843
+ };
844
+ const t = A(n);
845
+ if (!t.success || !t.diagram)
846
+ return {
847
+ success: !1,
848
+ error: `Invalid diagram DSL: ${t.errors?.map((i) => i.message).join("; ") || "Unknown parse error"}`,
849
+ rawResponse: o,
850
+ parseResult: t,
851
+ duration: Date.now() - e
852
+ };
853
+ try {
854
+ return {
855
+ success: !0,
856
+ renderResult: N(t.diagram, {
857
+ clearCanvas: a?.clearCanvas ?? !0,
858
+ zoomToFit: !0
859
+ }),
860
+ rawResponse: o,
861
+ parseResult: t,
862
+ duration: Date.now() - e,
863
+ usage: r
864
+ };
865
+ } catch (p) {
866
+ return {
867
+ success: !1,
868
+ error: `Render failed: ${p.message}`,
869
+ rawResponse: o,
870
+ parseResult: t,
871
+ duration: Date.now() - e
872
+ };
873
+ }
874
+ }
875
+ function C(o) {
876
+ const e = o.trim();
877
+ if (e.startsWith("{"))
878
+ try {
879
+ return JSON.parse(e), e;
880
+ } catch {
881
+ }
882
+ const a = e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
883
+ if (a) {
884
+ const t = a[1].trim();
885
+ try {
886
+ return JSON.parse(t), t;
887
+ } catch {
888
+ }
889
+ }
890
+ const r = e.indexOf("{"), n = e.lastIndexOf("}");
891
+ if (r !== -1 && n > r) {
892
+ const t = e.substring(r, n + 1);
893
+ try {
894
+ return JSON.parse(t), t;
895
+ } catch {
896
+ }
897
+ }
898
+ return null;
899
+ }
900
+ export {
901
+ $ as generateDiagram,
902
+ K as generateDiagramFromSketch
903
+ };