lincd-cli 1.1.9 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/defaults/app-static/.env-cmdrc.json +17 -0
  2. package/defaults/app-static/package.json +8 -0
  3. package/defaults/app-static/src/index-static.tsx +3 -3
  4. package/defaults/app-with-backend/.env-cmdrc.json +1 -4
  5. package/defaults/app-with-backend/package.json +8 -9
  6. package/defaults/app-with-backend/scripts/storage-config.js +2 -2
  7. package/defaults/app-with-backend/src/package.ts +1 -2
  8. package/defaults/component.tsx +1 -3
  9. package/defaults/package/package.json +2 -2
  10. package/defaults/package/src/index.ts +1 -0
  11. package/defaults/package/src/ontologies/example-ontology.ts +10 -3
  12. package/defaults/package/src/package.ts +11 -3
  13. package/defaults/package/src/types.d.ts +9 -0
  14. package/defaults/package/tsconfig-cjs.json +8 -0
  15. package/defaults/package/tsconfig-esm.json +9 -0
  16. package/defaults/set-component.tsx +2 -5
  17. package/defaults/shape.ts +2 -2
  18. package/lib/{cli-methods.js → cjs/cli-methods.js} +665 -291
  19. package/lib/cjs/cli-methods.js.map +1 -0
  20. package/lib/cjs/cli.js +202 -0
  21. package/lib/cjs/cli.js.map +1 -0
  22. package/lib/{config-grunt.js → cjs/config-grunt.cjs} +15 -13
  23. package/lib/cjs/config-grunt.cjs.map +1 -0
  24. package/lib/cjs/config-webpack-app.js +353 -0
  25. package/lib/cjs/config-webpack-app.js.map +1 -0
  26. package/lib/cjs/config-webpack.js +436 -0
  27. package/lib/cjs/config-webpack.js.map +1 -0
  28. package/lib/{index.js → cjs/index.js} +3 -5
  29. package/lib/cjs/index.js.map +1 -0
  30. package/lib/{interfaces.js.map → cjs/interfaces.js.map} +1 -1
  31. package/lib/cjs/loaders/css-loader.mjs +82 -0
  32. package/lib/cjs/loaders/css-loader.mjs.map +1 -0
  33. package/lib/cjs/loaders/register.js +6 -0
  34. package/lib/cjs/loaders/register.js.map +1 -0
  35. package/lib/cjs/metadata.js +155 -0
  36. package/lib/cjs/metadata.js.map +1 -0
  37. package/lib/cjs/package.json +140 -0
  38. package/lib/cjs/plugins/check-imports.js.map +1 -0
  39. package/lib/cjs/plugins/declaration-plugin.js +275 -0
  40. package/lib/cjs/plugins/declaration-plugin.js.map +1 -0
  41. package/lib/cjs/plugins/externalise-modules.js +190 -0
  42. package/lib/cjs/plugins/externalise-modules.js.map +1 -0
  43. package/lib/cjs/plugins/watch-run.js.map +1 -0
  44. package/lib/{utils.js → cjs/utils.js} +23 -18
  45. package/lib/cjs/utils.js.map +1 -0
  46. package/lib/esm/cli-methods.js +1966 -0
  47. package/lib/esm/cli-methods.js.map +1 -0
  48. package/lib/{cli.js → esm/cli.js} +59 -44
  49. package/lib/esm/cli.js.map +1 -0
  50. package/lib/esm/config-grunt.cjs +270 -0
  51. package/lib/esm/config-grunt.cjs.map +1 -0
  52. package/lib/esm/config-webpack-app.js +326 -0
  53. package/lib/esm/config-webpack-app.js.map +1 -0
  54. package/lib/{config-webpack.js → esm/config-webpack.js} +27 -39
  55. package/lib/esm/config-webpack.js.map +1 -0
  56. package/lib/esm/index.js +9 -0
  57. package/lib/esm/index.js.map +1 -0
  58. package/lib/esm/interfaces.js +2 -0
  59. package/lib/esm/interfaces.js.map +1 -0
  60. package/lib/esm/loaders/css-loader.mjs +75 -0
  61. package/lib/esm/loaders/css-loader.mjs.map +1 -0
  62. package/lib/esm/loaders/register.js +4 -0
  63. package/lib/esm/loaders/register.js.map +1 -0
  64. package/lib/esm/metadata.js +155 -0
  65. package/lib/esm/metadata.js.map +1 -0
  66. package/lib/esm/package.json +140 -0
  67. package/lib/esm/plugins/check-imports.js +65 -0
  68. package/lib/esm/plugins/check-imports.js.map +1 -0
  69. package/lib/{plugins → esm/plugins}/declaration-plugin.js +9 -8
  70. package/lib/esm/plugins/declaration-plugin.js.map +1 -0
  71. package/lib/{plugins → esm/plugins}/externalise-modules.js +5 -6
  72. package/lib/esm/plugins/externalise-modules.js.map +1 -0
  73. package/lib/esm/plugins/watch-run.js +44 -0
  74. package/lib/esm/plugins/watch-run.js.map +1 -0
  75. package/lib/esm/utils.js +479 -0
  76. package/lib/esm/utils.js.map +1 -0
  77. package/package.json +53 -15
  78. package/tsconfig-cjs.json +9 -0
  79. package/tsconfig-esm.json +10 -0
  80. package/lib/cli-methods.js.map +0 -1
  81. package/lib/cli.js.map +0 -1
  82. package/lib/config-grunt.js.map +0 -1
  83. package/lib/config-webpack-app.js +0 -367
  84. package/lib/config-webpack-app.js.map +0 -1
  85. package/lib/config-webpack.js.map +0 -1
  86. package/lib/index.js.map +0 -1
  87. package/lib/metadata.js +0 -149
  88. package/lib/metadata.js.map +0 -1
  89. package/lib/plugins/check-imports.js.map +0 -1
  90. package/lib/plugins/declaration-plugin.js.map +0 -1
  91. package/lib/plugins/externalise-modules.js.map +0 -1
  92. package/lib/plugins/watch-run.js.map +0 -1
  93. package/lib/utils.js.map +0 -1
  94. /package/{expose-grunt.js → expose-grunt.cjs} +0 -0
  95. /package/lib/{interfaces.js → cjs/interfaces.js} +0 -0
  96. /package/lib/{plugins → cjs/plugins}/check-imports.js +0 -0
  97. /package/lib/{plugins → cjs/plugins}/watch-run.js +0 -0
