zelos-recad 0.1.0 → 0.2.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.
Files changed (166) hide show
  1. package/README.md +18 -5
  2. package/UPSTREAM-LICENSE +21 -21
  3. package/build-info.json +26 -0
  4. package/mcp/index.js +2 -1
  5. package/package.json +22 -10
  6. package/protocol/src/bundle.d.ts +7 -1
  7. package/protocol/src/contracts.d.ts +18 -6
  8. package/protocol/src/contracts.js +20 -7
  9. package/protocol/src/native-evidence.d.ts +20 -0
  10. package/service/app.js +4 -2
  11. package/service/options.d.ts +2 -1
  12. package/service/options.js +2 -1
  13. package/shared/build-identity.d.mts +6 -0
  14. package/shared/build-identity.mjs +63 -0
  15. package/shared/client.d.mts +1 -0
  16. package/shared/client.mjs +9 -0
  17. package/shared/command.d.mts +1 -0
  18. package/shared/command.mjs +22 -4
  19. package/shared/contracts/src/paths.d.ts +3 -0
  20. package/shared/contracts/src/paths.js +31 -0
  21. package/shared/mcp.d.mts +1 -0
  22. package/shared/service-storage/src/capacity.d.ts +36 -0
  23. package/shared/service-storage/src/capacity.js +71 -0
  24. package/shared/service-storage/src/consumption.d.ts +15 -0
  25. package/shared/service-storage/src/consumption.js +27 -0
  26. package/shared/service-storage/src/documents.d.ts +43 -0
  27. package/shared/service-storage/src/documents.js +210 -0
  28. package/shared/service-storage/src/downloads.d.ts +10 -0
  29. package/shared/service-storage/src/downloads.js +58 -0
  30. package/shared/service-storage/src/files.d.ts +18 -0
  31. package/shared/service-storage/src/files.js +118 -0
  32. package/shared/service-storage/src/footprint.d.ts +14 -0
  33. package/shared/service-storage/src/footprint.js +72 -0
  34. package/shared/service-storage/src/process-temp.d.ts +22 -0
  35. package/shared/service-storage/src/process-temp.js +181 -0
  36. package/shared/service-storage/src/quota.d.ts +30 -0
  37. package/shared/service-storage/src/quota.js +166 -0
  38. package/shared/service-storage/src/retention.d.ts +38 -0
  39. package/shared/service-storage/src/retention.js +148 -0
  40. package/shared/service-storage/src/staging.d.ts +15 -0
  41. package/shared/service-storage/src/staging.js +116 -0
  42. package/source/README.md +1 -3
  43. package/source/mcp/index.ts +2 -1
  44. package/source/package.json +4 -2
  45. package/source/protocol/src/contracts.ts +20 -7
  46. package/source/protocol/src/native-evidence.ts +21 -0
  47. package/source/rebuild.mjs +12 -4
  48. package/source/service/app.ts +6 -2
  49. package/source/service/options.ts +3 -2
  50. package/source/shared/build-identity.d.mts +6 -0
  51. package/source/shared/build-identity.mjs +63 -0
  52. package/source/shared/client.d.mts +1 -0
  53. package/source/shared/client.mjs +9 -0
  54. package/source/shared/command.d.mts +1 -0
  55. package/source/shared/command.mjs +22 -4
  56. package/source/shared/contracts/src/paths.ts +33 -0
  57. package/source/shared/mcp.d.mts +1 -0
  58. package/source/shared/service-storage/src/capacity.ts +101 -0
  59. package/source/shared/service-storage/src/consumption.ts +45 -0
  60. package/source/shared/service-storage/src/documents.ts +262 -0
  61. package/source/shared/service-storage/src/downloads.ts +62 -0
  62. package/source/shared/service-storage/src/files.ts +135 -0
  63. package/source/shared/service-storage/src/footprint.ts +78 -0
  64. package/source/shared/service-storage/src/process-temp.ts +205 -0
  65. package/source/shared/service-storage/src/quota.ts +198 -0
  66. package/source/shared/service-storage/src/retention.ts +180 -0
  67. package/source/shared/service-storage/src/staging.ts +106 -0
  68. package/source/src/application-objects.ts +2 -2
  69. package/source/src/assets.ts +15 -0
  70. package/source/src/block-clip.ts +1 -1
  71. package/source/src/block-metadata.ts +12 -5
  72. package/source/src/build-info.ts +15 -0
  73. package/source/src/cad-engine.ts +18 -8
  74. package/source/src/command.ts +2 -2
  75. package/source/src/constraints.ts +2 -2
  76. package/source/src/conversion.ts +2 -0
  77. package/source/src/dwg-fallback.ts +2 -0
  78. package/source/src/dwg.ts +7 -0
  79. package/source/src/dxf-export.ts +3 -3
  80. package/source/src/dxf.ts +7 -4
  81. package/source/src/native-evidence.ts +33 -1
  82. package/source/src/native-segmented-path.ts +22 -35
  83. package/source/src/point-dictionaries.ts +65 -0
  84. package/source/src/readback.ts +7 -6
  85. package/source/src/reader.ts +19 -10
  86. package/source/src/render-operation.ts +39 -7
  87. package/source/src/runner.ts +5 -4
  88. package/source/src/runtime/documents.ts +23 -142
  89. package/source/src/runtime/index.ts +71 -17
  90. package/source/src/runtime/jobs.ts +176 -153
  91. package/source/src/runtime/managed-worker.ts +37 -0
  92. package/source/src/runtime/storage-policy.ts +39 -0
  93. package/source/src/runtime/storage.ts +9 -44
  94. package/source/src/source-scene.ts +125 -23
  95. package/source/src/text/glyphs.ts +63 -0
  96. package/source/src/text/ink-bounds.ts +7 -36
  97. package/source/src/text/scene-geometry.ts +92 -0
  98. package/source/src/text/source-fonts.ts +31 -0
  99. package/source/src/vendor-object-data.ts +265 -0
  100. package/source/src/xref.ts +4 -3
  101. package/source/tsconfig.json +4 -2
  102. package/src/application-objects.js +2 -2
  103. package/src/assets.d.ts +9 -0
  104. package/src/assets.js +14 -0
  105. package/src/block-clip.js +1 -1
  106. package/src/block-metadata.js +11 -5
  107. package/src/build-info.d.ts +2 -0
  108. package/src/build-info.js +14 -0
  109. package/src/cad-engine.js +19 -8
  110. package/src/command.js +2 -2
  111. package/src/constraints.js +2 -2
  112. package/src/conversion.d.ts +2 -0
  113. package/src/conversion.js +2 -0
  114. package/src/dwg-fallback.d.ts +1 -0
  115. package/src/dwg-fallback.js +2 -0
  116. package/src/dwg.d.ts +3 -0
  117. package/src/dwg.js +7 -0
  118. package/src/dxf-export.js +3 -3
  119. package/src/dxf.d.ts +14 -1
  120. package/src/dxf.js +7 -3
  121. package/src/native-evidence.d.ts +33 -1
  122. package/src/native-evidence.js +33 -0
  123. package/src/native-segmented-path.js +1 -3
  124. package/src/point-dictionaries.d.ts +12 -0
  125. package/src/point-dictionaries.js +88 -0
  126. package/src/readback.d.ts +12 -4
  127. package/src/readback.js +7 -6
  128. package/src/reader.d.ts +12 -1
  129. package/src/reader.js +22 -11
  130. package/src/render-operation.js +36 -7
  131. package/src/runner.js +5 -4
  132. package/src/runtime/documents.d.ts +8 -20
  133. package/src/runtime/documents.js +17 -116
  134. package/src/runtime/index.d.ts +41 -4
  135. package/src/runtime/index.js +72 -18
  136. package/src/runtime/jobs.d.ts +21 -2
  137. package/src/runtime/jobs.js +120 -100
  138. package/src/runtime/managed-worker.d.ts +8 -0
  139. package/src/runtime/managed-worker.js +29 -0
  140. package/src/runtime/storage-policy.d.ts +25 -0
  141. package/src/runtime/storage-policy.js +29 -0
  142. package/src/runtime/storage.d.ts +1 -7
  143. package/src/runtime/storage.js +1 -38
  144. package/src/source-scene.d.ts +4 -2
  145. package/src/source-scene.js +136 -20
  146. package/src/text/glyphs.d.ts +12 -0
  147. package/src/text/glyphs.js +53 -0
  148. package/src/text/ink-bounds.d.ts +2 -1
  149. package/src/text/ink-bounds.js +6 -34
  150. package/src/text/scene-geometry.d.ts +21 -0
  151. package/src/text/scene-geometry.js +70 -0
  152. package/src/text/source-fonts.d.ts +7 -0
  153. package/src/text/source-fonts.js +30 -0
  154. package/src/vendor-object-data.d.ts +19 -0
  155. package/src/vendor-object-data.js +241 -0
  156. package/src/xref.js +3 -3
  157. package/vendor/libredwg/COPYING +674 -674
  158. package/vendor/libredwg/Dockerfile +2 -0
  159. package/vendor/libredwg/README.md +41 -28
  160. package/vendor/libredwg/build-local.sh +1 -1
  161. package/vendor/libredwg/libredwg-web.wasm +0 -0
  162. package/vendor/libredwg/manifest.json +5 -3
  163. package/vendor/libredwg/opaque-object-binding.patch +29 -0
  164. package/vendor/libredwg/rebuild.mjs +2 -1
  165. package/source/service/README.md +0 -152
  166. package/source/src/text/UPSTREAM.md +0 -26
