@intelligentgraphics/ig.gfx.packager 3.0.20 → 3.0.22

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 (28) hide show
  1. package/build/bin.mjs +1 -1
  2. package/build/{cli-c7da3faf.mjs → cli-f6586dd5.mjs} +91 -93
  3. package/build/cli-f6586dd5.mjs.map +1 -0
  4. package/build/{dependencies-93832b40.mjs → dependencies-e2aa1797.mjs} +2 -2
  5. package/build/{dependencies-93832b40.mjs.map → dependencies-e2aa1797.mjs.map} +1 -1
  6. package/build/{generateIndex-056000f0.mjs → generateIndex-019c6946.mjs} +3 -3
  7. package/build/{generateIndex-056000f0.mjs.map → generateIndex-019c6946.mjs.map} +1 -1
  8. package/build/{generateParameterType-8584bc43.mjs → generateParameterType-ae69726a.mjs} +4 -4
  9. package/build/{generateParameterType-8584bc43.mjs.map → generateParameterType-ae69726a.mjs.map} +1 -1
  10. package/build/{index-41cb0257.mjs → index-39c79102.mjs} +18 -19
  11. package/build/index-39c79102.mjs.map +1 -0
  12. package/build/index-3d1291e7.mjs +1120 -0
  13. package/build/index-3d1291e7.mjs.map +1 -0
  14. package/build/{postinstall-eb863946.mjs → postinstall-3328545c.mjs} +3 -3
  15. package/build/{postinstall-eb863946.mjs.map → postinstall-3328545c.mjs.map} +1 -1
  16. package/build/{publishNpm-0af8ba37.mjs → publishNpm-532e17a0.mjs} +12 -6
  17. package/build/publishNpm-532e17a0.mjs.map +1 -0
  18. package/build/scripts-7ed8dff6.mjs.map +1 -1
  19. package/build/{versionFile-4f3df7f1.mjs → versionFile-644c7ff8.mjs} +6 -10
  20. package/build/{versionFile-4f3df7f1.mjs.map → versionFile-644c7ff8.mjs.map} +1 -1
  21. package/lib/lib.mjs +581 -175
  22. package/package.json +7 -6
  23. package/readme.md +11 -0
  24. package/build/cli-c7da3faf.mjs.map +0 -1
  25. package/build/index-41cb0257.mjs.map +0 -1
  26. package/build/index-7d81fa31.mjs +0 -706
  27. package/build/index-7d81fa31.mjs.map +0 -1
  28. package/build/publishNpm-0af8ba37.mjs.map +0 -1
package/lib/lib.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import * as path from 'path';
2
+ import * as fs$1 from 'fs/promises';
3
+ import * as terser from 'terser';
2
4
  import * as fs from 'fs';
3
5
  import { createWriteStream, createReadStream } from 'fs';
4
- import * as terser from 'terser';
5
6
  import resolve from 'resolve';
6
7
  import 'write-pkg';
7
8
  import glob from 'glob';
@@ -9,8 +10,9 @@ import 'write-json-file';
9
10
  import axios from 'axios';
10
11
  import ts from 'typescript';
11
12
  import typedoc from 'typedoc';
13
+ import EventEmitter from 'events';
14
+ import { SourceMapGenerator, SourceMapConsumer } from 'source-map-js';
12
15
  import Ajv from 'ajv';
13
- import * as fs$1 from 'fs/promises';
14
16
  import { pipeline } from 'stream/promises';
15
17
  import { exec } from 'child_process';
16
18
  import { promisify } from 'util';
@@ -71,7 +73,7 @@ const readPackageCreatorManifest = (location)=>{
71
73
  };
72
74
  const writePackageCreatorManifest = (location, creatorPackage)=>{
73
75
  const packageJsonPath = path.join(location.manifestDir, PACKAGE_FILE);
74
- fs.writeFileSync(packageJsonPath, JSON.stringify(creatorPackage, null, "\t") + "\n");
76
+ fs.writeFileSync(packageJsonPath, JSON.stringify(creatorPackage, null, " ") + "\n");
75
77
  };
76
78
  const getPackageCreatorIndexPath = (location)=>path.join(location.manifestDir, INDEX_FILE);
