circuitscript 0.1.5 → 0.1.8

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 (97) hide show
  1. package/dist/cjs/BaseVisitor.js +127 -73
  2. package/dist/cjs/SemanticTokenVisitor.js +19 -13
  3. package/dist/cjs/antlr/CircuitScriptParser.js +711 -671
  4. package/dist/cjs/builtinMethods.js +29 -25
  5. package/dist/cjs/environment.js +118 -0
  6. package/dist/cjs/execute.js +53 -12
  7. package/dist/cjs/export.js +0 -5
  8. package/dist/cjs/geometry.js +1 -0
  9. package/dist/cjs/globals.js +11 -6
  10. package/dist/cjs/helpers.js +152 -127
  11. package/dist/cjs/index.js +5 -0
  12. package/dist/cjs/layout.js +86 -44
  13. package/dist/cjs/main.js +31 -19
  14. package/dist/cjs/objects/ExecutionScope.js +33 -0
  15. package/dist/cjs/objects/ParamDefinition.js +15 -15
  16. package/dist/cjs/parser.js +27 -21
  17. package/dist/cjs/regenerate-tests.js +14 -10
  18. package/dist/cjs/render.js +3 -1
  19. package/dist/cjs/sizing.js +5 -58
  20. package/dist/cjs/utils.js +85 -30
  21. package/dist/cjs/validate/SymbolTable.js +96 -0
  22. package/dist/cjs/validate/SymbolValidatorResolveVisitor.js +14 -0
  23. package/dist/cjs/validate/SymbolValidatorVisitor.js +170 -0
  24. package/dist/cjs/validate.js +71 -44
  25. package/dist/cjs/visitor.js +140 -24
  26. package/dist/esm/{BaseVisitor.mjs → BaseVisitor.js} +98 -45
  27. package/dist/esm/{SemanticTokenVisitor.mjs → SemanticTokenVisitor.js} +17 -11
  28. package/dist/esm/antlr/{CircuitScriptParser.mjs → CircuitScriptParser.js} +711 -671
  29. package/dist/esm/{builtinMethods.mjs → builtinMethods.js} +20 -16
  30. package/dist/esm/{draw_symbols.mjs → draw_symbols.js} +7 -7
  31. package/dist/esm/environment.js +110 -0
  32. package/dist/esm/{execute.mjs → execute.js} +66 -25
  33. package/dist/esm/{export.mjs → export.js} +2 -7
  34. package/dist/esm/{geometry.mjs → geometry.js} +6 -5
  35. package/dist/esm/{globals.mjs → globals.js} +6 -1
  36. package/dist/esm/helpers.js +394 -0
  37. package/dist/esm/index.js +20 -0
  38. package/dist/esm/{layout.mjs → layout.js} +72 -53
  39. package/dist/esm/{lexer.mjs → lexer.js} +2 -2
  40. package/dist/esm/{main.mjs → main.js} +33 -21
  41. package/dist/esm/objects/{ClassComponent.mjs → ClassComponent.js} +5 -4
  42. package/dist/esm/objects/{ExecutionScope.mjs → ExecutionScope.js} +33 -0
  43. package/dist/esm/objects/{Frame.mjs → Frame.js} +1 -1
  44. package/dist/esm/objects/{ParamDefinition.mjs → ParamDefinition.js} +1 -1
  45. package/dist/esm/objects/{PinDefinition.mjs → PinDefinition.js} +1 -1
  46. package/dist/esm/parser.js +71 -0
  47. package/dist/esm/{regenerate-tests.mjs → regenerate-tests.js} +15 -11
  48. package/dist/esm/{render.mjs → render.js} +11 -9
  49. package/dist/esm/{sizing.mjs → sizing.js} +6 -34
  50. package/dist/esm/{utils.mjs → utils.js} +61 -17
  51. package/dist/esm/validate/SymbolTable.js +90 -0
  52. package/dist/esm/validate/SymbolValidatorResolveVisitor.js +10 -0
  53. package/dist/esm/validate/SymbolValidatorVisitor.js +163 -0
  54. package/dist/esm/validate.js +105 -0
  55. package/dist/esm/{visitor.mjs → visitor.js} +151 -35
  56. package/dist/fonts/Arial.ttf +0 -0
  57. package/dist/fonts/Inter-Bold.ttf +0 -0
  58. package/dist/fonts/Inter-Regular.ttf +0 -0
  59. package/dist/fonts/OpenSans-Regular.ttf +0 -0
  60. package/dist/fonts/Roboto-Regular.ttf +0 -0
  61. package/dist/libs/lib.cst +423 -0
  62. package/dist/types/BaseVisitor.d.ts +34 -21
  63. package/dist/types/SemanticTokenVisitor.d.ts +6 -5
  64. package/dist/types/antlr/CircuitScriptParser.d.ts +4 -2
  65. package/dist/types/builtinMethods.d.ts +3 -2
  66. package/dist/types/environment.d.ts +31 -0
  67. package/dist/types/globals.d.ts +4 -1
  68. package/dist/types/helpers.d.ts +12 -14
  69. package/dist/types/index.d.ts +5 -0
  70. package/dist/types/layout.d.ts +2 -2
  71. package/dist/types/objects/ClassComponent.d.ts +1 -0
  72. package/dist/types/objects/ExecutionScope.d.ts +11 -0
  73. package/dist/types/objects/types.d.ts +6 -1
  74. package/dist/types/parser.d.ts +7 -11
  75. package/dist/types/sizing.d.ts +0 -3
  76. package/dist/types/utils.d.ts +30 -6
  77. package/dist/types/validate/SymbolTable.d.ts +40 -0
  78. package/dist/types/validate/SymbolValidatorResolveVisitor.d.ts +7 -0
  79. package/dist/types/validate/SymbolValidatorVisitor.d.ts +32 -0
  80. package/dist/types/validate.d.ts +1 -1
  81. package/package.json +15 -14
  82. package/dist/cjs/SymbolValidatorVisitor.js +0 -233
  83. package/dist/esm/SymbolValidatorVisitor.mjs +0 -222
  84. package/dist/esm/helpers.mjs +0 -364
  85. package/dist/esm/index.mjs +0 -15
  86. package/dist/esm/parser.mjs +0 -64
  87. package/dist/esm/validate.mjs +0 -74
  88. package/dist/types/SymbolValidatorVisitor.d.ts +0 -61
  89. /package/dist/esm/antlr/{CircuitScriptLexer.mjs → CircuitScriptLexer.js} +0 -0
  90. /package/dist/esm/antlr/{CircuitScriptVisitor.mjs → CircuitScriptVisitor.js} +0 -0
  91. /package/dist/esm/{fonts.mjs → fonts.js} +0 -0
  92. /package/dist/esm/{logger.mjs → logger.js} +0 -0
  93. /package/dist/esm/objects/{Net.mjs → Net.js} +0 -0
  94. /package/dist/esm/objects/{PinTypes.mjs → PinTypes.js} +0 -0
  95. /package/dist/esm/objects/{Wire.mjs → Wire.js} +0 -0
  96. /package/dist/esm/objects/{types.mjs → types.js} +0 -0
  97. /package/dist/esm/{server.mjs → server.js} +0 -0
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getPaperSize = exports.isSupportedPaperSize = exports.PaperGridReferences = exports.pxToMM = exports.milsToMM = exports.UnitDimension = exports.getPackageVersion = exports.getDefaultLibsPath = exports.getFontsPath = exports.getCurrentPath = exports.detectJSModuleType = exports.renderScript = exports.validateScript = exports.ParseErrorStrategy = exports.getSemanticTokens = exports.getScriptText = exports.prepareFile = exports.JSModuleType = void 0;
6
+ exports.getPaperSize = exports.isSupportedPaperSize = exports.PaperGridReferences = exports.pxToMM = exports.milsToMM = exports.UnitDimension = exports.detectJSModuleType = exports.renderScript = exports.validateScript = exports.ParseErrorStrategy = exports.getSemanticTokens = exports.prepareFile = exports.JSModuleType = void 0;
7
7
  const fs_1 = require("fs");
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const pdfkit_1 = __importDefault(require("pdfkit"));
@@ -13,8 +13,8 @@ const parser_js_1 = require("./parser.js");
13
13
  const render_js_1 = require("./render.js");
