@intelligentgraphics/ig.gfx.packager 3.0.10 → 3.0.12

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 (34) hide show
  1. package/build/bin.mjs +6 -0
  2. package/build/bin.mjs.map +1 -0
  3. package/build/{cli-cb85e4b5.js → cli-2ce0c074.mjs} +8 -12
  4. package/build/cli-2ce0c074.mjs.map +1 -0
  5. package/build/{dependencies-2565d80c.js → dependencies-a8a9faba.mjs} +3 -7
  6. package/build/dependencies-a8a9faba.mjs.map +1 -0
  7. package/build/{generateIndex-f386d332.js → generateIndex-d7e7000f.mjs} +47 -9
  8. package/build/generateIndex-d7e7000f.mjs.map +1 -0
  9. package/build/{generateParameterType-151ab313.js → generateParameterType-24d37c5f.mjs} +2 -2
  10. package/build/generateParameterType-24d37c5f.mjs.map +1 -0
  11. package/build/{index-67a112b8.js → index-2cdef238.mjs} +6 -6
  12. package/build/index-2cdef238.mjs.map +1 -0
  13. package/build/{index-7a955335.js → index-2fa7b516.mjs} +46 -30
  14. package/build/index-2fa7b516.mjs.map +1 -0
  15. package/build/{postinstall-962af586.js → postinstall-0ffa4499.mjs} +3 -3
  16. package/build/postinstall-0ffa4499.mjs.map +1 -0
  17. package/build/{publishNpm-1838e45c.js → publishNpm-2b3321c5.mjs} +4 -4
  18. package/build/publishNpm-2b3321c5.mjs.map +1 -0
  19. package/build/{versionFile-cf6657c8.js → versionFile-e8fdf88c.mjs} +2 -2
  20. package/build/versionFile-e8fdf88c.mjs.map +1 -0
  21. package/lib/lib.mjs +1754 -0
  22. package/package.json +12 -6
  23. package/readme.md +11 -0
  24. package/build/cli-cb85e4b5.js.map +0 -1
  25. package/build/dependencies-2565d80c.js.map +0 -1
  26. package/build/generateIndex-f386d332.js.map +0 -1
  27. package/build/generateParameterType-151ab313.js.map +0 -1
  28. package/build/index-67a112b8.js.map +0 -1
  29. package/build/index-7a955335.js.map +0 -1
  30. package/build/index.mjs +0 -6
  31. package/build/index.mjs.map +0 -1
  32. package/build/postinstall-962af586.js.map +0 -1
  33. package/build/publishNpm-1838e45c.js.map +0 -1
  34. package/build/versionFile-cf6657c8.js.map +0 -1