@@ -21,16 +21,42 @@ const extent = (ps) => {
21
21
  };
22
22
  const union = (boxes) => extent(boxes.flatMap(rectangle));
23
23
  const contains = (a, b, t = 0) => a[0] - t <= b[0] && a[1] - t <= b[1] && a[2] + t >= b[2] && a[3] + t >= b[3];
24
+ /** Size the scene's plain JSON tree without allocating an oversized UTF-16 string. */
25
+ export function sceneJsonBytes(value) {
26
+ function size(value) {
27
+ if (value === null || typeof value !== 'object') {
28
+ const encoded = JSON.stringify(value);
29
+ return encoded === undefined ? undefined : Buffer.byteLength(encoded);
30
+ }
31
+ if (Array.isArray(value))
32
+ return 2 + Math.max(0, value.length - 1) + value.reduce((sum, item) => sum + (size(item) ?? 4), 0);
33
+ let bytes = 2, comma = 0;
34
+ for (const [key, item] of Object.entries(value)) {
35
+ const count = size(item);
36
+ if (count === undefined)
37
+ continue;
38
+ bytes += comma + Buffer.byteLength(JSON.stringify(key)) + 1 + count;
39
+ comma = 1;
40
+ }
41
+ return bytes;
42
+ }
43
+ return size(value);
44
+ }
24
45
  /** Same sheet policy as XDTerminal: outer rectangular frames, reading order,
25
46
  * intact overlapping frames and a separate page for every unassigned object.
26
47
  * Bounds of clipped/specialized objects remain conservative and are labelled. */