14
14
  const utils_js_1 = require("./utils.js");
15
15
  const visitor_js_1 = require("./visitor.js");
16
- const this_file_1 = require("this-file");
17
- const SymbolValidatorVisitor_js_1 = require("./SymbolValidatorVisitor.js");
16
+ const SymbolValidatorVisitor_js_1 = require("./validate/SymbolValidatorVisitor.js");
17
+ const SymbolValidatorResolveVisitor_js_1 = require("./validate/SymbolValidatorResolveVisitor.js");
18
18
  const antlr4ng_1 = require("antlr4ng");
19
19
  const lexer_js_1 = require("./lexer.js");
20
20
  const CircuitScriptParser_js_1 = require("./antlr/CircuitScriptParser.js");
@@ -44,22 +44,12 @@ function prepareFile(textData) {
44
44
  };
45
45
  }
46
46
  exports.prepareFile = prepareFile;
47
- function getScriptText(filePath) {
48
- try {
49
- return (0, fs_1.readFileSync)(filePath, { encoding: 'utf-8' });
50
- }
51
- catch (err) {
52
- return null;
53
- }
54
- }
55
- exports.getScriptText = getScriptText;
56
- function getSemanticTokens(scriptData, options) {
47
+ async function getSemanticTokens(scriptData, options) {
57
48
  const { parser, lexer, tokens } = prepareFile(scriptData);
58
49
  const tree = parser.script();
59
- const { currentDirectory = null, defaultLibsPath, } = options;
60
- const visitor = new SemanticTokenVisitor_js_1.SemanticTokensVisitor(true, null, currentDirectory, defaultLibsPath, lexer, scriptData);
50
+ const visitor = new SemanticTokenVisitor_js_1.SemanticTokensVisitor(true, null, options.environment, lexer, scriptData);
61
51
  parser.removeErrorListeners();
62
- visitor.onImportFile = (visitor, textData) => {
52
+ visitor.onImportFile = async (visitor, filePath, textData) => {
63
53
  let hasError = false;
64
54
  let hasParseError = false;
65
55
  if (textData !== null) {
@@ -72,6 +62,7 @@ function getSemanticTokens(scriptData, options) {
72
62
  console.log('Error while parsing: ', err);
73
63
  hasParseError = true;
74
64
  hasError = true;
65
+ throw new utils_js_1.ParseError(`Error parsing semantic tokens in imported file: ${err}`);
75
66
  }
76
67
  }
77
68
  else {
@@ -82,7 +73,7 @@ function getSemanticTokens(scriptData, options) {
82
73
  hasError, hasParseError
83
74
  };
84
75
  };
85
- visitor.visit(tree);
76
+ await visitor.visitAsync(tree);
86
77
  const semanticTokens = visitor.getTokens();
87
78
  const parsedTokens = (0, SemanticTokenVisitor_js_1.prepareTokens)(tokens.getTokens(), lexer, scriptData);
88
79
  const finalParsedTokens = [];
@@ -120,27 +111,30 @@ class ParseErrorStrategy extends antlr4ng_1.DefaultErrorStrategy {
120
111
  }
121
112
  }
122
113
  exports.ParseErrorStrategy = ParseErrorStrategy;
123
- function validateScript(scriptData, options) {
114
+ async function validateScript(filePath, scriptData, options) {
124
115
  const { parser } = prepareFile(scriptData);
125
116
  parser.removeErrorListeners();
126
117
  parser.errorHandler = new ParseErrorStrategy();
127
118
  parser.addErrorListener(new TokenErrorListener());
128
119
  const tree = parser.script();
129
- const { currentDirectory = null, defaultLibsPath, } = options;
130
- const visitor = new SymbolValidatorVisitor_js_1.SymbolValidatorVisitor(true, null, currentDirectory, defaultLibsPath);
131
- visitor.onImportFile = (visitor, textData) => {
120
+ const visitor = new SymbolValidatorVisitor_js_1.SymbolValidatorVisitor(true, null, options.environment);
121
+ visitor.enterFile(filePath);
122
+ visitor.onImportFile = async (visitor, filePath, textData) => {
123
+ visitor.enterFile(filePath);
132
124
  let hasError = false;
133
125
  let hasParseError = false;
134
126
  if (textData !== null) {
135
127
  const { parser } = prepareFile(textData);
136
128
  const tree = parser.script();
137
129
  try {
138
- visitor.visit(tree);
130
+ await visitor.visitAsync(tree);
131
+ visitor.exitFile();
139
132
  }
140
133
  catch (err) {
141
134
  console.log('got an error while parsing tree: ', err);
142
135
  hasParseError = true;
143
136
  hasError = true;
137
+ throw new utils_js_1.ParseError(`Error parsing validation in imported file: ${err}`);
144
138
  }
145
139
  }
146
140
  else {
@@ -151,120 +145,177 @@ function validateScript(scriptData, options) {
151
145
  hasError, hasParseError
152
146
  };
153
147
  };
154
- visitor.visit(tree);
148
+ await visitor.visitAsync(tree);
155
149
  const symbolTable = visitor.getSymbols();
156
150
  symbolTable.clearUndefined();
157
- const visitorResolver = new SymbolValidatorVisitor_js_1.SymbolValidatorResolveVisitor(true, null, currentDirectory, defaultLibsPath);
151
+ const visitorResolver = new SymbolValidatorResolveVisitor_js_1.SymbolValidatorResolveVisitor(true, null, options.environment);
152
+ visitorResolver.enterFile(filePath);
158
153
  visitorResolver.setSymbols(visitor.getSymbols());
159
154
  visitorResolver.onImportFile = visitor.onImportFile;
160
- visitorResolver.visit(tree);
155
+ await visitorResolver.visitAsync(tree);
161
156
  return visitorResolver;
162
157
  }
163
158
  exports.validateScript = validateScript;
164
- function renderScript(scriptData, outputPath, options) {
165
- const { currentDirectory = null, defaultLibsPath, dumpNets = false, dumpData = false, showStats = false } = options;
166
- const onErrorHandler = (line, column, message, error) => {
167
- if (error instanceof visitor_js_1.VisitorExecutionException) {
168
- console.log('Error', line, column, message, error.errorMessage);
159
+ async function renderScript(scriptData, outputPath, options) {
160
+ const { dumpNets = false, dumpData = false, showStats = false, environment } = options;
161
+ const errors = [];
162
+ const onErrorHandler = (message, context, error) => {
163
+ if (error && error instanceof utils_js_1.RuntimeExecutionError) {
164
+ errors.push(error);
165
+ }
166
+ else if (error && error instanceof antlr4ng_1.RecognitionException) {
167
+ if (context !== null) {
168
+ errors.push(new utils_js_1.ParseSyntaxError(message, context.start, context.stop));
169
+ }
170
+ else {
171
+ if (error.recognizer) {
172
+ const recognizer = error.recognizer;
173
+ errors.push(new utils_js_1.ParseSyntaxError(message, {
174
+ line: recognizer.currentTokenStartLine,
175
+ column: recognizer.currentTokenColumn
176
+ }));
177
+ }
178
+ else {
179
+ errors.push(new utils_js_1.ParseSyntaxError(message));
180
+ }
181
+ }
182
+ }
183
+ else {
184
+ errors.push(new utils_js_1.ParseError(message, context.start, context.stop));
169
185
  }
170
186
  };
171
- const visitor = new visitor_js_1.ParserVisitor(true, onErrorHandler, currentDirectory, defaultLibsPath);
172
- visitor.onImportFile = (visitor, fileData) => {
173
- const { hasError, hasParseError } = (0, parser_js_1.parseFileWithVisitor)(visitor, fileData);
187
+ const visitor = new visitor_js_1.ParserVisitor(true, onErrorHandler, options.environment);
188
+ visitor.onImportFile = async (visitor, filePath, fileData) => {
189
+ const { hasError, hasParseError } = await (0, parser_js_1.parseFileWithVisitor)(visitor, fileData);
190
+ if (hasError || hasParseError) {
191
+ throw new utils_js_1.ParseError(`Error parsing imported file: ${filePath}`, undefined, undefined, filePath);
192
+ }
174
193
  return { hasError, hasParseError };
175
194
  };
176
195
  visitor.log('reading file');
177
196
  visitor.log('done reading file');
178
- const { tree, parser, hasParseError, hasError, parserTimeTaken, lexerTimeTaken } = (0, parser_js_1.parseFileWithVisitor)(visitor, scriptData);
197
+ const { tree, parser, parserTimeTaken, lexerTimeTaken } = await (0, parser_js_1.parseFileWithVisitor)(visitor, scriptData);
179
198
  showStats && console.log('Lexing took:', lexerTimeTaken);
180
199
  showStats && console.log('Parsing took:', parserTimeTaken);
181
200
  if (dumpNets) {
182
201
  const nets = visitor.dumpNets();
183
202
  nets.forEach(item => console.log(item.join(" | ")));
184
203
  }
185
- const dumpDirectory = currentDirectory + '/dump/';
204
+ const dumpDirectory = environment.getRelativeToModule('/dump/');
186
205
  if (dumpData) {
206
+ console.log('Dump data to:', dumpDirectory);
187
207
  if (!(0, fs_1.existsSync)(dumpDirectory)) {
188
208
  (0, fs_1.mkdirSync)(dumpDirectory);
189
209
  }
190
210
  }
191
211
  dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'tree.lisp', tree.toStringTree(null, parser));
192
212
  dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'raw-parser.txt', visitor.logger.dump());
193
- if (hasError || hasParseError) {
194
- console.log('Error while parsing');
195
- return null;
196
- }
197
- const { frameComponent } = visitor.applySheetFrameComponent();
198
- try {
199
- visitor.annotateComponents();
200
- }
201
- catch (err) {
202
- console.log('Error during annotation: ', err);
203
- }
204
- const { sequence, nets } = visitor.getGraph();
205
- const tmpSequence = (0, utils_js_1.generateDebugSequenceAction)(sequence).map(item => (0, utils_js_1.sequenceActionString)(item));
206
- dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'raw-sequence.txt', tmpSequence.join('\n'));
207
213
  let svgOutput = "";
208
- try {
209
- let fileExtension = null;
210
- let outputDefaultZoom = globals_js_1.defaultZoomScale;
211
- if (outputPath) {
212
- fileExtension = path_1.default.extname(outputPath).substring(1);
213
- if (fileExtension === "pdf") {
214
- outputDefaultZoom = 1;
215
- }
214
+ if (errors.length === 0) {
215
+ const { frameComponent } = visitor.applySheetFrameComponent();
216
+ try {
217
+ visitor.annotateComponents();
216
218
  }
217
- if (fileExtension === 'net') {
218
- const { tree: kicadNetList, missingFootprints } = (0, export_js_1.generateKiCADNetList)(visitor.getNetList());
219
- missingFootprints.forEach(entry => {
220
- console.log(`${entry.refdes} (${entry.instanceName}) does not have footprint`);
221
- });
222
- (0, fs_1.writeFileSync)(outputPath, (0, export_js_1.printTree)(kicadNetList));
223
- console.log('Generated file', outputPath);
224
- return null;
219
+ catch (err) {
220
+ throw new utils_js_1.RenderError(`Error during component annotation: ${err}`, 'annotation');
225
221
  }
226
- const layoutEngine = new layout_js_1.LayoutEngine();
227
- const layoutTimer = new utils_js_1.SimpleStopwatch();
228
- const sheetFrames = layoutEngine.runLayout(sequence, nets);
229
- layoutEngine.printWarnings();
230
- showStats && console.log('Layout took:', layoutTimer.lap());
231
- dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'raw-layout.txt', layoutEngine.logger.dump());
232
- const generateSvgTimer = new utils_js_1.SimpleStopwatch();
233
- const renderLogger = new logger_js_1.Logger();
234
- const svgCanvas = (0, render_js_1.renderSheetsToSVG)(sheetFrames, renderLogger);
235
- showStats && console.log('Render took:', generateSvgTimer.lap());
236
- dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'raw-render.txt', renderLogger.dump());
237
- svgOutput = (0, render_js_1.generateSvgOutput)(svgCanvas, outputDefaultZoom);
238
- if (outputPath) {
239
- if (fileExtension === 'svg') {
240
- (0, fs_1.writeFileSync)(outputPath, svgOutput);
241
- }
242
- else if (fileExtension === 'pdf') {
243
- let sheetSize = "A4";
244
- let sheetSizeDefined = false;
245
- if (frameComponent) {
246
- sheetSize = frameComponent.getParam(Frame_js_1.FrameParamKeys.PaperSize);
247
- sheetSizeDefined = true;
222
+ const { sequence, nets } = visitor.getGraph();
223
+ const tmpSequence = (0, utils_js_1.generateDebugSequenceAction)(sequence).map(item => (0, utils_js_1.sequenceActionString)(item));
224
+ dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'raw-sequence.txt', tmpSequence.join('\n'));
225
+ try {
226
+ let fileExtension = null;
227
+ let outputDefaultZoom = globals_js_1.defaultZoomScale;
228
+ if (outputPath) {
229
+ fileExtension = path_1.default.extname(outputPath).substring(1);
230
+ if (fileExtension === "pdf") {
231
+ outputDefaultZoom = 1;
248
232
  }
249
- const doc = new pdfkit_1.default({
250
- layout: 'landscape',
251
- size: sheetSize
233
+ }
234
+ if (fileExtension === 'net') {
235
+ const { tree: kicadNetList, missingFootprints } = (0, export_js_1.generateKiCADNetList)(visitor.getNetList());
236
+ missingFootprints.forEach(entry => {
237
+ console.log(`${entry.refdes} (${entry.instanceName}) does not have footprint`);
252
238
  });
253
- const outputStream = (0, fs_1.createWriteStream)(outputPath);
254
- (0, render_js_1.generatePdfOutput)(doc, svgCanvas, sheetSize, sheetSizeDefined, outputDefaultZoom);
255
- doc.pipe(outputStream);
256
- doc.end();
239
+ (0, fs_1.writeFileSync)(outputPath, (0, export_js_1.printTree)(kicadNetList));
240
+ console.log('Generated file', outputPath);
241
+ return {
242
+ svgOutput: null,
243
+ errors,
244
+ };
257
245
  }
258
- else {
259
- throw "Invalid output format";
246
+ const layoutEngine = new layout_js_1.LayoutEngine();
247
+ const layoutTimer = new utils_js_1.SimpleStopwatch();
248
+ let sheetFrames;
249
+ try {
250
+ sheetFrames = layoutEngine.runLayout(sequence, nets);
251
+ }
252
+ catch (err) {
253
+ throw new utils_js_1.RenderError(`Error during layout generation: ${err}`, 'layout');
254
+ }
255
+ layoutEngine.printWarnings();
256
+ showStats && console.log('Layout took:', layoutTimer.lap());
257
+ dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'raw-layout.txt', layoutEngine.logger.dump());
258
+ const generateSvgTimer = new utils_js_1.SimpleStopwatch();
259
+ const renderLogger = new logger_js_1.Logger();
260
+ let svgCanvas;
261
+ try {
262
+ svgCanvas = (0, render_js_1.renderSheetsToSVG)(sheetFrames, renderLogger);
263
+ }
264
+ catch (err) {
265
+ throw new utils_js_1.RenderError(`Error during SVG generation: ${err}`, 'svg_generation');
266
+ }
267
+ showStats && console.log('Render took:', generateSvgTimer.lap());
268
+ dumpData && (0, fs_1.writeFileSync)(dumpDirectory + 'raw-render.txt', renderLogger.dump());
269
+ try {
270
+ svgOutput = (0, render_js_1.generateSvgOutput)(svgCanvas, outputDefaultZoom);
271
+ }
272
+ catch (err) {
273
+ throw new utils_js_1.RenderError(`Error generating SVG output: ${err}`, 'svg_output');
274
+ }
275
+ if (outputPath) {
276
+ if (fileExtension === 'svg') {
277
+ try {
278
+ (0, fs_1.writeFileSync)(outputPath, svgOutput);
279
+ }
280
+ catch (err) {
281
+ throw new utils_js_1.RenderError(`Error writing SVG file: ${err}`, 'file_output');
282
+ }
283
+ }
284
+ else if (fileExtension === 'pdf') {
285
+ let sheetSize = "A4";
286
+ let sheetSizeDefined = false;
287
+ if (frameComponent) {
288
+ sheetSize = frameComponent.getParam(Frame_js_1.FrameParamKeys.PaperSize);
289
+ sheetSizeDefined = true;
290
+ }
291
+ try {
292
+ const doc = new pdfkit_1.default({
293
+ layout: 'landscape',
294
+ size: sheetSize
295
+ });
296
+ const outputStream = (0, fs_1.createWriteStream)(outputPath);
297
+ (0, render_js_1.generatePdfOutput)(doc, svgCanvas, sheetSize, sheetSizeDefined, outputDefaultZoom);
298
+ doc.pipe(outputStream);
299
+ doc.end();
300
+ }
301
+ catch (err) {
302
+ throw new utils_js_1.RenderError(`Error generating PDF file: ${err}`, 'pdf_output');
303
+ }
304
+ }
305
+ else {
306
+ throw new utils_js_1.RenderError(`Invalid output format: ${fileExtension}`, 'file_output');
307
+ }
308
+ console.log('Generated file', outputPath);
260
309
  }
261
- console.log('Generated file', outputPath);
310
+ }
311
+ catch (err) {
312
+ throw new utils_js_1.RenderError(`Error during rendering: ${err}`, 'output_generation');
262
313
  }
263
314
  }
264
- catch (err) {
265
- console.log('Error during render: ', err);
266
- }
267
- return svgOutput;
315
+ return {
316
+ svgOutput,
317
+ errors
318
+ };
268
319
  }
269
320
  exports.renderScript = renderScript;
270
321
  function detectJSModuleType() {
@@ -277,32 +328,6 @@ function detectJSModuleType() {
277
328
  }
278
329
  }
279
330
  exports.detectJSModuleType = detectJSModuleType;
280
- const context = (0, this_file_1.createContext)();
281
- function getCurrentPath() {
282
- const filename = context.filename;
283
- return { filePath: filename };
284
- }
285
- exports.getCurrentPath = getCurrentPath;
286
- function getToolsPath() {
287
- const { filePath } = getCurrentPath();
288
- return path_1.default.normalize(path_1.default.dirname(filePath) + '/../../');
289
- }
290
- function getFontsPath() {
291
- const toolsPath = getToolsPath();
292
- return path_1.default.normalize(toolsPath + "fonts");
293
- }
294
- exports.getFontsPath = getFontsPath;
295
- function getDefaultLibsPath() {
296
- const toolsPath = getToolsPath();
297
- return path_1.default.normalize(toolsPath + "libs");
298
- }
299
- exports.getDefaultLibsPath = getDefaultLibsPath;
300
- function getPackageVersion() {
301
- const packageJson = JSON.parse((0, fs_1.readFileSync)(getToolsPath() + 'package.json').toString());
302
- const { version } = packageJson;
303
- return version;
304
- }
305
- exports.getPackageVersion = getPackageVersion;
306
331
  class UnitDimension {
307
332
  constructor(value, type = globals_js_1.LengthUnit.mils) {
308
333
  this.value = value;
package/dist/cjs/index.js CHANGED
@@ -29,3 +29,8 @@ __exportStar(require("./utils.js"), exports);
29
29
  __exportStar(require("./visitor.js"), exports);
30
30
  __exportStar(require("./sizing.js"), exports);
31
31
  __exportStar(require("./objects/types.js"), exports);
32
+ __exportStar(require("./builtinMethods.js"), exports);
33
+ __exportStar(require("./validate/SymbolTable.js"), exports);
34
+ __exportStar(require("./validate/SymbolValidatorResolveVisitor.js"), exports);
35
+ __exportStar(require("./validate/SymbolValidatorVisitor.js"), exports);
36
+ __exportStar(require("./environment.js"), exports);
@@ -1,7 +1,31 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  Object.defineProperty(exports, "__esModule", { value: true });
3
26
  exports.ExtractDrawingRects = exports.CalculatePinPositions = exports.RenderJunction = exports.RenderFrameType = exports.RenderFrame = exports.RenderText = exports.RenderComponent = exports.RenderWire = exports.RenderObject = exports.getBounds = exports.applyComponentParamsToSymbol = exports.LayoutEngine = void 0;
4
- const graphlib_1 = require("@dagrejs/graphlib");
27
+ const graphlib_1 = __importStar(require("@dagrejs/graphlib"));
28
+ const { alg } = graphlib_1.default;
5
29
  const draw_symbols_js_1 = require("./draw_symbols.js");
6
30
  const ExecutionScope_js_1 = require("./objects/ExecutionScope.js");
7
31
  const globals_js_1 = require("./globals.js");
@@ -31,7 +55,7 @@ class LayoutEngine {
31
55
  return "[" + value + "]" + padding;
32
56
  }
33
57
  runLayout(sequence, nets) {
34
- const logNodesAndEdges = false;
58
+ const logNodesAndEdges = true;
35
59
  this.print('===== creating graph and populating with nodes =====');
36
60
  const { graph, containerFrames } = this.generateLayoutGraph(sequence, nets);
37
61
  this.print('===== done populating graph =====');
@@ -48,7 +72,7 @@ class LayoutEngine {
48
72
  this.print('===== graph nodes =====');
49
73
  const nodes = graph.nodes();
50
74
  nodes.forEach(node => {
51
- this.print(node, graph.node(node));
75
+ this.print(`name:${node}, value:${graph.node(node)}`);
52
76
  });
53
77
  this.print('===== end nodes =====');
54
78
  this.print('');
@@ -111,6 +135,7 @@ class LayoutEngine {
111
135
  findJunctions(wireGroups) {
112
136
  const junctions = [];
113
137
  const mergedWires = [];
138
+ const debugSegments = false;
114
139
  for (const [key, wires] of wireGroups) {
115
140
  const allLines = wires.map(wire => {
116
141
  return wire.points.map(pt => {
@@ -120,15 +145,35 @@ class LayoutEngine {
120
145
  };
121
146
  });
122
147
  });
123
- const { intersectPoints, segments } = geometry_js_1.Geometry.mergeWires(allLines);
124
- mergedWires.push({
125
- netName: key,
126
- segments,
127
- intersectPoints,
128
- });
129
- intersectPoints.forEach(([x, y]) => {
130
- junctions.push(new RenderJunction((0, ParamDefinition_js_1.numeric)(x), (0, ParamDefinition_js_1.numeric)(y)));
131
- });
148
+ if (debugSegments) {
149
+ const tmpSegments = [];
150
+ allLines.forEach(wire => {
151
+ for (let i = 1; i < wire.length; i++) {
152
+ const pt1 = wire[i - 1];
153
+ const pt2 = wire[i];
154
+ tmpSegments.push([
155
+ [pt1.x.toNumber(), pt1.y.toNumber()],
156
+ [pt2.x.toNumber(), pt2.y.toNumber()],
157
+ ]);
158
+ }
159
+ });
160
+ mergedWires.push({
161
+ netName: key,
162
+ segments: tmpSegments,
163
+ intersectPoints: [],
164
+ });
165
+ }
166
+ else {
167
+ const { intersectPoints, segments } = geometry_js_1.Geometry.mergeWires(allLines);
168
+ mergedWires.push({
169
+ netName: key,
170
+ segments,
171
+ intersectPoints,
172
+ });
173
+ intersectPoints.forEach(([x, y]) => {
174
+ junctions.push(new RenderJunction((0, ParamDefinition_js_1.numeric)(x), (0, ParamDefinition_js_1.numeric)(y)));
175
+ });
176
+ }
132
177
  }
133
178
  return {
134
179
  junctions,
@@ -586,7 +631,7 @@ class LayoutEngine {
586
631
  let previousNode = null;
587
632
  let previousPin = null;
588
633
  const graph = new graphlib_1.Graph({
589
- directed: false,
634
+ directed: true,
590
635
  compound: true,
591
636
  });
592
637
  this.print('sequence length:', sequence.length);
@@ -604,7 +649,7 @@ class LayoutEngine {
604
649
  const tmpInstanceName = component.instanceName;
605
650
  if (!graph.hasNode(tmpInstanceName)) {
606
651
  this.print('create instance', tmpInstanceName);
607
- const { displayProp = null, widthProp = null, heightProp = null } = component;
652
+ const { displayProp = null } = component;
608
653
  let tmpSymbol;
609
654
  if (displayProp instanceof draw_symbols_js_1.SymbolDrawing) {
610
655
  tmpSymbol = new draw_symbols_js_1.SymbolPlaceholder(displayProp);
@@ -620,26 +665,6 @@ class LayoutEngine {
620
665
  }
621
666
  }
622
667
  applyComponentParamsToSymbol(component, tmpSymbol);
623
- if (component.parameters.has(globals_js_1.ParamKeys.angle)) {
624
- const value = component.parameters.get(globals_js_1.ParamKeys.angle).toNumber();
625
- tmpSymbol.angle = value;
626
- }
627
- if (component.parameters.has(globals_js_1.ParamKeys.flipX)) {
628
- tmpSymbol.flipX =
629
- component.parameters.get(globals_js_1.ParamKeys.flipX);
630
- }
631
- if (component.parameters.has(globals_js_1.ParamKeys.flipY)) {
632
- tmpSymbol.flipY =
633
- component.parameters.get(globals_js_1.ParamKeys.flipY);
634
- }
635
- if (tmpSymbol instanceof draw_symbols_js_1.SymbolCustom) {
636
- if (widthProp) {
637
- tmpSymbol.bodyWidth = (0, helpers_js_1.milsToMM)(widthProp);
638
- }
639
- if (heightProp) {
640
- tmpSymbol.bodyHeight = (0, helpers_js_1.milsToMM)(heightProp);
641
- }
642
- }
643
668
  tmpSymbol.refreshDrawing();
644
669
  const { width: useWidth, height: useHeight } = tmpSymbol.size();
645
670
  tmpComponent = new RenderComponent(component, useWidth, useHeight);
@@ -745,10 +770,14 @@ class LayoutEngine {
745
770
  };
746
771
  }
747
772
  setGraphEdge(graph, node1, node2, edgeValue) {
773
+ if (!graph.isDirected && graph.hasEdge(node1, node2)) {
774
+ this.print(`Warning: edge already exists ${node1} ${node2}`);
775
+ }
748
776
  graph.setEdge(node1, node2, edgeValue);
777
+ this.print(`created edge: node1:${node1} node2:${node2} edgeValue:${edgeValue}`);
749
778
  }
750
779
  sizeSubGraphs(graph) {
751
- const subGraphs = graphlib_1.alg.components(graph);
780
+ const subGraphs = alg.components(graph);
752
781
  const subGraphsStarts = [];
753
782
  this.print('===== placing subgraphs =====');
754
783
  this.print('number of subgraphs: ', subGraphs.length);
@@ -802,7 +831,6 @@ class LayoutEngine {
802
831
  this.placeSubgraphV2(graph, firstNodeId, subgraphEdges);
803
832
  }
804
833
  placeSubgraphV2(graph, firstNodeId, subgraphEdges) {
805
- let firstNodePlaced = false;
806
834
  const originNodes = [];
807
835
  const originNodeGroups = new Map();
808
836
  function findOriginNode(node) {
@@ -828,14 +856,6 @@ class LayoutEngine {
828
856
  const [nodeId1, pin1, nodeId2, pin2] = graph.edge(edge);
829
857
  const [, node1] = graph.node(nodeId1);
830
858
  const [, node2] = graph.node(nodeId2);
831
- if (nodeId1 === firstNodeId && !firstNodePlaced) {
832
- this.print('first node placed at origin');
833
- this.placeNodeAtPosition((0, ParamDefinition_js_1.numeric)(0), (0, ParamDefinition_js_1.numeric)(0), node1, pin1);
834
- firstNodePlaced = true;
835
- node1.isFloating = false;
836
- originNodes.push(node1);
837
- originNodeGroups.set(node1.toString(), [node1]);
838
- }
839
859
  this.print('edge:', '[', node1, pin1, node1.isFloating, ']', '[', node2, pin2, node2.isFloating, ']');
840
860
  if (!node1.isFloating && node2.isFloating) {
841
861
  fixedNode = node1;
@@ -913,6 +933,7 @@ class LayoutEngine {
913
933
  this.print(`set wire auto end at: ${untilX} ${untilY}`);
914
934
  }
915
935
  });
936
+ this.print('----');
916
937
  });
917
938
  }
918
939
  mergeOriginNodes(node1, pin1, node2, pin2, originNode1, originNode2, originNodes, originNodeGroups) {
@@ -1113,11 +1134,32 @@ function generateLayoutPinDefinition(component) {
1113
1134
  return symbolPinDefinitions;
1114
1135
  }
1115
1136
  function applyComponentParamsToSymbol(component, symbol) {
1137
+ const { widthProp = null, heightProp = null } = component;
1116
1138
  const newMap = new Map(component.parameters);
1117
1139
  if (!newMap.has('refdes')) {
1118
1140
  newMap.set('refdes', component.assignedRefDes ?? "?");
1119
1141
  }
1120
1142
  symbol.drawing.variables = newMap;
1143
+ if (component.parameters.has(globals_js_1.ParamKeys.angle)) {
1144
+ const value = component.parameters.get(globals_js_1.ParamKeys.angle).toNumber();
1145
+ symbol.angle = value;
1146
+ }
1147
+ if (component.parameters.has(globals_js_1.ParamKeys.flipX)) {
1148
+ symbol.flipX =
1149
+ component.parameters.get(globals_js_1.ParamKeys.flipX);
1150
+ }
1151
+ if (component.parameters.has(globals_js_1.ParamKeys.flipY)) {
1152
+ symbol.flipY =
1153
+ component.parameters.get(globals_js_1.ParamKeys.flipY);
1154
+ }
1155
+ if (symbol instanceof draw_symbols_js_1.SymbolCustom) {
1156
+ if (widthProp) {
1157
+ symbol.bodyWidth = (0, helpers_js_1.milsToMM)(widthProp);
1158
+ }
1159
+ if (heightProp) {
1160
+ symbol.bodyHeight = (0, helpers_js_1.milsToMM)(heightProp);
1161
+ }
1162
+ }
1121
1163
  }
1122
1164
  exports.applyComponentParamsToSymbol = applyComponentParamsToSymbol;
1123
1165
  function calculateSymbolAngle(symbol, pin, direction) {