77
79
  const readPackageCreatorIndex = (location)=>{
@@ -90,7 +92,7 @@ const readPackageCreatorIndex = (location)=>{
90
92
  };
91
93
  const writePackageCreatorIndex = (location, index)=>{
92
94
  const indexPath = getPackageCreatorIndexPath(location);
93
- fs.writeFileSync(indexPath, JSON.stringify(index, null, "\t") + "\n");
95
+ fs.writeFileSync(indexPath, JSON.stringify(index, null, " ") + "\n");
94
96
  };
95
97
  const readPackageNpmManifest = (location)=>{
96
98
  try {
@@ -263,10 +265,10 @@ const readStringFromFileOrUndefined = (filePath)=>{
263
265
  }
264
266
  };
265
267
 
266
- const logPackageMessage = (name, step, index, total)=>{
268
+ const logPackageMessage = (name, step, index, total, maxNameLength = 15)=>{
267
269
  const numLength = total === undefined ? undefined : total.toString().length;
268
270
  const indexString = total === undefined || total < 2 ? "" : `${index.toString().padStart(numLength, "0")}/${total} `;
269
- const identifierString = `${indexString}${name.padEnd(15)}`;
271
+ const identifierString = `${indexString}${name.padEnd(maxNameLength)}`;
270
272
  console.log(`${identifierString} >> ${step}`);
271
273
  };
272
274
 
@@ -282,7 +284,7 @@ const PLUGIN_ID = "0feba3a0-b6d1-11e6-9598-0800200c9a66";
282
284
  *
283
285
  * @param {SessionStartParams} params
284
286
  * @returns
285
- */ const startSession = async ({ url , authentication , ...params })=>{
287
+ */ const startSession = async ({ url, authentication, ...params })=>{
286
288
  const payload = {
287
289
  ...params,
288
290
  user: undefined,
@@ -296,7 +298,7 @@ const PLUGIN_ID = "0feba3a0-b6d1-11e6-9598-0800200c9a66";
296
298
  } else if (authentication.type === "license") {
297
299
  payload.license = authentication.license;
298
300
  }
299
- const { data: { session: sessionId , state , response } } = await axios.post(`Session/Start2`, JSON.stringify(payload), {
301
+ const { data: { session: sessionId, state, response } } = await axios.post(`Session/Start2`, JSON.stringify(payload), {
300
302
  baseURL: url
301
303
  });
302
304
  if (state !== "SUCCESS") {
@@ -319,11 +321,11 @@ const closeSession = async (session)=>{
319
321
  baseURL: session.url
320
322
  });
321
323
  };
322
- const uploadPackageFromStream = async (session, { name , version }, stream)=>{
324
+ const uploadPackageFromStream = async (session, { name, version }, stream)=>{
323
325
  await uploadPackageToUrl(session.url, `UploadPackage/${session.sessionId}/${name}_${version}/`, stream);
324
326
  };
325
327
  const uploadPackageToUrl = async (url, path, stream)=>{
326
- const { data , status } = await axios.post(path, stream, {
328
+ const { data, status } = await axios.post(path, stream, {
327
329
  baseURL: url
328
330
  });
329
331
  let objectBody;
@@ -358,7 +360,7 @@ const uploadPackageToUrl = async (url, path, stream)=>{
358
360
  return data;
359
361
  };
360
362
  const getExistingPackages = async (session)=>{
361
- const { data } = await axios.get(`Script/GetInformation/${session.sessionId}`, {
363
+ const { data } = await axios.get(`Script/GetInformation/${session.sessionId}`, {
362
364
  baseURL: session.url,
363
365
  validateStatus: (status)=>status === 404 || status === 200
364
366
  }).catch((err)=>{
@@ -368,7 +370,7 @@ const getExistingPackages = async (session)=>{
368
370
  };
369
371
 
370
372
  const tryReadTsConfig = (location)=>{
371
- const { config } = ts.readConfigFile(path.join(location.scriptsDir, "tsconfig.json"), (path)=>{
373
+ const { config } = ts.readConfigFile(path.join(location.scriptsDir, "tsconfig.json"), (path)=>{
372
374
  try {
373
375
  return fs.readFileSync(path, "utf8");
374
376
  } catch {
@@ -377,7 +379,187 @@ const tryReadTsConfig = (location)=>{
377
379
  });
378
380
  return config;
379
381
  };
380
- const build = async (location, outputDir)=>{
382
+ const createTSCBuildParticipant = (location, outputDir)=>(env)=>{
383
+ const files = getPackageTypescriptFiles(location);
384
+ if (files.length === 0) {
385
+ env.onBuildStart();
386
+ env.onBuildEnd({
387
+ type: "success",
388
+ artefacts: {
389
+ js: "",
390
+ definitions: ""
391
+ }
392
+ });
393
+ return {
394
+ destroy: ()=>{}
395
+ };
396
+ }
397
+ try {
398
+ env.onBuildStart();
399
+ env.log("Compiling typescript files");
400
+ const compilerOptions = getCompilerOptions(location, outputDir);
401
+ const host = ts.createCompilerHost(compilerOptions);
402
+ host.getCurrentDirectory = ()=>location.scriptsDir;
403
+ let js;
404
+ let definitions;
405
+ let sourceMap;
406
+ host.writeFile = (fileName, data, writeByteOrderMark)=>{
407
+ if (fileName.endsWith(".js")) {
408
+ js = data;
409
+ } else if (fileName.endsWith(".d.ts")) {
410
+ definitions = data;
411
+ } else if (fileName.endsWith(".js.map")) {
412
+ sourceMap = data;
413
+ }
414
+ };
415
+ const programOptions = {
416
+ rootNames: files,
417
+ options: compilerOptions,
418
+ host
419
+ };
420
+ const program = ts.createProgram(programOptions);
421
+ const emitResult = program.emit();
422
+ const allDiagnostics = ts.getPreEmitDiagnostics(program);
423
+ if (!emitResult.emitSkipped) {
424
+ if (allDiagnostics.length > 0) {
425
+ console.log(allDiagnostics.map(createErrorMessage).join("\n"));
426
+ }
427
+ if (js === undefined || definitions === undefined) {
428
+ throw new Error(`Unexpected: no js or definitions were created`);
429
+ }
430
+ env.onBuildEnd({
431
+ type: "success",
432
+ artefacts: {
433
+ js: js.replace(`//# sourceMappingURL=out.js.map`, ""),
434
+ definitions,
435
+ sourceMap
436
+ }
437
+ });
438
+ } else {
439
+ const error = allDiagnostics.map(createErrorMessage).join("\n");
440
+ throw new Error(error);
441
+ }
442
+ } catch (err) {
443
+ env.onBuildEnd({
444
+ type: "error",
445
+ error: err.message
446
+ });
447
+ }
448
+ return {
449
+ destroy: ()=>{}
450
+ };
451
+ };
452
+ const createTSCWatchBuildParticipant = (location, outputDir)=>{
453
+ return ({ onBuildStart, onBuildEnd })=>{
454
+ let state = {
455
+ diagnostics: [],
456
+ js: undefined,
457
+ definitions: undefined,
458
+ sourceMap: undefined
459
+ };
460
+ const customSys = {
461
+ ...ts.sys,
462
+ writeFile: (fileName, data, writeByteOrderMark)=>{
463
+ if (fileName.endsWith(".js")) {
464
+ state.js = data;
465
+ } else if (fileName.endsWith(".d.ts")) {
466
+ state.definitions = data;
467
+ } else if (fileName.endsWith(".js.map")) {
468
+ state.sourceMap = data;
469
+ }
470
+ }
471
+ };
472
+ const reportDiagnostic = (diagnostic)=>{
473
+ switch(diagnostic.code){
474
+ // file not found - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L4640
475
+ // probably deleted -> ignore
476
+ case 6053:
477
+ return;
478
+ // no inputs were found - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L6838
479
+ // we don't care about this error. a user might have temporarily deleted the last ts file and will readd one later.
480
+ case 18003:
481
+ return;
482
+ }
483
+ state.diagnostics.push(diagnostic);
484
+ };
485
+ const reportWatchStatusChanged = (diagnostic)=>{
486
+ switch(diagnostic.code){
487
+ // regular watch mode - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L4567
488
+ case 6031:
489
+ // incremental watch mode - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L4571
490
+ case 6032:
491
+ // build start
492
+ onBuildStart();
493
+ break;
494
+ // found one error - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L5119
495
+ case 6193:
496
+ // found n or 0 errors - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L5123
497
+ case 6194:
498
+ // build end
499
+ const emitState = state;
500
+ state = {
501
+ diagnostics: [],
502
+ js: undefined,
503
+ definitions: undefined,
504
+ sourceMap: undefined
505
+ };
506
+ if (emitState.diagnostics.length > 0) {
507
+ const message = emitState.diagnostics.map(createErrorMessage).join("\n");
508
+ onBuildEnd({
509
+ type: "error",
510
+ error: message
511
+ });
512
+ return;
513
+ }
514
+ if (emitState.js === undefined || emitState.definitions === undefined) {
515
+ onBuildEnd({
516
+ type: "success",
517
+ artefacts: {
518
+ js: ""
519
+ }
520
+ });
521
+ return;
522
+ }
523
+ onBuildEnd({
524
+ type: "success",
525
+ artefacts: {
526
+ js: emitState.js.replace(`//# sourceMappingURL=out.js.map`, ""),
527
+ definitions: emitState.definitions,
528
+ sourceMap: emitState.sourceMap
529
+ }
530
+ });
531
+ break;
532
+ }
533
+ };
534
+ const host = ts.createWatchCompilerHost(path.join(location.scriptsDir, "tsconfig.json"), getCompilerOptions(location, outputDir), customSys, ts.createSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportWatchStatusChanged);
535
+ const watchProgram = ts.createWatchProgram(host);
536
+ const files = getPackageTypescriptFiles(location);
537
+ if (files.length === 0) {
538
+ onBuildStart();
539
+ onBuildEnd({
540
+ type: "success",
541
+ artefacts: {
542
+ js: "",
543
+ definitions: ""
544
+ }
545
+ });
546
+ }
547
+ return {
548
+ destroy: ()=>{
549
+ watchProgram.close();
550
+ }
551
+ };
552
+ };
553
+ };
554
+ const createErrorMessage = (diagnostic)=>{
555
+ if (!diagnostic.file) {
556
+ return `${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`;
557
+ }
558
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
559
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
560
+ return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
561
+ };
562
+ const getCompilerOptions = (location, outputDir)=>{
381
563
  const config = tryReadTsConfig(location);
382
564
  config.compilerOptions.lib = [
383
565
  "es5",
@@ -388,58 +570,15 @@ const build = async (location, outputDir)=>{
388
570
  ...result.options,
389
571
  removeComments: false,
390
572
  declaration: true,
391
- sourceMap: false,
573
+ sourceMap: true,
574
+ inlineSources: false,
392
575
  // We don't use tsc to actually emit the files, but we still need to set the correct
393
576
  // output directory so the compiler can rewrite the `reference path` directives.
394
577
  outFile: path.join(outputDir, "out.js"),
395
578
  target: ts.ScriptTarget.ES5,
396
579
  noEmitOnError: true
397
580
  };
398
- const host = ts.createCompilerHost(compilerOptions);
399
- host.getCurrentDirectory = ()=>location.scriptsDir;
400
- let js;
401
- let definitions;
402
- host.writeFile = (fileName, data, writeByteOrderMark)=>{
403
- if (fileName.endsWith(".js")) {
404
- js = data;
405
- } else if (fileName.endsWith(".d.ts")) {
406
- definitions = data;
407
- }
408
- };
409
- const files = getPackageTypescriptFiles(location);
410
- if (files.length === 0) {
411
- throw new Error(`Expected typescript files to exist when building a package. Packages only consisting of animation jsons do not need to be built.`);
412
- }
413
- const programOptions = {
414
- rootNames: files,
415
- options: compilerOptions,
416
- host
417
- };
418
- const program = ts.createProgram(programOptions);
419
- const emitResult = program.emit();
420
- const allDiagnostics = ts.getPreEmitDiagnostics(program);
421
- if (!emitResult.emitSkipped) {
422
- if (allDiagnostics.length > 0) {
423
- console.log(allDiagnostics.map(createErrorMessage).join("\n"));
424
- }
425
- if (js === undefined || definitions === undefined) {
426
- throw new Error(`Unexpected: no js or definitions were created`);
427
- }
428
- return {
429
- js,
430
- definitions
431
- };
432
- }
433
- const error = allDiagnostics.map(createErrorMessage).join("\n");
434
- throw new Error(error);
435
- };
436
- const createErrorMessage = (diagnostic)=>{
437
- if (!diagnostic.file) {
438
- return `${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`;
439
- }
440
- const { line , character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
441
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
442
- return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
581
+ return compilerOptions;
443
582
  };
444
583
 
445
584
  const generateDocs = async (location, declarationFile, outFolder, name)=>{
@@ -496,6 +635,120 @@ const toposort = (packages)=>{
496
635
  return result;
497
636
  };
498
637
 
638
+ class BuildManager extends EventEmitter {
639
+ constructor(manifest, writer, logStep){
640
+ super();
641
+ this.manifest = manifest;
642
+ this.writer = writer;
643
+ this.logStep = logStep;
644
+ this.participants = new Map();
645
+ this.states = new Map();
646
+ }
647
+ addParticipant(name, participant) {
648
+ this.participants.set(name, participant);
649
+ }
650
+ run() {
651
+ for (const [name] of this.participants){
652
+ this.states.set(name, {
653
+ type: "busy"
654
+ });
655
+ }
656
+ this.emit("start");
657
+ for (const [name, participant] of this.participants){
658
+ participant({
659
+ onBuildStart: ()=>{
660
+ let alreadyBusy = false;
661
+ for (const [name, state] of this.states){
662
+ if (state.type === "busy") {
663
+ alreadyBusy = true;
664
+ continue;
665
+ }
666
+ }
667
+ this.states.set(name, {
668
+ type: "busy"
669
+ });
670
+ if (!alreadyBusy) {
671
+ this.emit("start");
672
+ }
673
+ },
674
+ onBuildEnd: (result)=>{
675
+ this.states.set(name, result);
676
+ this.maybeEmit();
677
+ },
678
+ log: this.logStep
679
+ });
680
+ }
681
+ }
682
+ maybeEmit() {
683
+ const errors = [];
684
+ const results = [];
685
+ for (const [_, state] of this.states){
686
+ if (state.type === "busy") {
687
+ return;
688
+ }
689
+ if (state.type === "success") {
690
+ results.push(state);
691
+ } else if (state.type === "error") {
692
+ errors.push(state.error);
693
+ }
694
+ }
695
+ if (errors.length > 0) {
696
+ this.emit("error", errors.join("\n"));
697
+ return;
698
+ }
699
+ const completeResult = {
700
+ js: ""
701
+ };
702
+ const sourceMapGenerator = new SourceMapGenerator();
703
+ for (const result of results){
704
+ if (result.artefacts.js) {
705
+ if (completeResult.js) {
706
+ completeResult.js += "\n";
707
+ }
708
+ if (result.artefacts.sourceMap) {
709
+ const lines = completeResult.js.split("\n").length - 1;
710
+ const sourceMap = new SourceMapConsumer(JSON.parse(result.artefacts.sourceMap));
711
+ const sources = new Set();
712
+ sourceMap.eachMapping((mapping)=>{
713
+ sourceMapGenerator.addMapping({
714
+ generated: {
715
+ line: lines + mapping.generatedLine,
716
+ column: mapping.generatedColumn
717
+ },
718
+ original: {
719
+ line: mapping.originalLine,
720
+ column: mapping.originalColumn
721
+ },
722
+ source: mapping.source,
723
+ name: mapping.name
724
+ });
725
+ sources.add(mapping.source);
726
+ });
727
+ for (const source of sources){
728
+ const content = sourceMap.sourceContentFor(source);
729
+ if (content !== null) {
730
+ sourceMapGenerator.setSourceContent(source, content);
731
+ }
732
+ }
733
+ }
734
+ completeResult.js += result.artefacts.js;
735
+ }
736
+ if (result.artefacts.definitions) {
737
+ if (completeResult.definitions) {
738
+ completeResult.definitions += "\n";
739
+ } else {
740
+ completeResult.definitions = "";
741
+ }
742
+ completeResult.definitions += result.artefacts.definitions;
743
+ }
744
+ }
745
+ completeResult.sourceMap = sourceMapGenerator.toString();
746
+ this.writer(completeResult).then(()=>{
747
+ this.emit("build");
748
+ });
749
+ }
750
+ }
751
+
499
752
  var animationSchema = {
500
753
  $schema: "http://json-schema.org/draft-07/schema",
501
754
  $id: "https://archive.intelligentgraphics.biz/schemas/gfx/animation.json",
@@ -822,6 +1075,115 @@ var animationSchema = {
822
1075
  }
823
1076
  };
824
1077
 
1078
+ const createAnimationBuildParticipant = (location, manifest)=>{
1079
+ return (env)=>{
1080
+ env.onBuildStart();
1081
+ bundleAnimations(location, manifest, env.log).then((result)=>{
1082
+ env.onBuildEnd({
1083
+ type: "success",
1084
+ artefacts: {
1085
+ js: (result == null ? void 0 : result.js) ?? ""
1086
+ }
1087
+ });
1088
+ }).catch((err)=>{
1089
+ env.onBuildEnd({
1090
+ type: "error",
1091
+ error: err.message
1092
+ });
1093
+ });
1094
+ return {
1095
+ destroy: ()=>{}
1096
+ };
1097
+ };
1098
+ };
1099
+ const createAnimationWatchBuildParticipant = (location, manifest)=>(env)=>{
1100
+ env.onBuildStart();
1101
+ bundleAnimations(location, manifest, env.log).then((result)=>{
1102
+ env.onBuildEnd({
1103
+ type: "success",
1104
+ artefacts: {
1105
+ js: (result == null ? void 0 : result.js) ?? ""
1106
+ }
1107
+ });
1108
+ }).catch((err)=>{
1109
+ env.onBuildEnd({
1110
+ type: "error",
1111
+ error: err.message
1112
+ });
1113
+ });
1114
+ (async ()=>{
1115
+ for await (const event of fs$1.watch(location.scriptsDir)){
1116
+ if (event.filename.endsWith(".animation.json")) {
1117
+ env.onBuildStart();
1118
+ try {
1119
+ const result = await bundleAnimations(location, manifest, env.log);
1120
+ env.onBuildEnd({
1121
+ type: "success",
1122
+ artefacts: {
1123
+ js: (result == null ? void 0 : result.js) ?? ""
1124
+ }
1125
+ });
1126
+ } catch (err) {
1127
+ env.onBuildEnd({
1128
+ type: "error",
1129
+ error: err.message
1130
+ });
1131
+ }
1132
+ }
1133
+ }
1134
+ })();
1135
+ return {
1136
+ destroy: ()=>{}
1137
+ };
1138
+ };
1139
+ const bundleAnimations = async (location, manifest, logStep)=>{
1140
+ const animations = new Map();
1141
+ for (const scriptFilePath of readPackageAnimationList(location)){
1142
+ const content = await fs$1.readFile(scriptFilePath, {
1143
+ encoding: "utf8"
1144
+ });
1145
+ let data;
1146
+ try {
1147
+ data = JSON.parse(content);
1148
+ } catch (err) {
1149
+ const relativePath = path.relative(location.path, scriptFilePath);
1150
+ if (err instanceof SyntaxError) {
1151
+ throw new Error(`Encountered invalid syntax in file "${relativePath}": ${String(err)}`);
1152
+ }
1153
+ throw new Error(`Encountered an unexpected error while parsing animation json file at path "${relativePath}"`, {
1154
+ cause: err
1155
+ });
1156
+ }
1157
+ if (!data.Id) {
1158
+ const fileName = path.basename(scriptFilePath, ".animation.json");
1159
+ data.Id = fileName;
1160
+ }
1161
+ (await getAnimationJsonValidation())(data);
1162
+ delete data.$schema;
1163
+ animations.set(data.Id, JSON.stringify(data));
1164
+ }
1165
+ if (animations.size > 0) {
1166
+ const scope = manifest.Scope ?? manifest.Package;
1167
+ const scopeParts = scope.split(".");
1168
+ let js = createNamespace(scopeParts);
1169
+ for (const [name, content] of animations){
1170
+ js += `${scope}["${name}"] = ` + content + ";";
1171
+ logStep(`Adding animation ${scope}.${name}`);
1172
+ }
1173
+ return {
1174
+ js
1175
+ };
1176
+ }
1177
+ return undefined;
1178
+ };
1179
+ const createNamespace = (parts)=>{
1180
+ let code = `var ${parts[0]};`;
1181
+ for(let index = 0; index < parts.length; index++){
1182
+ const path = parts.slice(0, index + 1).join(".");
1183
+ code += `\n(${path} = ${path} || {});`;
1184
+ }
1185
+ return code;
1186
+ };
825
1187
  let validateAnimationJson;
826
1188
  const getAnimationJsonValidation = async ()=>{
827
1189
  if (validateAnimationJson === undefined) {
@@ -835,9 +1197,10 @@ const getAnimationJsonValidation = async ()=>{
835
1197
  }
836
1198
  return validateAnimationJson;
837
1199
  };
1200
+
838
1201
  const buildFolders = async (options)=>{
839
1202
  if (options.outDir !== undefined && options.clean) {
840
- fs.rmSync(options.outDir, {
1203
+ await fs$1.rm(options.outDir, {
841
1204
  recursive: true
842
1205
  });
843
1206
  }
@@ -845,93 +1208,38 @@ const buildFolders = async (options)=>{
845
1208
  const folders = options.packages;
846
1209
  let sortedPackages = sortPackagesByBuildOrder(folders);
847
1210
  let index = 1;
1211
+ const manifests = new Map(sortedPackages.map((location)=>[
1212
+ location,
1213
+ readPackageCreatorManifest(location)
1214
+ ]));
1215
+ const maxNameLength = Array.from(manifests.values(), (manifest)=>manifest.Package.length).reduce((acc, length)=>Math.max(acc, length), 0);
848
1216
  for (const location of sortedPackages){
849
- const hasTypescript = getPackageTypescriptFiles(location).length > 0;
850
- ensureTsConfig(location);
851
- const data = readPackageCreatorManifest(location);
852
- const logStep = (step)=>logPackageMessage(data.Package, step, index, folders.length);
1217
+ await ensureTsConfig(location);
1218
+ const data = manifests.get(location);
1219
+ const logStep = (step)=>logPackageMessage(data.Package, step, index, folders.length, maxNameLength);
853
1220
  const outputDirectory = options.outDir || location.scriptsDir;
854
- fs.mkdirSync(outputDirectory, {
1221
+ await fs$1.mkdir(outputDirectory, {
855
1222
  recursive: true
856
1223
  });
857
- let buildResult;
858
- if (hasTypescript) {
859
- logStep("Compiling typescript to javascript");
860
- buildResult = await build(location, outputDirectory);
861
- } else {
862
- buildResult = {
863
- js: ""
864
- };
865
- }
866
- const banner = options.banner ? createBannerComment(options.banner) : undefined;
867
- if (banner) {
868
- buildResult.js = banner + "\n" + buildResult.js;
869
- if (buildResult.definitions !== undefined) {
870
- buildResult.definitions = banner + "\n" + buildResult.definitions;
871
- }
872
- }
873
- const animations = new Map();
874
- for (const scriptFilePath of readPackageAnimationList(location)){
875
- const content = fs.readFileSync(scriptFilePath, {
876
- encoding: "utf8"
877
- });
878
- let data;
879
- try {
880
- data = JSON.parse(content);
881
- } catch (err) {
882
- const relativePath = path.relative(options.workspace.path, scriptFilePath);
883
- if (err instanceof SyntaxError) {
884
- throw new Error(`Encountered invalid syntax in file "${relativePath}": ${String(err)}`);
885
- }
886
- throw new Error(`Encountered an unexpected error while parsing animation json file at path "${relativePath}"`, {
887
- cause: err
888
- });
889
- }
890
- if (!data.Id) {
891
- const fileName = path.basename(scriptFilePath, ".animation.json");
892
- data.Id = fileName;
893
- }
894
- (await getAnimationJsonValidation())(data);
895
- delete data.$schema;
896
- animations.set(data.Id, JSON.stringify(data));
897
- }
898
- if (animations.size > 0) {
899
- const scope = data.Scope ?? data.Package;
900
- const scopeParts = scope.split(".");
901
- buildResult.js += createNamespace(scopeParts);
902
- for (const [name, content] of animations){
903
- buildResult.js += `${scope}["${name}"] = ` + content + ";";
904
- logPackageMessage(data.Package, `Adding animation ${scope}.${name}`);
905
- }
906
- } else if (!hasTypescript) {
907
- throw new Error(`Expected package to have a least one ts file or one animation.json file`);
908
- }
909
- fs.writeFileSync(path.join(outputDirectory, `${data.Package}.js`), buildResult.js, {
910
- encoding: "utf8"
911
- });
912
- if (buildResult.definitions !== undefined) {
913
- fs.writeFileSync(path.join(outputDirectory, `${data.Package}.d.ts`), buildResult.definitions, {
914
- encoding: "utf8"
1224
+ const manager = new BuildManager(data, (result)=>writeBuildResult(result, data, location, workspace, outputDirectory, options.minimize, logStep), logStep);
1225
+ if (options.banner) {
1226
+ manager.addParticipant("banner", createBannerCommentBuildParticipant(options.banner));
1227
+ }
1228
+ manager.addParticipant("tsc", createTSCBuildParticipant(location, outputDirectory));
1229
+ manager.addParticipant("animation", createAnimationBuildParticipant(location, data));
1230
+ await new Promise((resolve, reject)=>{
1231
+ manager.addListener("start", ()=>{
1232
+ logStep(`Build started`);
915
1233
  });
916
- }
917
- if (options.minimize) {
918
- const minifyResult = await terser.minify(buildResult.js, {
919
- ecma: 5
1234
+ manager.addListener("error", (error)=>{
1235
+ reject(new Error(error));
920
1236
  });
921
- const minifiedPath = path.join(outputDirectory, `${data.Package}.min.js`);
922
- fs.writeFileSync(minifiedPath, minifyResult.code, {
923
- encoding: "utf8"
924
- });
925
- }
926
- if (location.path.includes("Basics") && buildResult.definitions !== undefined) {
927
- fs.mkdirSync(path.join(workspace.path, "lib"), {
928
- recursive: true
1237
+ manager.addListener("build", ()=>{
1238
+ logStep(`Build complete`);
1239
+ resolve();
929
1240
  });
930
- logStep("Copying basics definition file to the lib folder");
931
- fs.writeFileSync(path.join(workspace.path, "lib", `${data.Package}.d.ts`), buildResult.definitions, {
932
- encoding: "utf8"
933
- });
934
- }
1241
+ manager.run();
1242
+ });
935
1243
  if (options.docs) {
936
1244
  logStep("Generating typedoc documentation");
937
1245
  await generateDocs(location, path.join(outputDirectory, `${data.Package}.d.ts`), path.join(workspace.path, "docs", data.Package), data.Package);
@@ -939,24 +1247,128 @@ const buildFolders = async (options)=>{
939
1247
  index++;
940
1248
  }
941
1249
  };
942
- const createNamespace = (parts)=>{
943
- let code = `var ${parts[0]};`;
944
- for(let index = 0; index < parts.length; index++){
945
- const path = parts.slice(0, index + 1).join(".");
946
- code += `\n(${path} = ${path} || {});`;
1250
+ const buildFoldersWatch = async (options)=>{
1251
+ if (options.outDir !== undefined && options.clean) {
1252
+ await fs$1.rm(options.outDir, {
1253
+ recursive: true
1254
+ });
1255
+ }
1256
+ const workspace = options.workspace;
1257
+ const folders = options.packages;
1258
+ let sortedPackages = sortPackagesByBuildOrder(folders);
1259
+ let index = 1;
1260
+ const manifests = new Map(sortedPackages.map((location)=>[
1261
+ location,
1262
+ readPackageCreatorManifest(location)
1263
+ ]));
1264
+ const maxNameLength = Array.from(manifests.values(), (manifest)=>manifest.Package.length).reduce((acc, length)=>Math.max(acc, length), 0);
1265
+ for (const location of sortedPackages){
1266
+ await ensureTsConfig(location);
1267
+ const data = manifests.get(location);
1268
+ const currentIndex = index;
1269
+ const logStep = (step)=>logPackageMessage(data.Package, step, currentIndex, folders.length, maxNameLength);
1270
+ const outputDirectory = options.outDir || location.scriptsDir;
1271
+ await fs$1.mkdir(outputDirectory, {
1272
+ recursive: true
1273
+ });
1274
+ const manager = new BuildManager(data, (result)=>writeBuildResult(result, data, location, workspace, outputDirectory, options.minimize, logStep), logStep);
1275
+ if (options.banner) {
1276
+ manager.addParticipant("banner", createBannerCommentBuildParticipant(options.banner));
1277
+ }
1278
+ manager.addParticipant("tsc", createTSCWatchBuildParticipant(location, outputDirectory));
1279
+ manager.addParticipant("animation", createAnimationWatchBuildParticipant(location, data));
1280
+ await new Promise((resolve, reject)=>{
1281
+ manager.addListener("start", ()=>{
1282
+ logStep(`Build started`);
1283
+ });
1284
+ manager.addListener("error", (error)=>{
1285
+ logStep(`Build failed: ${error}`);
1286
+ resolve();
1287
+ });
1288
+ manager.addListener("build", ()=>{
1289
+ logStep(`Build complete`);
1290
+ resolve();
1291
+ });
1292
+ manager.run();
1293
+ });
1294
+ index++;
1295
+ }
1296
+ await new Promise(()=>{});
1297
+ };
1298
+ const writeBuildResult = async (buildResult, manifest, location, workspace, outputDirectory, minimize, logStep)=>{
1299
+ let js = buildResult.js;
1300
+ if (buildResult.sourceMap) {
1301
+ js += `\n//# sourceMappingURL=${manifest.Package}.js.map`;
1302
+ }
1303
+ await fs$1.writeFile(path.join(outputDirectory, `${manifest.Package}.js`), js, {
1304
+ encoding: "utf8"
1305
+ });
1306
+ if (buildResult.definitions !== undefined) {
1307
+ await fs$1.writeFile(path.join(outputDirectory, `${manifest.Package}.d.ts`), buildResult.definitions, {
1308
+ encoding: "utf8"
1309
+ });
1310
+ }
1311
+ if (buildResult.sourceMap !== undefined) {
1312
+ await fs$1.writeFile(path.join(outputDirectory, `${manifest.Package}.js.map`), buildResult.sourceMap, {
1313
+ encoding: "utf8"
1314
+ });
1315
+ }
1316
+ if (minimize) {
1317
+ logStep("Minifying the output");
1318
+ const minifyResult = await terser.minify(js, {
1319
+ ecma: 5,
1320
+ sourceMap: {
1321
+ content: buildResult.sourceMap,
1322
+ includeSources: false
1323
+ }
1324
+ });
1325
+ const minifiedPath = path.join(outputDirectory, `${manifest.Package}.min.js`);
1326
+ await fs$1.writeFile(minifiedPath, minifyResult.code, {
1327
+ encoding: "utf8"
1328
+ });
1329
+ if (minifyResult.map !== undefined) {
1330
+ await fs$1.writeFile(minifiedPath + ".map", typeof minifyResult.map === "string" ? minifyResult.map : JSON.stringify(minifyResult.map), {
1331
+ encoding: "utf8"
1332
+ });
1333
+ }
1334
+ }
1335
+ if (location.path.includes("Basics") && buildResult.definitions !== undefined) {
1336
+ await fs$1.mkdir(path.join(workspace.path, "lib"), {
1337
+ recursive: true
1338
+ });
1339
+ logStep("Copying basics definition file to the lib folder");
1340
+ await fs$1.writeFile(path.join(workspace.path, "lib", `${manifest.Package}.d.ts`), buildResult.definitions, {
1341
+ encoding: "utf8"
1342
+ });
947
1343
  }
948
- return code;
949
1344
  };
950
- const ensureTsConfig = (location)=>{
1345
+ const createBannerCommentBuildParticipant = (options)=>(env)=>{
1346
+ env.onBuildStart();
1347
+ const banner = createBannerComment(options);
1348
+ env.onBuildEnd({
1349
+ type: "success",
1350
+ artefacts: {
1351
+ js: banner ?? "",
1352
+ definitions: banner ?? ""
1353
+ }
1354
+ });
1355
+ return {
1356
+ destroy: ()=>{}
1357
+ };
1358
+ };
1359
+ const ensureTsConfig = async (location)=>{
951
1360
  const tsconfigPath = path.join(location.scriptsDir, "tsconfig.json");
952
- if (!fs.existsSync(tsconfigPath)) {
953
- const content = {};
1361
+ try {
1362
+ const content = JSON.parse(await fs$1.readFile(tsconfigPath, "utf8"));
954
1363
  applyTsConfigOption(content);
955
- fs.writeFileSync(tsconfigPath, JSON.stringify(content, undefined, "\t"), "utf8");
956
- } else {
957
- const content = JSON.parse(fs.readFileSync(tsconfigPath, "utf8"));
1364
+ await fs$1.writeFile(tsconfigPath, JSON.stringify(content, undefined, " "), "utf8");
1365
+ } catch (err) {
1366
+ if (!isErrorENOENT(err)) {
1367
+ throw err;
1368
+ }
1369
+ const content = {};
958
1370
  applyTsConfigOption(content);
959
- fs.writeFileSync(tsconfigPath, JSON.stringify(content, undefined, "\t"), "utf8");
1371
+ await fs$1.writeFile(tsconfigPath, JSON.stringify(content, undefined, " "), "utf8");
960
1372
  }
961
1373
  };
962
1374
  const applyTsConfigOption = (data)=>{
@@ -1095,13 +1507,9 @@ const getWorkspaceBannerText = (manifest)=>{
1095
1507
 
1096
1508
  // Stolen from ig.tools.core
1097
1509
  class PackageVersion {
1098
- static #_ = (()=>{
1099
- // https://regex101.com/r/90PEY9/1
1100
- this.fullTextMatcher = /(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?/;
1101
- })();
1102
- static #_1 = (()=>{
1103
- this.lineMatcher = /^(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?$/;
1104
- })();
1510
+ static #_ = // https://regex101.com/r/90PEY9/1
1511
+ this.fullTextMatcher = /(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?/;
1512
+ static #_2 = this.lineMatcher = /^(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?$/;
1105
1513
  static extractFromText(input, description) {
1106
1514
  if (input === undefined) {
1107
1515
  throw new Error(`Can not parse version from undefined`);
@@ -1221,7 +1629,7 @@ class PackageVersion {
1221
1629
  this.preRelease = undefined;
1222
1630
  this.buildNumber = 100;
1223
1631
  }
1224
- toVersionString({ buildNumber } = {}) {
1632
+ toVersionString({ buildNumber } = {}) {
1225
1633
  let version = [
1226
1634
  this.major,
1227
1635
  this.minor,
@@ -1414,7 +1822,7 @@ const buildArchiveFromPublishedPackage = (location, manifest, creatorPackage)=>{
1414
1822
  if (fs.existsSync(source)) {
1415
1823
  const images = fs.readdirSync(source);
1416
1824
  for (const file of images){
1417
- const { ext } = path.parse(file);
1825
+ const { ext } = path.parse(file);
1418
1826
  switch(ext){
1419
1827
  case ".png":
1420
1828
  case ".jpeg":
@@ -1438,10 +1846,9 @@ const notRuntimeScripts = [
1438
1846
  "Context",
1439
1847
  "Evaluator"
1440
1848
  ];
1441
- const buildArchiveFromPackage = async (packageLocation, data, binDir)=>{
1442
- const { domain } = parseCreatorPackageName(data);
1849
+ const buildArchiveFromPackage = async (packageLocation, data, binDir, minified = true)=>{
1850
+ const { domain } = parseCreatorPackageName(data);
1443
1851
  const logStep = (step)=>logPackageMessage(data.Package, step);
1444
- const libFilePath = path.join(binDir, `${data.Package}.min.js`);
1445
1852
  const scriptDirectories = [
1446
1853
  packageLocation.path,
1447
1854
  packageLocation.scriptsDir
@@ -1468,6 +1875,7 @@ const buildArchiveFromPackage = async (packageLocation, data, binDir)=>{
1468
1875
  }
1469
1876
  let libFile;
1470
1877
  try {
1878
+ const libFilePath = minified ? path.join(binDir, `${data.Package}.min.js`) : path.join(binDir, `${data.Package}.js`);
1471
1879
  libFile = fs.readFileSync(libFilePath, {
1472
1880
  encoding: "utf8"
1473
1881
  });
@@ -1486,10 +1894,7 @@ const buildArchiveFromPackage = async (packageLocation, data, binDir)=>{
1486
1894
  library = `/* This file is part of the ${domain} Data Packages.
1487
1895
  * Copyright (C) ${date.getFullYear()} intelligentgraphics. All Rights Reserved. */`;
1488
1896
  }
1489
- const minifyResult = await terser.minify(library, {
1490
- ecma: 5
1491
- });
1492
- archive.file(`${data.Package}.js`, minifyResult.code);
1897
+ archive.file(`${data.Package}.js`, library);
1493
1898
  archive.file(PACKAGE_FILE, JSON.stringify(data, null, 2));
1494
1899
  const creatorIndex = readPackageCreatorIndex(packageLocation);
1495
1900
  if (creatorIndex !== undefined) {
@@ -1498,7 +1903,7 @@ const buildArchiveFromPackage = async (packageLocation, data, binDir)=>{
1498
1903
  for (const directory of scriptDirectories){
1499
1904
  try {
1500
1905
  for (const file of fs.readdirSync(directory)){
1501
- const { ext } = path.parse(file);
1906
+ const { ext } = path.parse(file);
1502
1907
  switch(ext){
1503
1908
  case ".png":
1504
1909
  case ".jpeg":
@@ -1520,10 +1925,10 @@ const execAsync = promisify(exec);
1520
1925
  const releaseFolder = async (options)=>{
1521
1926
  const workspace = options.workspace;
1522
1927
  const location = options.directory;
1523
- const { write: writeVersionFile , reset: resetVersionFile } = getVersionFileHandler(location);
1928
+ const { write: writeVersionFile, reset: resetVersionFile } = getVersionFileHandler(location);
1524
1929
  const packageDescription = readPackageCreatorManifest(location);
1525
1930
  const fullPackageName = packageDescription.Package;
1526
- const { domain , subdomain } = parseCreatorPackageName(packageDescription);
1931
+ const { domain, subdomain } = parseCreatorPackageName(packageDescription);
1527
1932
  const publishDomain = options.domain ?? domain;
1528
1933
  const publishSubdomain = options.subdomain ?? subdomain;
1529
1934
  const sharedPackageJson = readWorkspaceNpmManifest(workspace);
@@ -1631,7 +2036,8 @@ const releaseFolder = async (options)=>{
1631
2036
  }
1632
2037
  }
1633
2038
  }
1634
- const archive = await buildArchiveFromPackage(location, packageDescription, binDir);
2039
+ logPackageMessage(packageDescription.Package, `Creating zip file`);
2040
+ const archive = await buildArchiveFromPackage(location, packageDescription, binDir, options.minimize);
1635
2041
  try {
1636
2042
  const zipOutputStream = createWriteStream(zipFilePath);
1637
2043
  await pipeline(archive.generateNodeStream(), zipOutputStream);
@@ -1837,7 +2243,7 @@ const createSessionManager = async (params)=>{
1837
2243
  * Extracts and returns script array for _Index.json from a src folder
1838
2244
  *
1839
2245
  * @param folderPath path to a src folder
1840
- */ function generateIndex({ location , ignore =[] , strictOptional =false }) {
2246
+ */ function generateIndex({ location, ignore = [], strictOptional = false }) {
1841
2247
  const files = getPackageTypescriptFiles(location);
1842
2248
  const filtered = files.filter((path)=>{
1843
2249
  return !ignore.some((suffix)=>path.endsWith(suffix));
@@ -2107,5 +2513,5 @@ const detectScriptingClass = (node)=>{
2107
2513
  }
2108
2514
  };
2109
2515
 
2110
- export { buildFolders, generateIndex, releaseFolder };
2516
+ export { buildFolders, buildFoldersWatch, generateIndex, releaseFolder };
2111
2517
  //# sourceMappingURL=lib.mjs.map