package/lib/lib.mjs ADDED
@@ -0,0 +1,1754 @@
1
+ import * as path from 'path';
2
+ import * as fs from 'fs';
3
+ import * as terser from 'terser';
4
+ import resolve from 'resolve';
5
+ import 'write-pkg';
6
+ import glob from 'glob';
7
+ import 'write-json-file';
8
+ import axios from 'axios';
9
+ import ts from 'typescript';
10
+ import typedoc from 'typedoc';
11
+ import { pipeline } from 'stream/promises';
12
+ import { execSync } from 'child_process';
13
+ import simpleGit from 'simple-git';
14
+ import Ajv from 'ajv';
15
+ import JSZip from 'jszip';
16
+
17
+ const stripUtf8Bom = (text)=>{
18
+ // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
19
+ // conversion translates it to FEFF (UTF-16 BOM).
20
+ if (text.charCodeAt(0) === 0xfeff) {
21
+ return text.slice(1);
22
+ }
23
+ return text;
24
+ };
25
+
26
+ const readNpmManifest = (directory)=>{
27
+ const packageJsonPath = path.join(directory, "package.json");
28
+ const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
29
+ encoding: "utf8"
30
+ }));
31
+ return JSON.parse(packageJson);
32
+ };
33
+
34
+ const getNodeErrorCode = (error)=>{
35
+ if (error !== null && typeof error === "object" && error.code !== undefined) {
36
+ return error.code;
37
+ }
38
+ };
39
+ /**
40
+ * No such file or directory: Commonly raised by fs operations to indicate that a component of the specified pathname does not exist. No entity (file or directory) could be found by the given path.
41
+ *
42
+ * @param {unknown} error
43
+ */ const isErrorENOENT = (error)=>getNodeErrorCode(error) === "ENOENT";
44
+
45
+ // Functionality related to working with a single package.
46
+ const PACKAGE_FILE = "_Package.json";
47
+ const INDEX_FILE = "_Index.json";
48
+ const ANIMATION_FILE_SUFFIX = ".animation.json";
49
+ const parseCreatorPackageName = (manifest)=>{
50
+ const [domain, ...subdomainParts] = manifest.Package.split(".");
51
+ return {
52
+ domain,
53
+ subdomain: subdomainParts.join(".")
54
+ };
55
+ };
56
+ const readPackageCreatorManifest = (location)=>{
57
+ const packageJsonPath = path.join(location.manifestDir, PACKAGE_FILE);
58
+ const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
59
+ encoding: "utf8"
60
+ }));
61
+ return JSON.parse(packageJson);
62
+ };
63
+ const writePackageCreatorManifest = (location, creatorPackage)=>{
64
+ const packageJsonPath = path.join(location.manifestDir, PACKAGE_FILE);
65
+ fs.writeFileSync(packageJsonPath, JSON.stringify(creatorPackage, null, "\t") + "\n");
66
+ };
67
+ const getPackageCreatorIndexPath = (location)=>path.join(location.manifestDir, INDEX_FILE);
68
+ const readPackageCreatorIndex = (location)=>{
69
+ try {
70
+ const indexPath = getPackageCreatorIndexPath(location);
71
+ const index = stripUtf8Bom(fs.readFileSync(indexPath, {
72
+ encoding: "utf8"
73
+ }));
74
+ return JSON.parse(index);
75
+ } catch (err) {
76
+ if (isErrorENOENT(err)) {
77
+ return undefined;
78
+ }
79
+ throw err;
80
+ }
81
+ };
82
+ const writePackageCreatorIndex = (location, index)=>{
83
+ const indexPath = getPackageCreatorIndexPath(location);
84
+ fs.writeFileSync(indexPath, JSON.stringify(index, null, "\t") + "\n");
85
+ };
86
+ const readPackageNpmManifest = (location)=>{
87
+ try {
88
+ return readNpmManifest(location.manifestDir);
89
+ } catch (err) {
90
+ if (isErrorENOENT(err)) {
91
+ return undefined;
92
+ }
93
+ throw err;
94
+ }
95
+ };
96
+ const readPackageAnimationList = (location)=>{
97
+ const directoryContent = fs.readdirSync(location.manifestDir);
98
+ const animationPathList = [];
99
+ for (const entry of directoryContent){
100
+ if (entry.endsWith(ANIMATION_FILE_SUFFIX)) {
101
+ const animationPath = path.join(location.manifestDir, entry);
102
+ animationPathList.push(animationPath);
103
+ }
104
+ }
105
+ return animationPathList;
106
+ };
107
+ const getPackageReleasesDirectory = (location)=>path.join(location.path, "Releases");
108
+
109
+ /**
110
+ * Detects a published package from a path.
111
+ *
112
+ * Can return undefined if the package is not installed.
113
+ *
114
+ * @param {string} resolveBasePath
115
+ * @param {string} name
116
+ * @return {*} {(PublishedPackageLocation | undefined)}
117
+ */ const detectPublishedPackageFromPath = (resolveBasePath, name)=>{
118
+ try {
119
+ const manifestPath = resolve.sync(name + "/package.json", {
120
+ basedir: resolveBasePath
121
+ });
122
+ const dir = path.dirname(manifestPath);
123
+ return {
124
+ _kind: "PublishedPackageLocation",
125
+ path: dir
126
+ };
127
+ } catch (err) {
128
+ return undefined;
129
+ }
130
+ };
131
+ const readPublishedPackageNpmManifest = (location)=>{
132
+ return readNpmManifest(location.path);
133
+ };
134
+ const readPublishedPackageCreatorManifest = (location)=>{
135
+ try {
136
+ const packageJsonPath = path.join(location.path, PACKAGE_FILE);
137
+ const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
138
+ encoding: "utf8"
139
+ }));
140
+ return JSON.parse(packageJson);
141
+ } catch (err) {
142
+ if (isErrorENOENT(err)) {
143
+ return undefined;
144
+ }
145
+ throw err;
146
+ }
147
+ };
148
+ const readPublishedPackageCreatorIndex = (location)=>{
149
+ try {
150
+ const packageJsonPath = path.join(location.path, INDEX_FILE);
151
+ const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
152
+ encoding: "utf8"
153
+ }));
154
+ const result = JSON.parse(packageJson);
155
+ return result;
156
+ } catch (err) {
157
+ if (isErrorENOENT(err)) {
158
+ return undefined;
159
+ }
160
+ throw err;
161
+ }
162
+ };
163
+
164
+ const readWorkspaceNpmManifest = (workspace)=>{
165
+ try {
166
+ return readNpmManifest(workspace.path);
167
+ } catch (err) {
168
+ if (isErrorENOENT(err)) {
169
+ throw new Error(`Expected a package.json file to exist in ${workspace.path}. See packager readme for instructions on how to create the package.json.`);
170
+ }
171
+ throw err;
172
+ }
173
+ };
174
+ const getWorkspaceOutputPath = (workspace)=>path.join(workspace.path, "bin");
175
+
176
+ // /**
177
+ // * Determines the implicit dependencies of a an actual data workspace package.
178
+ // *
179
+ // * An implicit dependency is a dependency that is installed for the workspace and has the same runtime environment (evaluator, interactor) as the package.
180
+ // *
181
+ // * @param {WorkspaceLocation} workspace
182
+ // * @param {CreatorPackage} creatorPackage
183
+ // * @returns {PublishedPackageLocation[]}
184
+ // */
185
+ // export const determinePackageImplicitDependencies = (
186
+ // workspace: WorkspaceLocation,
187
+ // creatorPackage: CreatorPackage,
188
+ // ): PublishedPackageLocation[] => {
189
+ // const libraries = determineWorkspaceIGLibraries(workspace);
190
+ // const results: PublishedPackageLocation[] = [];
191
+ // for (const librarylocation of libraries) {
192
+ // const libraryManifest =
193
+ // readPublishedPackageCreatorManifest(librarylocation);
194
+ // if (
195
+ // libraryManifest !== undefined &&
196
+ // (libraryManifest.Type === "Mixed" ||
197
+ // libraryManifest.RunTime === creatorPackage.RunTime)
198
+ // ) {
199
+ // results.push(librarylocation);
200
+ // }
201
+ // }
202
+ // return results;
203
+ // };
204
+ /**
205
+ * Recursively determines all installed ig libraries for a workspace.
206
+ *
207
+ * @param {WorkspaceLocation} workspace
208
+ * @returns {PublishedPackageLocation[]}
209
+ */ const determineWorkspaceIGLibraries = (workspace)=>{
210
+ const manifest = readWorkspaceNpmManifest(workspace);
211
+ const libraries = collectIGLibraries(workspace, manifest);
212
+ const results = new Map();
213
+ for (const location of libraries){
214
+ const manifest = readPublishedPackageNpmManifest(location);
215
+ if (!results.has(manifest.name)) {
216
+ results.set(manifest.name, location);
217
+ }
218
+ }
219
+ return Array.from(results.values());
220
+ };
221
+ const collectIGLibraries = (workspace, manifest)=>{
222
+ if (!manifest.dependencies) {
223
+ return [];
224
+ }
225
+ const runtimeDependencies = Object.getOwnPropertyNames(manifest.dependencies);
226
+ const result = [];
227
+ for (const runtimeDependency of runtimeDependencies){
228
+ var _runtimeManifest_ig;
229
+ const location = detectPublishedPackageFromPath(workspace.path, runtimeDependency);
230
+ if (location === undefined) {
231
+ continue;
232
+ }
233
+ const runtimeManifest = readPublishedPackageNpmManifest(location);
234
+ // packages need to explicitly be marked as ig scriptingLibraries
235
+ if ((_runtimeManifest_ig = runtimeManifest.ig) == null ? void 0 : _runtimeManifest_ig.scriptingLibrary) {
236
+ result.push(location);
237
+ result.push(...collectIGLibraries(workspace, runtimeManifest));
238
+ }
239
+ }
240
+ return result;
241
+ };
242
+
243
+ const readStringFromFile = (filePath)=>fs.readFileSync(filePath, {
244
+ encoding: "utf8"
245
+ });
246
+ const readStringFromFileOrUndefined = (filePath)=>{
247
+ try {
248
+ return readStringFromFile(filePath);
249
+ } catch (err) {
250
+ if (!isErrorENOENT(err)) {
251
+ throw err;
252
+ }
253
+ return undefined;
254
+ }
255
+ };
256
+
257
+ const logPackageMessage = (name, step, index, total)=>{
258
+ const numLength = total === undefined ? undefined : total.toString().length;
259
+ const indexString = total === undefined || total < 2 ? "" : `${index.toString().padStart(numLength, "0")}/${total} `;
260
+ const identifierString = `${indexString}${name.padEnd(15)}`;
261
+ console.log(`${identifierString} >> ${step}`);
262
+ };
263
+
264
+ const getPackageTypescriptFiles = (location)=>glob.sync("**/*.ts", {
265
+ absolute: true,
266
+ cwd: location.scriptsDir,
267
+ ignore: "node_modules/**/*"
268
+ });
269
+
270
+ var CreatorWorkspaceGeometryFileType;
271
+ (function(CreatorWorkspaceGeometryFileType) {
272
+ CreatorWorkspaceGeometryFileType["StandardObj"] = "standard.obj";
273
+ CreatorWorkspaceGeometryFileType["StandardCtm"] = "standard.ctm";
274
+ CreatorWorkspaceGeometryFileType["StandardNormals"] = "normals_std.png";
275
+ CreatorWorkspaceGeometryFileType["DeformationGlb"] = "deformation.glb";
276
+ })(CreatorWorkspaceGeometryFileType || (CreatorWorkspaceGeometryFileType = {}));
277
+
278
+ const PLUGIN_ID = "0feba3a0-b6d1-11e6-9598-0800200c9a66";
279
+ /**
280
+ * Starts an IG.Asset.Server session and returns the sessionId
281
+ *
282
+ * @param {SessionStartParams} params
283
+ * @returns
284
+ */ const startSession = async ({ url , authentication , ...params })=>{
285
+ const payload = {
286
+ ...params,
287
+ user: undefined,
288
+ password: undefined,
289
+ license: undefined,
290
+ plugin: PLUGIN_ID
291
+ };
292
+ if (authentication.type === "credentials") {
293
+ payload.user = authentication.username;
294
+ payload.password = authentication.password;
295
+ } else if (authentication.type === "license") {
296
+ payload.license = authentication.license;
297
+ }
298
+ const { data: { session: sessionId , state , response } } = await axios.post(`Session/Start2`, JSON.stringify(payload), {
299
+ baseURL: url
300
+ });
301
+ if (state !== "SUCCESS") {
302
+ let message = `Could not start session. IG.Asset.Server responded with ${state}`;
303
+ if (response) {
304
+ message += `: ${response}`;
305
+ }
306
+ throw new Error(message);
307
+ }
308
+ return {
309
+ _kind: "AssetService",
310
+ url,
311
+ sessionId,
312
+ domain: params.domain,
313
+ subDomain: params.subDomain
314
+ };
315
+ };
316
+ const closeSession = async (session)=>{
317
+ await axios.get(`Session/Close/${session.sessionId}`, {
318
+ baseURL: session.url
319
+ });
320
+ };
321
+ const uploadPackage = async (session, { name , version }, zipFilePath)=>{
322
+ try {
323
+ await uploadPackageToUrl(session.url, `UploadPackage/${session.sessionId}/${name}_${version}`, zipFilePath);
324
+ } catch (err) {
325
+ await uploadPackageToUrl(session.url, `UploadPackage/${session.sessionId}/${name}_${version}/`, zipFilePath);
326
+ }
327
+ };
328
+ const uploadPackageToUrl = async (url, path, zipFilePath)=>{
329
+ const { data , status } = await axios.post(path, fs.createReadStream(zipFilePath), {
330
+ baseURL: url
331
+ });
332
+ let objectBody;
333
+ if (typeof data === "string") {
334
+ try {
335
+ objectBody = JSON.parse(data);
336
+ } catch (err) {}
337
+ } else if (typeof data === "object") {
338
+ objectBody = data;
339
+ }
340
+ if (objectBody !== undefined) {
341
+ if ("state" in objectBody && objectBody.state !== "SUCCESS") {
342
+ throw new Error(objectBody.response ?? objectBody.state);
343
+ }
344
+ }
345
+ if (status >= 400) {
346
+ if (objectBody !== undefined) {
347
+ let text_1 = "";
348
+ for(const key in objectBody){
349
+ text_1 += key + ": \n";
350
+ if (typeof objectBody[key] === "object") {
351
+ text_1 += JSON.stringify(objectBody[key], undefined, 2);
352
+ } else {
353
+ text_1 += objectBody[key];
354
+ }
355
+ text_1 += "\n\n";
356
+ }
357
+ throw new Error(text_1);
358
+ }
359
+ throw new Error(data);
360
+ }
361
+ return data;
362
+ };
363
+ const getExistingPackages = async (session)=>{
364
+ const { data } = await axios.get(`Script/GetInformation/${session.sessionId}`, {
365
+ baseURL: session.url,
366
+ validateStatus: (status)=>status === 404 || status === 200
367
+ }).catch((err)=>{
368
+ throw new Error(`Failed to get existing packages: ${err.message}`);
369
+ });
370
+ return data;
371
+ };
372
+
373
+ const tryReadTsConfig = (location)=>{
374
+ const { config } = ts.readConfigFile(path.join(location.scriptsDir, "tsconfig.json"), (path)=>{
375
+ try {
376
+ return fs.readFileSync(path, "utf8");
377
+ } catch {
378
+ return undefined;
379
+ }
380
+ });
381
+ return config;
382
+ };
383
+ const build = async (location, outputDir)=>{
384
+ const config = tryReadTsConfig(location);
385
+ config.compilerOptions.lib = [
386
+ "es5",
387
+ "dom"
388
+ ];
389
+ const result = ts.convertCompilerOptionsFromJson(config.compilerOptions, location.scriptsDir);
390
+ const compilerOptions = {
391
+ ...result.options,
392
+ removeComments: false,
393
+ declaration: true,
394
+ sourceMap: false,
395
+ // We don't use tsc to actually emit the files, but we still need to set the correct
396
+ // output directory so the compiler can rewrite the `reference path` directives.
397
+ outFile: path.join(outputDir, "out.js"),
398
+ target: ts.ScriptTarget.ES5,
399
+ noEmitOnError: true
400
+ };
401
+ const host = ts.createCompilerHost(compilerOptions);
402
+ host.getCurrentDirectory = ()=>location.scriptsDir;
403
+ let js;
404
+ let definitions;
405
+ host.writeFile = (fileName, data, writeByteOrderMark)=>{
406
+ if (fileName.endsWith(".js")) {
407
+ js = data;
408
+ } else if (fileName.endsWith(".d.ts")) {
409
+ definitions = data;
410
+ }
411
+ };
412
+ const files = getPackageTypescriptFiles(location);
413
+ if (files.length === 0) {
414
+ throw new Error(`Expected typescript files to exist when building a package. Packages only consisting of animation jsons do not need to be built.`);
415
+ }
416
+ const programOptions = {
417
+ rootNames: files,
418
+ options: compilerOptions,
419
+ host
420
+ };
421
+ const program = ts.createProgram(programOptions);
422
+ const emitResult = program.emit();
423
+ const allDiagnostics = ts.getPreEmitDiagnostics(program);
424
+ if (!emitResult.emitSkipped) {
425
+ if (allDiagnostics.length > 0) {
426
+ console.log(allDiagnostics.map(createErrorMessage).join("\n"));
427
+ }
428
+ if (js === undefined || definitions === undefined) {
429
+ throw new Error(`Unexpected: no js or definitions were created`);
430
+ }
431
+ return {
432
+ js,
433
+ definitions
434
+ };
435
+ }
436
+ const error = allDiagnostics.map(createErrorMessage).join("\n");
437
+ throw new Error(error);
438
+ };
439
+ const createErrorMessage = (diagnostic)=>{
440
+ if (!diagnostic.file) {
441
+ return `${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`;
442
+ }
443
+ const { line , character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
444
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
445
+ return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
446
+ };
447
+
448
+ const generateDocs = async (location, declarationFile, outFolder, name)=>{
449
+ const app = new typedoc.Application();
450
+ const mediaDir = path.join(location.manifestDir, "Media");
451
+ app.bootstrap({
452
+ entryPoints: [
453
+ declarationFile
454
+ ],
455
+ media: mediaDir,
456
+ out: outFolder,
457
+ tsconfig: path.join(location.scriptsDir, "tsconfig.json"),
458
+ skipErrorChecking: true
459
+ });
460
+ app.options.setCompilerOptions([
461
+ declarationFile
462
+ ], {
463
+ target: ts.ScriptTarget.ES5
464
+ }, undefined);
465
+ app.options.setValue("name", name);
466
+ const [readmePath] = glob.sync("**/readme.md", {
467
+ absolute: true,
468
+ cwd: location.manifestDir
469
+ });
470
+ if (readmePath) {
471
+ app.options.setValue("readme", readmePath);
472
+ }
473
+ const project = app.convert();
474
+ if (project) {
475
+ await app.generateDocs(project, outFolder);
476
+ }
477
+ };
478
+
479
+ // Stolen from ig.tools.core
480
+ const toposort = (packages)=>{
481
+ const queue = Object.getOwnPropertyNames(packages);
482
+ const result = [];
483
+ let index = 0;
484
+ while(queue.length > 0){
485
+ if (index >= queue.length) {
486
+ throw new Error("Packages can not have cyclic dependencies");
487
+ }
488
+ const queueEntry = queue[index];
489
+ const dependencies = packages[queueEntry];
490
+ const dependencyQueued = dependencies.some((dependency)=>queue.includes(dependency));
491
+ if (dependencyQueued) {
492
+ index++;
493
+ continue;
494
+ }
495
+ queue.splice(index, 1);
496
+ index = 0;
497
+ result.push(queueEntry);
498
+ }
499
+ return result;
500
+ };
501
+
502
+ const buildFolders = async (options)=>{
503
+ if (options.outDir !== undefined && options.clean) {
504
+ fs.rmSync(options.outDir, {
505
+ recursive: true
506
+ });
507
+ }
508
+ const workspace = options.workspace;
509
+ const folders = options.packages;
510
+ let sortedPackages = sortPackagesByBuildOrder(folders);
511
+ if (options.skipPackagesWithoutTsFiles) {
512
+ sortedPackages = sortedPackages.filter((location)=>getPackageTypescriptFiles(location).length > 0);
513
+ }
514
+ let index = 1;
515
+ for (const location of sortedPackages){
516
+ ensureTsConfig(location);
517
+ const data = readPackageCreatorManifest(location);
518
+ const logStep = (step)=>logPackageMessage(data.Package, step, index, folders.length);
519
+ logStep("Compiling typescript to javascript");
520
+ const outputDirectory = options.outDir || location.scriptsDir;
521
+ fs.mkdirSync(outputDirectory, {
522
+ recursive: true
523
+ });
524
+ const buildResult = await build(location, outputDirectory);
525
+ const banner = options.banner ? createBannerComment(options.banner) : undefined;
526
+ if (banner) {
527
+ buildResult.js = banner + "\n" + buildResult.js;
528
+ buildResult.definitions = banner + "\n" + buildResult.definitions;
529
+ }
530
+ fs.writeFileSync(path.join(outputDirectory, `${data.Package}.js`), buildResult.js, {
531
+ encoding: "utf8"
532
+ });
533
+ fs.writeFileSync(path.join(outputDirectory, `${data.Package}.d.ts`), buildResult.definitions, {
534
+ encoding: "utf8"
535
+ });
536
+ if (options.minimize) {
537
+ const minifyResult = await terser.minify(buildResult.js, {
538
+ ecma: 5
539
+ });
540
+ const minifiedPath = path.join(outputDirectory, `${data.Package}.min.js`);
541
+ fs.writeFileSync(minifiedPath, minifyResult.code, {
542
+ encoding: "utf8"
543
+ });
544
+ }
545
+ if (location.path.includes("Basics")) {
546
+ fs.mkdirSync(path.join(workspace.path, "lib"), {
547
+ recursive: true
548
+ });
549
+ logStep("Copying basics definition file to the lib folder");
550
+ fs.writeFileSync(path.join(workspace.path, "lib", `${data.Package}.d.ts`), buildResult.definitions, {
551
+ encoding: "utf8"
552
+ });
553
+ }
554
+ if (options.docs) {
555
+ logStep("Generating typedoc documentation");
556
+ await generateDocs(location, path.join(outputDirectory, `${data.Package}.d.ts`), path.join(workspace.path, "docs", data.Package), data.Package);
557
+ }
558
+ index++;
559
+ }
560
+ };
561
+ const ensureTsConfig = (location)=>{
562
+ const tsconfigPath = path.join(location.scriptsDir, "tsconfig.json");
563
+ if (!fs.existsSync(tsconfigPath)) {
564
+ const content = {};
565
+ applyTsConfigOption(content);
566
+ fs.writeFileSync(tsconfigPath, JSON.stringify(content, undefined, "\t"), "utf8");
567
+ } else {
568
+ const content = JSON.parse(fs.readFileSync(tsconfigPath, "utf8"));
569
+ applyTsConfigOption(content);
570
+ fs.writeFileSync(tsconfigPath, JSON.stringify(content, undefined, "\t"), "utf8");
571
+ }
572
+ };
573
+ const applyTsConfigOption = (data)=>{
574
+ data.compilerOptions = data.compilerOptions ?? {};
575
+ data.compilerOptions.target = "es5";
576
+ data.compilerOptions.lib = [
577
+ "es5",
578
+ "dom"
579
+ ];
580
+ };
581
+ const sortPackagesByBuildOrder = (folders)=>{
582
+ const packages = Array.from(folders).reduce((acc, location)=>{
583
+ const data = readPackageNpmManifest(location);
584
+ if (data !== undefined) {
585
+ acc[data.name] = {
586
+ data,
587
+ location
588
+ };
589
+ } else {
590
+ acc[location.path] = {
591
+ data: undefined,
592
+ location
593
+ };
594
+ }
595
+ return acc;
596
+ }, {});
597
+ const packageDependencies = Object.getOwnPropertyNames(packages).reduce((acc, packageName)=>{
598
+ const packageData = packages[packageName];
599
+ if (packageData.data === undefined) {
600
+ acc[packageName] = [];
601
+ } else {
602
+ acc[packageName] = Object.getOwnPropertyNames({
603
+ ...packageData.data.devDependencies,
604
+ ...packageData.data.dependencies,
605
+ ...packageData.data.peerDependencies
606
+ }).filter((packageName)=>packages[packageName] !== undefined);
607
+ }
608
+ return acc;
609
+ }, {});
610
+ const sortedPackages = toposort(packageDependencies);
611
+ const result = [];
612
+ for (const packageName of sortedPackages){
613
+ const location = packages[packageName].location;
614
+ if (readPackageCreatorManifest(location).Package.endsWith(".Basics")) {
615
+ result.unshift(location);
616
+ } else {
617
+ result.push(location);
618
+ }
619
+ }
620
+ return result;
621
+ };
622
+ const createBannerComment = (banner)=>{
623
+ const bannerParts = [];
624
+ if (banner.text) {
625
+ bannerParts.push(" * " + banner.text);
626
+ }
627
+ {
628
+ const details = [];
629
+ if (banner.version) {
630
+ details.push(`Version: ${banner.version}`);
631
+ }
632
+ if (banner.commit) {
633
+ if (banner.commitDirty) {
634
+ details.push(`Commit: ${banner.commit} (dirty)`);
635
+ } else {
636
+ details.push(`Commit: ${banner.commit}`);
637
+ }
638
+ }
639
+ if (banner.date) {
640
+ details.push(`Date: ${banner.date.toISOString()}`);
641
+ }
642
+ const detailsText = details.map((line)=>` * ${line}`).join("\n");
643
+ if (detailsText) {
644
+ bannerParts.push(detailsText);
645
+ }
646
+ }
647
+ const bannerText = bannerParts.join("\n\n");
648
+ if (bannerText) {
649
+ return `/*
650
+ ${bannerText}
651
+ *
652
+ * @preserve
653
+ */`;
654
+ }
655
+ return undefined;
656
+ };
657
+
658
+ const getVersionInformationFromGit = async (workspaceLocation, packageLocation)=>{
659
+ try {
660
+ var _log_latest, _log_latest1;
661
+ const git = simpleGit({
662
+ baseDir: workspaceLocation.path
663
+ });
664
+ // check wether the files for a folder are changed
665
+ // if so, mark as dirty
666
+ const diff = await git.diffSummary();
667
+ const dirty = diff.files.some((file)=>{
668
+ if (file.file.toLowerCase().includes("releases") || file.file.toLowerCase().endsWith("version.ts") || file.file.toLowerCase().endsWith("package.json")) {
669
+ return false;
670
+ }
671
+ const fullPath = path.resolve(workspaceLocation.path, file.file);
672
+ const relativePath = path.relative(packageLocation.path, fullPath);
673
+ return !relativePath.startsWith("..");
674
+ });
675
+ const log = await git.log({
676
+ maxCount: 1
677
+ });
678
+ const commit = !((_log_latest = log.latest) == null ? void 0 : _log_latest.hash) ? undefined : log.latest.hash.substring(0, 7);
679
+ return {
680
+ commit,
681
+ dirty,
682
+ commitDate: (_log_latest1 = log.latest) == null ? void 0 : _log_latest1.date
683
+ };
684
+ } catch (err) {
685
+ return {};
686
+ }
687
+ };
688
+
689
+ const getWorkspaceBannerText = (manifest)=>{
690
+ var _manifest_packager;
691
+ let bannerText = manifest == null ? void 0 : (_manifest_packager = manifest.packager) == null ? void 0 : _manifest_packager.banner;
692
+ if (bannerText) {
693
+ const match = bannerText.match(/Copyright \(C\) (\d+)( ?- ?(\d+))?/);
694
+ if (match !== null) {
695
+ const startYear = parseInt(match[1]);
696
+ const endYear = new Date().getFullYear();
697
+ if (startYear !== endYear) {
698
+ bannerText = bannerText.replace(match[0], `Copyright (C) ${startYear} - ${endYear}`);
699
+ } else {
700
+ bannerText = bannerText.replace(match[0], `Copyright (C) ${startYear}`);
701
+ }
702
+ }
703
+ }
704
+ return bannerText;
705
+ };
706
+
707
+ // Stolen from ig.tools.core
708
+ class PackageVersion {
709
+ static #_ = (()=>{
710
+ // https://regex101.com/r/90PEY9/1
711
+ this.fullTextMatcher = /(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?/;
712
+ })();
713
+ static #_1 = (()=>{
714
+ this.lineMatcher = /^(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?$/;
715
+ })();
716
+ static extractFromText(input, description) {
717
+ if (input === undefined) {
718
+ throw new Error(`Can not parse version from undefined`);
719
+ }
720
+ const match = input.match(PackageVersion.fullTextMatcher);
721
+ if (!match) {
722
+ throw new Error(`Could not extract a version from input: ${input}`);
723
+ }
724
+ return PackageVersion.fromMatch(match, description);
725
+ }
726
+ static extractFromLine(input, description) {
727
+ if (input === undefined) {
728
+ throw new Error(`Can not parse version from undefined`);
729
+ }
730
+ const match = input.match(PackageVersion.lineMatcher);
731
+ if (!match) {
732
+ throw new Error(`Could not parse version from input: ${input}`);
733
+ }
734
+ return PackageVersion.fromMatch(match, description);
735
+ }
736
+ static equals(a, b, checkPrerelease = false) {
737
+ if (a.major !== b.major || a.minor !== b.minor || a.patch !== b.patch) {
738
+ return false;
739
+ }
740
+ if (checkPrerelease === false) {
741
+ return true;
742
+ }
743
+ if (a.preRelease === b.preRelease) {
744
+ return true;
745
+ }
746
+ if (a.preRelease === undefined || b.preRelease === undefined) {
747
+ return false;
748
+ }
749
+ return a.preRelease.type === b.preRelease.type && a.preRelease.version === b.preRelease.version;
750
+ }
751
+ static fromMatch([, major, , minor = "0", , patch = "0", , build, , preReleaseType, preReleaseNumber], description) {
752
+ let preRelease = undefined;
753
+ let buildNumber = 100;
754
+ if (preReleaseType && preReleaseNumber) {
755
+ preRelease = {
756
+ type: preReleaseType,
757
+ version: parseInt(preReleaseNumber)
758
+ };
759
+ }
760
+ if (build) {
761
+ buildNumber = Number(build);
762
+ } else if (description) {
763
+ const descriptionMatch = description.match(/(\d+)\)$/);
764
+ if (descriptionMatch) {
765
+ buildNumber = parseInt(descriptionMatch[1]);
766
+ }
767
+ }
768
+ return new PackageVersion(parseInt(major), parseInt(minor), parseInt(patch), preRelease, buildNumber);
769
+ }
770
+ static sort(a, b, ascending = true) {
771
+ const createSortResult = (a, b)=>ascending ? a - b : b - a;
772
+ if (a.major !== b.major) {
773
+ return createSortResult(a.major, b.major);
774
+ }
775
+ if (a.minor !== b.minor) {
776
+ return createSortResult(a.minor, b.minor);
777
+ }
778
+ if (a.patch !== b.patch) {
779
+ return createSortResult(a.patch, b.patch);
780
+ }
781
+ return createSortResult(a.preRelease ? a.preRelease.version : 0, b.preRelease ? b.preRelease.version : 0);
782
+ }
783
+ static toNumber(version) {
784
+ return ((version.major * 1000 + version.minor) * 1000 + version.patch) * 1000 + version.buildNumber;
785
+ }
786
+ constructor(major, minor, patch, preRelease, buildNumber){
787
+ this.major = major;
788
+ this.minor = minor;
789
+ this.patch = patch;
790
+ this.preRelease = preRelease;
791
+ this.buildNumber = buildNumber;
792
+ }
793
+ isPreRelease() {
794
+ return this.preRelease !== undefined;
795
+ }
796
+ clone() {
797
+ return new PackageVersion(this.major, this.minor, this.patch, this.preRelease ? {
798
+ ...this.preRelease
799
+ } : undefined, this.buildNumber);
800
+ }
801
+ incrementMajor() {
802
+ this.preRelease = undefined;
803
+ this.patch = 0;
804
+ this.minor = 0;
805
+ this.major++;
806
+ }
807
+ incrementMinor() {
808
+ this.preRelease = undefined;
809
+ this.patch = 0;
810
+ this.minor++;
811
+ }
812
+ incrementPatch() {
813
+ this.preRelease = undefined;
814
+ this.patch++;
815
+ }
816
+ createPreRelease(type) {
817
+ if (!this.preRelease) {
818
+ this.buildNumber = 1;
819
+ } else {
820
+ this.buildNumber++;
821
+ }
822
+ if (this.preRelease && type === this.preRelease.type) {
823
+ this.preRelease.version++;
824
+ return;
825
+ }
826
+ this.preRelease = {
827
+ version: 0,
828
+ type
829
+ };
830
+ }
831
+ createRelease() {
832
+ this.preRelease = undefined;
833
+ this.buildNumber = 100;
834
+ }
835
+ toVersionString({ buildNumber } = {}) {
836
+ let version = [
837
+ this.major,
838
+ this.minor,
839
+ this.patch
840
+ ].join(".");
841
+ if (buildNumber) {
842
+ version += "." + this.buildNumber;
843
+ }
844
+ if (this.preRelease) {
845
+ version += `-${this.preRelease.type}.${this.preRelease.version}`;
846
+ }
847
+ return version;
848
+ }
849
+ toDescriptionString(packageName) {
850
+ const base = [
851
+ this.major,
852
+ this.minor,
853
+ this.patch
854
+ ].join(".");
855
+ const parts = [
856
+ packageName,
857
+ base
858
+ ];
859
+ if (this.preRelease) {
860
+ parts.push(upperCaseFirst(this.preRelease.type));
861
+ parts.push(this.preRelease.version);
862
+ }
863
+ parts.push(`(${base}.${this.buildNumber})`);
864
+ return parts.join(" ");
865
+ }
866
+ /**
867
+ * Determines wether the version is lesser than the input version
868
+ *
869
+ * @param {PackageVersion} version
870
+ * @returns
871
+ */ isLesserThan(version) {
872
+ return PackageVersion.toNumber(this) < PackageVersion.toNumber(version);
873
+ }
874
+ /**
875
+ * Determines wether the version is greater than the input version
876
+ *
877
+ * @param {PackageVersion} version
878
+ * @returns
879
+ */ isGreaterThan(version) {
880
+ return PackageVersion.toNumber(this) > PackageVersion.toNumber(version);
881
+ }
882
+ }
883
+ const upperCaseFirst = (input)=>{
884
+ return input.slice(0, 1).toUpperCase() + input.slice(1);
885
+ };
886
+
887
+ const parseVersionFromString = (input)=>{
888
+ if (input === undefined) {
889
+ throw new Error(`Can not parse version from undefined`);
890
+ }
891
+ let match;
892
+ let major;
893
+ let minor;
894
+ let patch;
895
+ let build;
896
+ let preReleaseType;
897
+ let preReleaseNumber;
898
+ if (// first try to find a full match with build number
899
+ (match = input.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)(-([^\.]+)\.(\d+))?/)) !== null) {
900
+ [, major, minor, patch, build, preReleaseType, preReleaseNumber] = match;
901
+ } else if ((match = input.match(/(\d+)\.(\d+)\.(\d+)(-([^\.]+)\.(\d+))?/)) !== null) {
902
+ [, major, minor, patch, , preReleaseType, preReleaseNumber] = match;
903
+ }
904
+ if (match === null) {
905
+ throw new Error(`Could not parse version from input: ${input}`);
906
+ }
907
+ let preRelease = undefined;
908
+ let buildNumber = 100;
909
+ if (preReleaseType && preReleaseNumber) {
910
+ preRelease = {
911
+ type: preReleaseType,
912
+ version: parseInt(preReleaseNumber)
913
+ };
914
+ }
915
+ if (build) {
916
+ buildNumber = Number(build);
917
+ } else if (input) {
918
+ const descriptionMatch = input.match(/(\d+)\)$/);
919
+ if (descriptionMatch) {
920
+ buildNumber = parseInt(descriptionMatch[1]);
921
+ }
922
+ }
923
+ return new PackageVersion(parseInt(major), parseInt(minor), parseInt(patch), preRelease, buildNumber);
924
+ };
925
+ // 1000001001 -> 1.0.1.1
926
+ // 1002017001 -> 1.2.17.1
927
+ const parseVersionFromNumericVersion = (version)=>{
928
+ const major = Math.floor(version / 1000000000);
929
+ const minor = Math.floor(version % 1000000000 / 1000000);
930
+ const patch = Math.floor(version % 1000000 / 1000);
931
+ const buildNumber = version % 1000;
932
+ return new PackageVersion(major, minor, patch, undefined, buildNumber);
933
+ };
934
+
935
+ // https://regex101.com/r/LtGAu5/1
936
+ const logRegex = /console\.log\(\s*"([\w\s\.\(\)]+)\ *Copyright[\w\s\(\)\.]+(\d{4}|\d{4} - \d{4})([\w\s\(\)\.]+)?",?\s*\)/i;
937
+ const currentYear = new Date(Date.now()).getFullYear();
938
+ const getVersionFileHandler = (location)=>{
939
+ const filePath = path.join(location.scriptsDir, "Version.ts");
940
+ const invalidVersionFile = (versionFile)=>({
941
+ version: undefined,
942
+ write: (name, newVersion)=>{
943
+ const scriptsContent = fs.readdirSync(location.scriptsDir);
944
+ const tsFiles = scriptsContent.filter((file)=>file.endsWith(".ts"));
945
+ if (tsFiles.length > 0) {
946
+ return createVersionFileWriter([
947
+ currentYear
948
+ ], "")(name, newVersion);
949
+ }
950
+ },
951
+ reset: ()=>{
952
+ if (versionFile !== undefined) {
953
+ fs.writeFileSync(filePath, versionFile, {
954
+ encoding: "utf8"
955
+ });
956
+ } else {
957
+ try {
958
+ fs.rmSync(filePath);
959
+ } catch (err) {
960
+ if (!isErrorENOENT(err)) {
961
+ throw err;
962
+ }
963
+ }
964
+ }
965
+ }
966
+ });
967
+ const createVersionFileWriter = (copyright = [
968
+ currentYear
969
+ ], copyrightStuff = "")=>(name, newVersion)=>{
970
+ const descriptionText = newVersion.toDescriptionString(name);
971
+ const copyrightText = createYearString(copyright);
972
+ const result = `console.log("${descriptionText}. Copyright (C) ${copyrightText}${copyrightStuff}");`;
973
+ fs.writeFileSync(filePath, result, {
974
+ encoding: "utf-8"
975
+ });
976
+ };
977
+ let rawVersionFile = readStringFromFileOrUndefined(filePath);
978
+ if (rawVersionFile === undefined) {
979
+ return invalidVersionFile(rawVersionFile);
980
+ }
981
+ const versionFile = rawVersionFile.replace(/\n/g, "");
982
+ const match = versionFile.match(logRegex);
983
+ if (!match) {
984
+ return invalidVersionFile(versionFile);
985
+ }
986
+ const [_full, _description, copyright, copyrightStuff] = match;
987
+ const copyrightYears = copyright.match(/^(\d+)( ?- ?(\d+))?$/);
988
+ let years;
989
+ if (copyrightYears === null) {
990
+ years = [
991
+ currentYear
992
+ ];
993
+ } else {
994
+ years = [
995
+ Number(copyrightYears[1]),
996
+ currentYear
997
+ ];
998
+ }
999
+ return {
1000
+ write: createVersionFileWriter(years, copyrightStuff),
1001
+ reset: ()=>{
1002
+ fs.writeFileSync(filePath, versionFile, {
1003
+ encoding: "utf8"
1004
+ });
1005
+ }
1006
+ };
1007
+ };
1008
+ const createYearString = (years)=>{
1009
+ if (years[1] === undefined || years[0] === years[1]) {
1010
+ return years[0].toString();
1011
+ }
1012
+ return `${years[0]} - ${years[1]}`;
1013
+ };
1014
+
1015
+ const buildArchiveFromPublishedPackage = (location, manifest, creatorPackage)=>{
1016
+ const archive = new JSZip();
1017
+ archive.file(PACKAGE_FILE, JSON.stringify(creatorPackage, null, 2));
1018
+ const index = readPublishedPackageCreatorIndex(location);
1019
+ if (index !== undefined) {
1020
+ archive.file(INDEX_FILE, JSON.stringify(index, null, 2));
1021
+ }
1022
+ archive.file(manifest.main, fs.createReadStream(path.join(location.path, manifest.main)));
1023
+ return archive;
1024
+ };
1025
+ let validateSchema;
1026
+ const runtimeScripts = [
1027
+ "Interactor",
1028
+ "Core",
1029
+ "Mixed"
1030
+ ];
1031
+ const notRuntimeScripts = [
1032
+ "Context",
1033
+ "Evaluator"
1034
+ ];
1035
+ const buildArchiveFromPackage = async (workspaceLocation, packageLocation, data)=>{
1036
+ const { domain , subdomain } = parseCreatorPackageName(data);
1037
+ const logStep = (step)=>logPackageMessage(data.Package, step);
1038
+ if (validateSchema === undefined) {
1039
+ validateSchema = await axios.get("https://archive.intelligentgraphics.biz/schemas/gfx/animation.json").then(({ data })=>new Ajv({
1040
+ coerceTypes: true,
1041
+ allErrors: true,
1042
+ removeAdditional: true,
1043
+ useDefaults: "empty",
1044
+ validateSchema: "log"
1045
+ }).compile(data));
1046
+ }
1047
+ const libFilePath = path.join(getWorkspaceOutputPath(workspaceLocation), `${data.Package}.min.js`);
1048
+ const scriptDirectories = [
1049
+ packageLocation.path,
1050
+ packageLocation.scriptsDir
1051
+ ];
1052
+ if (subdomain === "GFX.Standard") {
1053
+ logStep(`Including Images folder`);
1054
+ scriptDirectories.push(path.join(packageLocation.path, "Images"));
1055
+ }
1056
+ const manifest = readPackageCreatorManifest(packageLocation);
1057
+ if (manifest !== undefined) {
1058
+ if (manifest.RunTime && notRuntimeScripts.includes(manifest.Type)) {
1059
+ logStep("Setting script RunTime to false because of script type");
1060
+ writePackageCreatorManifest(packageLocation, {
1061
+ ...manifest,
1062
+ RunTime: false
1063
+ });
1064
+ } else if (!manifest.RunTime && runtimeScripts.includes(manifest.Type)) {
1065
+ logStep("Setting script RunTime to true because of script type");
1066
+ writePackageCreatorManifest(packageLocation, {
1067
+ ...manifest,
1068
+ RunTime: true
1069
+ });
1070
+ }
1071
+ }
1072
+ // if (index === undefined) {
1073
+ // throw new Error(
1074
+ // `Could not find an "${INDEX_FILE}" file in "${primaryScriptDir}"`,
1075
+ // );
1076
+ // }
1077
+ const animations = new Map();
1078
+ for (const scriptFilePath of readPackageAnimationList(packageLocation)){
1079
+ const content = fs.readFileSync(scriptFilePath, {
1080
+ encoding: "utf8"
1081
+ });
1082
+ let data;
1083
+ try {
1084
+ data = JSON.parse(content);
1085
+ } catch (err) {
1086
+ const relativePath = path.relative(workspaceLocation.path, scriptFilePath);
1087
+ if (err instanceof SyntaxError) {
1088
+ throw new Error(`Encountered invalid syntax in file "${relativePath}": ${String(err)}`);
1089
+ }
1090
+ throw new Error(`Encountered an unexpected error while parsing animation json file at path "${relativePath}"`, {
1091
+ cause: err
1092
+ });
1093
+ }
1094
+ validateSchema(data);
1095
+ animations.set(data.Id, JSON.stringify(data));
1096
+ }
1097
+ let libFile;
1098
+ try {
1099
+ libFile = fs.readFileSync(libFilePath, {
1100
+ encoding: "utf8"
1101
+ });
1102
+ } catch (err) {
1103
+ if (!isErrorENOENT(err)) {
1104
+ throw err;
1105
+ }
1106
+ }
1107
+ if (libFile === undefined) {
1108
+ if (animations.size === 0) {
1109
+ throw new Error(`Could not find a javascript file at "${libFilePath}".
1110
+ Packaging without a javascript file is only allowed when animation json files are available`);
1111
+ }
1112
+ }
1113
+ const archive = new JSZip();
1114
+ let library = "";
1115
+ if (libFile) {
1116
+ library = libFile;
1117
+ }
1118
+ if (!library) {
1119
+ const date = new Date(Date.now());
1120
+ library = `/* This file is part of the ${domain} Data Packages.
1121
+ * Copyright (C) ${date.getFullYear()} intelligentgraphics. All Rights Reserved. */`;
1122
+ }
1123
+ if (animations.size > 0) {
1124
+ const scope = data.Scope ?? data.Package;
1125
+ const scopeParts = scope.split(".");
1126
+ library += createNamespace(scopeParts);
1127
+ for (const [name, data] of animations){
1128
+ library += `${scope}["${name}"] = ` + data + ";";
1129
+ logPackageMessage(manifest.Package, `Added animation ${scope}.${name}`);
1130
+ }
1131
+ }
1132
+ const minifyResult = await terser.minify(library, {
1133
+ ecma: 5
1134
+ });
1135
+ archive.file(`${data.Package}.js`, minifyResult.code);
1136
+ archive.file(PACKAGE_FILE, JSON.stringify(data, null, 2));
1137
+ const creatorIndex = readPackageCreatorIndex(packageLocation);
1138
+ if (creatorIndex !== undefined) {
1139
+ archive.file(INDEX_FILE, JSON.stringify(creatorIndex, null, 2));
1140
+ }
1141
+ for (const directory of scriptDirectories){
1142
+ try {
1143
+ for (const file of fs.readdirSync(directory)){
1144
+ const { ext } = path.parse(file);
1145
+ switch(ext){
1146
+ case ".png":
1147
+ case ".jpeg":
1148
+ case ".jpg":
1149
+ break;
1150
+ default:
1151
+ continue;
1152
+ }
1153
+ archive.file(file, fs.createReadStream(path.join(directory, file)));
1154
+ }
1155
+ } catch (err) {
1156
+ console.error(`Script directory "${directory}" does not exist`);
1157
+ }
1158
+ }
1159
+ return archive;
1160
+ };
1161
+ const createNamespace = (parts)=>{
1162
+ let code = `var ${parts[0]};`;
1163
+ for(let index = 0; index < parts.length; index++){
1164
+ const path = parts.slice(0, index + 1).join(".");
1165
+ code += `\n(${path} = ${path} || {});`;
1166
+ }
1167
+ return code;
1168
+ };
1169
+
1170
+ const releaseFolder = async (options)=>{
1171
+ const workspace = options.workspace;
1172
+ const location = options.directory;
1173
+ const { write: writeVersionFile , reset: resetVersionFile } = getVersionFileHandler(location);
1174
+ const packageDescription = readPackageCreatorManifest(location);
1175
+ const fullPackageName = packageDescription.Package;
1176
+ const { domain , subdomain } = parseCreatorPackageName(packageDescription);
1177
+ const publishDomain = options.domain ?? domain;
1178
+ const publishSubdomain = options.subdomain ?? subdomain;
1179
+ const sharedPackageJson = readWorkspaceNpmManifest(workspace);
1180
+ let newVersion;
1181
+ try {
1182
+ newVersion = parseVersionFromString(options.newVersion);
1183
+ } catch (err) {
1184
+ throw new Error(`Please enter a version in this format 1.0.0.100`);
1185
+ }
1186
+ packageDescription.Version = newVersion.toVersionString({
1187
+ buildNumber: true
1188
+ });
1189
+ writePackageCreatorManifest(location, packageDescription);
1190
+ if (newVersion.buildNumber < 100) {
1191
+ newVersion.preRelease = {
1192
+ type: "beta",
1193
+ version: newVersion.buildNumber
1194
+ };
1195
+ } else if (newVersion.buildNumber > 100) {
1196
+ newVersion.preRelease = {
1197
+ type: "patch",
1198
+ version: newVersion.buildNumber - 100
1199
+ };
1200
+ }
1201
+ if (sharedPackageJson !== undefined) {
1202
+ logPackageMessage(packageDescription.Package, `Running npm install to make sure all dependencies are up to date`);
1203
+ execSync(`npm install`, {
1204
+ encoding: "utf-8",
1205
+ cwd: workspace.path
1206
+ });
1207
+ }
1208
+ const binDir = getWorkspaceOutputPath(workspace);
1209
+ fs.mkdirSync(binDir, {
1210
+ recursive: true
1211
+ });
1212
+ let assetServerPackageDetails;
1213
+ let packageNameWithVersion;
1214
+ {
1215
+ const versionWithoutPrelease = newVersion.clone();
1216
+ versionWithoutPrelease.preRelease = undefined;
1217
+ const newVersionString = versionWithoutPrelease.toVersionString({
1218
+ buildNumber: true
1219
+ });
1220
+ packageNameWithVersion = `${packageDescription.Package}_${newVersionString}`;
1221
+ assetServerPackageDetails = {
1222
+ name: packageDescription.Package,
1223
+ version: newVersionString
1224
+ };
1225
+ }
1226
+ const zipFilePath = path.join(binDir, packageNameWithVersion + ".zip");
1227
+ try {
1228
+ if (options.pushOnly) {
1229
+ if (!fs.existsSync(zipFilePath)) {
1230
+ throw new Error(`Expected a zip file to exist at path ${zipFilePath} since pushOnly is specified`);
1231
+ }
1232
+ } else {
1233
+ const gitVersionInformation = await getVersionInformationFromGit(workspace, location);
1234
+ writeVersionFile(fullPackageName, newVersion);
1235
+ const bannerText = sharedPackageJson !== undefined ? getWorkspaceBannerText(sharedPackageJson) : undefined;
1236
+ await buildFolders({
1237
+ ...options,
1238
+ packages: [
1239
+ location
1240
+ ],
1241
+ skipPackagesWithoutTsFiles: true,
1242
+ banner: options.banner ? {
1243
+ text: bannerText,
1244
+ commit: gitVersionInformation.commit,
1245
+ commitDirty: gitVersionInformation.dirty,
1246
+ version: newVersion.toVersionString({
1247
+ buildNumber: true
1248
+ }),
1249
+ date: new Date(Date.now())
1250
+ } : undefined
1251
+ });
1252
+ newVersion.preRelease = undefined;
1253
+ try {
1254
+ fs.rmSync(zipFilePath);
1255
+ } catch (err) {
1256
+ if (!isErrorENOENT(err)) {
1257
+ throw err;
1258
+ }
1259
+ }
1260
+ if (readPackageAnimationList(location).length > 0) {
1261
+ var _workspaceManifest_dependencies;
1262
+ const workspaceManifest = readWorkspaceNpmManifest(workspace);
1263
+ if (!((_workspaceManifest_dependencies = workspaceManifest.dependencies) == null ? void 0 : _workspaceManifest_dependencies["@intelligentgraphics/3d.ig.gfx.standard"])) {
1264
+ const install = await options.prompter.confirm(`Animation.json files expect the library 'IG.GFX.Standard' to be available, but it is not registered as a dependency. Do you want it to be added now?`);
1265
+ if (install) {
1266
+ execSync(`npm install @intelligentgraphics/3d.ig.gfx.standard`, {
1267
+ encoding: "utf-8",
1268
+ cwd: workspace.path,
1269
+ stdio: "inherit"
1270
+ });
1271
+ execSync(`npm run postinstall`, {
1272
+ cwd: workspace.path
1273
+ });
1274
+ }
1275
+ }
1276
+ }
1277
+ const archive = await buildArchiveFromPackage(workspace, location, packageDescription);
1278
+ const zipOutputStream = fs.createWriteStream(zipFilePath);
1279
+ await pipeline(archive.generateNodeStream(), zipOutputStream);
1280
+ }
1281
+ if (!options.noUpload) {
1282
+ if (!options.authentication) {
1283
+ throw new Error(`Expected authentication to be available`);
1284
+ }
1285
+ logPackageMessage(packageDescription.Package, `Opening connection to IG.Asset.Server`);
1286
+ const sessionManager = await createSessionManager({
1287
+ url: options.service,
1288
+ address: options.address,
1289
+ domain: publishDomain,
1290
+ subDomain: publishSubdomain,
1291
+ authentication: options.authentication
1292
+ });
1293
+ try {
1294
+ if (!options.skipDependencies) {
1295
+ await ensureRequiredVersions(workspace, packageDescription, sessionManager, options.prompter);
1296
+ }
1297
+ logPackageMessage(packageDescription.Package, `Uploading package to ${publishDomain}.${publishSubdomain}`);
1298
+ await uploadPackage(sessionManager.getTargetSession(), assetServerPackageDetails, zipFilePath);
1299
+ } finally{
1300
+ await sessionManager.destroy().catch((err)=>{
1301
+ logPackageMessage(packageDescription.Package, `Failed to close IG.Asset.Server session(s): ${err}`);
1302
+ });
1303
+ }
1304
+ }
1305
+ } catch (err) {
1306
+ resetVersionFile();
1307
+ throw err;
1308
+ }
1309
+ if (newVersion.buildNumber >= 100 && !options.pushOnly) {
1310
+ logPackageMessage(fullPackageName, "Copying zip to releases folder");
1311
+ const zipFileName = `${packageNameWithVersion}.zip`;
1312
+ const releasesPath = getPackageReleasesDirectory(location);
1313
+ fs.mkdirSync(releasesPath, {
1314
+ recursive: true
1315
+ });
1316
+ fs.copyFileSync(zipFilePath, path.join(releasesPath, zipFileName));
1317
+ }
1318
+ };
1319
+ const ensureRequiredVersions = async (workspaceLocation, creatorPackage, sessionManager, prompter)=>{
1320
+ const libraries = determineWorkspaceIGLibraries(workspaceLocation);
1321
+ // If there are no libraries, we don't need to check for required versions
1322
+ if (libraries.length === 0) {
1323
+ return true;
1324
+ }
1325
+ const targetSession = sessionManager.getTargetSession();
1326
+ const rawUploadedPackages = await getExistingPackages(targetSession);
1327
+ const uploadedPackages = rawUploadedPackages.map((entry)=>{
1328
+ let version;
1329
+ try {
1330
+ version = parseVersionFromNumericVersion(entry.numericVersion);
1331
+ } catch (err) {
1332
+ throw new Error(`Encountered invalid format for version ${entry.numericVersion}`);
1333
+ }
1334
+ if (version.buildNumber < 100) {
1335
+ version.preRelease = {
1336
+ type: "beta",
1337
+ version: version.buildNumber
1338
+ };
1339
+ } else if (version.buildNumber > 100) {
1340
+ version.preRelease = {
1341
+ type: "patch",
1342
+ version: version.buildNumber - 100
1343
+ };
1344
+ }
1345
+ return {
1346
+ ...entry,
1347
+ version
1348
+ };
1349
+ });
1350
+ for (const libraryLocation of libraries){
1351
+ const libraryManifest = readPublishedPackageNpmManifest(libraryLocation);
1352
+ const libraryCreatorPackage = readPublishedPackageCreatorManifest(libraryLocation);
1353
+ if (libraryCreatorPackage === undefined || libraryManifest.main === undefined || libraryCreatorPackage.Package === creatorPackage.Package) {
1354
+ continue;
1355
+ }
1356
+ const libraryVersion = PackageVersion.extractFromLine(libraryManifest.version);
1357
+ if (libraryVersion.preRelease) {
1358
+ libraryVersion.buildNumber = libraryVersion.preRelease.version;
1359
+ libraryVersion.preRelease = undefined;
1360
+ } else {
1361
+ libraryVersion.buildNumber = 100;
1362
+ }
1363
+ let uploadedPackageInBasics;
1364
+ let uploadedPackageInTarget;
1365
+ for (const uploadedPackage of uploadedPackages){
1366
+ if (uploadedPackage.scope === libraryCreatorPackage.Package) {
1367
+ if (uploadedPackage.support) {
1368
+ uploadedPackageInBasics = uploadedPackage;
1369
+ } else {
1370
+ uploadedPackageInTarget = uploadedPackage;
1371
+ }
1372
+ }
1373
+ }
1374
+ const validInBasics = uploadedPackageInBasics !== undefined && !uploadedPackageInBasics.version.isLesserThan(libraryVersion);
1375
+ const validInTarget = uploadedPackageInTarget !== undefined && !uploadedPackageInTarget.version.isLesserThan(libraryVersion);
1376
+ if (validInBasics || validInTarget) {
1377
+ if (targetSession.subDomain !== "Basics" && uploadedPackageInBasics !== undefined && uploadedPackageInTarget !== undefined) {
1378
+ logPackageMessage(creatorPackage.Package, `Package ${libraryCreatorPackage.Package} is uploaded both for Basics and ${targetSession.subDomain}. The package within ${targetSession.subDomain} will be used.`);
1379
+ }
1380
+ continue;
1381
+ }
1382
+ const possibleTargets = [];
1383
+ if (uploadedPackageInBasics) {
1384
+ const version = uploadedPackageInBasics.version.toVersionString({
1385
+ buildNumber: true
1386
+ });
1387
+ possibleTargets.push({
1388
+ value: "Basics",
1389
+ name: `Basics (Current: ${version})`
1390
+ });
1391
+ } else {
1392
+ possibleTargets.push({
1393
+ value: "Basics",
1394
+ name: "Basics (Current: None)"
1395
+ });
1396
+ }
1397
+ if (targetSession.subDomain !== "Basics") {
1398
+ if (uploadedPackageInTarget) {
1399
+ const version = uploadedPackageInTarget.version.toVersionString({
1400
+ buildNumber: true
1401
+ });
1402
+ possibleTargets.push({
1403
+ value: targetSession.subDomain,
1404
+ name: `${targetSession.subDomain} (Current: ${version})`
1405
+ });
1406
+ } else {
1407
+ possibleTargets.push({
1408
+ value: targetSession.subDomain,
1409
+ name: `${targetSession.subDomain} (Current: None)`
1410
+ });
1411
+ }
1412
+ }
1413
+ const libraryVersionString = libraryVersion.toVersionString({
1414
+ buildNumber: true
1415
+ });
1416
+ const uploadTargetScope = await prompter.ask({
1417
+ message: `Version ${libraryVersionString} of dependency ${libraryCreatorPackage.Package} is required but not available. Please select a subdomain to upload the correct dependency version to`,
1418
+ options: [
1419
+ ...possibleTargets,
1420
+ {
1421
+ name: "Skip upload",
1422
+ value: "Skip"
1423
+ }
1424
+ ],
1425
+ default: possibleTargets[0].value
1426
+ });
1427
+ if (uploadTargetScope === "Skip") {
1428
+ continue;
1429
+ }
1430
+ const archive = buildArchiveFromPublishedPackage(libraryLocation, libraryManifest, libraryCreatorPackage);
1431
+ const newVersionString = libraryVersion.toVersionString({
1432
+ buildNumber: true
1433
+ });
1434
+ const packageNameWithVersion = `${libraryCreatorPackage.Package}_${newVersionString}`;
1435
+ const zipFilePath = path.join(getWorkspaceOutputPath(workspaceLocation), `${packageNameWithVersion}.zip`);
1436
+ try {
1437
+ fs.rmSync(zipFilePath);
1438
+ } catch (err) {
1439
+ if (!isErrorENOENT(err)) {
1440
+ throw err;
1441
+ }
1442
+ }
1443
+ const zipOutputStream = fs.createWriteStream(zipFilePath);
1444
+ await pipeline(archive.generateNodeStream(), zipOutputStream);
1445
+ const session = uploadTargetScope === "Basics" ? await sessionManager.getBasicsSession() : targetSession;
1446
+ logPackageMessage(creatorPackage.Package, `Uploading package ${libraryCreatorPackage.Package} with version ${newVersionString} to ${session.domain}.${session.subDomain}`);
1447
+ await uploadPackage(session, {
1448
+ name: libraryCreatorPackage.Package,
1449
+ version: newVersionString
1450
+ }, zipFilePath);
1451
+ }
1452
+ };
1453
+ const createSessionManager = async (params)=>{
1454
+ const targetSession = await startSession(params);
1455
+ let basicsSession;
1456
+ return {
1457
+ getBasicsSession: async ()=>{
1458
+ if (targetSession.subDomain === "Basics") {
1459
+ return targetSession;
1460
+ }
1461
+ if (basicsSession === undefined) {
1462
+ basicsSession = await startSession({
1463
+ ...params,
1464
+ subDomain: "Basics"
1465
+ });
1466
+ }
1467
+ return basicsSession;
1468
+ },
1469
+ getTargetSession: ()=>targetSession,
1470
+ destroy: async ()=>{
1471
+ await closeSession(targetSession);
1472
+ if (basicsSession !== undefined) {
1473
+ await closeSession(basicsSession);
1474
+ }
1475
+ }
1476
+ };
1477
+ };
1478
+
1479
+ /**
1480
+ * Extracts and returns script array for _Index.json from a src folder
1481
+ *
1482
+ * @param folderPath path to a src folder
1483
+ */ function generateIndex({ location , ignore =[] , strictOptional =false }) {
1484
+ const files = getPackageTypescriptFiles(location);
1485
+ const filtered = files.filter((path)=>{
1486
+ return !ignore.some((suffix)=>path.endsWith(suffix));
1487
+ });
1488
+ const arr = [];
1489
+ const existingIndex = readPackageCreatorIndex(location) ?? [];
1490
+ const program = ts.createProgram(filtered, {
1491
+ allowJs: true
1492
+ });
1493
+ const typeChecker = program.getTypeChecker();
1494
+ filtered.forEach((file)=>{
1495
+ // Create a Program to represent the project, then pull out the
1496
+ // source file to parse its AST.
1497
+ const sourceFile = program.getSourceFile(file);
1498
+ // Loop through the root AST nodes of the file
1499
+ ts.forEachChild(sourceFile, (node)=>{
1500
+ for (const scriptingClass of findScriptingClasses(node)){
1501
+ if (scriptingClass.node.name === undefined) {
1502
+ throw new Error(`Expected ${scriptingClass.type} class to have a name`);
1503
+ }
1504
+ const name = typeChecker.getFullyQualifiedName(typeChecker.getSymbolAtLocation(scriptingClass.node.name));
1505
+ if (name.length > 45) {
1506
+ throw new Error(`Package name length >45 '${name}'`);
1507
+ }
1508
+ const parameterDeclaration = getScriptingClassParameterdeclaration(scriptingClass);
1509
+ const parametersType = parameterDeclaration === undefined ? undefined : typeChecker.getTypeAtLocation(parameterDeclaration);
1510
+ if (parametersType === undefined) {
1511
+ console.log(`Failed to find parameters type declaration for ${scriptingClass.type} ${name}. Skipping parameter list generation`);
1512
+ }
1513
+ const existingIndexEntry = existingIndex.find((entry)=>entry.Name === name);
1514
+ const obj = {
1515
+ Name: name,
1516
+ Description: (existingIndexEntry == null ? void 0 : existingIndexEntry.Description) ?? name,
1517
+ Type: scriptingClass.type === "evaluator" ? "Evaluator" : "Interactor",
1518
+ Parameters: []
1519
+ };
1520
+ const rawDocTags = ts.getJSDocTags(scriptingClass.node);
1521
+ const dict = getTagDict(rawDocTags);
1522
+ if (dict.summary) {
1523
+ obj.Description = dict.summary;
1524
+ } else {
1525
+ const comment = typeChecker.getTypeAtLocation(scriptingClass.node).symbol.getDocumentationComment(typeChecker).map((comment)=>comment.text).join(" ");
1526
+ if (comment) {
1527
+ obj.Description = comment;
1528
+ }
1529
+ }
1530
+ if (parametersType !== undefined) {
1531
+ obj.Parameters = parseParametersList(typeChecker.getPropertiesOfType(parametersType), strictOptional);
1532
+ if (obj.Parameters.length === 0 && parametersType.getStringIndexType() !== undefined) {
1533
+ obj.Parameters = (existingIndexEntry == null ? void 0 : existingIndexEntry.Parameters) ?? [];
1534
+ }
1535
+ } else if (existingIndexEntry !== undefined) {
1536
+ obj.Parameters = existingIndexEntry.Parameters;
1537
+ }
1538
+ arr.push(obj);
1539
+ }
1540
+ });
1541
+ });
1542
+ arr.sort((a, b)=>a.Name.localeCompare(b.Name));
1543
+ writePackageCreatorIndex(location, arr);
1544
+ }
1545
+ function capitalizeFirstLetter(string) {
1546
+ return (string == null ? void 0 : string.charAt(0).toUpperCase()) + (string == null ? void 0 : string.slice(1));
1547
+ }
1548
+ const parseDefault = (value, type)=>{
1549
+ const uType = capitalizeFirstLetter(type);
1550
+ if (value === "null") return null;
1551
+ switch(uType){
1552
+ case "LengthM":
1553
+ case "ArcDEG":
1554
+ case "Float":
1555
+ return parseFloat(value);
1556
+ case "Integer":
1557
+ case "Int":
1558
+ return parseInt(value);
1559
+ case "Boolean":
1560
+ case "Bool":
1561
+ return value === "true";
1562
+ case "Material":
1563
+ case "String":
1564
+ case "Geometry":
1565
+ default:
1566
+ return value.replace(/^"/, "").replace(/"$/, "");
1567
+ }
1568
+ };
1569
+ const parseTypeFromName = (name)=>{
1570
+ const parts = name.split(".");
1571
+ const identifier = parts[parts.length - 1];
1572
+ switch(identifier){
1573
+ case "LengthM":
1574
+ case "ArcDEG":
1575
+ case "Float":
1576
+ case "Integer":
1577
+ return identifier;
1578
+ case "GeometryReference":
1579
+ return "Geometry";
1580
+ case "MaterialReference":
1581
+ return "Material";
1582
+ case "AnimationReference":
1583
+ return "Animation";
1584
+ case "InteractorReference":
1585
+ return "Interactor";
1586
+ case "EvaluatorReference":
1587
+ return "Evaluator";
1588
+ case "String":
1589
+ case "string":
1590
+ return "String";
1591
+ case "number":
1592
+ case "Number":
1593
+ return "Float";
1594
+ case "boolean":
1595
+ case "Boolean":
1596
+ return "Boolean";
1597
+ }
1598
+ };
1599
+ const parseParametersList = (properties, strictOptional)=>{
1600
+ return properties.map((symbol, i)=>{
1601
+ var _symbol_getDeclarations;
1602
+ const parameter = {
1603
+ Name: symbol.name,
1604
+ Description: undefined,
1605
+ Type: "String",
1606
+ Default: undefined,
1607
+ DisplayIndex: i + 1
1608
+ };
1609
+ if (parameter.Name.length > 45) {
1610
+ throw new Error(`Parameter name length >45 '${parameter.Name}'`);
1611
+ }
1612
+ let declaration = (_symbol_getDeclarations = symbol.getDeclarations()) == null ? void 0 : _symbol_getDeclarations[0];
1613
+ let documentationComment = symbol.getDocumentationComment(undefined);
1614
+ let checkLinksSymbol = symbol;
1615
+ while(checkLinksSymbol !== undefined && declaration === undefined){
1616
+ const links = checkLinksSymbol.links;
1617
+ if (links == null ? void 0 : links.syntheticOrigin) {
1618
+ var _links_syntheticOrigin_getDeclarations;
1619
+ declaration = (_links_syntheticOrigin_getDeclarations = links.syntheticOrigin.getDeclarations()) == null ? void 0 : _links_syntheticOrigin_getDeclarations[0];
1620
+ if (documentationComment.length === 0) {
1621
+ documentationComment = links.syntheticOrigin.getDocumentationComment(undefined);
1622
+ }
1623
+ checkLinksSymbol = links.syntheticOrigin;
1624
+ }
1625
+ }
1626
+ if (declaration !== undefined) {
1627
+ const rawDocTags = ts.getJSDocTags(declaration);
1628
+ const dict = getTagDict(rawDocTags);
1629
+ if (dict.summary) {
1630
+ parameter.Description = dict.summary;
1631
+ } else {
1632
+ const comment = documentationComment.map((comment)=>comment.text).join(" ");
1633
+ if (comment) {
1634
+ parameter.Description = comment;
1635
+ }
1636
+ }
1637
+ if (dict.creatorType) {
1638
+ parameter.Type = dict.creatorType;
1639
+ } else {
1640
+ const propertySignature = declaration;
1641
+ if (propertySignature.type !== undefined) {
1642
+ const parsedType = parseTypeFromName(propertySignature.type.getText());
1643
+ if (parsedType !== undefined) {
1644
+ parameter.Type = parsedType;
1645
+ }
1646
+ }
1647
+ }
1648
+ if (dict.default) {
1649
+ parameter.Default = parseDefault(dict.default, parameter.Type);
1650
+ }
1651
+ if (strictOptional && declaration.kind === ts.SyntaxKind.PropertySignature) {
1652
+ const propertySignature = declaration;
1653
+ if (propertySignature.questionToken === undefined) {
1654
+ parameter.Required = true;
1655
+ }
1656
+ }
1657
+ }
1658
+ return parameter;
1659
+ });
1660
+ };
1661
+ function getTagDict(tags) {
1662
+ const dict = {};
1663
+ for (const tag of tags){
1664
+ dict[tag.tagName.text] = tag.comment;
1665
+ }
1666
+ return dict;
1667
+ }
1668
+ const getScriptingClassParameterdeclaration = (scriptingClass)=>{
1669
+ for (const member of scriptingClass.node.members){
1670
+ if (ts.isMethodDeclaration(member)) {
1671
+ for(let index = 0; index < member.parameters.length; index++){
1672
+ const parameter = member.parameters[index];
1673
+ if (isScriptingClassParameterDeclaration(scriptingClass, member, index)) {
1674
+ return parameter;
1675
+ }
1676
+ }
1677
+ }
1678
+ if (ts.isConstructorDeclaration(member)) {
1679
+ for(let index = 0; index < member.parameters.length; index++){
1680
+ const parameter = member.parameters[index];
1681
+ if (isScriptingClassParameterDeclaration(scriptingClass, member, index)) {
1682
+ return parameter;
1683
+ }
1684
+ }
1685
+ }
1686
+ }
1687
+ };
1688
+ const isScriptingClassParameterDeclaration = (scriptingClass, memberNode, parameterIndex)=>{
1689
+ if (scriptingClass.type === "evaluator") {
1690
+ var _memberNode_name;
1691
+ return (memberNode == null ? void 0 : (_memberNode_name = memberNode.name) == null ? void 0 : _memberNode_name.getText()) == "Create" && parameterIndex === 2;
1692
+ }
1693
+ if (scriptingClass.type === "interactor") {
1694
+ return memberNode.kind === ts.SyntaxKind.Constructor && parameterIndex === 0;
1695
+ }
1696
+ return false;
1697
+ };
1698
+ /**
1699
+ * Finds interactors and evaluators within a script file
1700
+ *
1701
+ * @param {ts.Node} node
1702
+ * @return {*}
1703
+ */ const findScriptingClasses = (node)=>{
1704
+ let body;
1705
+ if (ts.isModuleDeclaration(node)) {
1706
+ body = node.body;
1707
+ }
1708
+ if (body !== undefined && ts.isModuleDeclaration(body)) {
1709
+ body = body.body;
1710
+ }
1711
+ const classes = [];
1712
+ if (body !== undefined) {
1713
+ ts.forEachChild(body, (child)=>{
1714
+ if (!ts.isClassDeclaration(child)) {
1715
+ return;
1716
+ }
1717
+ const scriptingClass = detectScriptingClass(child);
1718
+ if (scriptingClass !== undefined) {
1719
+ classes.push(scriptingClass);
1720
+ }
1721
+ });
1722
+ }
1723
+ return classes;
1724
+ };
1725
+ const detectScriptingClass = (node)=>{
1726
+ var _node_heritageClauses, _node_heritageClauses1;
1727
+ const isEvaluator = (_node_heritageClauses = node.heritageClauses) == null ? void 0 : _node_heritageClauses.some((clause)=>{
1728
+ if (clause.token !== ts.SyntaxKind.ExtendsKeyword && clause.token !== ts.SyntaxKind.ImplementsKeyword) {
1729
+ return false;
1730
+ }
1731
+ return clause.types.some((type)=>type.getText().includes("Evaluator"));
1732
+ });
1733
+ if (isEvaluator) {
1734
+ return {
1735
+ node,
1736
+ type: "evaluator"
1737
+ };
1738
+ }
1739
+ const isInteractor = (_node_heritageClauses1 = node.heritageClauses) == null ? void 0 : _node_heritageClauses1.some((clause)=>{
1740
+ if (clause.token !== ts.SyntaxKind.ExtendsKeyword) {
1741
+ return false;
1742
+ }
1743
+ return clause.types.some((type)=>type.getText().includes("Interactor"));
1744
+ });
1745
+ if (isInteractor) {
1746
+ return {
1747
+ node,
1748
+ type: "interactor"
1749
+ };
1750
+ }
1751
+ };
1752
+
1753
+ export { buildFolders, generateIndex, releaseFolder };
1754
+ //# sourceMappingURL=lib.mjs.map