@studio8collective/patent-render 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,1150 @@
1
+ "use server";
2
+ "use server";
3
+
4
+ // ../../src/patent-render/schema/document.ts
5
+ import { z } from "zod";
6
+ function vec(n) {
7
+ return z.array(z.number()).length(n);
8
+ }
9
+ var Point = vec(2);
10
+ var StrokeStyle = z.enum(["solid", "dashed", "centre", "phantom"]);
11
+ var Stroke = z.object({
12
+ width: z.number().positive().default(0.35),
13
+ style: StrokeStyle.default("solid")
14
+ });
15
+ var Fill = z.enum(["none", "black", "white"]);
16
+ var base = {
17
+ id: z.string().min(1),
18
+ name: z.string().optional(),
19
+ /** Degrees, clockwise, about the item's bounding-box centre. */
20
+ rotation: z.number().default(0),
21
+ locked: z.boolean().default(false),
22
+ hidden: z.boolean().default(false)
23
+ };
24
+ var stroked = { stroke: Stroke.default({ width: 0.35, style: "solid" }) };
25
+ var LineItem = z.object({ ...base, ...stroked, type: z.literal("line"), a: Point, b: Point });
26
+ var PolylineItem = z.object({
27
+ ...base,
28
+ ...stroked,
29
+ type: z.literal("polyline"),
30
+ points: z.array(Point).min(2),
31
+ closed: z.boolean().default(false),
32
+ fill: Fill.default("none")
33
+ });
34
+ var PathItem = z.object({ ...base, ...stroked, type: z.literal("path"), d: z.string().min(1), fill: Fill.default("none") });
35
+ var RectItem = z.object({
36
+ ...base,
37
+ ...stroked,
38
+ type: z.literal("rect"),
39
+ x: z.number(),
40
+ y: z.number(),
41
+ w: z.number().positive(),
42
+ h: z.number().positive(),
43
+ radius: z.number().min(0).default(0),
44
+ fill: Fill.default("none")
45
+ });
46
+ var EllipseItem = z.object({
47
+ ...base,
48
+ ...stroked,
49
+ type: z.literal("ellipse"),
50
+ cx: z.number(),
51
+ cy: z.number(),
52
+ rx: z.number().positive(),
53
+ ry: z.number().positive(),
54
+ fill: Fill.default("none")
55
+ });
56
+ var ArcItem = z.object({
57
+ ...base,
58
+ ...stroked,
59
+ type: z.literal("arc"),
60
+ cx: z.number(),
61
+ cy: z.number(),
62
+ r: z.number().positive(),
63
+ /** Degrees, 0 = +x axis, clockwise (SVG convention). */
64
+ start: z.number(),
65
+ end: z.number()
66
+ });
67
+ var TextAnchor = z.enum(["start", "middle", "end"]);
68
+ var TextItem = z.object({
69
+ ...base,
70
+ type: z.literal("text"),
71
+ x: z.number(),
72
+ y: z.number(),
73
+ text: z.string().min(1),
74
+ /** Cap height in mm. */
75
+ size: z.number().positive().default(3.5),
76
+ anchor: TextAnchor.default("start")
77
+ });
78
+ var NumeralItem = z.object({
79
+ ...base,
80
+ type: z.literal("numeral"),
81
+ /** Numeral text, e.g. "102" or "102a". Looked up in Document.numerals. */
82
+ n: z.string().regex(/^\d+[a-z']*$/i),
83
+ at: Point,
84
+ target: Point,
85
+ leader: z.enum(["straight", "curved", "none"]).default("curved"),
86
+ /** When true, numeral is underlined (refers to the whole assembly). */
87
+ underline: z.boolean().default(false),
88
+ size: z.number().positive().default(3.5)
89
+ });
90
+ var FigLabelItem = z.object({
91
+ ...base,
92
+ type: z.literal("figLabel"),
93
+ x: z.number(),
94
+ y: z.number(),
95
+ size: z.number().positive().default(5)
96
+ });
97
+ var Side = z.enum(["top", "bottom", "left", "right"]);
98
+ var ConnectorEnd = z.union([
99
+ z.object({ itemId: z.string() }),
100
+ z.object({ point: Point })
101
+ ]);
102
+ var ConnectorItem = z.object({
103
+ ...base,
104
+ ...stroked,
105
+ type: z.literal("connector"),
106
+ from: ConnectorEnd,
107
+ to: ConnectorEnd,
108
+ routing: z.enum(["straight", "orthogonal", "curved"]).default("orthogonal"),
109
+ /** Which side of an attached item the connector leaves/enters; auto when omitted. */
110
+ fromSide: Side.optional(),
111
+ toSide: Side.optional(),
112
+ arrow: z.enum(["none", "end", "start", "both"]).default("end"),
113
+ arrowStyle: z.enum(["filled", "open"]).default("filled"),
114
+ label: z.string().optional()
115
+ });
116
+ var HatchItem = z.object({
117
+ ...base,
118
+ type: z.literal("hatch"),
119
+ points: z.array(Point).min(3),
120
+ angle: z.number().default(45),
121
+ spacing: z.number().positive().default(1.5),
122
+ lineWidth: z.number().positive().default(0.25)
123
+ });
124
+ var SectionLineItem = z.object({
125
+ ...base,
126
+ ...stroked,
127
+ type: z.literal("sectionLine"),
128
+ a: Point,
129
+ b: Point,
130
+ label: z.string().min(1).max(3)
131
+ });
132
+ var Item = z.discriminatedUnion("type", [
133
+ LineItem,
134
+ PolylineItem,
135
+ PathItem,
136
+ RectItem,
137
+ EllipseItem,
138
+ ArcItem,
139
+ TextItem,
140
+ NumeralItem,
141
+ FigLabelItem,
142
+ ConnectorItem,
143
+ HatchItem,
144
+ SectionLineItem
145
+ ]);
146
+ var Offset = z.object({ dx: z.number(), dy: z.number() });
147
+ var Layer = z.object({
148
+ id: z.string().min(1),
149
+ name: z.string().min(1),
150
+ visible: z.boolean().default(true),
151
+ locked: z.boolean().default(false),
152
+ /** Where this component moves to in the exploded view (mm). */
153
+ explode: Offset.optional(),
154
+ items: z.array(Item).default([])
155
+ });
156
+ var JurisdictionId = z.enum(["uspto", "pct", "epo", "ipo"]);
157
+ var SheetSize = z.enum(["a4", "letter"]);
158
+ var Sheet = z.object({
159
+ size: SheetSize.default("a4"),
160
+ orientation: z.enum(["portrait", "landscape"]).default("portrait")
161
+ });
162
+ var LetteringStyle = z.object({
163
+ numeralWeight: z.enum(["regular", "bold"]).default("regular"),
164
+ figLabel: z.enum(["sans-bold", "serif-italic"]).default("sans-bold")
165
+ });
166
+ var NumeralRegistry = z.record(z.string(), z.string());
167
+ var ChatTranscript = z.array(z.unknown());
168
+ var PatentDocument = z.object({
169
+ version: z.literal(1).default(1),
170
+ id: z.string().min(1),
171
+ figureNumber: z.string().min(1),
172
+ /** Patent office whose drawing rules apply. Defaults to India (IPO). */
173
+ jurisdiction: JurisdictionId.default("ipo"),
174
+ sheet: Sheet.default({ size: "a4", orientation: "portrait" }),
175
+ layers: z.array(Layer).default([]),
176
+ numerals: NumeralRegistry.default({}),
177
+ lettering: LetteringStyle.default({ numeralWeight: "regular", figLabel: "sans-bold" }),
178
+ /** Which view of the same model is shown and exported. */
179
+ view: z.enum(["composite", "exploded"]).default("composite"),
180
+ /** Exploded view: dash-dot alignment lines between separated components. */
181
+ explodeLines: z.boolean().default(true),
182
+ /** Sheet number shown top-centre inside the sight, e.g. "1/3" (37 CFR 1.84(t)). Set by the host. */
183
+ sheetLabel: z.string().max(12).optional(),
184
+ chat: ChatTranscript.default([])
185
+ });
186
+
187
+ // ../../src/patent-render/schema/patch.ts
188
+ import { z as z2 } from "zod";
189
+ var ItemChanges = z2.record(z2.string(), z2.unknown());
190
+ var LayerChanges = Layer.omit({ id: true, items: true }).partial();
191
+ var Patch = z2.discriminatedUnion("op", [
192
+ z2.object({ op: z2.literal("addLayer"), layer: Layer, index: z2.number().int().optional() }),
193
+ z2.object({ op: z2.literal("updateLayer"), id: z2.string(), changes: LayerChanges }),
194
+ z2.object({ op: z2.literal("removeLayer"), id: z2.string() }),
195
+ z2.object({ op: z2.literal("moveLayer"), id: z2.string(), toIndex: z2.number().int() }),
196
+ z2.object({ op: z2.literal("addItem"), layerId: z2.string(), item: Item, index: z2.number().int().optional() }),
197
+ z2.object({ op: z2.literal("updateItem"), id: z2.string(), changes: ItemChanges }),
198
+ z2.object({ op: z2.literal("removeItem"), id: z2.string() }),
199
+ z2.object({ op: z2.literal("moveItem"), id: z2.string(), toLayerId: z2.string(), toIndex: z2.number().int().optional() }),
200
+ z2.object({ op: z2.literal("setNumeral"), n: z2.string(), label: z2.string().nullable() }),
201
+ z2.object({ op: z2.literal("setSheet"), sheet: Sheet }),
202
+ z2.object({ op: z2.literal("setJurisdiction"), jurisdiction: JurisdictionId }),
203
+ z2.object({ op: z2.literal("setLettering"), lettering: LetteringStyle }),
204
+ z2.object({ op: z2.literal("setView"), view: z2.enum(["composite", "exploded"]), explodeLines: z2.boolean().optional() }),
205
+ z2.object({ op: z2.literal("setSheetLabel"), sheetLabel: z2.string().max(12).nullable() }),
206
+ z2.object({ op: z2.literal("batch"), patches: z2.array(z2.lazy(() => Patch)) })
207
+ ]);
208
+ function findItem(doc, id) {
209
+ for (let li = 0; li < doc.layers.length; li++) {
210
+ const ii = doc.layers[li].items.findIndex((it) => it.id === id);
211
+ if (ii >= 0) return { layerIndex: li, itemIndex: ii, item: doc.layers[li].items[ii] };
212
+ }
213
+ return null;
214
+ }
215
+
216
+ // ../../src/patent-render/geometry/transform.ts
217
+ var ARITY = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0 };
218
+ function parsePath(d) {
219
+ const out = [];
220
+ const re = /([MLHVCSQTAZmlhvcsqtaz])|(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/g;
221
+ let cur = null;
222
+ let m;
223
+ while (m = re.exec(d)) {
224
+ if (m[1]) {
225
+ cur = { c: m[1], v: [] };
226
+ out.push(cur);
227
+ } else if (cur) {
228
+ const n = ARITY[cur.c.toLowerCase()];
229
+ if (n > 0 && cur.v.length === n) {
230
+ const c = cur.c === "M" ? "L" : cur.c === "m" ? "l" : cur.c;
231
+ cur = { c, v: [] };
232
+ out.push(cur);
233
+ }
234
+ cur.v.push(Number(m[2]));
235
+ }
236
+ }
237
+ return out;
238
+ }
239
+ var fmt = (n) => String(Math.round(n * 1e3) / 1e3);
240
+ function serializePath(cmds) {
241
+ return cmds.map((k) => [k.c, ...k.v.map(fmt)].join(" ")).join(" ");
242
+ }
243
+ function cubicPoint(a, c1, c2, b, t) {
244
+ const u = 1 - t;
245
+ return [
246
+ u * u * u * a[0] + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t * t * t * b[0],
247
+ u * u * u * a[1] + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t * t * t * b[1]
248
+ ];
249
+ }
250
+ function pathPoints(d) {
251
+ const pts2 = [];
252
+ let x = 0, y = 0, sx = 0, sy = 0;
253
+ parsePath(d).forEach((k, i) => {
254
+ const rel = k.c === k.c.toLowerCase() && !(i === 0 && k.c === "m");
255
+ const ox = rel ? x : 0, oy = rel ? y : 0;
256
+ const v = k.v;
257
+ switch (k.c.toLowerCase()) {
258
+ case "m":
259
+ case "l":
260
+ case "t":
261
+ x = ox + v[0];
262
+ y = oy + v[1];
263
+ pts2.push([x, y]);
264
+ if (k.c.toLowerCase() === "m") {
265
+ sx = x;
266
+ sy = y;
267
+ }
268
+ break;
269
+ case "h":
270
+ x = (rel ? x : 0) + v[0];
271
+ pts2.push([x, y]);
272
+ break;
273
+ case "v":
274
+ y = (rel ? y : 0) + v[0];
275
+ pts2.push([x, y]);
276
+ break;
277
+ case "c": {
278
+ const p0 = [x, y], c1 = [ox + v[0], oy + v[1]], c2 = [ox + v[2], oy + v[3]];
279
+ x = ox + v[4];
280
+ y = oy + v[5];
281
+ for (let k2 = 1; k2 <= 16; k2++) pts2.push(cubicPoint(p0, c1, c2, [x, y], k2 / 16));
282
+ break;
283
+ }
284
+ case "q": {
285
+ const p0 = [x, y], q = [ox + v[0], oy + v[1]];
286
+ x = ox + v[2];
287
+ y = oy + v[3];
288
+ for (let k2 = 1; k2 <= 16; k2++) {
289
+ const t = k2 / 16, u = 1 - t;
290
+ pts2.push([u * u * p0[0] + 2 * u * t * q[0] + t * t * x, u * u * p0[1] + 2 * u * t * q[1] + t * t * y]);
291
+ }
292
+ break;
293
+ }
294
+ case "s":
295
+ pts2.push([ox + v[0], oy + v[1]]);
296
+ x = ox + v[2];
297
+ y = oy + v[3];
298
+ pts2.push([x, y]);
299
+ break;
300
+ case "a":
301
+ x = ox + v[5];
302
+ y = oy + v[6];
303
+ pts2.push([x - v[0], y - v[1]], [x + v[0], y + v[1]]);
304
+ break;
305
+ case "z":
306
+ x = sx;
307
+ y = sy;
308
+ break;
309
+ }
310
+ });
311
+ return pts2;
312
+ }
313
+ function mapPath(d, s, t, origin = [0, 0]) {
314
+ const ax = (x) => origin[0] + (x - origin[0]) * s[0] + t[0];
315
+ const ay = (y) => origin[1] + (y - origin[1]) * s[1] + t[1];
316
+ const cmds = parsePath(d).map((k, i) => {
317
+ const abs = k.c === k.c.toUpperCase() || i === 0 && k.c === "m";
318
+ const v = k.v.slice();
319
+ const lc = k.c.toLowerCase();
320
+ if (lc === "h") v[0] = abs ? ax(v[0]) : v[0] * s[0];
321
+ else if (lc === "v") v[0] = abs ? ay(v[0]) : v[0] * s[1];
322
+ else if (lc === "a") {
323
+ v[0] *= Math.abs(s[0]);
324
+ v[1] *= Math.abs(s[1]);
325
+ if (s[0] * s[1] < 0) v[4] = v[4] ? 0 : 1;
326
+ v[5] = abs ? ax(v[5]) : v[5] * s[0];
327
+ v[6] = abs ? ay(v[6]) : v[6] * s[1];
328
+ } else {
329
+ for (let j = 0; j + 1 < v.length; j += 2) {
330
+ v[j] = abs ? ax(v[j]) : v[j] * s[0];
331
+ v[j + 1] = abs ? ay(v[j + 1]) : v[j + 1] * s[1];
332
+ }
333
+ }
334
+ return { c: k.c, v };
335
+ });
336
+ return serializePath(cmds);
337
+ }
338
+ var tp = ([x, y], dx, dy) => [x + dx, y + dy];
339
+ function translateChanges(item, dx, dy) {
340
+ switch (item.type) {
341
+ case "line":
342
+ case "sectionLine":
343
+ return { a: tp(item.a, dx, dy), b: tp(item.b, dx, dy) };
344
+ case "polyline":
345
+ case "hatch":
346
+ return { points: item.points.map((p) => tp(p, dx, dy)) };
347
+ case "path":
348
+ return { d: mapPath(item.d, [1, 1], [dx, dy]) };
349
+ case "rect":
350
+ case "text":
351
+ case "figLabel":
352
+ return { x: item.x + dx, y: item.y + dy };
353
+ case "ellipse":
354
+ case "arc":
355
+ return { cx: item.cx + dx, cy: item.cy + dy };
356
+ case "numeral":
357
+ return { at: tp(item.at, dx, dy), target: tp(item.target, dx, dy) };
358
+ case "connector": {
359
+ const ch = {};
360
+ if ("point" in item.from) ch.from = { point: tp(item.from.point, dx, dy) };
361
+ if ("point" in item.to) ch.to = { point: tp(item.to.point, dx, dy) };
362
+ return ch;
363
+ }
364
+ }
365
+ }
366
+
367
+ // ../../src/patent-render/geometry/index.ts
368
+ var SHEET_MM = {
369
+ a4: { w: 210, h: 297 },
370
+ letter: { w: 215.9, h: 279.4 }
371
+ };
372
+ function sheetDims(sheet) {
373
+ const d = SHEET_MM[sheet.size];
374
+ return sheet.orientation === "portrait" ? { w: d.w, h: d.h } : { w: d.h, h: d.w };
375
+ }
376
+ var CAP_RATIO = 0.7;
377
+ var AVG_CHAR_W = 0.6;
378
+ function fontSize(capHeight) {
379
+ return capHeight / CAP_RATIO;
380
+ }
381
+ function textBox(x, y, text, capHeight, anchor) {
382
+ const fs = fontSize(capHeight);
383
+ const w = text.length * fs * AVG_CHAR_W;
384
+ const left = anchor === "start" ? x : anchor === "middle" ? x - w / 2 : x - w;
385
+ return { x: left, y: y - capHeight, w, h: capHeight + fs * 0.2 };
386
+ }
387
+ function boxFromPoints(pts2) {
388
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
389
+ for (const [x, y] of pts2) {
390
+ x0 = Math.min(x0, x);
391
+ y0 = Math.min(y0, y);
392
+ x1 = Math.max(x1, x);
393
+ y1 = Math.max(y1, y);
394
+ }
395
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
396
+ }
397
+ function unionBox(boxes) {
398
+ if (!boxes.length) return null;
399
+ return boxFromPoints(boxes.flatMap((b) => [[b.x, b.y], [b.x + b.w, b.y + b.h]]));
400
+ }
401
+ function centre(b) {
402
+ return [b.x + b.w / 2, b.y + b.h / 2];
403
+ }
404
+ function pathBox(d) {
405
+ const pts2 = pathPoints(d);
406
+ return pts2.length ? boxFromPoints(pts2) : { x: 0, y: 0, w: 0, h: 0 };
407
+ }
408
+ function figLabelText(doc) {
409
+ return `FIG. ${doc.figureNumber}`;
410
+ }
411
+ function itemBox(doc, item) {
412
+ switch (item.type) {
413
+ case "line":
414
+ case "sectionLine":
415
+ return boxFromPoints([item.a, item.b]);
416
+ case "polyline":
417
+ case "hatch":
418
+ return boxFromPoints(item.points);
419
+ case "path":
420
+ return pathBox(item.d);
421
+ case "rect":
422
+ return { x: item.x, y: item.y, w: item.w, h: item.h };
423
+ case "ellipse":
424
+ return { x: item.cx - item.rx, y: item.cy - item.ry, w: item.rx * 2, h: item.ry * 2 };
425
+ case "arc":
426
+ return { x: item.cx - item.r, y: item.cy - item.r, w: item.r * 2, h: item.r * 2 };
427
+ case "text":
428
+ return textBox(item.x, item.y, item.text, item.size, item.anchor);
429
+ case "figLabel":
430
+ return textBox(item.x, item.y, figLabelText(doc), item.size, "middle");
431
+ case "numeral": {
432
+ const label = numeralLabelBox(item.at, item.n, item.size);
433
+ return unionBox([label, boxFromPoints([item.target, item.target])]);
434
+ }
435
+ case "connector": {
436
+ const [a, b] = connectorEnds(doc, item);
437
+ return boxFromPoints([a, b]);
438
+ }
439
+ }
440
+ }
441
+ function numeralLabelBox(at, n, size) {
442
+ const b = textBox(at[0], at[1], n, size, "middle");
443
+ return { ...b, y: at[1] - b.h / 2 };
444
+ }
445
+ function rotatePoint([x, y], [cx, cy], deg) {
446
+ const r = deg * Math.PI / 180;
447
+ const c = Math.cos(r), s = Math.sin(r);
448
+ return [cx + (x - cx) * c - (y - cy) * s, cy + (x - cx) * s + (y - cy) * c];
449
+ }
450
+ function itemBoundsRotated(doc, item) {
451
+ const b = itemBox(doc, item);
452
+ if (!item.rotation) return b;
453
+ const c = centre(b);
454
+ const corners = [
455
+ [b.x, b.y],
456
+ [b.x + b.w, b.y],
457
+ [b.x + b.w, b.y + b.h],
458
+ [b.x, b.y + b.h]
459
+ ].map((p) => rotatePoint(p, c, item.rotation));
460
+ return boxFromPoints(corners);
461
+ }
462
+ function boxExitPoint(b, toward) {
463
+ const [cx, cy] = centre(b);
464
+ const dx = toward[0] - cx, dy = toward[1] - cy;
465
+ if (dx === 0 && dy === 0) return [cx, cy];
466
+ const sx = dx === 0 ? Infinity : b.w / 2 / Math.abs(dx);
467
+ const sy = dy === 0 ? Infinity : b.h / 2 / Math.abs(dy);
468
+ const s = Math.min(sx, sy);
469
+ return [cx + dx * s, cy + dy * s];
470
+ }
471
+ function endTargetBox(doc, end) {
472
+ if ("point" in end) return end.point;
473
+ const loc = findItem(doc, end.itemId);
474
+ if (!loc || loc.item.type === "connector") return [0, 0];
475
+ return itemBoundsRotated(doc, loc.item);
476
+ }
477
+ function facingSide(b, toward) {
478
+ const [cx, cy] = centre(b);
479
+ const dx = toward[0] - cx, dy = toward[1] - cy;
480
+ if (Math.abs(dy) / (b.h || 1) >= Math.abs(dx) / (b.w || 1)) return dy >= 0 ? "bottom" : "top";
481
+ return dx >= 0 ? "right" : "left";
482
+ }
483
+ function sidePoint(b, s) {
484
+ const [cx, cy] = centre(b);
485
+ return s === "top" ? [cx, b.y] : s === "bottom" ? [cx, b.y + b.h] : s === "left" ? [b.x, cy] : [b.x + b.w, cy];
486
+ }
487
+ function connectorGeometry(doc, item) {
488
+ const A = endTargetBox(doc, item.from);
489
+ const B = endTargetBox(doc, item.to);
490
+ const aC = Array.isArray(A) ? A : centre(A);
491
+ const bC = Array.isArray(B) ? B : centre(B);
492
+ let a = aC, b = bC, sideA = null, sideB = null;
493
+ if (!Array.isArray(A)) {
494
+ sideA = item.fromSide ?? facingSide(A, bC);
495
+ a = sidePoint(A, sideA);
496
+ }
497
+ if (!Array.isArray(B)) {
498
+ sideB = item.toSide ?? facingSide(B, a);
499
+ b = sidePoint(B, sideB);
500
+ }
501
+ return { a, b, sideA, sideB };
502
+ }
503
+ function connectorEnds(doc, item) {
504
+ const g = connectorGeometry(doc, item);
505
+ return [g.a, g.b];
506
+ }
507
+ var DIR = { top: [0, -1], bottom: [0, 1], left: [-1, 0], right: [1, 0] };
508
+ var STUB = 6;
509
+ var isV = (s) => s === "top" || s === "bottom";
510
+ function inferSide(from, to) {
511
+ const dx = to[0] - from[0], dy = to[1] - from[1];
512
+ return Math.abs(dy) >= Math.abs(dx) ? dy >= 0 ? "bottom" : "top" : dx >= 0 ? "right" : "left";
513
+ }
514
+ function simplify(pts2) {
515
+ const out = [];
516
+ for (const p of pts2) {
517
+ const last = out[out.length - 1];
518
+ if (last && Math.abs(last[0] - p[0]) < 1e-6 && Math.abs(last[1] - p[1]) < 1e-6) continue;
519
+ if (out.length >= 2) {
520
+ const q = out[out.length - 2];
521
+ const collinear = Math.abs(q[0] - last[0]) < 1e-6 && Math.abs(last[0] - p[0]) < 1e-6 || Math.abs(q[1] - last[1]) < 1e-6 && Math.abs(last[1] - p[1]) < 1e-6;
522
+ if (collinear) {
523
+ out[out.length - 1] = p;
524
+ continue;
525
+ }
526
+ }
527
+ out.push(p);
528
+ }
529
+ return out;
530
+ }
531
+ function orthogonalRoute(a, b, sideA = null, sideB = null) {
532
+ const sA = sideA ?? inferSide(a, b);
533
+ const sB = sideB ?? (isV(sA) ? b[1] >= a[1] ? "top" : "bottom" : b[0] >= a[0] ? "left" : "right");
534
+ const dA = DIR[sA], dB = DIR[sB];
535
+ const aheadA = (b[0] - a[0]) * dA[0] + (b[1] - a[1]) * dA[1];
536
+ const aheadB = (a[0] - b[0]) * dB[0] + (a[1] - b[1]) * dB[1];
537
+ if (isV(sA) && isV(sB) && sA !== sB && aheadA > STUB && aheadB > STUB) {
538
+ const my = (a[1] + b[1]) / 2;
539
+ return simplify([a, [a[0], my], [b[0], my], b]);
540
+ }
541
+ if (!isV(sA) && !isV(sB) && sA !== sB && aheadA > STUB && aheadB > STUB) {
542
+ const mx = (a[0] + b[0]) / 2;
543
+ return simplify([a, [mx, a[1]], [mx, b[1]], b]);
544
+ }
545
+ if (isV(sA) !== isV(sB) && aheadA > 0 && aheadB > 0) {
546
+ return simplify(isV(sA) ? [a, [a[0], b[1]], b] : [a, [b[0], a[1]], b]);
547
+ }
548
+ if (sA === sB) {
549
+ if (isV(sA)) {
550
+ const y = sA === "bottom" ? Math.max(a[1], b[1]) + STUB : Math.min(a[1], b[1]) - STUB;
551
+ return simplify([a, [a[0], y], [b[0], y], b]);
552
+ }
553
+ const x = sA === "right" ? Math.max(a[0], b[0]) + STUB : Math.min(a[0], b[0]) - STUB;
554
+ return simplify([a, [x, a[1]], [x, b[1]], b]);
555
+ }
556
+ const a1 = [a[0] + dA[0] * STUB, a[1] + dA[1] * STUB];
557
+ const b1 = [b[0] + dB[0] * STUB, b[1] + dB[1] * STUB];
558
+ const corner = isV(sA) ? [b1[0], a1[1]] : [a1[0], b1[1]];
559
+ return simplify([a, a1, corner, b1, b]);
560
+ }
561
+
562
+ // ../../src/patent-render/compliance/profiles.ts
563
+ var STD_MARGINS = { top: 25, left: 25, right: 15, bottom: 10 };
564
+ var PROFILES = {
565
+ uspto: {
566
+ id: "uspto",
567
+ name: "USPTO",
568
+ citation: "37 CFR 1.84",
569
+ sheetSizes: ["letter", "a4"],
570
+ margins: STD_MARGINS,
571
+ minCapHeight: 3.2,
572
+ minStrokeWidth: 0.2,
573
+ text: { mode: "lenient", maxWordsPerText: 8, maxWordsPerCatchword: 6 }
574
+ },
575
+ pct: {
576
+ id: "pct",
577
+ name: "PCT / WIPO",
578
+ citation: "PCT Rule 11",
579
+ sheetSizes: ["a4"],
580
+ margins: STD_MARGINS,
581
+ minCapHeight: 3.2,
582
+ minStrokeWidth: 0.2,
583
+ text: { mode: "strict", maxWordsPerText: 3, maxWordsPerCatchword: 5 }
584
+ },
585
+ epo: {
586
+ id: "epo",
587
+ name: "EPO",
588
+ citation: "EPC Rule 46",
589
+ sheetSizes: ["a4"],
590
+ margins: STD_MARGINS,
591
+ minCapHeight: 3.2,
592
+ minStrokeWidth: 0.2,
593
+ text: { mode: "strict", maxWordsPerText: 3, maxWordsPerCatchword: 5 }
594
+ },
595
+ ipo: {
596
+ id: "ipo",
597
+ name: "IPO India",
598
+ citation: "Patents Rules 2003, Rule 15",
599
+ sheetSizes: ["a4"],
600
+ margins: { top: 40, left: 40, right: 30, bottom: 30 },
601
+ minCapHeight: 3.2,
602
+ minStrokeWidth: 0.2,
603
+ text: { mode: "strict", maxWordsPerText: 4, maxWordsPerCatchword: 5 }
604
+ }
605
+ };
606
+ function effectiveMargins(p, orientation) {
607
+ const m = p.margins;
608
+ if (orientation === "portrait") return m;
609
+ return { top: m.left, right: m.top, bottom: m.right, left: m.bottom };
610
+ }
611
+
612
+ // ../../src/patent-render/geometry/explode.ts
613
+ var EXPLODE_LINES_LAYER = "__explode-lines";
614
+ var isAnnotationLayer = (l) => l.id === "annotations" || l.items.every((i) => i.type === "numeral" || i.type === "figLabel" || i.type === "text" || (i.type === "line" || i.type === "polyline") && (i.stroke.style === "centre" || i.stroke.style === "phantom"));
615
+ var off = (l) => l.explode && (l.explode.dx || l.explode.dy) ? l.explode : null;
616
+ function hasExplode(doc) {
617
+ return doc.layers.some((l) => off(l));
618
+ }
619
+ var shift = (item, dx, dy) => ({ ...item, ...translateChanges(item, dx, dy) });
620
+ function contains(b, p, pad = 1.5) {
621
+ return p[0] >= b.x - pad && p[0] <= b.x + b.w + pad && p[1] >= b.y - pad && p[1] <= b.y + b.h + pad;
622
+ }
623
+ function hostLayer(doc, target) {
624
+ for (let i = doc.layers.length - 1; i >= 0; i--) {
625
+ const l = doc.layers[i];
626
+ if (isAnnotationLayer(l)) continue;
627
+ for (const it of l.items) {
628
+ if (it.type === "numeral" || it.type === "figLabel" || it.type === "connector") continue;
629
+ if (contains(itemBoundsRotated(doc, it), target)) return l;
630
+ }
631
+ }
632
+ return null;
633
+ }
634
+ function viewDocument(doc) {
635
+ if (doc.view !== "exploded" || !hasExplode(doc)) return doc;
636
+ const layers = doc.layers.map((l) => {
637
+ const o = off(l);
638
+ return {
639
+ ...l,
640
+ items: l.items.map((it) => {
641
+ if (it.type === "numeral") {
642
+ const host = hostLayer(doc, it.target);
643
+ const ho = host && off(host);
644
+ return ho ? shift(it, ho.dx, ho.dy) : it;
645
+ }
646
+ if (o && !isAnnotationLayer(l) && it.type !== "figLabel") return shift(it, o.dx, o.dy);
647
+ return it;
648
+ })
649
+ };
650
+ });
651
+ const fig = layers.flatMap((l) => l.items).find((i) => i.type === "figLabel");
652
+ if (fig && fig.type === "figLabel") {
653
+ const partBoxes = layers.filter((l) => !isAnnotationLayer(l)).flatMap((l) => l.items.map((it) => itemBoundsRotated(doc, it)));
654
+ const fb = itemBoundsRotated(doc, fig);
655
+ const overlaps = partBoxes.some((b) => fb.x < b.x + b.w && b.x < fb.x + fb.w && fb.y < b.y + b.h && b.y < fb.y + fb.h);
656
+ const all = unionBox(partBoxes);
657
+ if (overlaps && all) {
658
+ const { h } = sheetDims(doc.sheet);
659
+ const m = effectiveMargins(PROFILES[doc.jurisdiction], doc.sheet.orientation);
660
+ const y = Math.min(all.y + all.h + 14, h - m.bottom - 4);
661
+ for (const l of layers) l.items = l.items.map((it) => it.id === fig.id ? { ...fig, y: Math.round(y * 10) / 10 } : it);
662
+ }
663
+ }
664
+ if (doc.explodeLines) {
665
+ const lines = [];
666
+ const parts = doc.layers.filter((l) => l.visible && !isAnnotationLayer(l) && l.items.length);
667
+ const boxes = parts.map((l) => unionBox(l.items.map((it) => itemBoundsRotated(doc, it))));
668
+ parts.forEach((l, i) => {
669
+ const o = off(l), b = boxes[i];
670
+ if (!o || !b) return;
671
+ const [cx, cy] = centre(b);
672
+ const len = Math.hypot(o.dx, o.dy) || 1;
673
+ const ux = o.dx / len, uy = o.dy / len;
674
+ const ext = Math.min(b.w, b.h) * 0.6;
675
+ const { w: sw, h: sh } = sheetDims(doc.sheet);
676
+ const mm = effectiveMargins(PROFILES[doc.jurisdiction], doc.sheet.orientation);
677
+ const clampP = (p) => [
678
+ Math.min(sw - mm.right - 1, Math.max(mm.left + 1, p[0])),
679
+ Math.min(sh - mm.bottom - 1, Math.max(mm.top + 1, p[1]))
680
+ ];
681
+ lines.push({
682
+ id: `${EXPLODE_LINES_LAYER}-${l.id}`,
683
+ type: "line",
684
+ a: clampP([cx - ux * ext, cy - uy * ext]),
685
+ b: clampP([cx + o.dx + ux * ext, cy + o.dy + uy * ext]),
686
+ stroke: { width: 0.25, style: "phantom" },
687
+ rotation: 0,
688
+ locked: true,
689
+ hidden: false
690
+ });
691
+ });
692
+ if (lines.length) layers.unshift({ id: EXPLODE_LINES_LAYER, name: "Explode lines", visible: true, locked: true, items: lines });
693
+ }
694
+ return { ...doc, layers };
695
+ }
696
+
697
+ // ../../src/patent-render/compliance/validate.ts
698
+ var EPS = 0.01;
699
+ function intersects(a, b) {
700
+ return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
701
+ }
702
+ var sheetSizeRule = ({ doc, profile }) => profile.sheetSizes.includes(doc.sheet.size) ? [] : [{
703
+ rule: "sheet-size",
704
+ severity: "error",
705
+ message: `${profile.name} requires ${profile.sheetSizes.map((s) => s.toUpperCase()).join(" or ")} sheets.`
706
+ }];
707
+ var marginsRule = ({ doc, profile, items }) => {
708
+ const { w, h } = sheetDims(doc.sheet);
709
+ const m = effectiveMargins(profile, doc.sheet.orientation);
710
+ const area = { x0: m.left, y0: m.top, x1: w - m.right, y1: h - m.bottom };
711
+ const out = [];
712
+ for (const { item, layerId } of items) {
713
+ const b = itemBoundsRotated(doc, item);
714
+ if (b.x < area.x0 - EPS || b.y < area.y0 - EPS || b.x + b.w > area.x1 + EPS || b.y + b.h > area.y1 + EPS) {
715
+ out.push({
716
+ rule: "margins",
717
+ severity: "error",
718
+ message: `"${item.name ?? item.id}" extends into the ${profile.name} margin.`,
719
+ itemId: item.id,
720
+ layerId
721
+ });
722
+ }
723
+ }
724
+ return out;
725
+ };
726
+ var minTextHeightRule = ({ profile, items }) => {
727
+ const out = [];
728
+ for (const { item, layerId } of items) {
729
+ if ((item.type === "text" || item.type === "numeral" || item.type === "figLabel") && item.size < profile.minCapHeight - EPS) {
730
+ out.push({
731
+ rule: "min-text-height",
732
+ severity: "error",
733
+ message: `Text height ${item.size} mm is below the ${profile.minCapHeight} mm minimum.`,
734
+ itemId: item.id,
735
+ layerId
736
+ });
737
+ }
738
+ }
739
+ return out;
740
+ };
741
+ var figLabelRule = ({ doc, items }) => {
742
+ const labels = items.filter((v) => v.item.type === "figLabel");
743
+ if (labels.length === 1) return [];
744
+ return [{
745
+ rule: "fig-label",
746
+ severity: "error",
747
+ message: labels.length === 0 ? `Missing "FIG. ${doc.figureNumber}" label.` : `Figure has ${labels.length} "FIG." labels; exactly one is required.`
748
+ }];
749
+ };
750
+ var strokeWidthRule = ({ profile, items }) => {
751
+ const out = [];
752
+ for (const { item, layerId } of items) {
753
+ if ("stroke" in item && item.stroke.width < profile.minStrokeWidth - EPS) {
754
+ out.push({
755
+ rule: "stroke-width",
756
+ severity: "warning",
757
+ message: `Line weight ${item.stroke.width} mm may not reproduce clearly (min ${profile.minStrokeWidth} mm).`,
758
+ itemId: item.id,
759
+ layerId
760
+ });
761
+ }
762
+ }
763
+ return out;
764
+ };
765
+ var numeralRegistryRule = ({ doc, items }) => {
766
+ const out = [];
767
+ for (const { item, layerId } of items) {
768
+ if (item.type === "numeral" && !(item.n in doc.numerals)) {
769
+ out.push({
770
+ rule: "numeral-undefined",
771
+ severity: "warning",
772
+ message: `Reference numeral ${item.n} has no description in the registry.`,
773
+ itemId: item.id,
774
+ layerId
775
+ });
776
+ }
777
+ }
778
+ return out;
779
+ };
780
+ var numeralOverlapRule = ({ items }) => {
781
+ const nums = items.filter((v) => v.item.type === "numeral");
782
+ const boxes = nums.map((v) => numeralLabelBox(v.item.at, v.item.n, v.item.size));
783
+ const out = [];
784
+ for (let i = 0; i < nums.length; i++) {
785
+ for (let j = i + 1; j < nums.length; j++) {
786
+ if (intersects(boxes[i], boxes[j])) {
787
+ out.push({
788
+ rule: "numeral-overlap",
789
+ severity: "warning",
790
+ message: `Numerals ${nums[i].item.n} and ${nums[j].item.n} overlap.`,
791
+ itemId: nums[j].item.id,
792
+ layerId: nums[j].layerId
793
+ });
794
+ }
795
+ }
796
+ }
797
+ return out;
798
+ };
799
+ var textDensityRule = ({ profile, items }) => {
800
+ const out = [];
801
+ const check = (text, limit, kind, itemId, layerId) => {
802
+ const n = countWords(text);
803
+ if (n > limit) {
804
+ out.push({
805
+ rule: "text-density",
806
+ severity: "warning",
807
+ message: `${kind} has ${n} words; ${profile.citation} allows ${limit} at most. Move the explanation to the description.`,
808
+ itemId,
809
+ layerId
810
+ });
811
+ }
812
+ };
813
+ for (const { item, layerId } of items) {
814
+ if (item.type === "text") check(item.text, profile.text.maxWordsPerText, "Text", item.id, layerId);
815
+ else if (item.type === "connector" && item.label) {
816
+ check(item.label, profile.text.maxWordsPerCatchword, "Connector label", item.id, layerId);
817
+ }
818
+ }
819
+ return out;
820
+ };
821
+ function countWords(text) {
822
+ return text.split(/\s+/).filter((t) => /[a-z]/i.test(t) && !/^[a-z]?\d+[a-z']*$/i.test(t) && !/^[a-z]$/i.test(t)).length;
823
+ }
824
+ var DEFAULT_RULES = [
825
+ sheetSizeRule,
826
+ marginsRule,
827
+ minTextHeightRule,
828
+ figLabelRule,
829
+ strokeWidthRule,
830
+ numeralRegistryRule,
831
+ numeralOverlapRule,
832
+ textDensityRule
833
+ ];
834
+ function visibleItems(doc) {
835
+ return doc.layers.filter((l) => l.visible).flatMap((l) => l.items.filter((it) => !it.hidden).map((item) => ({ item, layerId: l.id })));
836
+ }
837
+ function validate(model, rules = DEFAULT_RULES) {
838
+ const doc = viewDocument(model);
839
+ const profile = PROFILES[doc.jurisdiction];
840
+ const ctx = { doc, profile, items: visibleItems(doc) };
841
+ const issues = rules.flatMap((r) => r(ctx));
842
+ const errors = issues.filter((i) => i.severity === "error");
843
+ const warnings = issues.filter((i) => i.severity === "warning");
844
+ return { jurisdiction: doc.jurisdiction, ok: errors.length === 0, errors, warnings };
845
+ }
846
+
847
+ // ../../src/patent-render/server/png.ts
848
+ import { Resvg } from "@resvg/resvg-js";
849
+
850
+ // ../../src/patent-render/render/nodes.ts
851
+ var INK = "#000";
852
+ var FONT_FAMILY = "Arial, Helvetica, sans-serif";
853
+ var SERIF_FAMILY = "'Times New Roman', Times, Georgia, serif";
854
+ var ARROW_MARKER_ID = "pr-arrow";
855
+ var ARROW_START_MARKER_ID = "pr-arrow-start";
856
+ var OPEN = "-open";
857
+ var DASH = {
858
+ solid: null,
859
+ dashed: "3 1.5",
860
+ centre: "8 1.5 1.5 1.5",
861
+ phantom: "8 1.5 1.5 1.5 1.5 1.5"
862
+ };
863
+ var r3 = (n) => Math.round(n * 1e3) / 1e3;
864
+ var pts = (p) => p.map(([x, y]) => `${r3(x)},${r3(y)}`).join(" ");
865
+ function strokeAttrs(s) {
866
+ const a = {
867
+ stroke: INK,
868
+ "stroke-width": s.width,
869
+ "stroke-linecap": "round",
870
+ "stroke-linejoin": "round"
871
+ };
872
+ const dash = DASH[s.style];
873
+ if (dash) a["stroke-dasharray"] = dash;
874
+ return a;
875
+ }
876
+ var fillAttr = (f) => f === "black" ? INK : f === "white" ? "#fff" : "none";
877
+ function textNode(x, y, text, cap, anchor, extra = {}) {
878
+ return {
879
+ tag: "text",
880
+ attrs: {
881
+ x: r3(x),
882
+ y: r3(y),
883
+ "font-size": r3(fontSize(cap)),
884
+ "font-family": FONT_FAMILY,
885
+ "text-anchor": anchor,
886
+ fill: INK,
887
+ ...extra
888
+ },
889
+ text
890
+ };
891
+ }
892
+ function arcPath(cx, cy, r, start, end) {
893
+ const rad = (d) => d * Math.PI / 180;
894
+ const sweep = ((end - start) % 360 + 360) % 360 || 360;
895
+ if (sweep >= 359.999) {
896
+ return `M ${r3(cx - r)} ${r3(cy)} a ${r3(r)} ${r3(r)} 0 1 1 ${r3(2 * r)} 0 a ${r3(r)} ${r3(r)} 0 1 1 ${r3(-2 * r)} 0`;
897
+ }
898
+ const p0 = [cx + r * Math.cos(rad(start)), cy + r * Math.sin(rad(start))];
899
+ const p1 = [cx + r * Math.cos(rad(start + sweep)), cy + r * Math.sin(rad(start + sweep))];
900
+ return `M ${r3(p0[0])} ${r3(p0[1])} A ${r3(r)} ${r3(r)} 0 ${sweep > 180 ? 1 : 0} 1 ${r3(p1[0])} ${r3(p1[1])}`;
901
+ }
902
+ function hatchLines(points, angle, spacing) {
903
+ const b = boxFromPoints(points);
904
+ const [cx, cy] = centre(b);
905
+ const half = Math.hypot(b.w, b.h) / 2 + spacing;
906
+ const t = angle * Math.PI / 180;
907
+ const dir = [Math.cos(t), Math.sin(t)];
908
+ const nrm = [-dir[1], dir[0]];
909
+ const segs = [];
910
+ for (let o = -half; o <= half; o += spacing) {
911
+ const px = cx + nrm[0] * o, py = cy + nrm[1] * o;
912
+ segs.push(`M ${r3(px - dir[0] * half)} ${r3(py - dir[1] * half)} L ${r3(px + dir[0] * half)} ${r3(py + dir[1] * half)}`);
913
+ }
914
+ return segs.join(" ");
915
+ }
916
+ function numeralNodes(item, bold) {
917
+ const label = numeralLabelBox(item.at, item.n, item.size);
918
+ const baseline = item.at[1] + item.size / 2;
919
+ const out = [textNode(item.at[0], baseline, item.n, item.size, "middle", bold ? { "font-weight": "bold" } : {})];
920
+ if (item.underline) {
921
+ out.push({
922
+ tag: "line",
923
+ attrs: { x1: r3(label.x), y1: r3(baseline + 0.8), x2: r3(label.x + label.w), y2: r3(baseline + 0.8), ...strokeAttrs({ width: 0.25, style: "solid" }) }
924
+ });
925
+ }
926
+ if (item.leader !== "none") {
927
+ const padded = { x: label.x - 0.8, y: label.y - 0.8, w: label.w + 1.6, h: label.h + 1.6 };
928
+ const s = boxExitPoint(padded, item.target);
929
+ const t = item.target;
930
+ let d;
931
+ if (item.leader === "curved") {
932
+ const mx = (s[0] + t[0]) / 2, my = (s[1] + t[1]) / 2;
933
+ const dx = t[0] - s[0], dy = t[1] - s[1];
934
+ const k = 0.2;
935
+ d = `M ${r3(s[0])} ${r3(s[1])} Q ${r3(mx - dy * k)} ${r3(my + dx * k)} ${r3(t[0])} ${r3(t[1])}`;
936
+ } else {
937
+ d = `M ${r3(s[0])} ${r3(s[1])} L ${r3(t[0])} ${r3(t[1])}`;
938
+ }
939
+ out.push({ tag: "path", attrs: { d, fill: "none", ...strokeAttrs({ width: 0.25, style: "solid" }) } });
940
+ }
941
+ return out;
942
+ }
943
+ function curveControls(cg) {
944
+ const { a, b } = cg;
945
+ const k = Math.max(8, Math.hypot(b[0] - a[0], b[1] - a[1]) / 2.5);
946
+ const dir = (side, from, to) => {
947
+ if (side === "top") return [0, -1];
948
+ if (side === "bottom") return [0, 1];
949
+ if (side === "left") return [-1, 0];
950
+ if (side === "right") return [1, 0];
951
+ const d = Math.hypot(to[0] - from[0], to[1] - from[1]) || 1;
952
+ return [(to[0] - from[0]) / d, (to[1] - from[1]) / d];
953
+ };
954
+ const da = dir(cg.sideA, a, b), db = dir(cg.sideB, b, a);
955
+ return [a, [a[0] + da[0] * k, a[1] + da[1] * k], [b[0] + db[0] * k, b[1] + db[1] * k], b];
956
+ }
957
+ function itemNode(doc, item) {
958
+ const transform = {};
959
+ if (item.rotation) {
960
+ const [cx, cy] = centre(itemBox(doc, item));
961
+ transform.transform = `rotate(${r3(item.rotation)} ${r3(cx)} ${r3(cy)})`;
962
+ }
963
+ const g = (children) => ({ tag: "g", attrs: { ...transform }, children });
964
+ switch (item.type) {
965
+ case "line":
966
+ return g([{ tag: "line", attrs: { x1: item.a[0], y1: item.a[1], x2: item.b[0], y2: item.b[1], ...strokeAttrs(item.stroke) } }]);
967
+ case "polyline":
968
+ return g([{
969
+ tag: item.closed ? "polygon" : "polyline",
970
+ attrs: { points: pts(item.points), fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) }
971
+ }]);
972
+ case "path":
973
+ return g([{ tag: "path", attrs: { d: item.d, fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) } }]);
974
+ case "rect":
975
+ return g([{
976
+ tag: "rect",
977
+ attrs: { x: item.x, y: item.y, width: item.w, height: item.h, rx: item.radius, fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) }
978
+ }]);
979
+ case "ellipse":
980
+ return g([{
981
+ tag: "ellipse",
982
+ attrs: { cx: item.cx, cy: item.cy, rx: item.rx, ry: item.ry, fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) }
983
+ }]);
984
+ case "arc":
985
+ return g([{ tag: "path", attrs: { d: arcPath(item.cx, item.cy, item.r, item.start, item.end), fill: "none", ...strokeAttrs(item.stroke) } }]);
986
+ case "text": {
987
+ const lines = item.text.split("\n");
988
+ const lh = fontSize(item.size) * 1.2;
989
+ return g(lines.map((ln, i) => textNode(item.x, item.y + i * lh, ln, item.size, item.anchor)));
990
+ }
991
+ case "figLabel":
992
+ return g([textNode(
993
+ item.x,
994
+ item.y,
995
+ figLabelText(doc),
996
+ item.size,
997
+ "middle",
998
+ doc.lettering?.figLabel === "serif-italic" ? { "font-weight": "bold", "font-style": "italic", "font-family": SERIF_FAMILY } : { "font-weight": "bold" }
999
+ )]);
1000
+ case "numeral":
1001
+ return g(numeralNodes(item, doc.lettering?.numeralWeight === "bold"));
1002
+ case "connector": {
1003
+ const cg = connectorGeometry(doc, item);
1004
+ const curved = item.routing === "curved";
1005
+ const route = item.routing === "orthogonal" ? orthogonalRoute(cg.a, cg.b, cg.sideA, cg.sideB) : curved ? curveControls(cg) : [cg.a, cg.b];
1006
+ const attrs = curved ? { d: `M ${r3(route[0][0])} ${r3(route[0][1])} C ${route.slice(1).map(([x, y]) => `${r3(x)} ${r3(y)}`).join(" ")}`, fill: "none", ...strokeAttrs(item.stroke) } : { points: pts(route), fill: "none", ...strokeAttrs(item.stroke) };
1007
+ const style = item.arrowStyle === "open" ? OPEN : "";
1008
+ if (item.arrow === "end" || item.arrow === "both") attrs["marker-end"] = `url(#${ARROW_MARKER_ID}${style})`;
1009
+ if (item.arrow === "start" || item.arrow === "both") attrs["marker-start"] = `url(#${ARROW_START_MARKER_ID}${style})`;
1010
+ const children = [{ tag: curved ? "path" : "polyline", attrs }];
1011
+ if (item.label) {
1012
+ const [p0, p1] = route;
1013
+ const vertical = Math.abs(p1[0] - p0[0]) < Math.abs(p1[1] - p0[1]);
1014
+ const dir = vertical ? Math.sign(p1[1] - p0[1]) || 1 : Math.sign(p1[0] - p0[0]) || 1;
1015
+ const along = Math.min(5, Math.hypot(p1[0] - p0[0], p1[1] - p0[1]) / 2);
1016
+ if (vertical) children.push(textNode(p0[0] + 1.5, p0[1] + dir * along + 1.6, item.label, 3.2, "start"));
1017
+ else children.push(textNode(p0[0] + dir * along, p0[1] - 1.5, item.label, 3.2, dir > 0 ? "start" : "end"));
1018
+ }
1019
+ return g(children);
1020
+ }
1021
+ case "hatch": {
1022
+ const clipId = `pr-clip-${item.id}`;
1023
+ return g([
1024
+ { tag: "clipPath", attrs: { id: clipId }, children: [{ tag: "polygon", attrs: { points: pts(item.points) } }] },
1025
+ {
1026
+ tag: "path",
1027
+ attrs: { d: hatchLines(item.points, item.angle, item.spacing), "clip-path": `url(#${clipId})`, fill: "none", ...strokeAttrs({ width: item.lineWidth, style: "solid" }) }
1028
+ }
1029
+ ]);
1030
+ }
1031
+ case "sectionLine": {
1032
+ const children = [
1033
+ { tag: "line", attrs: { x1: item.a[0], y1: item.a[1], x2: item.b[0], y2: item.b[1], ...strokeAttrs({ ...item.stroke, style: "centre" }) } }
1034
+ ];
1035
+ for (const p of [item.a, item.b]) {
1036
+ children.push(textNode(p[0], p[1] - 2, item.label, 3.5, "middle"));
1037
+ }
1038
+ return g(children);
1039
+ }
1040
+ }
1041
+ }
1042
+ function defsNode() {
1043
+ return {
1044
+ tag: "defs",
1045
+ attrs: {},
1046
+ // Fixed 3.2 mm arrowheads, independent of line weight (legible after reduction).
1047
+ // Start arrows use their own reversed marker: resvg ignores orient="auto-start-reverse".
1048
+ children: [
1049
+ {
1050
+ tag: "marker",
1051
+ attrs: { id: ARROW_MARKER_ID, viewBox: "0 0 10 10", refX: 9, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
1052
+ children: [{ tag: "path", attrs: { d: "M 0 0 L 10 5 L 0 10 z", fill: INK } }]
1053
+ },
1054
+ {
1055
+ tag: "marker",
1056
+ attrs: { id: ARROW_START_MARKER_ID, viewBox: "0 0 10 10", refX: 1, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
1057
+ children: [{ tag: "path", attrs: { d: "M 10 0 L 0 5 L 10 10 z", fill: INK } }]
1058
+ },
1059
+ // Open (line) arrowheads.
1060
+ {
1061
+ tag: "marker",
1062
+ attrs: { id: `${ARROW_MARKER_ID}${OPEN}`, viewBox: "0 0 10 10", refX: 9.5, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
1063
+ children: [{ tag: "path", attrs: { d: "M 0 0.5 L 9.5 5 L 0 9.5", fill: "none", stroke: INK, "stroke-width": 1.1, "stroke-linejoin": "miter" } }]
1064
+ },
1065
+ {
1066
+ tag: "marker",
1067
+ attrs: { id: `${ARROW_START_MARKER_ID}${OPEN}`, viewBox: "0 0 10 10", refX: 0.5, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
1068
+ children: [{ tag: "path", attrs: { d: "M 10 0.5 L 0.5 5 L 10 9.5", fill: "none", stroke: INK, "stroke-width": 1.1, "stroke-linejoin": "miter" } }]
1069
+ }
1070
+ ]
1071
+ };
1072
+ }
1073
+ function layerNodes(doc, opts = {}) {
1074
+ return doc.layers.filter((l) => opts.includeHidden || l.visible).map((layer) => ({
1075
+ tag: "g",
1076
+ attrs: opts.editorAttrs ? { "data-layer-id": layer.id } : {},
1077
+ children: layer.items.filter((it) => opts.includeHidden || !it.hidden).map((it) => {
1078
+ const n = itemNode(doc, it);
1079
+ if (opts.editorAttrs) n.attrs["data-item-id"] = it.id;
1080
+ return n;
1081
+ })
1082
+ }));
1083
+ }
1084
+ function sheetLabelNodes(doc) {
1085
+ if (!doc.sheetLabel) return [];
1086
+ const { w } = sheetDims(doc.sheet);
1087
+ const p = PROFILES[doc.jurisdiction];
1088
+ const m = effectiveMargins(p, doc.sheet.orientation);
1089
+ return [textNode(m.left + (w - m.left - m.right) / 2, m.top + 5, doc.sheetLabel, 3.5, "middle")];
1090
+ }
1091
+ function documentNode(model, opts = {}) {
1092
+ const doc = viewDocument(model);
1093
+ const { w, h } = sheetDims(doc.sheet);
1094
+ return {
1095
+ tag: "svg",
1096
+ attrs: {
1097
+ xmlns: "http://www.w3.org/2000/svg",
1098
+ width: `${w}mm`,
1099
+ height: `${h}mm`,
1100
+ viewBox: `0 0 ${w} ${h}`
1101
+ },
1102
+ children: [
1103
+ defsNode(),
1104
+ { tag: "rect", attrs: { x: 0, y: 0, width: w, height: h, fill: "#fff" } },
1105
+ ...sheetLabelNodes(doc),
1106
+ ...layerNodes(doc, opts)
1107
+ ]
1108
+ };
1109
+ }
1110
+
1111
+ // ../../src/patent-render/render/serialize.ts
1112
+ var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1113
+ function serializeNode(n) {
1114
+ const attrs = Object.entries(n.attrs).map(([k, v]) => ` ${k}="${esc(String(v))}"`).join("");
1115
+ const inner = (n.text !== void 0 ? esc(n.text) : "") + (n.children ?? []).map(serializeNode).join("");
1116
+ return inner ? `<${n.tag}${attrs}>${inner}</${n.tag}>` : `<${n.tag}${attrs}/>`;
1117
+ }
1118
+ function renderSvg(doc, opts = {}) {
1119
+ return `<?xml version="1.0" encoding="UTF-8"?>
1120
+ ${serializeNode(documentNode(doc, { ...opts, editorAttrs: false }))}`;
1121
+ }
1122
+
1123
+ // ../../src/patent-render/server/png.ts
1124
+ function renderPng(doc, opts = {}) {
1125
+ const dpi = opts.dpi ?? 300;
1126
+ const { w } = sheetDims(doc.sheet);
1127
+ const widthPx = Math.round(w / 25.4 * dpi);
1128
+ const resvg = new Resvg(renderSvg(doc), {
1129
+ fitTo: { mode: "width", value: widthPx },
1130
+ background: "#ffffff",
1131
+ font: {
1132
+ loadSystemFonts: true,
1133
+ defaultFontFamily: "Arial",
1134
+ sansSerifFamily: "Arial",
1135
+ ...opts.fontFiles ? { fontFiles: opts.fontFiles } : {}
1136
+ }
1137
+ });
1138
+ return resvg.render().asPng();
1139
+ }
1140
+
1141
+ // ../../src/patent-render/server/actions.ts
1142
+ async function exportPatentPng(document, dpi = 300) {
1143
+ const doc = PatentDocument.parse(document);
1144
+ const png = renderPng(doc, { dpi: Math.min(600, Math.max(72, dpi)) });
1145
+ return { dataUrl: `data:image/png;base64,${png.toString("base64")}`, report: validate(doc) };
1146
+ }
1147
+ export {
1148
+ exportPatentPng
1149
+ };
1150
+ //# sourceMappingURL=server-actions.js.map