27
- export function splitSourceSheets(entities) {
48
+ export function splitSourceSheets(entities, mode = 'auto') {
28
49
  if (!entities.length)
29
50
  throw new CadError('EMPTY_SCENE', '模型空间没有场景图元');
30
51
  const total = union(entities.map((e) => e.bounds));
52
+ if (mode === 'single')
53
+ return [{ box: total, entityIds: entities.map(e => e.id), frame: false, issues: [] }];
31
54
  const span = Math.max(total[2] - total[0], total[3] - total[1]);
55
+ // A long row/column grows only one dimension; each real sheet remains
56
+ // comparable to the short axis of the occupied drawing area.
57
+ const frameSpan = Math.min(total[2] - total[0], total[3] - total[1]);
32
58
  const tolerance = Math.max(span * 1e-5, 1e-5);
33
- const horizontal = new Map(), vertical = [];
59
+ const horizontal = new Map(), sourceSegments = new Map();
34
60
  let work = 0;
35
61
  const step = () => {
36
62
  if (++work > 2_000_000)
@@ -39,21 +65,76 @@ export function splitSourceSheets(entities) {
39
65
  for (const entity of entities) {
40
66
  if (entity.kind !== 'path' || entity.clips.length)
41
67
  continue;
68
+ const root = entity.instancePath?.[0] || (entity.closed ? entity.id : 'unscoped');
69
+ if (!sourceSegments.has(root))
70
+ sourceSegments.set(root, { horizontal: [], vertical: [] });
71
+ const segments = sourceSegments.get(root);
42
72
  const ps = entity.closed ? [...entity.points, entity.points[0]] : entity.points;
43
73
  for (let i = 1; i < ps.length; i++) {
44
74
  step();
45
75
  const a = ps[i - 1], b = ps[i];
46
- if (Math.abs(a.y - b.y) <= tolerance && Math.abs(a.x - b.x) >= span * 0.12) {
47
- const x0 = Math.min(a.x, b.x), x1 = Math.max(a.x, b.x);
76
+ if (Math.abs(a.y - b.y) <= tolerance && Math.abs(a.x - b.x) > tolerance) {
77
+ segments.horizontal.push([(a.y + b.y) / 2, Math.min(a.x, b.x), Math.max(a.x, b.x)]);
78
+ }
79
+ else if (Math.abs(a.x - b.x) <= tolerance)
80
+ segments.vertical.push([(a.x + b.x) / 2, Math.min(a.y, b.y), Math.max(a.y, b.y)]);
81
+ }
82
+ }
83
+ // CAD frames are often split at grid labels or block boundaries. Join only
84
+ // touching collinear intervals for frame search; source strokes stay intact.
85
+ const merge = (segments) => {
86
+ const groups = [];
87
+ for (const segment of segments.sort((a, b) => a[0] - b[0] || a[1] - b[1])) {
88
+ const group = groups.at(-1);
89
+ if (group && segment[0] - group[0][0] <= tolerance)
90
+ group.push(segment);
91
+ else
92
+ groups.push([segment]);
93
+ }
94
+ const joined = [];
95
+ for (const group of groups) {
96
+ let current;
97
+ for (const segment of group.sort((a, b) => a[1] - b[1])) {
98
+ if (current && segment[1] <= current[2] + tolerance)
99
+ current[2] = Math.max(current[2], segment[2]);
100
+ else {
101
+ current = [group[0][0], segment[1], segment[2]];
102
+ joined.push(current);
103
+ }
104
+ }
105
+ }
106
+ return joined;
107
+ };
108
+ for (const source of sourceSegments.values())
109
+ for (const [y, x0, x1] of merge(source.horizontal))
110
+ if (x1 - x0 >= frameSpan * .12) {
48
111
  const key = Math.round(x0 / tolerance) + ':' + Math.round(x1 / tolerance);
49
112
  if (!horizontal.has(key))
50
113
  horizontal.set(key, []);
51
- horizontal.get(key).push([x0, x1, (a.y + b.y) / 2]);
114
+ horizontal.get(key).push([x0, x1, y]);
52
115
  }
53
- else if (Math.abs(a.x - b.x) <= tolerance)
54
- vertical.push([(a.x + b.x) / 2, Math.min(a.y, b.y), Math.max(a.y, b.y)]);
116
+ const vertical = [...sourceSegments.values()].flatMap(source => merge(source.vertical));
117
+ // Restrict side searches to the relevant x coordinate. Dense wiring sheets
118
+ // contain many short vertical strokes unrelated to any candidate frame.
119
+ vertical.sort((a, b) => a[0] - b[0]);
120
+ const spans = (x, y0, y1) => {
121
+ let lo = 0, hi = vertical.length;
122
+ while (lo < hi) {
123
+ step();
124
+ const mid = (lo + hi) >>> 1;
125
+ if (vertical[mid][0] < x - tolerance)
126
+ lo = mid + 1;
127
+ else
128
+ hi = mid;
55
129
  }
56
- }
130
+ for (let i = lo; i < vertical.length && vertical[i][0] <= x + tolerance; i++) {
131
+ step();
132
+ const v = vertical[i];
133
+ if (Math.abs(v[0] - x) <= tolerance && v[1] <= y0 + tolerance && v[2] >= y1 - tolerance)
134
+ return true;
135
+ }
136
+ return false;
137
+ };
57
138
  const frames = [];
58
139
  for (const edges of horizontal.values()) {
59
140
  edges.sort((a, b) => a[2] - b[2]);
@@ -61,14 +142,9 @@ export function splitSourceSheets(entities) {
61
142
  for (let j = i + 1; j < edges.length; j++) {
62
143
  step();
63
144
  const [x0, x1, y0] = edges[i], y1 = edges[j][2], ratio = (x1 - x0) / (y1 - y0);
64
- if (ratio < 0.4 || ratio > 2.6 || y1 - y0 < span * 0.12)
145
+ if (ratio < 0.4 || ratio > 2.6 || y1 - y0 < frameSpan * 0.12)
65
146
  continue;
66
- if ([x0, x1].every((x) => vertical.some((v) => {
67
- step();
68
- return (Math.abs(v[0] - x) <= tolerance &&
69
- v[1] <= y0 + tolerance &&
70
- v[2] >= y1 - tolerance);
71
- })))
147
+ if ([x0, x1].every((x) => spans(x, y0, y1)))
72
148
  frames.push([x0, y0, x1, y1]);
73
149
  }
74
150
  }
@@ -91,7 +167,17 @@ export function splitSourceSheets(entities) {
91
167
  if (!outer.length)
92
168
  return [sheet(total, entities, false, ['frame-not-found'])];
93
169
  const assigned = new Set(), result = [];
170
+ const rows = [];
94
171
  for (const box of outer.sort((a, b) => b[3] - a[3] || a[0] - b[0])) {
172
+ const row = rows.at(-1);
173
+ const aligned = row && (row[0][3] - box[3] <= tolerance ||
174
+ Math.min(row[0][3], box[3]) - Math.max(row[0][1], box[1]) >= .9 * Math.min(row[0][3] - row[0][1], box[3] - box[1]));
175
+ if (aligned)
176
+ row.push(box);
177
+ else
178
+ rows.push([box]);
179
+ }
180
+ for (const box of rows.flatMap(row => row.sort((a, b) => a[0] - b[0]))) {
95
181
  const selected = entities.filter((e) => contains(box, e.bounds, tolerance));
96
182
  if (!selected.length)
97
183
  continue;
@@ -108,16 +194,17 @@ export function splitSourceSheets(entities) {
108
194
  }
109
195
  /** Export collected draw operations BEFORE print transforms. Instances use the
110
196
  * renderer's composed affine matrices; raw entity extents are never substituted. */
111
- export function sourceScene(roots, db, textInk, provenance, native) {
197
+ export function sourceScene(roots, db, textInk, provenance, native, textGeometry) {
112
198
  const layers = new Map([...db.tables.layerTable.newIterator()].map((l) => [l.name.toLowerCase(), l]));
113
199
  const entities = [], issues = [];
200
+ const textShapes = [];
114
201
  const nativeInstances = [];
115
202
  const nativeHandles = new Map();
116
203
  if (native)
117
204
  for (const [record, id] of native.references)
118
205
  nativeHandles.set(String(record.objectId).toUpperCase(), id);
119
206
  let points = 0, nodes = 0;
120
- function visit(node, parent, inherited, path, clips, textParent = false) {
207
+ function visit(node, parent, inherited, path, clips, textParent = false, textOwner) {
121
208
  if (++nodes > 1_000_000 || path.length > 64)
122
209
  throw new CadError('SCENE_LIMIT', '场景实例数量或深度超过预算');
123
210
  const layer = effectivePdfLayer(node.layerName, inherited), record = layers.get(layer.toLowerCase());
@@ -182,6 +269,22 @@ export function sourceScene(roots, db, textInk, provenance, native) {
182
269
  instance?.sceneEntityIds.push(String(entities.length));
183
270
  };
184
271
  const actual = String(node.actualText || '');
272
+ if (textGeometry &&
273
+ !textOwner &&
274
+ !textParent &&
275
+ (actual || node._ops.some((op) => op.kind === 'text'))) {
276
+ textOwner = {
277
+ ...common,
278
+ ...(instance ? { nativeRecordId: recordId, nativeInstanceId: instance.id } : {}),
279
+ text: actual ||
280
+ node._ops
281
+ .filter((op) => op.kind === 'text')
282
+ .map((op) => op.text)
283
+ .join(''),
284
+ primitives: [],
285
+ };
286
+ textShapes.push(textOwner);
287
+ }
185
288
  if (actual && !textParent) {
186
289
  const quad = node.userData?.xdtraceTextQuad;
187
290
  if (quad)
@@ -205,6 +308,8 @@ export function sourceScene(roots, db, textInk, provenance, native) {
205
308
  }
206
309
  }
207
310
  for (const op of node._ops) {
311
+ if (textGeometry && textOwner)
312
+ textOwner.primitives.push(...textGeometry(op, map));
208
313
  // Glyph strokes stay in the PDF; scene consumers use their native text.
209
314
  if (actual || textParent)
210
315
  continue;
@@ -230,8 +335,16 @@ export function sourceScene(roots, db, textInk, provenance, native) {
230
335
  }
231
336
  else {
232
337
  const b = node.box, ps = rectangle([b.min.x, b.min.y, b.max.x, b.max.y]);
338
+ // Preserve the actual POINT marker operation separately from its native
339
+ // zero-dimensional record. Consumers retain POINT and replay this paint.
340
+ const nativePoint = op.kind === 'circle' && db.getObjectById(common.handle)?.dxfTypeName === 'POINT'
341
+ ? { version: 1, displayMode: db.pdmode, displaySize: db.pdsize,
342
+ center: map({ x: op.x, y: op.y }),
343
+ axisX: { x: (m?.[0] ?? 1) * op.r, y: (m?.[1] ?? 0) * op.r },
344
+ axisY: { x: (m?.[4] ?? 0) * op.r, y: (m?.[5] ?? 1) * op.r }, style: op.style }
345
+ : undefined;
233
346
  if (ps.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y)))
234
- add('specialized', ps, { operation: op.kind, boundsPolicy: 'conservative-world-box' });
347
+ add('specialized', ps, { operation: op.kind, boundsPolicy: 'conservative-world-box', ...(nativePoint ? { nativePoint } : {}) });
235
348
  issues.push({
236
349
  code: 'scene-specialized-bounds',
237
350
  handle: common.handle,
@@ -241,7 +354,7 @@ export function sourceScene(roots, db, textInk, provenance, native) {
241
354
  }
242
355
  }
243
356
  for (let i = 0; i < node.childCount; i++)
244
- visit(node.childAt(i), matrix, layer, [...path, `${i}:${node.childAt(i).objectId || ''}`], clips, textParent || !!actual);
357
+ visit(node.childAt(i), matrix, layer, [...path, `${i}:${node.childAt(i).objectId || ''}`], clips, textParent || !!actual, textOwner);
245
358
  }
246
359
  roots.forEach((root, i) => visit(root, undefined, '0', [`${i}:${root.objectId || ''}`], []));
247
360
  if (entities.some((e) => e.clips.length))
@@ -262,6 +375,9 @@ export function sourceScene(roots, db, textInk, provenance, native) {
262
375
  ...provenance,
263
376
  paperLayouts,
264
377
  entities,
378
+ ...(textGeometry
379
+ ? { textGeometry: { version: 1, coordinateSystem: 'cad-world-y-up-v1', groups: textShapes } }
380
+ : {}),
265
381
  ...(native
266
382
  ? {
267
383
  nativeEvidence: {
@@ -279,6 +395,6 @@ export function sourceScene(roots, db, textInk, provenance, native) {
279
395
  }
280
396
  : {}),
281
397
  issues,
282
- sheets: splitSourceSheets(entities),
398
+ sheets: splitSourceSheets(entities, provenance.sheetMode || 'auto'),
283
399
  };
284
400
  }
@@ -0,0 +1,12 @@
1
+ export type GlyphPoint = {
2
+ x: number;
3
+ y: number;
4
+ };
5
+ export interface PlacedGlyph {
6
+ glyph: any;
7
+ place: (x: number, y: number) => GlyphPoint;
8
+ }
9
+ export type TextGlyphs = (op: any) => PlacedGlyph[];
10
+ /** Follow the pinned PDF writer's shaped glyph order, tracking and text matrix.
11
+ * Bounds and optional outline export share this placement; CAD layout stays upstream. */
12
+ export declare function textGlyphs(fonts: any): TextGlyphs;
@@ -0,0 +1,53 @@
1
+ import { CadError } from "../contracts.js";
2
+ /** Follow the pinned PDF writer's shaped glyph order, tracking and text matrix.
3
+ * Bounds and optional outline export share this placement; CAD layout stays upstream. */
4
+ export function textGlyphs(fonts) {
5
+ const cache = new WeakMap();
6
+ return (op) => {
7
+ const cached = cache.get(op);
8
+ if (cached)
9
+ return cached;
10
+ const loaded = fonts._loaded.get(op.font), font = loaded?.fk, units = font?.unitsPerEm;
11
+ if (!font || !Number.isFinite(units) || units <= 0)
12
+ throw new CadError('FONT_INVALID', '文字字形缺少有效字体:' + op.font);
13
+ const rad = (op.angleDeg * Math.PI) / 180, c = Math.cos(rad), s = Math.sin(rad);
14
+ const shear = Math.tan(((op.obliqueDeg || 0) * Math.PI) / 180);
15
+ const flip = op.flipX === true ? -1 : 1, tracking = op.tracking ?? 1;
16
+ const extra = ((tracking - 1) / loaded.scaleFactor) * units;
17
+ let pen = 0;
18
+ const result = [];
19
+ const add = (glyph) => {
20
+ if (result.length >= 250_000)
21
+ throw new CadError('SCENE_LIMIT', '单段文字字形数量超过预算');
22
+ if (!Number.isFinite(glyph.advanceWidth))
23
+ throw new CadError('FONT_INVALID', '文字字距无效:' + op.font);
24
+ const offset = pen;
25
+ result.push({
26
+ glyph,
27
+ place(x, y) {
28
+ x += offset;
29
+ const p = {
30
+ x: op.x + (op.size / units) * (x * op.hScale * flip * c + y * (shear * c - s)),
31
+ y: op.y + (op.size / units) * (x * op.hScale * flip * s + y * (shear * s + c)),
32
+ };
33
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y))
34
+ throw new CadError('FONT_INVALID', '文字字形坐标无效:' + op.font);
35
+ return p;
36
+ },
37
+ });
38
+ pen += glyph.advanceWidth;
39
+ };
40
+ for (const glyph of font.layout(op.text).glyphs) {
41
+ if (tracking === 1)
42
+ add(glyph);
43
+ else {
44
+ // The PDF writer encodes each shaped glyph's code points again for tracking.
45
+ for (const encoded of font.layout(String.fromCodePoint(...glyph.codePoints)).glyphs)
46
+ add(encoded);
47
+ pen += extra;
48
+ }
49
+ }
50
+ cache.set(op, result);
51
+ return result;
52
+ };
53
+ }
@@ -1,3 +1,4 @@
1
+ import type { TextGlyphs } from './glyphs.js';
1
2
  type Point = {
2
3
  x: number;
3
4
  y: number;
@@ -7,5 +8,5 @@ export type TextInkBounds = (op: any) => Point[][];
7
8
  * layout box can omit capitals, descenders, shear and later MTEXT lines.
8
9
  * Follow pdf-renderer 1.7.4 / pdf-lib's actual glyph advances and text matrix;
9
10
  * this does not change layout, encoding, or PDF painting. */
10
- export declare function textInkBounds(fonts: any): TextInkBounds;
11
+ export declare function textInkBounds(glyphs: TextGlyphs): TextInkBounds;
11
12
  export {};
@@ -3,36 +3,21 @@ import { CadError } from "../contracts.js";
3
3
  * layout box can omit capitals, descenders, shear and later MTEXT lines.
4
4
  * Follow pdf-renderer 1.7.4 / pdf-lib's actual glyph advances and text matrix;
5
5
  * this does not change layout, encoding, or PDF painting. */
6
- export function textInkBounds(fonts) {
6
+ export function textInkBounds(glyphs) {
7
7
  const cache = new WeakMap();
8
8
  return (op) => {
9
9
  const cached = cache.get(op);
10
10
  if (cached)
11
11
  return cached;
12
- // Reuse the exact normalized face loaded by the pinned PDF font manager.
13
- const loaded = fonts._loaded.get(op.font);
14
- const font = loaded?.fk, units = font?.unitsPerEm;
15
- if (!font || !Number.isFinite(units) || units <= 0)
16
- throw new CadError('FONT_INVALID', '文字范围缺少有效字体:' + op.font);
17
- const rad = (op.angleDeg * Math.PI) / 180, c = Math.cos(rad), s = Math.sin(rad);
18
- const shear = Math.tan(((op.obliqueDeg || 0) * Math.PI) / 180);
19
- const flip = op.flipX === true ? -1 : 1;
20
- const tracking = op.tracking ?? 1;
21
- const extra = ((tracking - 1) / loaded.scaleFactor) * units;
22
- let pen = 0;
23
12
  const loops = [];
24
- const place = (x, y) => ({
25
- x: op.x + (op.size / units) * (x * op.hScale * flip * c + y * (shear * c - s)),
26
- y: op.y + (op.size / units) * (x * op.hScale * flip * s + y * (shear * s + c)),
27
- });
28
- const add = (glyph) => {
13
+ for (const { glyph, place } of glyphs(op)) {
29
14
  const box = glyph.bbox;
30
15
  if ([box.minX, box.minY, box.maxX, box.maxY].every(Number.isFinite)) {
31
16
  const loop = [
32
- place(pen + box.minX, box.minY),
33
- place(pen + box.maxX, box.minY),
34
- place(pen + box.maxX, box.maxY),
35
- place(pen + box.minX, box.maxY),
17
+ place(box.minX, box.minY),
18
+ place(box.maxX, box.minY),
19
+ place(box.maxX, box.maxY),
20
+ place(box.minX, box.maxY),
36
21
  ];
37
22
  if (!loop.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y)))
38
23
  throw new CadError('FONT_INVALID', '文字字形范围无效:' + op.font);
@@ -40,19 +25,6 @@ export function textInkBounds(fonts) {
40
25
  }
41
26
  else if (glyph.path.commands.length)
42
27
  throw new CadError('FONT_INVALID', '文字字形范围无效:' + op.font);
43
- if (!Number.isFinite(glyph.advanceWidth))
44
- throw new CadError('FONT_INVALID', '文字字距无效:' + op.font);
45
- pen += glyph.advanceWidth;
46
- };
47
- for (const glyph of font.layout(op.text).glyphs) {
48
- if (tracking === 1)
49
- add(glyph);
50
- else {
51
- // Tracking's embedOp encodes each shaped glyph's code points again.
52
- for (const encoded of font.layout(String.fromCodePoint(...glyph.codePoints)).glyphs)
53
- add(encoded);
54
- pen += extra;
55
- }
56
28
  }
57
29
  cache.set(op, loops);
58
30
  return loops;
@@ -0,0 +1,21 @@
1
+ import type { TextGlyphs, GlyphPoint } from './glyphs.js';
2
+ export interface TextScenePrimitive {
3
+ paint: 'fill' | 'stroke';
4
+ path: string;
5
+ fillRule?: 'nonzero' | 'evenodd';
6
+ font?: string;
7
+ style: {
8
+ rgb: {
9
+ r: number;
10
+ g: number;
11
+ b: number;
12
+ };
13
+ opacity: number;
14
+ lineWidth?: number;
15
+ dashArray?: number[];
16
+ exactWidth?: boolean;
17
+ };
18
+ }
19
+ export type TextSceneGeometry = (op: any, map: (p: GlyphPoint) => GlyphPoint) => TextScenePrimitive[];
20
+ /** Serialize actual CAD draw operations without introducing a second layout engine. */
21
+ export declare function textSceneGeometry(glyphs: TextGlyphs): TextSceneGeometry;
@@ -0,0 +1,70 @@
1
+ import { CadError } from "../contracts.js";
2
+ const commands = {
3
+ moveTo: ['M', 2],
4
+ lineTo: ['L', 2],
5
+ quadraticCurveTo: ['Q', 4],
6
+ bezierCurveTo: ['C', 6],
7
+ closePath: ['Z', 0],
8
+ };
9
+ /** Serialize actual CAD draw operations without introducing a second layout engine. */
10
+ export function textSceneGeometry(glyphs) {
11
+ let count = 0, work = 0;
12
+ const step = () => {
13
+ if (++work > 2_000_000)
14
+ throw new CadError('SCENE_LIMIT', '文字轮廓指令超过预算');
15
+ };
16
+ const point = (p) => {
17
+ if (++count > 1_000_000)
18
+ throw new CadError('SCENE_LIMIT', '文字轮廓控制点超过预算');
19
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y))
20
+ throw new CadError('FONT_INVALID', '文字轮廓坐标无效');
21
+ return p.x + ' ' + p.y;
22
+ };
23
+ return (op, map) => {
24
+ if (op.kind === 'text') {
25
+ const paths = [];
26
+ for (const { glyph, place } of glyphs(op)) {
27
+ step();
28
+ const d = [];
29
+ for (const command of glyph.path.commands) {
30
+ step();
31
+ const spec = commands[command.command];
32
+ if (!spec || command.args.length !== spec[1])
33
+ throw new CadError('FONT_INVALID', '字体轮廓指令尚未支持:' + command.command);
34
+ d.push(spec[0]);
35
+ for (let i = 0; i < command.args.length; i += 2)
36
+ d.push(point(map(place(command.args[i], command.args[i + 1]))));
37
+ }
38
+ if (d.length)
39
+ paths.push(d.join(' '));
40
+ }
41
+ return paths.length
42
+ ? [
43
+ {
44
+ paint: 'fill',
45
+ path: paths.join(' '),
46
+ fillRule: 'nonzero',
47
+ font: op.font,
48
+ style: op.style,
49
+ },
50
+ ]
51
+ : [];
52
+ }
53
+ if (op.kind === 'stroke') {
54
+ const d = op.points
55
+ .map((p, i) => (i ? 'L ' : 'M ') + point(map(p)))
56
+ .join(' ');
57
+ return d ? [{ paint: 'stroke', path: d + (op.closed ? ' Z' : ''), style: op.style }] : [];
58
+ }
59
+ if (op.kind === 'fill') {
60
+ const d = op.loops
61
+ .filter((loop) => loop.length)
62
+ .map((loop) => loop.map((p, i) => (i ? 'L ' : 'M ') + point(map(p))).join(' ') + ' Z')
63
+ .join(' ');
64
+ return d
65
+ ? [{ paint: 'fill', path: d, fillRule: op.fillRule || 'nonzero', style: op.style }]
66
+ : [];
67
+ }
68
+ throw new CadError('TEXT_GEOMETRY_UNSUPPORTED', '文字绘制指令需要专项适配:' + op.kind);
69
+ };
70
+ }
@@ -0,0 +1,7 @@
1
+ import type { FontResource } from './fonts.js';
2
+ /** Export the renderer's resolved aliases and effective bytes, including extracted TTC faces. */
3
+ export declare function sourceFontResources(fonts: Map<string, FontResource>, used: Set<string>, output: string): {
4
+ name: string;
5
+ sha256: string;
6
+ bytes: number;
7
+ }[];
@@ -0,0 +1,30 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ /** Export the renderer's resolved aliases and effective bytes, including extracted TTC faces. */
5
+ export function sourceFontResources(fonts, used, output) {
6
+ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
7
+ const artifacts = [];
8
+ const entries = new Map();
9
+ for (const [alias, font] of fonts) {
10
+ if (!used.has(font.canonical) || font.kind === 'shape')
11
+ continue;
12
+ const digest = sha(font.bytes), key = font.canonical;
13
+ let entry = entries.get(key);
14
+ if (!entry) {
15
+ const extension = font.faceIndex === undefined ? path.extname(font.file).toLowerCase() : '.ttf';
16
+ const file = `font-${digest}${extension}`;
17
+ if (!artifacts.some(a => a.name === file)) {
18
+ writeFileSync(path.join(output, file), font.bytes);
19
+ artifacts.push({ name: file, sha256: digest, bytes: font.bytes.length });
20
+ }
21
+ entry = { file, sha256: digest, sourceSha256: font.sha256, fileName: font.faceIndex === undefined ? path.basename(font.file) : path.parse(font.file).name + '.ttf', names: [], ...(font.faceIndex === undefined ? {} : { faceIndex: font.faceIndex }) };
22
+ entries.set(key, entry);
23
+ }
24
+ entry.names.push(alias);
25
+ }
26
+ const bytes = Buffer.from(JSON.stringify({ version: 'source-font-resources/1', fonts: [...entries.values()] }));
27
+ writeFileSync(path.join(output, 'font-resources.json'), bytes);
28
+ artifacts.push({ name: 'font-resources.json', sha256: sha(bytes), bytes: bytes.length });
29
+ return artifacts;
30
+ }
@@ -0,0 +1,19 @@
1
+ export declare function parseCcYjInfo(raw: any): {
2
+ format: "cc-yj-info/1";
3
+ dataBits: number;
4
+ fields: {
5
+ name: string;
6
+ encoding: string;
7
+ bitStart: number;
8
+ bitEnd: number;
9
+ value: unknown;
10
+ }[];
11
+ values: {
12
+ [k: string]: unknown;
13
+ };
14
+ uninterpretedFields: string[];
15
+ };
16
+ /** Capture bounded raw records before freeing native memory. Unknown root data
17
+ * stays opaque and retains its original decoder failure; it never authorizes a block. */
18
+ export declare function captureCcObjects(module: any, pointer: number, source: Buffer, sourceSha256: string, codepage: number): any;
19
+ export declare function validateCcOwnership(records: any[], model: any): void;