@@ -0,0 +1,1966 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import chalk from 'chalk';
11
+ import { exec } from 'child_process';
12
+ import depcheck from 'depcheck';
13
+ import { getEnvFile } from 'env-cmd/dist/get-env-vars.js';
14
+ import fs from 'fs-extra';
15
+ import path, { dirname } from 'path';
16
+ import { debugInfo, execp, execPromise, getFileImports, getFiles, getLastCommitTime, getPackageJSON, isValidLINCDImport, needsRebuilding, } from './utils.js';
17
+ import { statSync } from 'fs';
18
+ import { findNearestPackageJson } from 'find-nearest-package-json';
19
+ import { LinkedFileStorage } from 'lincd/utils/LinkedFileStorage';
20
+ // import pkg from 'lincd/utils/LinkedFileStorage';
21
+ // const { LinkedFileStorage } = pkg;
22
+ // const config = require('lincd-server/site.webpack.config');
23
+ import { glob } from 'glob';
24
+ import webpack from 'webpack';
25
+ import stagedGitFiles from 'staged-git-files';
26
+ import ora from 'ora';
27
+ var variables = {};
28
+ export const createApp = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
29
+ if (!name) {
30
+ console.warn('Please provide a name as the first argument');
31
+ }
32
+ let { hyphenName, camelCaseName, underscoreName } = setNameVariables(name);
33
+ let targetFolder = path.join(basePath, hyphenName);
34
+ if (!fs.existsSync(targetFolder)) {
35
+ fs.mkdirSync(targetFolder);
36
+ }
37
+ fs.copySync(path.join(__dirname, '..', 'defaults', 'app-with-backend'), targetFolder);
38
+ //make sure the data folder exists (even though its empty).. copying empty folders does not work with fs.copySync
39
+ fs.mkdirSync(path.join(targetFolder, 'data'), { recursive: true });
40
+ fs.mkdirSync(path.join(targetFolder, 'data/uploads/resized'), {
41
+ recursive: true,
42
+ });
43
+ fs.renameSync(path.join(targetFolder, 'gitignore.template'), path.join(targetFolder, '.gitignore'));
44
+ fs.renameSync(path.join(targetFolder, 'yarnrc.yml.template'), path.join(targetFolder, '.yarnrc.yml'));
45
+ // fs.copySync(path.join(__dirname, '..', 'defaults', 'app'), targetFolder);
46
+ log('Creating new LINCD application \'' + name + '\'');
47
+ //replace variables in some copied files
48
+ yield replaceVariablesInFolder(targetFolder);
49
+ let hasYarn = yield hasYarnInstalled();
50
+ let installCommand = hasYarn
51
+ ? 'export NODE_OPTIONS="--no-network-family-autoselection" && yarn install'
52
+ : 'npm install';
53
+ yield execp(`cd ${hyphenName} && ${installCommand}`, true).catch((err) => {
54
+ console.warn('Could not install dependencies or start application');
55
+ });
56
+ log(`Your LINCD App is ready at ${chalk.blueBright(targetFolder)}`, `To start, run\n${chalk.blueBright(`cd ${hyphenName}`)} and then ${chalk.blueBright((hasYarn ? 'yarn' : 'npm') + ' start')}`);
57
+ });
58
+ function logHelp() {
59
+ execp('yarn exec lincd help');
60
+ }
61
+ function log(...messages) {
62
+ messages.forEach((message) => {
63
+ console.log(chalk.cyan('Info: ') + message);
64
+ });
65
+ }
66
+ function progressUpdate(message) {
67
+ process.stdout.write(' \r');
68
+ process.stdout.write(message + '\r');
69
+ }
70
+ export function warn(...messages) {
71
+ messages.forEach((message) => {
72
+ console.log(chalk.redBright('Warning: ') + message);
73
+ // console.log(chalk.red(message));
74
+ });
75
+ }
76
+ export function developPackage(target, mode) {
77
+ if (!target)
78
+ target = 'es6';
79
+ if (mode !== 'production')
80
+ mode = '';
81
+ else if (target !== 'es6')
82
+ log('target must be es6 when developing for production');
83
+ if (target == 'es5' || target == 'es6') {
84
+ // log('> Starting continuous development build for '+target+' target')
85
+ log('starting continuous development build');
86
+ log('grunt dev' +
87
+ (target ? '-' + target : '') +
88
+ (mode ? '-' + mode : '') +
89
+ ' --color');
90
+ var command = exec('grunt dev' +
91
+ (target ? '-' + target : '') +
92
+ (mode ? '-' + mode : '') +
93
+ ' --color');
94
+ command.stdout.pipe(process.stdout);
95
+ command.stderr.pipe(process.stderr);
96
+ }
97
+ else {
98
+ console.warn('unknown build target. Use es5 or es6');
99
+ }
100
+ }
101
+ function checkWorkspaces(rootPath, workspaces, res) {
102
+ // console.log('checking workspaces at '+rootPath+": "+workspaces.toString());
103
+ if (workspaces.packages) {
104
+ workspaces = workspaces.packages;
105
+ }
106
+ workspaces.forEach((workspace) => {
107
+ let workspacePath = path.join(rootPath, workspace.replace('/*', ''));
108
+ if (workspace.indexOf('/*') !== -1) {
109
+ // console.log(workspacePath);
110
+ if (fs.existsSync(workspacePath)) {
111
+ let folders = fs.readdirSync(workspacePath);
112
+ folders.forEach((folder) => {
113
+ if (folder !== './' && folder !== '../') {
114
+ checkPackagePath(rootPath, path.join(workspacePath, folder), res);
115
+ }
116
+ });
117
+ }
118
+ }
119
+ else {
120
+ checkPackagePath(rootPath, workspacePath, res);
121
+ }
122
+ });
123
+ }
124
+ function checkPackagePath(rootPath, packagePath, res) {
125
+ let packageJsonPath = path.join(packagePath, 'package.json');
126
+ // console.log('checking '+packagePath);
127
+ if (fs.existsSync(packageJsonPath)) {
128
+ var pack = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
129
+ //some packages are not true lincd packages, but we still want them to be re-built automatically. This is what lincd_util is for
130
+ if (pack && pack.workspaces) {
131
+ checkWorkspaces(packagePath, pack.workspaces, res);
132
+ }
133
+ else if (pack && pack.lincd === true) {
134
+ res.push({
135
+ path: packagePath,
136
+ packageName: pack.name,
137
+ });
138
+ }
139
+ }
140
+ }
141
+ function runOnPackagesGroupedByDependencies(lincdPackages, onBuildStack, onStackEnd, sync = false) {
142
+ let dependencies = new Map();
143
+ //get dependencies of each package
144
+ let leastDependentPackage;
145
+ lincdPackages.forEach((pkg) => {
146
+ var pack = getPackageJSON(pkg.path);
147
+ if (pack) {
148
+ //get lincd related dependencies and get the actual package details from the package map by removing '@dacore/' from the package name
149
+ let packageDependencies = Object.keys(pack.dependencies)
150
+ .filter((dependency) => lincdPackages.has(dependency))
151
+ .map((dependency) => {
152
+ return lincdPackages.has(dependency)
153
+ ? lincdPackages.get(dependency)
154
+ : dependency;
155
+ });
156
+ // console.log(package.packageName,packageDependencies.map())
157
+ dependencies.set(pkg, packageDependencies);
158
+ }
159
+ });
160
+ dependencies.forEach((PackageDependencies, pkg) => {
161
+ if (!PackageDependencies.some((dependency) => {
162
+ return (typeof dependency !== 'string' &&
163
+ lincdPackages.has(dependency.packageName));
164
+ })) {
165
+ leastDependentPackage = pkg;
166
+ }
167
+ });
168
+ let startStack = [leastDependentPackage];
169
+ const runPackage = (runFunction, pck) => {
170
+ return runFunction(pck)
171
+ .catch((errorObj) => {
172
+ if (errorObj.error) {
173
+ let { error, stdout, stderr } = errorObj;
174
+ warn('Uncaught exception whilst running parallel function on ' +
175
+ pck.packageName, (error === null || error === void 0 ? void 0 : error.message) ? error.message : error === null || error === void 0 ? void 0 : error.toString());
176
+ }
177
+ else {
178
+ warn('Uncaught exception whilst running parallel function on ' +
179
+ pck.packageName, errorObj === null || errorObj === void 0 ? void 0 : errorObj.toString());
180
+ process.exit();
181
+ }
182
+ // warn(chalk.red(pck.packageName+' failed:'));
183
+ // console.log(stdout);
184
+ })
185
+ .then((res) => {
186
+ done.add(pck);
187
+ return res;
188
+ });
189
+ };
190
+ let done = new Set();
191
+ let results = [];
192
+ let runStack = (stack) => __awaiter(this, void 0, void 0, function* () {
193
+ let runFunction = onBuildStack(stack, dependencies);
194
+ let stackPromise;
195
+ if (sync) {
196
+ //build the stack in parallel
197
+ stackPromise = Promise.resolve(true);
198
+ stack.forEach((pck) => {
199
+ stackPromise = stackPromise.then(() => {
200
+ return runPackage(runFunction, pck);
201
+ });
202
+ });
203
+ }
204
+ else {
205
+ //build the stack in parallel
206
+ stackPromise = Promise.all(stack.map((pck) => {
207
+ return runPackage(runFunction, pck);
208
+ }));
209
+ }
210
+ //wait till stack is completed
211
+ let stackResults = yield stackPromise;
212
+ results = results.concat(stackResults);
213
+ //clear stack for next round
214
+ stack = [];
215
+ //find those packages who have all their dependencies already built and add them to the stack
216
+ lincdPackages.forEach((pkg) => {
217
+ let deps = dependencies.get(pkg);
218
+ //if the package is not done yet
219
+ //but every dependency is now done OR was not something we can build (some @dacore dependencies may not be local)
220
+ if (!done.has(pkg) &&
221
+ deps.every((dependency) => {
222
+ return (typeof dependency !== 'string' &&
223
+ (done.has(dependency) || !lincdPackages.has(dependency.packageName)));
224
+ })) {
225
+ stack.push(pkg);
226
+ }
227
+ });
228
+ if (stack.length <= 0 && done.size < lincdPackages.size) {
229
+ console.log(chalk.red('Only ' +
230
+ done.size +
231
+ ' out of ' +
232
+ lincdPackages.size +
233
+ ' packages have been built'));
234
+ console.log('ALL remaining packages have dependencies that have not been met. This may point to ' +
235
+ chalk.red('circular dependencies.'));
236
+ console.log('Already built: ' +
237
+ Array.from(done)
238
+ .map((p) => chalk.green(p.packageName))
239
+ .join(', '));
240
+ console.log(chalk.blue('\nTo solve this issue') +
241
+ ': find the circular dependencies below and fix the dependencies:\n\n');
242
+ //TODO: actually find and name the packages that have circular dependencies
243
+ // let circular = [];
244
+ // lincdPackages.forEach((pkg) => {
245
+ // if (!done.has(pkg))
246
+ // {
247
+ // let deps = dependencies.get(pkg);
248
+ // if (deps.some(dependency => {
249
+ // //return true if this dependency (indirectly) depends on the package whos' dependency it is
250
+ // return hasDependency(dependency,pkg,dependencies)
251
+ // }))
252
+ // {
253
+ // circular.push(pkg);
254
+ // }
255
+ // process.exit();
256
+ // }
257
+ // });
258
+ lincdPackages.forEach((pkg) => {
259
+ let deps = dependencies.get(pkg);
260
+ if (!done.has(pkg)) {
261
+ console.log(chalk.red(pkg.packageName) +
262
+ ' has not been built yet. Unbuilt dependencies:\n' +
263
+ deps
264
+ .filter((dependency) => {
265
+ return !Array.from(done).some((p) => {
266
+ // console.log(p.packageName,dependency.packageName,p===dependency)
267
+ return p === dependency;
268
+ });
269
+ })
270
+ .map((p) => chalk.red('\t- ' +
271
+ ((p === null || p === void 0 ? void 0 : p.packageName) ? p.packageName : p.toString()) +
272
+ '\n'))
273
+ .join(' '));
274
+ // console.log(chalk.red(pkg.packageName)+' has not been built yet. Built dependencies:\n' + deps.filter(dependency => {
275
+ // return Array.from(done).some(p => p.packageName === pkg.packageName)
276
+ // }).map(p => chalk.green('\t- '+p.packageName+'\n')).join(" "))
277
+ // console.log(chalk.red(pkg.packageName)+' has not been built yet. Built dependencies:\n' + deps.filter(dependency => done.has(pkg)).map(p => chalk.green('\t- '+p.packageName+'\n')).join(" "))
278
+ }
279
+ });
280
+ }
281
+ //if more to be built, iterate
282
+ if (stack.length > 0) {
283
+ return runStack(stack);
284
+ }
285
+ else {
286
+ onStackEnd(dependencies, results.filter(Boolean));
287
+ }
288
+ });
289
+ //starts the process
290
+ runStack(startStack);
291
+ }
292
+ function hasDependency(pkg, childPkg, dependencies, depth = 1) {
293
+ console.log('Does ' + pkg.packageName + ' have dep ' + childPkg.packageName + ' ?');
294
+ let deps = dependencies.get(pkg);
295
+ if (deps.some((dependency) => {
296
+ console.log(dependency.packageName, childPkg.packageName, dependency === childPkg);
297
+ if (depth === 2)
298
+ return false;
299
+ // return dependency === childPkg;
300
+ return (dependency === childPkg ||
301
+ hasDependency(dependency, childPkg, dependencies, depth++));
302
+ })) {
303
+ console.log('##YES');
304
+ return true;
305
+ }
306
+ console.log('going up');
307
+ return false;
308
+ }
309
+ export function buildAll(options) {
310
+ console.log('Building all LINCD packages of this repository in order of dependencies');
311
+ let lincdPackages = getLocalLincdPackageMap();
312
+ let startFrom;
313
+ //by default start building
314
+ let building = true;
315
+ let from = options === null || options === void 0 ? void 0 : options.from;
316
+ let sync = (options === null || options === void 0 ? void 0 : options.sync) || false;
317
+ // console.log('from', from);
318
+ // console.log('sync', sync);
319
+ // process.exit();
320
+ //option to start from a specific package in the stack
321
+ if (from) {
322
+ startFrom = from;
323
+ //if we have a startFrom, then we havnt started the build process yet
324
+ building = startFrom ? false : true;
325
+ //clear targets
326
+ // target = '';
327
+ // target2 = '';
328
+ console.log(chalk.blue('Will skip builds until ' + startFrom));
329
+ // return async (pkg) => {};
330
+ }
331
+ // if (target2 == 'from') {
332
+ // startFrom = target3;
333
+ // //if we have a startFrom, then we havnt started the build process yet
334
+ // building = startFrom ? false : true;
335
+ //
336
+ // //clear targets
337
+ // target2 = '';
338
+ // target3 = '';
339
+ // console.log(chalk.blue('Will skip builds until ' + startFrom));
340
+ //
341
+ // // return async (pkg) => {};
342
+ // }
343
+ let done = new Set();
344
+ let failedModules = [];
345
+ progressUpdate(lincdPackages.size + ' packages left');
346
+ let packagesLeft = lincdPackages.size;
347
+ // let packagesLeft = lincdPackages.size - done.size;
348
+ runOnPackagesGroupedByDependencies(lincdPackages, (packageGroup, dependencies) => {
349
+ if (done.size > 0) {
350
+ debugInfo(chalk.magenta('\n-------\nThese packages are next, since all their dependencies have now been build:'));
351
+ // log(stack);
352
+ }
353
+ debugInfo('Now building: ' + chalk.blue(packageGroup.map((i) => i.packageName)));
354
+ return (pkg) => __awaiter(this, void 0, void 0, function* () {
355
+ let command;
356
+ let skipping = false;
357
+ //if we're skipping builds until a certain package
358
+ if (!building) {
359
+ //if the package name matches the package we're supposed to start from then start building packages
360
+ if (pkg.packageName == startFrom || pkg.packageName == startFrom) {
361
+ building = true;
362
+ }
363
+ //else still waiting for the package
364
+ else {
365
+ log(chalk.blue('skipping ' + pkg.packageName));
366
+ command = Promise.resolve(true);
367
+ skipping = true;
368
+ }
369
+ }
370
+ //unless told otherwise, build the package
371
+ if (!command) {
372
+ command = buildPackage(null, null, path.join(process.cwd(), pkg.path), false);
373
+ // command = execPromise(
374
+ // 'cd ' + pkg.path + ' && yarn exec lincd build',
375
+ // // (target ? ' ' + target : '') +
376
+ // // (target2 ? ' ' + target2 : ''),
377
+ // false,
378
+ // false,
379
+ // {},
380
+ // false,
381
+ // );
382
+ log(chalk.cyan('Building ' + pkg.packageName));
383
+ process.stdout.write(packagesLeft + ' packages left\r');
384
+ }
385
+ return command.then(res => {
386
+ //empty string or true is success
387
+ //false is success with warnings
388
+ //any other string is the build error text
389
+ //undefined result means it failed
390
+ // if (res !== '' && res !== true && res !== false) {
391
+ if (typeof res === 'undefined') {
392
+ failedModules.push(pkg.packageName);
393
+ let dependentModules = getDependentPackages(dependencies, pkg);
394
+ if (dependentModules.length > 0) {
395
+ printBuildResults(failedModules, done);
396
+ console.log('Stopping build process because an error occurred whilst building ' +
397
+ pkg.packageName +
398
+ ', which ' +
399
+ dependentModules.length +
400
+ ' other packages depend on.'); //"+dependentModules.map(d => d.packageName).join(", ")));
401
+ log('Run ' +
402
+ chalk.greenBright(`lincd build-all --from=${pkg.packageName}`) +
403
+ ' to build only the remaining packages'); //"+dependentModules.map(d => d.packageName).join(", ")));
404
+ process.exit(1);
405
+ }
406
+ }
407
+ else {
408
+ if (!skipping) {
409
+ log(chalk.green('Built ' + pkg.packageName) + (res === false ? chalk.redBright(' (with warnings)') : ''));
410
+ }
411
+ done.add(pkg);
412
+ packagesLeft--;
413
+ // log(chalk.magenta(packagesLeft + ' packages left'));
414
+ process.stdout.write(packagesLeft + ' packages left\r');
415
+ if (packagesLeft == 0) {
416
+ printBuildResults(failedModules, done);
417
+ if (failedModules.length > 0) {
418
+ process.exit(1);
419
+ }
420
+ }
421
+ return res;
422
+ }
423
+ })
424
+ .catch(({ error, stdout, stderr }) => {
425
+ warn(chalk.red('Failed to build ' + pkg.packageName));
426
+ console.log(stdout);
427
+ process.exit(1);
428
+ // let dependentModules = getDependentP
429
+ });
430
+ //undefined result means it failed
431
+ /*if (typeof res === 'undefined')
432
+ {
433
+ // .catch(({ error,stdout,stderr }) => {
434
+ //this prints out the webpack output, including the build errors
435
+ // warn('Failed to build ' + pkg.packageName);
436
+ // console.log(stdout);
437
+ failedModules.push(pkg.packageName);
438
+ let dependentModules = getDependentPackages(dependencies,pkg);
439
+ if (dependentModules.length > 0)
440
+ {
441
+ printBuildResults(failedModules,done);
442
+ console.log(
443
+ 'Stopping build process because an error occurred whilst building ' +
444
+ pkg.packageName +
445
+ ', which ' +
446
+ dependentModules.length +
447
+ ' other packages depend on.',
448
+ ); //"+dependentModules.map(d => d.packageName).join(", ")));
449
+ log(
450
+ 'Run ' +
451
+ chalk.greenBright(`lincd build-all --from=${pkg.packageName}`) +
452
+ ' to build only the remaining packages',
453
+ ); //"+dependentModules.map(d => d.packageName).join(", ")));
454
+ process.exit(1);
455
+ }
456
+ }
457
+ else //true is successful build, false is successful but with warnings
458
+ {
459
+ //successful build
460
+ // })
461
+ // .then((res) => {
462
+ if (!skipping)
463
+ {
464
+ log(chalk.green('Built ' + pkg.packageName)+(res === false ? chalk.redBright(' (with warnings)') : ''));
465
+ }
466
+ done.add(pkg);
467
+
468
+ packagesLeft--;
469
+ // log(chalk.magenta(packagesLeft + ' packages left'));
470
+ process.stdout.write(packagesLeft + ' packages left\r');
471
+ if (packagesLeft == 0)
472
+ {
473
+ printBuildResults(failedModules,done);
474
+ if (failedModules.length > 0)
475
+ {
476
+ process.exit(1);
477
+ }
478
+ }
479
+
480
+ return res;
481
+ }*/
482
+ // }).catch(err => {
483
+ // console.log(err);
484
+ // })
485
+ });
486
+ }, (dependencies) => {
487
+ //if no more packages to build but we never started building...
488
+ if (!building) {
489
+ console.log(chalk.red('Could not find the package to start from. Please provide a correct package name or package name to build from'));
490
+ }
491
+ else {
492
+ //Detecting cyclical dependencies that caused some packages not to be build
493
+ let first = true;
494
+ lincdPackages.forEach((pkg) => {
495
+ if (!done.has(pkg)) {
496
+ let deps = dependencies.get(pkg);
497
+ if (first) {
498
+ console.log(chalk.red('CYCLICAL DEPENDENCIES? - could not build some packages because they depend on each other.'));
499
+ first = false;
500
+ }
501
+ //print the cyclical dependencies
502
+ console.log(chalk.red(pkg.packageName) +
503
+ ' depends on ' +
504
+ deps
505
+ .filter((dependency) => {
506
+ return typeof dependency !== 'string';
507
+ })
508
+ .map((d) => {
509
+ return done.has(d)
510
+ ? d.packageName
511
+ : chalk.red(d.packageName);
512
+ })
513
+ .join(', '));
514
+ //also print some information why these packages have not been moved into the stack
515
+ let stringDependencies = deps.filter((d) => typeof d === 'string');
516
+ if (stringDependencies.length > 0) {
517
+ console.log(chalk.red('And it depends on these package(s) - which seem not to be proper packages :' +
518
+ stringDependencies.join(', ')));
519
+ console.log(chalk.red('Could you remove this from dependencies? Should it be a devDependency?'));
520
+ }
521
+ }
522
+ });
523
+ }
524
+ }, sync);
525
+ }
526
+ function getDependentPackages(dependencies, pkg) {
527
+ let dependentModules = [];
528
+ dependencies.forEach((dModuleDependencies, dModule) => {
529
+ if (dModuleDependencies.indexOf(pkg) !== -1) {
530
+ dependentModules.push(dModule);
531
+ }
532
+ });
533
+ return dependentModules;
534
+ }
535
+ /**
536
+ * Returns a map of the packages that this repository manages (so no packages found through the workspaces who's path contains ../ )
537
+ * @param rootPath
538
+ */
539
+ function getLocalLincdPackageMap(rootPath = './') {
540
+ let map = new Map();
541
+ getLincdPackages(rootPath).forEach((pkg) => {
542
+ if (pkg.path.indexOf('../') === -1 && pkg.path.indexOf('..\\') === -1) {
543
+ // console.log(package.path);
544
+ map.set(pkg.packageName, pkg);
545
+ }
546
+ });
547
+ return map;
548
+ }
549
+ function getLocalLincdModules(rootPath = './') {
550
+ return getLincdPackages(rootPath).filter((pkg) => {
551
+ return pkg.path.indexOf('..\\') === -1;
552
+ });
553
+ }
554
+ export function getLincdPackages(rootPath = process.cwd()) {
555
+ let pack = getPackageJSON();
556
+ if (!pack || !pack.workspaces) {
557
+ for (let i = 0; i <= 3; i++) {
558
+ rootPath = path.join(process.cwd(), ...Array(i).fill('..'));
559
+ pack = getPackageJSON(rootPath);
560
+ if (pack && pack.workspaces) {
561
+ // log('Found workspace at '+packagePath);
562
+ break;
563
+ }
564
+ }
565
+ }
566
+ if (!pack || !pack.workspaces) {
567
+ warn(chalk.red('Could not find package workspaces. Make sure you run this command from a yarn workspace.'));
568
+ logHelp();
569
+ process.exit();
570
+ }
571
+ // console.log(pack.workspaces);
572
+ let res = [];
573
+ checkWorkspaces(rootPath, pack.workspaces, res);
574
+ return res;
575
+ }
576
+ function setVariable(name, replacement) {
577
+ //prepare name for regexp
578
+ name = name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
579
+ variables[name] = replacement;
580
+ }
581
+ var replaceVariablesInFile = (filePath) => __awaiter(void 0, void 0, void 0, function* () {
582
+ var fileContent = yield fs.readFile(filePath, 'utf8').catch((err) => {
583
+ console.warn(chalk.red('Could not read file ' + filePath));
584
+ });
585
+ if (fileContent) {
586
+ var newContent = replaceCurlyVariables(fileContent);
587
+ return fs.writeFile(filePath, newContent);
588
+ }
589
+ else {
590
+ return Promise.resolve();
591
+ }
592
+ });
593
+ var replaceCurlyVariables = function (string) {
594
+ // var reg = new RegExp('\\$\\{'+key+'\\}','g');
595
+ for (var key in variables) {
596
+ string = string.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), variables[key]);
597
+ }
598
+ return string;
599
+ };
600
+ const capitalize = (str) => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1);
601
+ const camelCase = (str) => {
602
+ let string = str.replace(/[^A-Za-z0-9]/g, ' ').split(' ');
603
+ if (string.length > 1) {
604
+ return string.reduce((result, word) => result + capitalize(word));
605
+ }
606
+ return str;
607
+ };
608
+ export const createOntology = (prefix, uriBase, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
609
+ if (!prefix) {
610
+ console.warn('Please provide a suggested prefix as the first argument');
611
+ return;
612
+ }
613
+ let sourceFolder = getSourceFolder(basePath);
614
+ let targetFolder = ensureFolderExists(sourceFolder, 'ontologies');
615
+ if (!uriBase) {
616
+ uriBase = 'http://lincd.org/ont/' + prefix + '/';
617
+ }
618
+ setVariable('uri_base', uriBase);
619
+ let { hyphenName, camelCaseName, underscoreName } = setNameVariables(prefix);
620
+ //copy ontology accessor file
621
+ log('Creating files for ontology \'' + prefix + '\'');
622
+ let targetFile = path.join(targetFolder, hyphenName + '.ts');
623
+ fs.copySync(path.join(__dirname, '..', 'defaults', 'package', 'src', 'ontologies', 'example-ontology.ts'), targetFile);
624
+ //copy data files
625
+ let targetDataFile = path.join(targetFolder, '..', 'data', hyphenName + '.json');
626
+ let targetDataFile2 = path.join(targetFolder, '..', 'data', hyphenName + '.json.d.ts');
627
+ fs.copySync(path.join(__dirname, '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json'), targetDataFile);
628
+ fs.copySync(path.join(__dirname, '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json.d.ts'), targetDataFile2);
629
+ yield replaceVariablesInFiles(targetFile, targetDataFile, targetDataFile2);
630
+ log(`Prepared a new ontology data files in ${chalk.magenta(targetDataFile.replace(basePath, ''))}`, `And an ontology accessor file in ${chalk.magenta(targetFile.replace(basePath, ''))}`);
631
+ //if this is not a lincd app (but a lincd package instead)
632
+ if (!sourceFolder.includes('frontend')) {
633
+ //then also add an import to index
634
+ let indexPath = addLineToIndex(`import './ontologies/${hyphenName}';`, 'ontologies');
635
+ log(`Added an import of this file from ${chalk.magenta(indexPath)}`);
636
+ }
637
+ });
638
+ const addLineToIndex = function (line, insertMatchString, root = process.cwd(), insertAtStart = false) {
639
+ //import ontology in index
640
+ let indexPath = ['index.ts', 'index.tsx']
641
+ .map((f) => path.join(root, 'src', f))
642
+ .find((indexFileName) => {
643
+ return fs.existsSync(indexFileName);
644
+ });
645
+ if (indexPath) {
646
+ let indexContents = fs.readFileSync(indexPath, 'utf-8');
647
+ let lines = indexContents.split(/\n/g);
648
+ let newContents;
649
+ for (var key in lines) {
650
+ //if the match string is found
651
+ if (lines[key].indexOf(insertMatchString) !== -1) {
652
+ //add the new line after this line
653
+ lines[key] += `\n${line}`;
654
+ newContents = lines.join('\n');
655
+ // log("Found at "+key,lines,newContents);
656
+ break;
657
+ }
658
+ }
659
+ if (!newContents) {
660
+ if (insertAtStart) {
661
+ newContents = `${line}\n${indexContents}`;
662
+ }
663
+ else {
664
+ newContents = `${indexContents}\n${line}`;
665
+ }
666
+ // log("Added at end",newContents);
667
+ }
668
+ fs.writeFileSync(indexPath, newContents);
669
+ }
670
+ return indexPath;
671
+ };
672
+ const replaceVariablesInFiles = function (...files) {
673
+ return Promise.all(files.map((file) => {
674
+ return replaceVariablesInFile(file);
675
+ }));
676
+ };
677
+ const replaceVariablesInFolder = function (folder) {
678
+ //get all files in folder, including files that start with a dot
679
+ glob(folder + '/**/*', { dot: true, nodir: true }, function (err, files) {
680
+ return __awaiter(this, void 0, void 0, function* () {
681
+ if (err) {
682
+ console.log('Error', err);
683
+ }
684
+ else {
685
+ // console.log(files);
686
+ yield Promise.all(files.map((file) => {
687
+ return replaceVariablesInFile(file);
688
+ }));
689
+ }
690
+ });
691
+ });
692
+ };
693
+ const replaceVariablesInFilesWithRoot = function (root, ...files) {
694
+ return replaceVariablesInFiles(...files.map((f) => path.join(root, f)));
695
+ };
696
+ const hasYarnInstalled = function () {
697
+ return __awaiter(this, void 0, void 0, function* () {
698
+ let version = (yield execPromise('yarn --version').catch((err) => {
699
+ console.log('yarn probably not working');
700
+ return '';
701
+ }));
702
+ return version.toString().match(/[0-9]+/);
703
+ });
704
+ };
705
+ const ensureFolderExists = function (...folders) {
706
+ let target;
707
+ folders.forEach((folder) => {
708
+ target = target ? path.join(target, folder) : path.join(folder);
709
+ if (!fs.existsSync(target)) {
710
+ fs.mkdirSync(target);
711
+ }
712
+ });
713
+ return target;
714
+ /*let targetFolder = path.join(...folders);
715
+ let parentDirectory = folders.slice(0, folders.length - 1);
716
+ if (!fs.existsSync(targetFolder)) {
717
+ if (fs.existsSync(path.join(...parentDirectory))) {
718
+ fs.mkdirSync(targetFolder);
719
+ } else {
720
+ warn(
721
+ `Please run this command from the root of your package. This command expects ${parentDirectory.toString()} to exists from that folder`,
722
+ );
723
+ }
724
+ }
725
+ return targetFolder;*/
726
+ };
727
+ export const setNameVariables = function (name) {
728
+ let hyphenName = name.replace(/[-_\s]+/g, '-');
729
+ let camelCaseName = camelCase(name); //some-package --> someModule
730
+ let underscoreName = name.replace(/[-\s]+/g, '_');
731
+ let plainName = name.replace(/[-\s]+/g, '');
732
+ //longer similar variables names should come before the shorter ones
733
+ setVariable('underscore_name', underscoreName);
734
+ setVariable('hyphen_name', hyphenName);
735
+ setVariable('camel_name', camelCaseName);
736
+ setVariable('name', name);
737
+ setVariable('plain_name', plainName);
738
+ return { hyphenName, camelCaseName, underscoreName, plainName };
739
+ };
740
+ function getSourceFolder(basePath = process.cwd()) {
741
+ //LINCD App
742
+ if (fs.existsSync(path.join(basePath, 'frontend', 'src'))) {
743
+ return path.join(basePath, 'frontend', 'src');
744
+ }
745
+ //LINCD package
746
+ if (fs.existsSync(path.join(basePath, 'src'))) {
747
+ return path.join(basePath, 'src');
748
+ }
749
+ else {
750
+ console.warn('Cannot find source folder');
751
+ return path.join(basePath, 'src');
752
+ }
753
+ }
754
+ /**
755
+ * get __dirname for either ESM/CJS
756
+ */
757
+ export const getScriptDir = () => {
758
+ // @ts-ignore
759
+ if (typeof __dirname !== 'undefined') {
760
+ // @ts-ignore
761
+ return __dirname;
762
+ }
763
+ else {
764
+ // @ts-ignore
765
+ return dirname(import.meta.url).replace('file:/', '');
766
+ }
767
+ };
768
+ export const createShape = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
769
+ let sourceFolder = getSourceFolder(basePath);
770
+ let targetFolder = ensureFolderExists(sourceFolder, 'shapes');
771
+ let { hyphenName, camelCaseName, underscoreName } = setNameVariables(name);
772
+ //copy default shape file
773
+ // log("Creating files for shape '" + name + "'");
774
+ let targetFile = path.join(targetFolder, hyphenName + '.ts');
775
+ fs.copySync(path.join(getScriptDir(), '..', '..', 'defaults', 'shape.ts'), targetFile);
776
+ //replace variables in some of the copied files
777
+ yield replaceVariablesInFiles(targetFile);
778
+ log(`Created a new shape class template in ${chalk.magenta(targetFile.replace(basePath, ''))}`);
779
+ //if this is NOT a lincd app (but a lincd package)
780
+ let indexPath;
781
+ if (!sourceFolder.includes('frontend')) {
782
+ indexPath = addLineToIndex(`import './shapes/${hyphenName}';`, 'shapes');
783
+ log(`Added an import of this file from ${chalk.magenta(indexPath)}`);
784
+ }
785
+ });
786
+ export const createSetComponent = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
787
+ let targetFolder = ensureFolderExists(basePath, 'src', 'components');
788
+ let { hyphenName, camelCaseName, underscoreName } = setNameVariables(name);
789
+ //copy default shape file
790
+ log('Creating files for set component \'' + name + '\'');
791
+ let targetFile = path.join(targetFolder, hyphenName + '.tsx');
792
+ fs.copySync(path.join(getScriptDir(), '..', '..', 'defaults', 'set-component.tsx'), targetFile);
793
+ let targetFile2 = path.join(targetFolder, hyphenName + '.scss');
794
+ fs.copySync(path.join(getScriptDir(), '..', '..', 'defaults', 'component.scss'), targetFile2);
795
+ //replace variables in some of the copied files
796
+ yield replaceVariablesInFiles(targetFile, targetFile2);
797
+ let indexPath = addLineToIndex(`import './components/${hyphenName}';`, 'components');
798
+ log(`Created a new set component in ${chalk.magenta(targetFile.replace(basePath, ''))}`, `Created a new stylesheet in ${chalk.magenta(targetFile2.replace(basePath, ''))}`, `Added an import of this file from ${chalk.magenta(indexPath)}`);
799
+ });
800
+ export const createComponent = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
801
+ let sourceFolder = getSourceFolder(basePath);
802
+ let targetFolder = ensureFolderExists(sourceFolder, 'components');
803
+ let { hyphenName, camelCaseName, underscoreName } = setNameVariables(name);
804
+ //copy default shape file
805
+ log('Creating files for component \'' + name + '\'');
806
+ let targetFile = path.join(targetFolder, hyphenName + '.tsx');
807
+ fs.copySync(path.join(getScriptDir(), '..', 'defaults', 'component.tsx'), targetFile);
808
+ let targetFile2 = path.join(targetFolder, hyphenName + '.scss');
809
+ fs.copySync(path.join(getScriptDir(), '..', 'defaults', 'component.scss'), targetFile2);
810
+ //replace variables in some of the copied files
811
+ yield replaceVariablesInFiles(targetFile, targetFile2);
812
+ log(`Created a new component template in ${chalk.magenta(targetFile.replace(basePath, ''))}`, `Created component stylesheet template in ${chalk.magenta(targetFile2.replace(basePath, ''))}`);
813
+ //if this is not a lincd app (but a lincd package instead)
814
+ if (!sourceFolder.includes('frontend')) {
815
+ //then also add an import to index
816
+ let indexPath = addLineToIndex(`import './components/${hyphenName}';`, 'components');
817
+ log(`Added an import of this file from ${chalk.magenta(indexPath)}`);
818
+ }
819
+ });
820
+ //read the source of all ts/tsx files in the src folder
821
+ //if there is an import that imports a lincd package with /src/ in it, then warn
822
+ //if there is an import that imports outside of the src folder, then warn
823
+ export const checkImports = (sourceFolder = getSourceFolder(), depth = 0, // Used to check if the import is outside of the src folder
824
+ invalidImports = new Map()) => __awaiter(void 0, void 0, void 0, function* () {
825
+ const dir = fs.readdirSync(sourceFolder);
826
+ // Start checking each file in the source folder
827
+ for (const file of dir) {
828
+ const filename = path.join(sourceFolder, file);
829
+ // File is either a directory, or not a .ts(x)
830
+ // INFO: For future use - if this part fails, it could be due to user permissions
831
+ // i.e. the program not having access to check the file metadata
832
+ if (!filename.match(/\.tsx?$/)) {
833
+ if (statSync(filename).isDirectory()) {
834
+ yield checkImports(filename, depth + 1, invalidImports);
835
+ }
836
+ // Ignore all files that aren't one of the following:
837
+ // - .ts
838
+ // - .tsx
839
+ continue;
840
+ }
841
+ const allImports = yield getFileImports(filename);
842
+ const lincdImports = allImports.filter((i) => i.includes('lincd') || i.includes('..'));
843
+ lincdImports.forEach((i) => {
844
+ if (!isValidLINCDImport(i, depth)) {
845
+ if (!invalidImports.has(filename)) {
846
+ invalidImports.set(filename, []);
847
+ }
848
+ invalidImports.get(filename).push(i);
849
+ }
850
+ });
851
+ }
852
+ let res = '';
853
+ // All recursion must have finished, display any errors
854
+ if (depth === 0 && invalidImports.size > 0) {
855
+ res += chalk.red('Invalid imports found.\n');
856
+ invalidImports.forEach((value, key) => {
857
+ // res += '- '+chalk.blueBright(key.split('/').pop()) + ':\n';
858
+ value.forEach((i) => {
859
+ res += chalk.red(key.split('/').pop() + ' imports from \'' + i + '\'\n');
860
+ if (i.indexOf('../../') === 0) {
861
+ res +=
862
+ 'To fix: import from the NPM package directly.\n';
863
+ }
864
+ else if ('/src/') {
865
+ res += 'To fix: you likely need to replace /src with /lib\n';
866
+ }
867
+ });
868
+ });
869
+ throw res;
870
+ // process.exit(1);
871
+ }
872
+ else if (depth === 0 && invalidImports.size === 0) {
873
+ // console.info('All imports OK');
874
+ // process.exit(0);
875
+ return true;
876
+ }
877
+ });
878
+ export const depCheckStaged = () => __awaiter(void 0, void 0, void 0, function* () {
879
+ console.log('Checking dependencies of staged files');
880
+ stagedGitFiles(function (err, results) {
881
+ return __awaiter(this, void 0, void 0, function* () {
882
+ const packages = new Set();
883
+ yield Promise.all(results.map((file) => __awaiter(this, void 0, void 0, function* () {
884
+ // console.log('STAGED: ', file.filename);
885
+ let root = yield findNearestPackageJson(file.filename);
886
+ packages.add(root.path);
887
+ })));
888
+ [...packages].forEach((packageRoot) => {
889
+ const pack = JSON.parse(fs.readFileSync(packageRoot, 'utf8'));
890
+ const srcPath = packageRoot.replace('package.json', '');
891
+ console.log('Checking dependencies of ' + chalk.blue(pack.name) + ':');
892
+ return depCheck(process.cwd() + '/' + srcPath);
893
+ // console.log('check dependencies of ' + pack.name);
894
+ //
895
+ // console.log('ROOT of ' + file.filename + ': ' + root.path);
896
+ // console.log('ROOT of ' + file.filename + ': ' + root.data);
897
+ });
898
+ });
899
+ });
900
+ });
901
+ export const depCheck = (packagePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
902
+ return new Promise((resolve, reject) => {
903
+ depcheck(packagePath, {}, (results) => {
904
+ if (results.missing) {
905
+ let lincdPackages = getLocalLincdModules();
906
+ let missing = Object.keys(results.missing);
907
+ //filter out missing types, if it builds we're not too concerned about that at the moment?
908
+ //especially things like @types/react, @types/react-dom, @types/node (they are added elsewhere?)
909
+ // missing = missing.filter(m => m.indexOf('@types/') === 0);
910
+ //currently react is not an explicit dependency, but we should add it as a peer dependency
911
+ missing.splice(missing.indexOf('react'), 1);
912
+ let missingLincdPackages = missing.filter((missingDep) => {
913
+ return lincdPackages.some((lincdPackage) => {
914
+ return lincdPackage.packageName === missingDep;
915
+ });
916
+ });
917
+ //currently just missing LINCD packages cause a hard failure exit code
918
+ if (missingLincdPackages.length > 0) {
919
+ reject(chalk.red(packagePath.split('/').pop() +
920
+ '\n[ERROR] These LINCD packages are imported but they are not listed in package.json:\n- ' +
921
+ missingLincdPackages.join(',\n- ')));
922
+ }
923
+ else if (missing.length > 0) {
924
+ resolve(chalk.redBright('warning: ' + packagePath.split('/').pop() +
925
+ ' is missing dependencies:\n - ' +
926
+ missing.join('\n - ')));
927
+ }
928
+ else {
929
+ resolve(true);
930
+ }
931
+ }
932
+ // if(Object.keys(results.invalidFiles).length > 0) {
933
+ // console.warn(chalk.red("Invalid files:\n")+Object.keys(results.invalidFiles).join(",\n"));
934
+ // }
935
+ // if(Object.keys(results.invalidDirs).length > 0) {
936
+ // console.warn(chalk.red("Invalid dirs:\n")+results.invalidDirs.toString());
937
+ // }
938
+ // if(results.unused) {
939
+ // console.warn("Unused dependencies: "+results.missing.join(", "));
940
+ // }
941
+ });
942
+ });
943
+ });
944
+ export const ensureEnvironmentLoaded = () => __awaiter(void 0, void 0, void 0, function* () {
945
+ if (!process.env.NODE_ENV) {
946
+ //load env-cmd for development environment
947
+ let { GetEnvVars } = yield import('env-cmd');
948
+ let envCmdrcPath = path.join(process.cwd(), '.env-cmdrc.json');
949
+ if (!fs.existsSync(envCmdrcPath)) {
950
+ console.warn('No .env-cmdrc.json found in this folder. Are you running this command from the root of a LINCD app?');
951
+ process.exit();
952
+ }
953
+ let vars = yield GetEnvVars({
954
+ envFile: {
955
+ filePath: envCmdrcPath,
956
+ },
957
+ });
958
+ let environments = Object.keys(vars);
959
+ //if _main is present, load it first
960
+ if (environments.includes('_main')) {
961
+ process.env = Object.assign(Object.assign({}, process.env), vars._main);
962
+ }
963
+ //if --env is passed, load that environment
964
+ let args = process.argv.splice(2);
965
+ if (args.includes('--env')) {
966
+ let envIndex = args.indexOf('--env');
967
+ let env = args[envIndex + 1];
968
+ env.split(',').forEach((singleEnvironment) => {
969
+ if (environments.includes(singleEnvironment)) {
970
+ console.log('Environment: ' + singleEnvironment);
971
+ process.env = Object.assign(Object.assign({}, process.env), vars[singleEnvironment]);
972
+ }
973
+ else {
974
+ console.warn('Environment ' +
975
+ singleEnvironment +
976
+ ' not found in .env-cmdrc.json. Available environments: ' +
977
+ environments.join(', '));
978
+ }
979
+ });
980
+ }
981
+ else {
982
+ //chose development by default
983
+ process.env = Object.assign(Object.assign({}, process.env), vars.development);
984
+ console.log('No environment specified, using development');
985
+ }
986
+ }
987
+ });
988
+ export const startServer = (initOnly = false, ServerClass = null) => __awaiter(void 0, void 0, void 0, function* () {
989
+ yield ensureEnvironmentLoaded();
990
+ let lincdConfig = yield import(path.join(process.cwd(), 'lincd.config.js'));
991
+ // function scssLoadcall(source, filename) {
992
+ // return 'console.log("SCSS CALL: ' + filename + '");\n' + source;
993
+ // process.exit();
994
+ // }
995
+ // hook.hook('.scss', scssLoadcall);
996
+ // hook.hook('.css', scssLoadcall);
997
+ // import.meta.
998
+ // // hook.hook('*.css', scssLoadcall);
999
+ // // hook.hook('Body.module.css', scssLoadcall);
1000
+ // hook.hook('.module.css', scssLoadcall);
1001
+ if (!ServerClass) {
1002
+ //@ts-ignore
1003
+ ServerClass = (yield import('lincd-server/shapes/LincdServer')).LincdServer;
1004
+ }
1005
+ yield import(path.join(process.cwd(), 'scripts', 'storage-config.js'));
1006
+ let server = new ServerClass(Object.assign({ loadAppComponent: () => __awaiter(void 0, void 0, void 0, function* () { return (yield import(path.join(process.cwd(), 'src', 'App'))).default; }) }, lincdConfig));
1007
+ //Important to use slice, because when using clusers, child processes need to be able to read the same arguments
1008
+ let args = process.argv.slice(2);
1009
+ //if --initOnly is passed, only initialize the server and don't start it
1010
+ if (args.includes('--initOnly') || initOnly) {
1011
+ return server.initOnly();
1012
+ }
1013
+ else {
1014
+ return server.start();
1015
+ }
1016
+ });
1017
+ export const buildApp = () => __awaiter(void 0, void 0, void 0, function* () {
1018
+ yield ensureEnvironmentLoaded();
1019
+ const webpackAppConfig = yield (yield import('./config-webpack-app.js')).getWebpackAppConfig();
1020
+ console.log(chalk.magenta(`Building ${process.env.NODE_ENV} app bundles`));
1021
+ return new Promise((resolve, reject) => {
1022
+ webpack(webpackAppConfig, (err, stats) => __awaiter(void 0, void 0, void 0, function* () {
1023
+ if (err) {
1024
+ console.error(err.stack || err);
1025
+ process.exit(1);
1026
+ }
1027
+ const info = stats.toJson();
1028
+ if (stats.hasErrors()) {
1029
+ console.log('Finished running webpack with errors.');
1030
+ info.errors.forEach((e) => console.error(e));
1031
+ // process.exit(1);
1032
+ reject();
1033
+ }
1034
+ else {
1035
+ console.log(stats.toString({
1036
+ chunks: false,
1037
+ assets: true,
1038
+ entrypoints: false,
1039
+ modules: false,
1040
+ moduleAssets: false,
1041
+ colors: true,
1042
+ }));
1043
+ console.log('App build process finished');
1044
+ resolve(true);
1045
+ // console.log(
1046
+ // chalk.green('\t'+Object.keys(stats.compilation.assets).join('\n\t')),
1047
+ // );
1048
+ //build metadata (JSON-LD files containing metadata about the lincd components, shapes & ontologies in this app or its packages)
1049
+ // let updatedPaths = await buildMetadata();
1050
+ // console.log(chalk.green("Updated metadata:\n")+" - "+updatedPaths.map(p => chalk.magenta(p.replace(process.cwd(),''))).join("\n - "));
1051
+ }
1052
+ // process.exit();
1053
+ }));
1054
+ }).then(() => __awaiter(void 0, void 0, void 0, function* () {
1055
+ // make sure environment is not development for storage config
1056
+ // and if we want to upload to storage, we need set S3_BUCKET_ENDPOINT
1057
+ if (process.env.NODE_ENV === 'development' || !process.env.S3_BUCKET_ENDPOINT) {
1058
+ console.warn('Upload build to storage skip in development environment or S3_BUCKET_ENDPOINT is not set');
1059
+ process.exit();
1060
+ }
1061
+ if (process.env.APP_ENV) {
1062
+ console.warn('Not uploading to CDN for app builds');
1063
+ process.exit();
1064
+ }
1065
+ // load the storage config
1066
+ const storageConfig = yield import(path.join(process.cwd(), 'scripts', 'storage-config.js'));
1067
+ // check if LincdFileStorage has a default FileStore
1068
+ // if yes: copy all the files in the build folder over with LincdFileStorage
1069
+ if (LinkedFileStorage.getDefaultStore()) {
1070
+ // get public directory
1071
+ const rootDirectory = 'public';
1072
+ const pathDir = path.join(process.cwd(), rootDirectory);
1073
+ if (!fs.existsSync(pathDir)) {
1074
+ console.warn('No public directory found. Please create a public directory in the root of your project');
1075
+ return;
1076
+ }
1077
+ // get all files in the web directory and then upload them to the storage
1078
+ const files = yield getFiles(pathDir);
1079
+ const uploads = files.map((filePath) => __awaiter(void 0, void 0, void 0, function* () {
1080
+ // read file content
1081
+ const fileContent = yield fs.promises.readFile(filePath);
1082
+ // replace pathDir with rootDirectory in filePath to get pathname
1083
+ // example: /Users/username/project/www/index.html -> /project/www/index.html
1084
+ const pathname = filePath.replace(pathDir, `/${rootDirectory}`);
1085
+ // upload file to storage
1086
+ return yield LinkedFileStorage.saveFile(pathname, fileContent);
1087
+ }));
1088
+ const urls = yield Promise.all(uploads);
1089
+ console.log(`${urls.length} files uploaded to storage`);
1090
+ process.exit();
1091
+ }
1092
+ }));
1093
+ });
1094
+ export const upgradePackages = () => __awaiter(void 0, void 0, void 0, function* () {
1095
+ yield ensureEnvironmentLoaded();
1096
+ // let packages = getLincdPackages();
1097
+ // let packages = getLocalLincdModules();
1098
+ let packages = getLocalLincdPackageMap();
1099
+ let dirname = getScriptDir();
1100
+ const tsConfigCJS = path.join(dirname, '../../defaults/package', 'tsconfig-cjs.json');
1101
+ const tsConfigESM = path.join(dirname, '../../defaults/package', 'tsconfig-esm.json');
1102
+ const typesFile = path.join(dirname, '../../defaults/package/src', 'types.d.ts');
1103
+ const tsConfigTemplate = yield fs.readJson(path.join(dirname, '../../defaults/package', 'tsconfig.json')).catch(err => {
1104
+ console.log(err);
1105
+ });
1106
+ runOnPackagesGroupedByDependencies(packages, (packageGroup, dependencies) => {
1107
+ // packageGroup.forEach((pkg) => {
1108
+ // console.log(' Upgrading ' + pkg.packageName);
1109
+ console.log('-----');
1110
+ return (pkg) => __awaiter(void 0, void 0, void 0, function* () {
1111
+ if (pkg.packageName === 'lincd')
1112
+ return;
1113
+ // await execPromise(`cd ${pkg.path} && yarn upgrade`);
1114
+ console.log('Upgrading ' + pkg.packageName);
1115
+ //
1116
+ // //create a new file src/tsconfig-cjs.json
1117
+ // //copy the contents of tsconfig.json into it
1118
+ // if (!fs.existsSync(path.join(pkg.path,'tsconfig-cjs.json')))
1119
+ // {
1120
+ // await fs.copy(tsConfigCJS,path.join(pkg.path,'tsconfig-cjs.json'));
1121
+ // await fs.copy(tsConfigESM,path.join(pkg.path,'tsconfig-esm.json'));
1122
+ // console.log('Copied new tsconfig to ' + pkg.packageName);
1123
+ // }
1124
+ //
1125
+ // //read tsconfig
1126
+ // await fs.readJson(path.join(pkg.path,'tsconfig.json')).then((tsconfig) => {
1127
+ // let oldCompilerOpts = tsconfig.compilerOptions;
1128
+ // tsconfig.compilerOptions = tsConfigTemplate.compilerOptions;
1129
+ // tsconfig.compilerOptions.types = oldCompilerOpts.types;
1130
+ // tsconfig.compilerOptions.plugins = [{"name": "typescript-plugin-css-modules"}];
1131
+ //
1132
+ // console.log('Upgraded tsconfig for ' + pkg.packageName);
1133
+ // return fs.writeJson(path.join(pkg.path,'tsconfig.json'),tsconfig,{spaces: 2});
1134
+ // });
1135
+ // //import types at the beginning of index.ts
1136
+ // addLineToIndex(`import './types';`,null,pkg.path,true);
1137
+ // //copy over the types file
1138
+ // await fs.copy(typesFile,path.join(pkg.path,'src','types.d.ts'));
1139
+ // await fs.readJson(path.join(pkg.path,'package.json')).then((packageJson) => {
1140
+ // let version = packageJson.version;
1141
+ // let nextVersion;
1142
+ // if (version.split('.').shift() === '0')
1143
+ // {
1144
+ // nextVersion = getNextMajorVersion(version);
1145
+ // }
1146
+ // else
1147
+ // {
1148
+ // nextVersion = getNextMinorVersion(version);
1149
+ // }
1150
+ // console.log('Upgraded version for ' + pkg.packageName + ' to ' + nextVersion);
1151
+ //
1152
+ // packageJson.version = nextVersion;
1153
+ // packageJson.devDependencies['tsconfig-to-dual-package'] = '^1.2.0';
1154
+ // packageJson.devDependencies['typescript-plugin-css-modules'] = '^5.1.0';
1155
+ //
1156
+ // packageJson.main = 'lib/cjs/index.js';
1157
+ // packageJson.module = 'lib/esm/index.js';
1158
+ // packageJson.exports = {
1159
+ // '.': {
1160
+ // 'types': './lib/esm/index.d.ts',
1161
+ // 'import': './lib/esm/index.js',
1162
+ // 'require': './lib/cjs/index.js',
1163
+ // },
1164
+ // './*': {
1165
+ // 'types': './lib/esm/*.d.ts',
1166
+ // 'import': './lib/esm/*.js',
1167
+ // 'require': './lib/cjs/*.js',
1168
+ // },
1169
+ // };
1170
+ // packageJson.typesVersions = {
1171
+ // '*': {
1172
+ // '*': [
1173
+ // 'lib/esm/*',
1174
+ // ],
1175
+ // },
1176
+ // };
1177
+ //
1178
+ // return fs.writeJson(path.join(pkg.path,'package.json'),packageJson,{ spaces: 2 });
1179
+ // });
1180
+ //change .css files and .scss files to .module.css and .module.scss
1181
+ let files = yield getFiles(path.join(pkg.path, 'src'));
1182
+ // let tsFiles = files.filter(f => f.match(/\.(ts|tsx)$/));
1183
+ // let cssFiles = files.filter(f => f.match(/\.(css|scss)$/)).filter(f => !f.match(/\.module\.(css|scss)$/));
1184
+ // cssFiles.forEach(cssFile => {
1185
+ // let cssFileName = path.basename(cssFile);
1186
+ // let newFile = cssFileName.replace(/\.s?css$/,'.module$&');
1187
+ // let newFilePath = cssFile.replace(/\.s?css$/,'.module$&');
1188
+ // let jsonFile = cssFileName.replace(/\.s?css$/,'$&.json');
1189
+ // fs.renameSync(cssFile,newFilePath);
1190
+ // console.log('Renaming ' + cssFileName + ' to ' + newFilePath);
1191
+ // //find other files that import this file and update them
1192
+ // tsFiles.forEach(tsFile => {
1193
+ // //read contents of f2
1194
+ // let contents = fs.readFileSync(tsFile,'utf8');
1195
+ // //if it imports f
1196
+ // if (contents.indexOf(cssFileName) !== -1)
1197
+ // {
1198
+ // //find the whole line that imports f
1199
+ // let line = contents.split('\n').find(l => l.indexOf(cssFileName) !== -1);
1200
+ // // console.log("OLD: "+line);
1201
+ // let jsonLine = contents.split('\n').find(l => l.indexOf(jsonFile) !== -1);
1202
+ // // console.log("JSON: "+jsonLine);
1203
+ // //if not commented out
1204
+ // if(line.indexOf('//') === -1) {
1205
+ // let previousImportPath = line.match(/['"](.*)['"]/)[1];
1206
+ // let newImportPath = previousImportPath.replace(cssFileName,newFile);
1207
+ // let newContents = contents.replace(line,`import style from '${newImportPath}';`)
1208
+ // .replace(jsonLine+'\n','');
1209
+ // // console.log("\n");
1210
+ // fs.writeFileSync(tsFile,newContents);
1211
+ // console.log('Updated imports in ' + tsFile);
1212
+ // // fs.writeFileSync
1213
+ // // fs.writeFileSync(i,fs.readFileSync(i,'utf8').replace(f,newFile));
1214
+ // }
1215
+ // }
1216
+ // })
1217
+ // });
1218
+ files.filter(f => f.match(/\.(scss\.json|css\.json)$/)).forEach(cssJsonFile => {
1219
+ console.log('Removing ' + cssJsonFile);
1220
+ fs.unlinkSync(cssJsonFile);
1221
+ });
1222
+ });
1223
+ // });
1224
+ }, () => {
1225
+ console.log('Finished upgrading packages');
1226
+ });
1227
+ // packages.forEach((pkg,key) => {
1228
+ // console.log(key+' Upgrading ' + pkg.packageName);
1229
+ // execPromise(`cd ${pkg.path} && yarn upgrade`).then(() => {
1230
+ // console.log('Upgraded ' + pkg.packageName);
1231
+ // }).catch(err => {
1232
+ // console.warn(err);
1233
+ // })
1234
+ // });
1235
+ });
1236
+ export const createPackage = (name, uriBase, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
1237
+ if (!name) {
1238
+ console.warn('Please provide a name as the first argument');
1239
+ return;
1240
+ }
1241
+ //if ran with npx, basePath will be the root directory of the repository, even if we're executing from a sub folder (the root directory is where node_modules lives and package.json with workspaces)
1242
+ //so we manually find a packages folder, if it exists we go into that.
1243
+ if (fs.existsSync(path.join(basePath, 'packages'))) {
1244
+ basePath = path.join(basePath, 'packages');
1245
+ }
1246
+ //for lincd.org currently packages are stored in the modules folder
1247
+ else if (fs.existsSync(path.join(basePath, 'modules'))) {
1248
+ basePath = path.join(basePath, 'modules');
1249
+ }
1250
+ //let's remove scope for variable names
1251
+ let [packageName, scope, cleanPackageName] = name.match(/(@[\w\-]+\/)?([\w\-]+)/);
1252
+ let targetFolder = ensureFolderExists(basePath, cleanPackageName);
1253
+ if (!uriBase) {
1254
+ uriBase = 'http://lincd.org/ont/' + name;
1255
+ }
1256
+ setVariable('uri_base', uriBase + '/');
1257
+ //find @scope and the next part between 2 slashes after
1258
+ //so @dacore/some-mod/lib/file.js
1259
+ // --> match[0] = @dacore/some-mod
1260
+ // --> match[1] = @dacore
1261
+ // --> match[2] = some-mod
1262
+ //but save full scoped package name under ${package_name}
1263
+ setVariable('package_name', name);
1264
+ //extra variable for clarity (will be same as 'name')
1265
+ setVariable('output_file_name', name);
1266
+ let { hyphenName, camelCaseName, underscoreName } = setNameVariables(cleanPackageName);
1267
+ log('Creating new LINCD package \'' + name + '\'');
1268
+ fs.copySync(path.join(getScriptDir(), '..', '..', 'defaults', 'package'), targetFolder);
1269
+ //replace variables in some of the copied files
1270
+ yield Promise.all([
1271
+ 'src/index.ts',
1272
+ 'package.json',
1273
+ 'Gruntfile.js',
1274
+ 'src/package.ts',
1275
+ 'src/ontologies/example-ontology.ts',
1276
+ 'src/data/example-ontology.json',
1277
+ ]
1278
+ .map((f) => path.join(targetFolder, f))
1279
+ .map((file) => {
1280
+ return replaceVariablesInFile(file);
1281
+ }));
1282
+ //rename these to a file name similar to the pkg name
1283
+ [
1284
+ 'src/ontologies/example-ontology.ts',
1285
+ 'src/data/example-ontology.json',
1286
+ 'src/data/example-ontology.json.d.ts',
1287
+ ].forEach((f) => {
1288
+ let parts = f.split('/');
1289
+ let newParts = [...parts];
1290
+ let [name, ...extensions] = newParts.pop().split('.');
1291
+ let newName = hyphenName + '.' + extensions.join('.');
1292
+ console.log('rename ', path.join(targetFolder, f), path.join(targetFolder, ...newParts, newName));
1293
+ fs.renameSync(path.join(targetFolder, f), path.join(targetFolder, ...newParts, newName));
1294
+ });
1295
+ let version = (yield execPromise('yarn --version').catch((err) => {
1296
+ console.log('yarn probably not working');
1297
+ return '';
1298
+ }));
1299
+ let installCommand = version.toString().match(/[0-9]+/)
1300
+ ? 'yarn install'
1301
+ : 'npm install';
1302
+ yield execp(`cd ${targetFolder} && ${installCommand} && npm exec lincd build`, true).catch((err) => {
1303
+ console.warn('Could not install dependencies');
1304
+ });
1305
+ log(`Prepared a new LINCD package in ${chalk.magenta(targetFolder)}`, `Run ${chalk.blueBright('yarn build')} from this directory to build once`, `Or ${chalk.blueBright('yarn dev')} to continuously rebuild on file changes`);
1306
+ });
1307
+ var getNextVersion = function (version) {
1308
+ let parts = version.split('.');
1309
+ return parts[0] + '.' + parts[1] + '.' + (parseInt(parts[2]) + 1).toString();
1310
+ };
1311
+ var getNextMajorVersion = function (version) {
1312
+ let parts = version.split('.');
1313
+ return (parseInt(parts[0]) + 1).toString() + '.0.0';
1314
+ };
1315
+ var getNextMinorVersion = function (version) {
1316
+ let parts = version.split('.');
1317
+ return parts[0] + '.' + (parseInt(parts[1]) + 1).toString() + '.0';
1318
+ };
1319
+ var buildFailed = function (output) {
1320
+ return (output.indexOf('Aborted due to warnings') !== -1 &&
1321
+ output.indexOf('Command failed') !== -1);
1322
+ };
1323
+ export const register = function (registryURL) {
1324
+ if (fs.existsSync(process.cwd() + '/package.json')) {
1325
+ var pack = JSON.parse(fs.readFileSync(process.cwd() + '/package.json', 'utf8'));
1326
+ let version = pack.version;
1327
+ let packageName = pack.name;
1328
+ // let author = pack.author;
1329
+ // let description = pack.description;
1330
+ //
1331
+ // let authorName = pack.author;
1332
+ // if (pack.author.name) {
1333
+ // authorName = pack.author.name;
1334
+ // }
1335
+ console.log(chalk.cyan('registering package ' +
1336
+ packageName +
1337
+ ' ' +
1338
+ version +
1339
+ ' in the LINCD registry'));
1340
+ return fetch(registryURL + '/register', {
1341
+ method: 'POST',
1342
+ headers: {
1343
+ Accept: 'application/json, text/plain, */*',
1344
+ 'Content-Type': 'application/json',
1345
+ },
1346
+ body: JSON.stringify({ package: packageName, version }),
1347
+ // body: JSON.stringify({package: packageName, version, author}),
1348
+ })
1349
+ .then((res) => res.json())
1350
+ .then((json) => {
1351
+ if (json.error) {
1352
+ console.log(chalk.red('Response: ' + json.error));
1353
+ }
1354
+ else if (json.result) {
1355
+ console.log(chalk.blueBright('Response: ') + json.result);
1356
+ if (json.warning) {
1357
+ console.log(chalk.red('Warning: ') + json.warning);
1358
+ }
1359
+ }
1360
+ })
1361
+ .catch((err) => {
1362
+ console.warn(chalk.red('Warning: ') + 'Could not connect to LINCD registry');
1363
+ });
1364
+ }
1365
+ else {
1366
+ console.warn(chalk.red('Warning:') + ' not found: ' + process.cwd() + '/package.json');
1367
+ }
1368
+ };
1369
+ export const buildPackage = (target, target2, packagePath = process.cwd(), logResults = true) => __awaiter(void 0, void 0, void 0, function* () {
1370
+ let spinner;
1371
+ if (logResults) {
1372
+ //TODO: replace with listr so we can show multiple processes at once
1373
+ spinner = ora({
1374
+ discardStdin: true,
1375
+ text: 'Compiling code',
1376
+ }).start();
1377
+ }
1378
+ let buildProcess = Promise.resolve(true);
1379
+ let buildStep = (step) => {
1380
+ buildProcess = buildProcess.then((previousResult) => {
1381
+ if (logResults) {
1382
+ spinner.text = step.name;
1383
+ spinner.start();
1384
+ }
1385
+ return step.apply().then(stepResult => {
1386
+ if (typeof stepResult === 'string') {
1387
+ // spinner.text = step.name + ' - ' + stepResult;
1388
+ if (logResults) {
1389
+ spinner.warn(step.name + ' - ' + stepResult);
1390
+ spinner.stop();
1391
+ }
1392
+ //warning is shown, but build is still succesful with warnings
1393
+ return false;
1394
+ }
1395
+ else if (stepResult === true || typeof stepResult === 'undefined') {
1396
+ if (logResults) {
1397
+ spinner.succeed();
1398
+ }
1399
+ return previousResult && true;
1400
+ }
1401
+ });
1402
+ });
1403
+ };
1404
+ buildStep({
1405
+ name: 'Compiling code',
1406
+ apply: () => __awaiter(void 0, void 0, void 0, function* () {
1407
+ return compilePackage(packagePath);
1408
+ }),
1409
+ });
1410
+ buildStep({
1411
+ name: 'Copying files to lib folder',
1412
+ apply: () => __awaiter(void 0, void 0, void 0, function* () {
1413
+ const files = yield glob(packagePath + '/src/**/*.{json,d.ts,css,scss}');
1414
+ return Promise.all(files.map(((file) => __awaiter(void 0, void 0, void 0, function* () {
1415
+ try {
1416
+ yield fs.copy(file, packagePath + '/lib/esm/' + file.replace(packagePath + '/src/', ''));
1417
+ yield fs.copy(file, packagePath + '/lib/cjs/' + file.replace(packagePath + '/src/', ''));
1418
+ return true;
1419
+ }
1420
+ catch (err) {
1421
+ console.warn(err);
1422
+ return false;
1423
+ }
1424
+ ;
1425
+ })))).then((allResults) => {
1426
+ return allResults.every(r => r === true);
1427
+ });
1428
+ }),
1429
+ });
1430
+ buildStep({
1431
+ name: 'Dual package support',
1432
+ apply: () => {
1433
+ return execPromise('yarn tsconfig-to-dual-package ./tsconfig-cjs.json ./tsconfig-esm.json', false, false, { cwd: packagePath }).then(res => {
1434
+ return res === '';
1435
+ });
1436
+ },
1437
+ });
1438
+ buildStep({
1439
+ name: 'Removing old files from lib folder',
1440
+ apply: () => __awaiter(void 0, void 0, void 0, function* () {
1441
+ return removeOldFiles(packagePath);
1442
+ }),
1443
+ });
1444
+ buildStep({
1445
+ name: 'Checking imports',
1446
+ apply: () => checkImports(packagePath),
1447
+ });
1448
+ buildStep({
1449
+ name: 'Checking dependencies',
1450
+ apply: () => depCheck(packagePath),
1451
+ });
1452
+ let success = yield buildProcess.catch(err => {
1453
+ let msg = err.error ? err.error : err.stdout + '\n' + err.stderr;
1454
+ if (logResults) {
1455
+ spinner.stopAndPersist({
1456
+ symbol: chalk.red('✖'),
1457
+ text: 'Build failed',
1458
+ });
1459
+ }
1460
+ else {
1461
+ console.log(chalk.red(packagePath.split('/').pop(), ' - Build failed:'));
1462
+ }
1463
+ console.log(msg);
1464
+ });
1465
+ //will be undefined if there was an error
1466
+ if (typeof success !== 'undefined') {
1467
+ if (logResults) {
1468
+ spinner.stopAndPersist({
1469
+ symbol: chalk.greenBright('✔'),
1470
+ text: success === true ? 'Build successful' : 'Build successful with warnings',
1471
+ });
1472
+ }
1473
+ }
1474
+ return success;
1475
+ });
1476
+ export const compilePackage = (packagePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
1477
+ //echo 'compiling CJS' && tsc -p tsconfig-cjs.json && echo 'compiling ESM' && tsc -p tsconfig-esm.json
1478
+ let cjsConfig = fs.existsSync(path.join(packagePath, 'tsconfig-cjs.json'));
1479
+ let esmConfig = fs.existsSync(path.join(packagePath, 'tsconfig-esm.json'));
1480
+ let compileCJS = `yarn exec tsc -p tsconfig-cjs.json`;
1481
+ let compileESM = `yarn exec tsc -p tsconfig-esm.json`;
1482
+ let compileCommand;
1483
+ if (cjsConfig && esmConfig) {
1484
+ compileCommand = `${compileCJS} && ${compileESM}`;
1485
+ }
1486
+ else if (cjsConfig) {
1487
+ compileCommand = compileCJS;
1488
+ }
1489
+ else if (esmConfig) {
1490
+ compileCommand = compileESM;
1491
+ }
1492
+ else {
1493
+ compileCommand = `yarn exec tsc`;
1494
+ }
1495
+ return execPromise(compileCommand, false, false, { cwd: packagePath }).then(res => {
1496
+ return res === '';
1497
+ });
1498
+ });
1499
+ export var publishUpdated = function (test = false) {
1500
+ let packages = getLocalLincdModules();
1501
+ var p = Promise.resolve('');
1502
+ let packagesLeft = packages.length;
1503
+ let results = [];
1504
+ log('Checking which packages need to be published by comparing last published date with last git commit');
1505
+ // p = Promise.all(packages.map((pckg) => {
1506
+ packages.forEach((pckg) => {
1507
+ p = p
1508
+ .then((previousResult) => {
1509
+ // progressUpdate(packagesLeft-- + ' packages left. Now checking ' + pckg.packageName);
1510
+ log('# Checking package ' + pckg.packageName);
1511
+ // log('# Requesting ' + 'yarn info '+pkg.packageName+' --json');
1512
+ // return execPromise('yarn info '+pkg.packageName+' --json').then((output:string) => {
1513
+ // console.log("Will be requesting npm view from this current working directory:\n"+process.cwd());
1514
+ // return execPromise('npm view '+pkg.packageName+' --json').then((output:string) => {
1515
+ let shouldPublish;
1516
+ var pack = getPackageJSON(pckg.path);
1517
+ let version = getNextVersion(pack.version);
1518
+ if (pack.private) {
1519
+ shouldPublish = false;
1520
+ debugInfo(chalk.blue('--> is private, skipping'));
1521
+ return chalk.gray(pckg.packageName + ' is private');
1522
+ // return previousResult + ' ' + chalk.gray(pckg.packageName + ' is private\n');
1523
+ }
1524
+ console.log('testing npm');
1525
+ return execPromise('npm info ' + pckg.packageName + ' --json')
1526
+ .then((output) => __awaiter(this, void 0, void 0, function* () {
1527
+ console.log('testing npm done');
1528
+ var info;
1529
+ try {
1530
+ if (output == '' || output.includes('E404')) {
1531
+ debugInfo('Empty or 404 response from `npm info`. This package was probably not published before');
1532
+ // throw new Error('Empty response from `yarn info`. This pkg was probably not published before');
1533
+ // return;
1534
+ shouldPublish = true;
1535
+ //don't patch the version number (default, see above), use the current version
1536
+ version = pack.version;
1537
+ }
1538
+ else {
1539
+ info = JSON.parse(output);
1540
+ }
1541
+ if (info) {
1542
+ let lastPublish;
1543
+ //yarn:
1544
+ // let lastPublish = info.data.time[info.data.version];
1545
+ lastPublish = info.time[info.version];
1546
+ // }
1547
+ // catch (e) {
1548
+ // console.log(info);
1549
+ // console.error(chalk.red("Could not parse response from npm info. Format may have changed?"));
1550
+ // process.exit();
1551
+ // }
1552
+ let lastPublishDate = new Date(lastPublish);
1553
+ // let {lastModifiedTime, lastModifiedName, lastModified} = getLastModifiedSourceTime(pkg.path);
1554
+ let lastCommitInfo = yield getLastCommitTime(pckg.path);
1555
+ if (!lastCommitInfo) {
1556
+ shouldPublish = false;
1557
+ debugInfo('Could not determine last git commit');
1558
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' - could not determine last commit\n');
1559
+ return chalk.red(pckg.packageName + ' - could not determine last commit');
1560
+ }
1561
+ else {
1562
+ //NOTE: removed lastModified, because switching branches will say that the file was modified and cause everything to publish
1563
+ //SO: now you NEED TO commit before it picks up that you should publish
1564
+ shouldPublish =
1565
+ lastPublishDate.getTime() < lastCommitInfo.date.getTime();
1566
+ //ignore changes to package.json if that's the only change, because when we publish the version number changes, which is then committed
1567
+ //(note there is always 2 lines for commit info + number of files changed)
1568
+ let changedFiles = lastCommitInfo.changes
1569
+ .split('\n')
1570
+ .filter((line) => line.includes('|'));
1571
+ let numberOfFilesChanges = changedFiles.length;
1572
+ // console.log("CHECK "+lastCommitInfo.changes.includes("package.json")+" - "+numberOfFilesChanges)
1573
+ if (shouldPublish &&
1574
+ lastCommitInfo.changes.includes('package.json') &&
1575
+ numberOfFilesChanges === 1) {
1576
+ shouldPublish = false;
1577
+ }
1578
+ if (shouldPublish) {
1579
+ log(chalk.magenta(pckg.packageName) +
1580
+ ' should be published because:');
1581
+ log(lastPublishDate.toDateString() +
1582
+ ' ' +
1583
+ lastPublishDate.toTimeString() +
1584
+ ' published ' +
1585
+ info.version);
1586
+ log(lastCommitInfo.date.toDateString() +
1587
+ ' ' +
1588
+ new Date(lastCommitInfo.date).toTimeString() +
1589
+ ' source last committed:');
1590
+ log(lastCommitInfo.changes);
1591
+ }
1592
+ }
1593
+ }
1594
+ }
1595
+ catch (err) {
1596
+ // var stats = fs.statSync(path.join(packageDirectory));
1597
+ // var files = fs.readdirSync(path.join(packageDirectory,'src'));
1598
+ console.log(chalk.red(pckg.packageName + ' failed: ' + err.message + '\n'));
1599
+ console.warn('Returned JSON from npm: ' + output);
1600
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed: ' + err.message + '\n');
1601
+ return chalk.red(pckg.packageName + ' failed: ' + err.message);
1602
+ }
1603
+ if (shouldPublish) {
1604
+ return publishPackage(pckg, test, info, version);
1605
+ }
1606
+ return (chalk.blue(pckg.packageName) + ' latest version is up to date');
1607
+ }))
1608
+ .catch(({ error, stdout, stderr }) => {
1609
+ if (error) {
1610
+ console.log(error.message);
1611
+ }
1612
+ if (stdout) {
1613
+ console.log(stderr);
1614
+ }
1615
+ if (stderr) {
1616
+ console.log(stderr);
1617
+ }
1618
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed\n');
1619
+ console.warn(chalk.red(pckg.packageName + ' failed'));
1620
+ return chalk.red(pckg.packageName + ' failed');
1621
+ });
1622
+ })
1623
+ .then((res) => {
1624
+ log(res);
1625
+ results.push(res);
1626
+ })
1627
+ .catch((err) => {
1628
+ console.warn(chalk.red(pckg.packageName + ' failed: ' + err.toString()));
1629
+ results.push(chalk.red(pckg.packageName + ' failed: ' + err.toString()));
1630
+ });
1631
+ });
1632
+ return p.then(() => {
1633
+ // if (messages == '')
1634
+ // {
1635
+ // console.log('All published packages are already up-to-date.');
1636
+ // }
1637
+ // else
1638
+ // {
1639
+ console.log('Summary: \n' + results.join('\n'));
1640
+ // }
1641
+ });
1642
+ };
1643
+ function getEnvJsonPath(relativeToPath = process.cwd()) {
1644
+ return __awaiter(this, void 0, void 0, function* () {
1645
+ let path = '';
1646
+ if (!relativeToPath.endsWith('/')) {
1647
+ relativeToPath += '/';
1648
+ }
1649
+ // let path = './';
1650
+ for (let i = 0; i <= 10; i++) {
1651
+ let envFile = yield getEnvFile({
1652
+ filePath: relativeToPath + path + '.env.json',
1653
+ }).catch((err) => {
1654
+ return null;
1655
+ });
1656
+ if (envFile) {
1657
+ //note: we're getting the actual contents here, so we could also use that more directly?
1658
+ return path + '.env.json';
1659
+ }
1660
+ path += '../';
1661
+ }
1662
+ });
1663
+ }
1664
+ export var publishPackage = function (pkg, test, info, publishVersion) {
1665
+ return __awaiter(this, void 0, void 0, function* () {
1666
+ if (!pkg) {
1667
+ let localPackageJson = getPackageJSON();
1668
+ pkg = {
1669
+ path: process.cwd(),
1670
+ packageName: localPackageJson.name,
1671
+ };
1672
+ }
1673
+ if (!publishVersion) {
1674
+ publishVersion = info ? getNextVersion(info.version) : 'patch';
1675
+ }
1676
+ if (test) {
1677
+ debugInfo('should publish ' + pkg.packageName + ' ' + publishVersion);
1678
+ //when testing what needs to be published
1679
+ return chalk.blue(pkg.packageName + ' should publish');
1680
+ }
1681
+ console.log(chalk.blue('publishing ' + pkg.packageName + ' ' + publishVersion));
1682
+ //looking for an .env.json file in our workspace, which may store our NPM AUTH key
1683
+ let envJsonPath = yield getEnvJsonPath(pkg.path);
1684
+ return execPromise(`cd ${pkg.path} && ${envJsonPath ? `env-cmd -f ${envJsonPath} --use-shell "` : ''}yarn version ${publishVersion} && yarn npm publish${envJsonPath ? `"` : ''}`, true, false, {}, true)
1685
+ .then((res) => {
1686
+ if (res.indexOf('Aborted due to warnings') !== -1 ||
1687
+ res.indexOf('Could not publish') !== -1 ||
1688
+ res.indexOf('Couldn\'t publish') !== -1) {
1689
+ console.log(res);
1690
+ return chalk.red(pkg.packageName + ' failed\n');
1691
+ }
1692
+ console.log('Successfully published ' +
1693
+ chalk.green(pkg.path) +
1694
+ ' ' +
1695
+ chalk.magenta(publishVersion));
1696
+ return (chalk.green(pkg.packageName) +
1697
+ ' published ' +
1698
+ chalk.magenta(publishVersion));
1699
+ })
1700
+ .catch(({ error, stdout, stderr }) => {
1701
+ console.log(chalk.red('Failed to publish: ' + error.message));
1702
+ return chalk.red(pkg.packageName + ' failed to publish');
1703
+ });
1704
+ });
1705
+ };
1706
+ export var buildUpdated = function (back, target, target2, useGitForLastModified = false, test = false) {
1707
+ return __awaiter(this, void 0, void 0, function* () {
1708
+ // back = back || 1;
1709
+ // return execPromise(`git log -${back} --format=%ci`).then((result) => {
1710
+ // let now = new Date();
1711
+ let previousResult = '';
1712
+ log(test
1713
+ ? 'Checking which packages need to be rebuild'
1714
+ : 'Building updated packages');
1715
+ // let packages = getLocalLincdModules();
1716
+ let packages = getLocalLincdPackageMap();
1717
+ // console.log(packages);
1718
+ let jsonldPkgUpdated = yield needsRebuilding(packages.get('lincd-jsonld'), useGitForLastModified);
1719
+ // let cliPkgUpdated = await needsRebuilding(packages.get('lincd-cli'), useGitForLastModified);
1720
+ //if either cli or jsonldPkg needs to be rebuilt
1721
+ // if (jsonldPkgUpdated || cliPkgUpdated) {
1722
+ if (jsonldPkgUpdated) {
1723
+ yield execPromise('yarn exec tsc && echo "compiled lincd-jsonld"', false, false, {
1724
+ cwd: packages.get('lincd-jsonld').path,
1725
+ }, true);
1726
+ // await execPromise('yarn build-core', false, false, {}, true);
1727
+ }
1728
+ let rebuildAllModules = false;
1729
+ // if (cliPkgUpdated) {
1730
+ // rebuildAllModules = true;
1731
+ // log(chalk.magenta('Rebuilding all packages because the build tools (lincd-cli) got updated'));
1732
+ // }
1733
+ let packagesLeft = packages.size;
1734
+ runOnPackagesGroupedByDependencies(packages, (packageGroup, dependencies) => {
1735
+ debugInfo('Now checking: ' + chalk.blue(packageGroup.map((i) => i.packageName)));
1736
+ debugInfo(packagesLeft + ' packages left.');
1737
+ packagesLeft = packagesLeft - packageGroup.length;
1738
+ return (pkg) => __awaiter(this, void 0, void 0, function* () {
1739
+ // debugInfo('# Checking package ' + pkg.packageName);
1740
+ let needRebuild = yield needsRebuilding(pkg, useGitForLastModified);
1741
+ if (pkg.packageName === 'lincd-jsonld' && jsonldPkgUpdated) {
1742
+ needRebuild = true;
1743
+ }
1744
+ if (needRebuild || rebuildAllModules) {
1745
+ //TODO: when building a pkg, also rebuild all packages that depend on this package.. and iteratively build packages that depend on those packages..
1746
+ // log(packageName+' modified since last commit on '+now.toString());
1747
+ if (test) {
1748
+ debugInfo('Need to build ' + pkg.packageName);
1749
+ return chalk.blue(pkg.packageName + ' should be build');
1750
+ }
1751
+ log('Building ' + pkg.packageName);
1752
+ // return buildPackage(null,null,pkg.path)
1753
+ return execPromise('cd ' +
1754
+ pkg.path +
1755
+ ' && yarn build' +
1756
+ (target ? ' ' + target : '') +
1757
+ (target2 ? ' ' + target2 : ''))
1758
+ .then((res) => {
1759
+ if (res === '') {
1760
+ debugInfo(chalk.green(pkg.packageName + ' successfully built'));
1761
+ return chalk.green(pkg.packageName + ' built');
1762
+ }
1763
+ else if (typeof res === 'string') {
1764
+ warn(chalk.red('Failed to build ' + pkg.packageName));
1765
+ console.log(res);
1766
+ process.exit(1);
1767
+ }
1768
+ })
1769
+ .catch(({ error, stdout, stderr }) => {
1770
+ warn(chalk.red('Failed to build ' + pkg.packageName));
1771
+ console.log(stdout);
1772
+ process.exit(1);
1773
+ // let dependentModules = getDependentPackages(dependencies, pkg);
1774
+ // if (dependentModules.length > 0) {
1775
+ // // printBuildResults(failedModules, done);
1776
+ // warn(chalk.red(pkg.packageName + ' build failed'));
1777
+ // warn(
1778
+ // 'Stopping build-updated process because ' +
1779
+ // dependentModules.length +
1780
+ // ' other packages depend on this package.\n',
1781
+ // ); //"+dependentModules.map(d => d.packageName).join(", ")));
1782
+ // }
1783
+ });
1784
+ }
1785
+ });
1786
+ }, (results) => {
1787
+ if (results.length) {
1788
+ log('Summary:');
1789
+ log(results.join('\n'));
1790
+ }
1791
+ else {
1792
+ log(chalk.green('Nothing to rebuild'));
1793
+ }
1794
+ });
1795
+ return;
1796
+ });
1797
+ };
1798
+ const printBuildResults = function (failed, done) {
1799
+ if (done.size > 0 || done.length > 0) {
1800
+ log('Successfully built: ' +
1801
+ chalk.green([...done].map((m) => m.packageName).join(', ')) +
1802
+ '\n');
1803
+ }
1804
+ if (failed.length > 0) {
1805
+ warn('Failed to build: ' + chalk.red(failed.join(', ')) + '\n');
1806
+ }
1807
+ };
1808
+ export var executeCommandForEachPackage = function (packages, command, filterMethod, filterValue) {
1809
+ //if a specific set of packages is given
1810
+ if (filterMethod == 'exclude') {
1811
+ //filter packages, so that we only execute on the packages as provided in the command
1812
+ log('Excluding ' + filterValue);
1813
+ filterValue = filterValue.split(',');
1814
+ packages = packages.filter((pkg) => filterValue.indexOf(pkg.packageName) === -1);
1815
+ }
1816
+ let startFrom;
1817
+ //by default start executing, unless 'from' is given
1818
+ let executing = true;
1819
+ //option to start from a specific pkg in the stack
1820
+ if (filterMethod == 'from') {
1821
+ startFrom = filterValue;
1822
+ if (startFrom) {
1823
+ console.log(chalk.blue('Will skip ahead to ' + startFrom));
1824
+ }
1825
+ let seen = false;
1826
+ packages = packages.filter((pkg) => {
1827
+ if (!seen &&
1828
+ pkg.packageName.includes(startFrom)) {
1829
+ seen = true;
1830
+ }
1831
+ return seen;
1832
+ });
1833
+ }
1834
+ log('Executing \'' +
1835
+ chalk.blueBright(command) +
1836
+ '\' on packages ' +
1837
+ chalk.magenta(packages.map((m) => m.packageName).join(', ')));
1838
+ var p = Promise.resolve(true);
1839
+ packages.forEach((pkg) => {
1840
+ p = p.then(() => {
1841
+ log('# Package ' + chalk.magenta(pkg.packageName));
1842
+ return execp('cd ' + pkg.path + ' && ' + command);
1843
+ });
1844
+ });
1845
+ return p;
1846
+ };
1847
+ var gitIgnore = function (...entries) {
1848
+ //add each entry to the .gitignore file
1849
+ let gitIgnorePath = path.resolve(process.cwd(), '.gitignore');
1850
+ addLinesToFile(gitIgnorePath, entries);
1851
+ };
1852
+ export var addLinesToFile = function (filePath, entries) {
1853
+ let fileContents = fs.readFileSync(filePath, { encoding: 'utf8' });
1854
+ entries.forEach((entry) => {
1855
+ fileContents += '\n' + entry;
1856
+ });
1857
+ fs.writeFileSync(filePath, fileContents);
1858
+ };
1859
+ export var addCapacitor = function (basePath = process.cwd()) {
1860
+ return __awaiter(this, void 0, void 0, function* () {
1861
+ let targetFolder = ensureFolderExists(basePath);
1862
+ log('Adding capacitor');
1863
+ fs.copySync(path.join(getScriptDir(), '..', '..', 'defaults', 'app-static'), targetFolder);
1864
+ fs.copySync(path.join(getScriptDir(), '..', '..', 'defaults', 'capacitor', 'scripts'), path.join(targetFolder, 'scripts'));
1865
+ //update .env-cmdrc.json file
1866
+ let envCmdPath = path.resolve(basePath, '.env-cmdrc.json');
1867
+ let envCmd = JSON.parse(fs.readFileSync(envCmdPath, { encoding: 'utf8' }));
1868
+ envCmd['app-main'] = {
1869
+ APP_ENV: true,
1870
+ OUTPUT_PATH: './public/assets',
1871
+ ASSET_PATH: './assets/',
1872
+ ENTRY_PATH: './src/index-static.tsx',
1873
+ };
1874
+ envCmd['app-local-android'] = {
1875
+ NODE_ENV: 'app',
1876
+ SITE_ROOT: 'http://10.0.2.2:4000',
1877
+ };
1878
+ envCmd['app-local-ios'] = {
1879
+ NODE_ENV: 'app',
1880
+ SITE_ROOT: 'http://localhost:4000',
1881
+ };
1882
+ fs.writeFile(envCmdPath, JSON.stringify(envCmd, null, 2));
1883
+ log('Edited .env-cmdrc.json');
1884
+ gitIgnore('android/app/build', 'android/**/capacitor.build.gradle', 'ios/App/App/public');
1885
+ //update package.json scripts
1886
+ let pack = getPackageJSON(basePath);
1887
+ pack.scripts['build-staging'] =
1888
+ 'env-cmd -e _main, staging node scripts/build.js';
1889
+ pack.scripts['fix-app'] = 'node scripts/fix-namespace.js';
1890
+ pack.scripts['app'] =
1891
+ 'env-cmd -e _main,production,app-main node scripts/build.js && npx cap sync && yarn run fix-app';
1892
+ pack.scripts['app-local-ios'] =
1893
+ 'env-cmd -e _main,development,app-main,app-local-ios node scripts/build.js && npx cap sync && yarn run fix-app';
1894
+ pack.scripts['app-local-android'] =
1895
+ 'env-cmd -e _main,development,app-main,app-local-android node scripts/build.js && npx cap sync && yarn run fix-app';
1896
+ pack.scripts['cap:android'] = 'yarn cap open android';
1897
+ pack.scripts['cap:ios'] = 'yarn cap open ios';
1898
+ pack.scripts['cap:sync'] = 'yarn cap sync';
1899
+ fs.writeFile(path.resolve(basePath, 'package.json'), JSON.stringify(pack, null, 2));
1900
+ log('Added new run script to package.json');
1901
+ yield execPromise(`yarn add -D @capacitor/cli`, true, false, null, true);
1902
+ yield execPromise(`yarn add @capacitor/android @capacitor/core @capacitor/app @capacitor/ios`, false, false, null, true);
1903
+ // TODO: Do we need to add `npx cap init`? If yes, we should not copy capacitor config.ts yet
1904
+ // await execPromise(`npx cap init`, true, false, null, true);
1905
+ // got error:
1906
+ // [error] Non-interactive shell detected.
1907
+ // Run the command with --help to see a list of arguments that must be provided.
1908
+ // [error] Non-interactive shell detected.
1909
+ // Run the command with --help to see a list of arguments that must be provided.
1910
+ log(`Done! Now update your Capacitor configuration by providing an app name, app ID, and web directory at ${chalk.blue('capacitor.config.ts')}`);
1911
+ log(`And then run ${chalk.magenta('yarn cap add android')} and/or ${chalk.magenta('yarn cap add ios')}')`);
1912
+ log(`Last, run ${chalk.magenta('yarn app')} or ${chalk.magenta('yarn app-local-ios')} or ${chalk.magenta('yarn app-local-android')}`);
1913
+ });
1914
+ };
1915
+ export var executeCommandForPackage = function (packageName, command) {
1916
+ let packageDetails = getLincdPackages().find((modDetails) => modDetails.packageName.indexOf(packageName) !== -1 ||
1917
+ modDetails.packageName.indexOf(packageName) !== -1);
1918
+ if (packageDetails) {
1919
+ log('Executing \'cd ' +
1920
+ packageDetails.path +
1921
+ ' && yarn exec lincd' +
1922
+ (command ? ' ' + command : '') +
1923
+ '\'');
1924
+ return execp('cd ' +
1925
+ packageDetails.path +
1926
+ ' && yarn exec lincd' +
1927
+ (command ? ' ' + command : ''));
1928
+ }
1929
+ else {
1930
+ warn('Could not find a pkg who\'s name (partially) matched ' +
1931
+ chalk.cyan(packageName));
1932
+ }
1933
+ };
1934
+ /**
1935
+ * Function to remove files older than 10 seconds from the 'lib' folder.
1936
+ * @param {string} packagePath - The path to the package directory.
1937
+ */
1938
+ export const removeOldFiles = (packagePath) => __awaiter(void 0, void 0, void 0, function* () {
1939
+ const libPath = path.join(packagePath, 'lib');
1940
+ try {
1941
+ // Read all files in the 'lib' folder asynchronously
1942
+ const files = yield glob(packagePath + '/lib/**/*.*');
1943
+ // Iterate through each file
1944
+ for (const file of files) {
1945
+ // const filePath = path.join(libPath, file);
1946
+ // Check if the file exists before attempting to delete it
1947
+ // if (await fs.pathExists(filePath)) {
1948
+ const stats = yield fs.stat(file);
1949
+ const currentTime = new Date().getTime();
1950
+ const lastModifiedTime = stats.mtime.getTime();
1951
+ // Check if the difference between the current time and last modified time is greater than 120 seconds
1952
+ if (currentTime - lastModifiedTime > 120000) {
1953
+ // Attempt to delete the file
1954
+ yield fs.unlink(file);
1955
+ // console.log(`Removed: ${file}`);
1956
+ }
1957
+ // }
1958
+ }
1959
+ return true;
1960
+ }
1961
+ catch (error) {
1962
+ console.error(`Error removing files: ${error.message}`);
1963
+ return false;
1964
+ }
1965
+ });
1966
+ //# sourceMappingURL=cli-methods.js.map