@infomaximum/package-cli 1.21.0 → 2.0.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 (48) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +68 -7
  3. package/dist/arguments.js +3 -30
  4. package/dist/const.js +1 -6
  5. package/dist/{configs → package/configs}/webpack/buildPackage.js +15 -17
  6. package/dist/package/packagePaths.js +7 -0
  7. package/dist/{templates/package → package/templates}/packageManifest.js +1 -1
  8. package/dist/paths.js +20 -57
  9. package/dist/plopHelpers.js +6 -0
  10. package/dist/utils.js +3 -38
  11. package/dist/widget/commands.js +73 -0
  12. package/dist/widget/configs/file.js +11 -0
  13. package/dist/{configs → widget/configs}/webpack/common.js +17 -15
  14. package/dist/{configs → widget/configs}/webpack/sections/loaders/cssLoaders.js +1 -1
  15. package/dist/widget/configs/webpack/sections/plugins/modifyManifestWidget.js +27 -0
  16. package/dist/widget/configs/webpack/sections/plugins/zipWidget.js +13 -0
  17. package/dist/widget/const.js +8 -0
  18. package/dist/widget/index.js +1 -0
  19. package/dist/widget/scripts/build.js +83 -0
  20. package/dist/{scripts/widget → widget/scripts}/init/actions.js +20 -13
  21. package/dist/{scripts/widget → widget/scripts}/init/generators.js +2 -2
  22. package/dist/{scripts/widget → widget/scripts}/init/init.js +0 -9
  23. package/dist/{scripts/widget → widget/scripts}/start.js +11 -11
  24. package/dist/{templates/widget → widget/templates}/src/definition/definition.js +1 -1
  25. package/dist/{templates/widget → widget/templates}/src/definition/panel.js +1 -1
  26. package/dist/{templates/widget → widget/templates}/src/definition/settings.js +1 -1
  27. package/dist/{templates/widget → widget/templates}/src/widgetAppDTs.js +1 -1
  28. package/dist/{templates/widget → widget/templates}/src/widgetIndex.js +3 -2
  29. package/dist/{templates/widget → widget/templates}/widgetManifest.js +1 -1
  30. package/dist/{templates/widget → widget/templates}/widgetPackageJson.js +2 -1
  31. package/dist/widget/templates/widgetRCConfig.js +15 -0
  32. package/dist/widget/utils.js +41 -0
  33. package/dist/widget/widgetPaths.js +8 -0
  34. package/package.json +3 -2
  35. package/schemas/widgetConfigSchema.json +48 -0
  36. package/dist/configs/webpack/sections/plugins/modifyManifestWidget.js +0 -25
  37. package/dist/configs/webpack/sections/plugins/zipWidget.js +0 -11
  38. package/dist/scripts/widget/build.js +0 -66
  39. package/dist/scripts/widget/init/helpers.js +0 -6
  40. /package/dist/{templates/package → package/templates}/additionalFiles.js +0 -0
  41. /package/dist/{templates/package → package/templates}/packageIcon.js +0 -0
  42. /package/dist/{configs → widget/configs}/webpack/sections/devServer.js +0 -0
  43. /package/dist/{configs → widget/configs}/webpack/sections/devtool.js +0 -0
  44. /package/dist/{configs → widget/configs}/webpack/sections/plugins/minimizer.js +0 -0
  45. /package/dist/{configs → widget/configs}/webpack/sections/plugins/reactRefresh.js +0 -0
  46. /package/dist/{scripts/widget → widget/scripts}/init/prompts.js +0 -0
  47. /package/dist/{templates/widget → widget/templates}/src/widgetIndexCSS.js +0 -0
  48. /package/dist/{templates/widget → widget/templates}/widgetConfigs.js +0 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,33 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [2.0.0](https://github.com/Infomaximum/package-cli/compare/v1.21.1...v2.0.0) (2024-02-29)
6
+
7
+
8
+ ### ⚠ BREAKING CHANGES
9
+
10
+ * использование конфига для работы с проектам
11
+
12
+ ### Features
13
+
14
+ * добавлен шаблон конфига виджета ([10eb6e4](https://github.com/Infomaximum/package-cli/commit/10eb6e46e3864b30337fa34d4f1b25e8a1cf3b23))
15
+ * добавлено описание полей конфига ([704a72b](https://github.com/Infomaximum/package-cli/commit/704a72b19fc58419a58e524af3ae306ee211910f))
16
+ * использование конфига для работы с проектам ([46df151](https://github.com/Infomaximum/package-cli/commit/46df15186558105407c0abf5230546bd6dfc9d34))
17
+
18
+
19
+ ### Bug Fixes
20
+
21
+ * использованы константы ([42fac3e](https://github.com/Infomaximum/package-cli/commit/42fac3e14cf8dd80798d09c8debff96e089cab83))
22
+ * путь до пакета ([5941def](https://github.com/Infomaximum/package-cli/commit/5941defe45eda388aaa93c8dd5ad73626338a22d))
23
+ * удалено поле ([31dca08](https://github.com/Infomaximum/package-cli/commit/31dca08a70dccf4af8e0bd61096ed4e8e36e08ac))
24
+
25
+ ### [1.21.1](https://github.com/Infomaximum/package-cli/compare/v1.21.0...v1.21.1) (2024-02-26)
26
+
27
+
28
+ ### Bug Fixes
29
+
30
+ * удаление поля "$schema" из манифеста виджета ([752f68d](https://github.com/Infomaximum/package-cli/commit/752f68dcb9b191853a456c146151225136b4dbd3))
31
+
5
32
  ## [1.21.0](https://github.com/Infomaximum/package-cli/compare/v1.20.0...v1.21.0) (2024-02-26)
6
33
 
7
34
 
package/README.md CHANGED
@@ -6,7 +6,9 @@
6
6
  <img alt="npm" src="https://img.shields.io/npm/v/@infomaximum/package-cli?style=for-the-badge">
7
7
  </a>
8
8
 
9
- ## Инициализация проекта
9
+ ## Разработка виджета
10
+
11
+ ### Инициализация проекта
10
12
 
11
13
  Для создания нового пакета с виджетом необходимо выполнить следующую команду:
12
14
 
@@ -14,27 +16,86 @@
14
16
 
15
17
  После выполнения данной команды будет создан шаблонный проект **my_widget** и инициализирован git репозиторий.
16
18
 
17
- ## Разработка виджета
19
+ ### Разработка виджета
18
20
 
19
21
  Для разработки виджета нужно выполнить команду:
20
22
 
21
- `yarn build:dev`
23
+ `yarn im-package-cli widget build --dev`
22
24
 
23
25
  Данная команда выполняет сборку пакета для разработки. Далее, пакет (собранный архив из папки build) необходимо загрузить в систему. Для этого добавляем пакет в маркетплейс либо в пространство, а так же добавляем разрабатываемый виджет на холст (дашбординг).
24
26
 
25
27
  Затем необходимо запустить сервер разработки следующей командой:
26
28
 
27
- `yarn start`
29
+ `yarn im-package-cli widget start`
28
30
 
29
31
  В результате будет запущен сервер отслеживающий изменения проекта и выполняющий горячую перезагрузку разрабатываемого компонента.
30
32
 
31
- ## Сборка пакета
33
+ ### Сборка пакета
32
34
 
33
35
  Для того чтобы пользователи имели возможность использовать разработанный вами виджет, необходимо выполнить сборку пакета, для этого выполняем команду:
34
36
 
35
- `yarn build`
37
+ `yarn im-package-cli widget build`
38
+
39
+ Полученный в результате выполнения данной команды пакет можно загрузить в систему.
40
+
41
+ ### Файл конфигурации виджета
42
+
43
+ #### **`widgetrc.json`**
44
+
45
+ ```json
46
+ {
47
+ "$schema": "node_modules/@infomaximum/package-cli/schemas/widgetConfigSchema.json",
48
+ "entry": "src/index.tsx",
49
+ "widgetManifest": "manifest.json",
50
+ "packageManifest": "package/manifest.json",
51
+ "packageDir": "package",
52
+ "assetsDir": "_resources",
53
+ "buildDir": "build",
54
+ "port": 5555,
55
+ "host": "localhost"
56
+ }
57
+ ```
58
+
59
+ - `entry`: Путь к точке входа вашего приложения
60
+ - `widgetManifest`: Путь к файлу манифеста виджета
61
+
62
+ - `packageManifest`: Путь к файлу манифеста пакета
63
+
64
+ - `packageDir`: Путь к каталогу пакета
65
+
66
+ - `assetsDir`: Путь к каталогу ресурсов
67
+
68
+ - `buildDir`: Путь к каталогу сборки
69
+
70
+ - `port`: Порт, на котором будет запущен сервер разработки
71
+
72
+ - `host`: Хост, на котором будет запущен сервер разработки
73
+
74
+ Этот файл должен называться `widgetrc.json`, но также может иметь расширение `.js`, `.yaml`. Кроме того, конфигурацию можно добавить в `package.json` в поле `widget`. Примерно так:
75
+
76
+ #### **`package.json`**
77
+
78
+ ```json
79
+ {
80
+ "name": "my_widget",
81
+ "version": "1.0.0",
82
+ "dependencies": {
83
+ ...
84
+ },
85
+ "widget": {
86
+ "entry": "src/index.tsx",
87
+ "widgetManifest": "manifest.json",
88
+ "packageManifest": "package/manifest.json",
89
+ "packageDir": "package",
90
+ "assetsDir": "_resources",
91
+ "buildDir": "build",
92
+ "port": 5555,
93
+ "host": "localhost"
94
+ }
95
+ }
96
+ ```
36
97
 
37
- Полученный в результате выполнения данной команды пакет можно загрузить в маркетплейс.
98
+ Эта конфигурация определяет, как будут собираться и запускаться ваш пакет или виджет с использованием `@infomaximum/package-cli`.
38
99
 
39
100
  ## Вывод всех доступных команд
40
101
 
package/dist/arguments.js CHANGED
@@ -1,36 +1,9 @@
1
- import { runBuild } from "./scripts/widget/build.js";
2
- import { runDevServer } from "./scripts/widget/start.js";
3
- import { runInitWidget } from "./scripts/widget/init/init.js";
4
1
  import { systemRequire } from "./utils.js";
5
- import { DEFAULT_HOST, DEFAULT_PORT } from "./const.js";
2
+ import { registerWidgetCommands } from "./widget/index.js";
6
3
  const packageJson = systemRequire("../package.json");
7
- const registerWidgetCommands = (cli) => {
8
- const widgetCommand = cli.command("widget");
9
- const widgetBuildCommand = widgetCommand.command("build");
10
- widgetBuildCommand
11
- .description("Выполняет сборку пакета для дальнейшей загрузки в систему")
12
- .option("-e, --entry <path>", "Путь до entrypoint")
13
- .option("-p, --port <port>", "Порт который будет указан в манифесте виджета")
14
- .option("--host <host>", "host который будет указан в манифесте виджета")
15
- .description("Запускает сборку проекта")
16
- .action((options) => runBuild(options));
17
- const widgetStartCommand = widgetCommand.command("start");
18
- widgetStartCommand
19
- .description("Выполняет запуск проекта для разработки")
20
- .option("-e, --entry <path>", "Путь до entrypoint")
21
- .option("-p, --port <port>", "Порт на котором будет доступен виджет", DEFAULT_PORT)
22
- .option("--host <host>", "host на котором будет доступен виджет", DEFAULT_HOST)
23
- .action((options) => runDevServer(options));
24
- const widgetInitCommand = widgetCommand.command("init <project-directory>");
25
- widgetInitCommand
26
- .description("Создание виджета")
27
- .action((dirName) => {
28
- runInitWidget(dirName);
29
- });
30
- };
31
4
  export const registerCommands = (cli) => {
32
- cli.helpOption("-h", "Отображает помощь по командам");
5
+ cli.helpOption("-h", "отображает помощь по командам");
33
6
  cli.name("im-package-cli");
34
- cli.version(packageJson.version, "-v, --version", "Текущая версия библиотеки");
7
+ cli.version(packageJson.version, "-v, --version", "текущая версия библиотеки");
35
8
  registerWidgetCommands(cli);
36
9
  };
package/dist/const.js CHANGED
@@ -1,12 +1,7 @@
1
- export const WIDGET_SDK_LIB_NAME = "@infomaximum/widget-sdk";
2
1
  export const CUSTOM_PACKAGE_CLI_LIB_NAME = "@infomaximum/package-cli";
3
- export const WIDGET_ARCHIVE_NAME = "widget";
4
2
  export const BUILD_ARCHIVE_EXT = "zip";
5
- export const WIDGET_ARCHIVE_FULL_NAME = `${WIDGET_ARCHIVE_NAME}.${BUILD_ARCHIVE_EXT}`;
6
- export const DEFAULT_HOST = "localhost";
7
- export const DEFAULT_PORT = "5555";
8
3
  export const MANIFEST_JSON_FILE_NAME = "manifest.json";
9
4
  export const MANIFEST_REG_EXP = new RegExp(`${MANIFEST_JSON_FILE_NAME}$`, "i");
10
5
  export const DEV_POSTFIX = "__DEV";
11
- export const WIDGET_RESOURCES_DIR_NAME = "_resources";
6
+ export const DEFAULT_BUILD_DIR_NAME = "build";
12
7
  export const MANIFEST_SERVICE_FIELDS_FOR_DEVELOPMENT = ["$schema"];
@@ -2,26 +2,24 @@ import { __awaiter } from "tslib";
2
2
  import ZipPlugin from "zip-webpack-plugin";
3
3
  import RemovePlugin from "remove-files-webpack-plugin";
4
4
  import CopyWebpackPlugin from "copy-webpack-plugin";
5
- import path from "path";
6
5
  import { JsonModifyWebpackPlugin } from "@infomaximum/json-modify-webpack-plugin";
7
- import { isExist, removeServiceFieldsForDevelopment, systemRequire, } from "../../utils.js";
8
- import { BUILD_ARCHIVE_EXT, DEV_POSTFIX, MANIFEST_REG_EXP, WIDGET_ARCHIVE_FULL_NAME, } from "../../const.js";
6
+ import { isExist, removeServiceFieldsForDevelopment, systemRequire, } from "../../../utils.js";
7
+ import { BUILD_ARCHIVE_EXT, DEV_POSTFIX, MANIFEST_REG_EXP, } from "../../../const.js";
9
8
  import { assertSimple } from "@infomaximum/assert";
10
9
  const packageFilename = "main.js";
11
- export const getPackageConfig = (mode, PATHS, isBuildDevMode) => __awaiter(void 0, void 0, void 0, function* () {
12
- const widgetVersion = systemRequire(PATHS.appPackageJson).version;
13
- const manifestPackageName = systemRequire(PATHS.packageManifest).name;
14
- let widgetPackageName = `${manifestPackageName}_${widgetVersion}`;
10
+ export const getPackageBuildConfig = ({ mode, PATHS, isBuildDevMode, entityArchivePath, }) => __awaiter(void 0, void 0, void 0, function* () {
11
+ const entityVersion = systemRequire(PATHS.appPackageJson).version;
12
+ const manifestPackageName = systemRequire(PATHS.packageManifestPath).name;
13
+ let entityPackageName = `${manifestPackageName}_${entityVersion}`;
15
14
  if (isBuildDevMode)
16
- widgetPackageName += DEV_POSTFIX;
17
- const widgetArchivePath = path.resolve(PATHS.appBuild, WIDGET_ARCHIVE_FULL_NAME);
18
- assertSimple(yield isExist(PATHS.packageManifest), `File ${PATHS.packageManifest} not found`);
19
- assertSimple(yield isExist(widgetArchivePath), `File ${widgetArchivePath} not found`);
15
+ entityPackageName += DEV_POSTFIX;
16
+ assertSimple(yield isExist(PATHS.packageManifestPath), `File ${PATHS.packageManifestPath} not found`);
17
+ assertSimple(yield isExist(entityArchivePath), `File ${entityArchivePath} not found`);
20
18
  return {
21
19
  mode,
22
- entry: [PATHS.packageManifest, widgetArchivePath],
20
+ entry: [PATHS.packageManifestPath, entityArchivePath],
23
21
  output: {
24
- path: PATHS.appBuild,
22
+ path: PATHS.appBuildPath,
25
23
  filename: packageFilename,
26
24
  clean: true,
27
25
  },
@@ -50,7 +48,7 @@ export const getPackageConfig = (mode, PATHS, isBuildDevMode) => __awaiter(void
50
48
  new RemovePlugin({
51
49
  after: {
52
50
  log: false,
53
- root: PATHS.appBuild,
51
+ root: PATHS.appBuildPath,
54
52
  test: [
55
53
  {
56
54
  folder: ".",
@@ -58,11 +56,11 @@ export const getPackageConfig = (mode, PATHS, isBuildDevMode) => __awaiter(void
58
56
  recursive: true,
59
57
  },
60
58
  ],
61
- exclude: [`${widgetPackageName}.${BUILD_ARCHIVE_EXT}`],
59
+ exclude: [`${entityPackageName}.${BUILD_ARCHIVE_EXT}`],
62
60
  },
63
61
  }),
64
62
  new ZipPlugin({
65
- filename: widgetPackageName,
63
+ filename: entityPackageName,
66
64
  extension: BUILD_ARCHIVE_EXT,
67
65
  exclude: [packageFilename],
68
66
  }),
@@ -71,7 +69,7 @@ export const getPackageConfig = (mode, PATHS, isBuildDevMode) => __awaiter(void
71
69
  {
72
70
  matcher: MANIFEST_REG_EXP,
73
71
  action: (currentJsonContent) => {
74
- currentJsonContent.version = widgetVersion;
72
+ currentJsonContent.version = entityVersion;
75
73
  const packageName = currentJsonContent.name;
76
74
  if (isBuildDevMode && typeof packageName === "string") {
77
75
  Object.assign(currentJsonContent, {
@@ -0,0 +1,7 @@
1
+ import { _resolveApp, generateGlobalPaths } from "../paths.js";
2
+ export function generatePackagePaths({ packageDir, packageManifest, buildDirPath, }) {
3
+ const globalPaths = generateGlobalPaths({ buildDirPath });
4
+ const resolveApp = _resolveApp();
5
+ const packagePath = resolveApp(packageDir);
6
+ return Object.assign(Object.assign({}, globalPaths), { packagePath, packageDirPath: resolveApp(packageDir), packageManifestPath: resolveApp(packageManifest) });
7
+ }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { capitalizeHelperName } from "../../scripts/widget/init/helpers.js";
3
2
  import { CUSTOM_PACKAGE_CLI_LIB_NAME } from "../../const.js";
3
+ import { capitalizeHelperName } from "../../plopHelpers.js";
4
4
  export const PACKAGE_MANIFEST_TEMPLATE = `\
5
5
  {
6
6
  "$schema": "../node_modules/${CUSTOM_PACKAGE_CLI_LIB_NAME}/schemas/packageManifestSchema.json",
package/dist/paths.js CHANGED
@@ -2,61 +2,16 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { systemRequire } from "./utils.js";
4
4
  import chalk from "chalk";
5
- import { MANIFEST_JSON_FILE_NAME, WIDGET_RESOURCES_DIR_NAME } from "./const.js";
6
- const appDirectory = fs.realpathSync(process.cwd());
7
- const _resolveApp = (cwd = appDirectory) => (relativePath) => path.resolve(cwd, relativePath);
8
- const moduleFileExtensions = [
9
- "web.mjs",
10
- "mjs",
11
- "web.js",
12
- "js",
13
- "web.ts",
14
- "ts",
15
- "web.tsx",
16
- "tsx",
17
- "json",
18
- "web.jsx",
19
- "jsx",
20
- "module.ts",
21
- "module.tsx",
22
- ];
23
- const resolveModule = (resolveFn, filePath) => {
24
- const extension = moduleFileExtensions.find((extension) => fs.existsSync(resolveFn(`${filePath}.${extension}`)));
25
- if (extension) {
26
- return resolveFn(`${filePath}.${extension}`);
27
- }
28
- return resolveFn(`${filePath}.js`);
29
- };
30
- export const generatePaths = (args) => {
31
- const { entryPath, cwd } = args;
32
- const resolveApp = _resolveApp(cwd);
33
- const packagePath = resolveApp("package");
34
- return {
35
- appPath: resolveApp("."),
36
- appBuild: resolveApp("build"),
37
- resourcesWidget: resolveApp(WIDGET_RESOURCES_DIR_NAME),
38
- get moduleIndex() {
39
- return generateIndexPath(cwd, entryPath);
40
- },
41
- appPackageJson: resolveApp("package.json"),
42
- manifestJson: resolveApp(MANIFEST_JSON_FILE_NAME),
43
- packagePath,
44
- packageManifest: resolveApp(path.resolve(packagePath, MANIFEST_JSON_FILE_NAME)),
45
- appTsConfig: resolveApp("tsconfig.json"),
46
- appNodeModules: resolveApp("node_modules"),
47
- publicPath: "/",
48
- };
49
- };
50
- export const MODE = {
51
- DEV: "development",
52
- PROD: "production",
53
- };
54
- const generateIndexPath = (cwd, entryPath) => {
5
+ export const appDirectory = fs.realpathSync(process.cwd());
6
+ export const _resolveApp = (cwd = appDirectory) => (relativePath) => path.resolve(cwd, relativePath);
7
+ export const generateIndexPath = (entryPath) => {
55
8
  var _a;
56
- const resolveApp = _resolveApp(cwd);
57
- const indexSrcPath = resolveModule(resolveApp, "src/index");
58
- if (entryPath && fs.existsSync(entryPath)) {
59
- return entryPath;
9
+ const resolveApp = _resolveApp();
10
+ if (entryPath) {
11
+ const _entryPath = resolveApp(entryPath);
12
+ if (fs.existsSync(_entryPath)) {
13
+ return _entryPath;
14
+ }
60
15
  }
61
16
  try {
62
17
  const mainIndexPath = resolveApp((_a = systemRequire(resolveApp("package.json"))) === null || _a === void 0 ? void 0 : _a.main);
@@ -67,9 +22,17 @@ const generateIndexPath = (cwd, entryPath) => {
67
22
  catch (error) {
68
23
  console.error(chalk.red("main field not found in package.json"));
69
24
  }
70
- if (fs.existsSync(indexSrcPath)) {
71
- return indexSrcPath;
72
- }
73
25
  console.error(chalk.red("entry file not found"));
74
26
  process.exit(1);
75
27
  };
28
+ export const generateGlobalPaths = (args) => {
29
+ const { cwd, buildDirPath } = args || {};
30
+ const resolveApp = _resolveApp(cwd);
31
+ return {
32
+ appPath: resolveApp("."),
33
+ appBuildPath: resolveApp(buildDirPath),
34
+ appPackageJson: resolveApp("package.json"),
35
+ appTsConfig: resolveApp("tsconfig.json"),
36
+ appNodeModules: resolveApp("node_modules"),
37
+ };
38
+ };
@@ -0,0 +1,6 @@
1
+ import { capitalizeFirstLetter } from "./utils.js";
2
+ const capitalizeHelperName = "capitalize";
3
+ const addCommonHelpers = (plop) => {
4
+ plop.setHelper(capitalizeHelperName, capitalizeFirstLetter);
5
+ };
6
+ export { capitalizeHelperName, addCommonHelpers };
package/dist/utils.js CHANGED
@@ -4,9 +4,8 @@ import path from "node:path";
4
4
  import { spawn, exec } from "node:child_process";
5
5
  import util from "node:util";
6
6
  import Module from "node:module";
7
- import semver from "semver";
8
- import chalk from "chalk";
9
- import { CUSTOM_PACKAGE_CLI_LIB_NAME, MANIFEST_SERVICE_FIELDS_FOR_DEVELOPMENT, WIDGET_SDK_LIB_NAME, } from "./const.js";
7
+ import { CUSTOM_PACKAGE_CLI_LIB_NAME, MANIFEST_SERVICE_FIELDS_FOR_DEVELOPMENT, } from "./const.js";
8
+ import { WIDGET_SDK_LIB_NAME } from "./widget/const.js";
10
9
  const execPromise = util.promisify(exec);
11
10
  export const isExist = (entityPath) => __awaiter(void 0, void 0, void 0, function* () {
12
11
  try {
@@ -57,43 +56,9 @@ export function spawnCommand(command, args, options) {
57
56
  });
58
57
  });
59
58
  }
60
- export function checkLatestVersion(libName) {
61
- var _a, _b, _c;
62
- return __awaiter(this, void 0, void 0, function* () {
63
- const libVersionInProject = yield getLibraryVersionInProject(libName);
64
- if (!libVersionInProject)
65
- return;
66
- const libVersionFromProject = (_c = (((_a = libVersionInProject === null || libVersionInProject === void 0 ? void 0 : libVersionInProject.dependencies) === null || _a === void 0 ? void 0 : _a[libName]) ||
67
- ((_b = libVersionInProject === null || libVersionInProject === void 0 ? void 0 : libVersionInProject.devDependencies) === null || _b === void 0 ? void 0 : _b[libName]))) === null || _c === void 0 ? void 0 : _c.version;
68
- if (!libVersionFromProject)
69
- return;
70
- const latestVersion = yield getLatestVersionOfLibrary(libName);
71
- if (!latestVersion)
72
- return;
73
- const isOldVersion = semver.gt(latestVersion, libVersionFromProject);
74
- if (isOldVersion) {
75
- console.error(chalk.yellow(`\n\nA new version of the ${chalk.underline(`${libName}@${latestVersion}`)} library has been released,\n` +
76
- `old version ${libVersionFromProject} is used in the project, it is recommended to ` +
77
- `update to the latest version \n` +
78
- chalk.green.bold(chalk.underline(`npm i --save ${libName}@${latestVersion}`) +
79
- " or " +
80
- chalk.underline(`yarn upgrade ${libName}@${latestVersion}\n\n`))));
81
- }
82
- });
83
- }
84
- export function checkLatestLibsVersion() {
85
- return __awaiter(this, void 0, void 0, function* () {
86
- try {
87
- yield Promise.allSettled([
88
- checkLatestVersion(WIDGET_SDK_LIB_NAME),
89
- checkLatestVersion(CUSTOM_PACKAGE_CLI_LIB_NAME),
90
- ]);
91
- }
92
- catch (error) { }
93
- });
94
- }
95
59
  export function removeServiceFieldsForDevelopment(obj) {
96
60
  MANIFEST_SERVICE_FIELDS_FOR_DEVELOPMENT.forEach((key) => {
97
61
  delete obj[key];
98
62
  });
99
63
  }
64
+ export const compact = (items) => items.filter(Boolean);
@@ -0,0 +1,73 @@
1
+ import { runBuild } from "./scripts/build.js";
2
+ import { runDevServer } from "./scripts/start.js";
3
+ import { runInitWidget } from "./scripts/init/init.js";
4
+ import { getConfigFromFile } from "./configs/file.js";
5
+ import { assertSilent, assertSimple } from "@infomaximum/assert";
6
+ import chalk from "chalk";
7
+ import { WIDGET_DEFAULT_HOST, WIDGET_DEFAULT_PORT } from "./const.js";
8
+ import { DEFAULT_BUILD_DIR_NAME } from "../const.js";
9
+ function configMergeWithOptionsCommon(config, options) {
10
+ const entry = options.entry || (config === null || config === void 0 ? void 0 : config.entry);
11
+ const assetsDir = options["assets-dir"] || (config === null || config === void 0 ? void 0 : config.assetsDir);
12
+ const packageDir = options["package-dir"] || (config === null || config === void 0 ? void 0 : config.packageDir);
13
+ const buildDir = (config === null || config === void 0 ? void 0 : config.buildDir) || DEFAULT_BUILD_DIR_NAME;
14
+ const packageManifest = options["package-manifest"] || (config === null || config === void 0 ? void 0 : config.packageManifest);
15
+ const widgetManifest = options["widget-manifest"] || (config === null || config === void 0 ? void 0 : config.widgetManifest);
16
+ assertSimple(!!entry, chalk.red("В конфигурации не задан entry"));
17
+ assertSimple(!!packageDir, chalk.red("В конфигурации не задан packageDir"));
18
+ assertSimple(!!packageManifest, chalk.red("В конфигурации не задан packageManifest"));
19
+ assertSimple(!!widgetManifest, chalk.red("В конфигурации не задан widgetManifest"));
20
+ return {
21
+ entry,
22
+ assetsDir,
23
+ packageDir,
24
+ packageManifest,
25
+ widgetManifest,
26
+ buildDir,
27
+ };
28
+ }
29
+ function configMergeWithOptionsStart(options) {
30
+ const config = getConfigFromFile();
31
+ const host = options.host || (config === null || config === void 0 ? void 0 : config.host);
32
+ const port = options.port || (config === null || config === void 0 ? void 0 : config.port);
33
+ assertSilent(!!host, chalk.yellow(`В конфигурациях не найден host, используется host по умолчанию "${WIDGET_DEFAULT_HOST}"`));
34
+ assertSilent(!!port, chalk.yellow(`В конфигурациях не найден port, используется port по умолчанию "${WIDGET_DEFAULT_PORT}"`));
35
+ return Object.assign({ host: host || WIDGET_DEFAULT_HOST, port: port || WIDGET_DEFAULT_PORT }, configMergeWithOptionsCommon(config, options));
36
+ }
37
+ function configMergeWithOptionsBuild(options) {
38
+ const config = getConfigFromFile();
39
+ return Object.assign({ host: options.host || (config === null || config === void 0 ? void 0 : config.host), port: options.port || (config === null || config === void 0 ? void 0 : config.port), dev: options.dev }, configMergeWithOptionsCommon(config, options));
40
+ }
41
+ function registerCommonOption(command) {
42
+ command
43
+ .option("--entry <path>", "путь до entrypoint")
44
+ .option("--assets-dir <assetsDirPath>", "путь до директории с ресурсами виджета, которые будут перенесены в архив с виджетом")
45
+ .option("--package-manifest <manifestPath>", "путь до файла манифеста пакета")
46
+ .option("--package-dir <packageDirPath>", "путь до директории с файлами пакета")
47
+ .option("--widget-manifest <manifestPath>", "путь до файла манифеста виджета");
48
+ }
49
+ export const registerWidgetCommands = (cli) => {
50
+ const widgetCommand = cli.command("widget");
51
+ const widgetBuildCommand = widgetCommand.command("build");
52
+ registerCommonOption(widgetBuildCommand);
53
+ widgetBuildCommand
54
+ .description("Выполняет сборку пакета")
55
+ .option("--build-dir <buildDirPath>", "путь до директории в которую будет собран пакет")
56
+ .option("--dev", "собрать пакет для разработки", false)
57
+ .option("--host <host>", "хост который будет указан в манифесте виджета")
58
+ .option("--port <port>", "порт который будет указан в манифесте виджета")
59
+ .action((options) => runBuild(configMergeWithOptionsBuild(options)));
60
+ const widgetStartCommand = widgetCommand.command("start");
61
+ registerCommonOption(widgetStartCommand);
62
+ widgetStartCommand
63
+ .description("Выполняет запуск проекта для разработки")
64
+ .option("--port <port>", "порт на котором будет доступен виджет")
65
+ .option("--host <host>", "host на котором будет доступен виджет")
66
+ .action((options) => runDevServer(configMergeWithOptionsStart(options)));
67
+ const widgetInitCommand = widgetCommand.command("init <project-directory>");
68
+ widgetInitCommand
69
+ .description("Инициализация проекта виджета")
70
+ .action((dirName) => {
71
+ runInitWidget(dirName);
72
+ });
73
+ };
@@ -0,0 +1,11 @@
1
+ import { rcFile } from "rc-config-loader";
2
+ import { WIDGET_CONFIG_FILE_NAME, WIDGET_CONFIG_FIELD_NAME } from "../const.js";
3
+ export const getConfigFromFile = () => {
4
+ var _a;
5
+ const config = (_a = rcFile(WIDGET_CONFIG_FILE_NAME, {
6
+ cwd: process.cwd(),
7
+ packageJSON: { fieldName: WIDGET_CONFIG_FIELD_NAME },
8
+ configFileName: WIDGET_CONFIG_FILE_NAME,
9
+ })) === null || _a === void 0 ? void 0 : _a.config;
10
+ return config;
11
+ };
@@ -2,19 +2,20 @@ import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
2
2
  import { TsconfigPathsPlugin } from "tsconfig-paths-webpack-plugin";
3
3
  import CopyWebpackPlugin from "copy-webpack-plugin";
4
4
  import webpack, {} from "webpack";
5
- import { systemRequire } from "../../utils.js";
6
- import { WIDGET_RESOURCES_DIR_NAME, MANIFEST_REG_EXP } from "../../const.js";
7
5
  import { cssLoaders } from "./sections/loaders/cssLoaders.js";
6
+ import { systemRequire } from "../../../utils.js";
7
+ import { MANIFEST_REG_EXP } from "../../../const.js";
8
+ import path from "path";
8
9
  const { ProgressPlugin } = webpack;
9
10
  const isProduction = (mode) => mode === "production";
10
11
  const isDevelopment = (mode) => mode === "development";
11
12
  export const getCommonWidgetConfig = (mode, PATHS) => {
12
13
  return {
13
14
  mode,
14
- entry: [PATHS.moduleIndex, PATHS.manifestJson],
15
+ entry: [PATHS.moduleIndex, PATHS.widgetManifestJsonPath],
15
16
  output: {
16
- path: PATHS.appBuild,
17
- filename: systemRequire(PATHS.manifestJson).entry,
17
+ path: PATHS.appBuildPath,
18
+ filename: systemRequire(PATHS.widgetManifestJsonPath).entry,
18
19
  asyncChunks: false,
19
20
  clean: true,
20
21
  },
@@ -29,16 +30,17 @@ export const getCommonWidgetConfig = (mode, PATHS) => {
29
30
  },
30
31
  },
31
32
  }),
32
- new CopyWebpackPlugin({
33
- patterns: [
34
- {
35
- from: PATHS.resourcesWidget,
36
- toType: "dir",
37
- to: WIDGET_RESOURCES_DIR_NAME,
38
- noErrorOnMissing: true,
39
- },
40
- ],
41
- }),
33
+ PATHS.widgetResourcesPath &&
34
+ new CopyWebpackPlugin({
35
+ patterns: [
36
+ {
37
+ from: PATHS.widgetResourcesPath,
38
+ toType: "dir",
39
+ to: path.basename(PATHS.widgetResourcesPath),
40
+ noErrorOnMissing: true,
41
+ },
42
+ ],
43
+ }),
42
44
  ].filter(Boolean),
43
45
  module: {
44
46
  rules: [
@@ -1,4 +1,4 @@
1
- import { systemRequire } from "../../../../utils.js";
1
+ import { systemRequire } from "../../../../../utils.js";
2
2
  export const cssLoaders = [
3
3
  systemRequire.resolve("style-loader"),
4
4
  systemRequire.resolve("css-loader"),
@@ -0,0 +1,27 @@
1
+ import { JsonModifyWebpackPlugin } from "@infomaximum/json-modify-webpack-plugin";
2
+ import { DEV_POSTFIX } from "../../../../../const.js";
3
+ import { removeServiceFieldsForDevelopment } from "../../../../../utils.js";
4
+ export const getModifyManifestWidgetPlugin = ({ host, port, isBuildDevMode, }) => {
5
+ return new JsonModifyWebpackPlugin({
6
+ matchers: [
7
+ {
8
+ matcher: /^manifest.json$/,
9
+ action: (currentJsonContent) => {
10
+ if (isBuildDevMode && host && port) {
11
+ currentJsonContent.entry = `http://${host}:${port}/${currentJsonContent.entry}`;
12
+ if ((currentJsonContent === null || currentJsonContent === void 0 ? void 0 : currentJsonContent.name) &&
13
+ typeof currentJsonContent.name === "object") {
14
+ Object.keys(currentJsonContent.name).forEach((lang) => {
15
+ Object.assign(currentJsonContent.name, {
16
+ [lang]: currentJsonContent.name[lang] + DEV_POSTFIX,
17
+ });
18
+ });
19
+ }
20
+ }
21
+ removeServiceFieldsForDevelopment(currentJsonContent);
22
+ return currentJsonContent;
23
+ },
24
+ },
25
+ ],
26
+ });
27
+ };
@@ -0,0 +1,13 @@
1
+ import ZipPlugin from "zip-webpack-plugin";
2
+ import { WIDGET_ARCHIVE_NAME } from "../../../../const.js";
3
+ import { BUILD_ARCHIVE_EXT, MANIFEST_JSON_FILE_NAME, } from "../../../../../const.js";
4
+ import { compact } from "../../../../../utils.js";
5
+ export const getZipWidgetPlugin = ({ isOnlyManifest, widgetResourcesPath, }) => {
6
+ return new ZipPlugin({
7
+ filename: WIDGET_ARCHIVE_NAME,
8
+ extension: BUILD_ARCHIVE_EXT,
9
+ include: isOnlyManifest
10
+ ? compact([MANIFEST_JSON_FILE_NAME, widgetResourcesPath])
11
+ : undefined,
12
+ });
13
+ };
@@ -0,0 +1,8 @@
1
+ import { BUILD_ARCHIVE_EXT } from "../const.js";
2
+ export const WIDGET_SDK_LIB_NAME = "@infomaximum/widget-sdk";
3
+ export const WIDGET_CONFIG_FIELD_NAME = "widget";
4
+ export const WIDGET_CONFIG_FILE_NAME = `${WIDGET_CONFIG_FIELD_NAME}rc`;
5
+ export const WIDGET_ARCHIVE_NAME = "widget";
6
+ export const WIDGET_ARCHIVE_FULL_NAME = `${WIDGET_ARCHIVE_NAME}.${BUILD_ARCHIVE_EXT}`;
7
+ export const WIDGET_DEFAULT_HOST = "localhost";
8
+ export const WIDGET_DEFAULT_PORT = "5555";
@@ -0,0 +1 @@
1
+ export { registerWidgetCommands } from "./commands.js";
@@ -0,0 +1,83 @@
1
+ import { __awaiter } from "tslib";
2
+ import webpack, {} from "webpack";
3
+ import {} from "../../paths.js";
4
+ import { getPackageBuildConfig } from "../../package/configs/webpack/buildPackage.js";
5
+ import { merge } from "webpack-merge";
6
+ import chalk from "chalk";
7
+ import { getZipWidgetPlugin } from "../configs/webpack/sections/plugins/zipWidget.js";
8
+ import { getModifyManifestWidgetPlugin } from "../configs/webpack/sections/plugins/modifyManifestWidget.js";
9
+ import { getCommonWidgetConfig } from "../configs/webpack/common.js";
10
+ import { getMinimizer } from "../configs/webpack/sections/plugins/minimizer.js";
11
+ import path from "node:path";
12
+ import { WIDGET_ARCHIVE_FULL_NAME } from "../const.js";
13
+ import { generateWidgetPaths } from "../widgetPaths.js";
14
+ import { generatePackagePaths } from "../../package/packagePaths.js";
15
+ import { checkLatestLibsVersion } from "../utils.js";
16
+ export const runBuild = (args) => __awaiter(void 0, void 0, void 0, function* () {
17
+ const mode = "production";
18
+ const { buildDir, host, port, dev: isBuildDevMode, packageDir, packageManifest, assetsDir, } = args;
19
+ const WIDGET_PATHS = generateWidgetPaths(args);
20
+ const sections = {
21
+ plugins: [
22
+ getZipWidgetPlugin({
23
+ isOnlyManifest: isBuildDevMode,
24
+ widgetResourcesPath: WIDGET_PATHS.widgetResourcesPath,
25
+ }),
26
+ getModifyManifestWidgetPlugin({
27
+ isBuildDevMode,
28
+ host,
29
+ port,
30
+ }),
31
+ ],
32
+ };
33
+ if (isBuildDevMode) {
34
+ sections.entry = WIDGET_PATHS.widgetManifestJsonPath;
35
+ }
36
+ const configSections = [
37
+ getCommonWidgetConfig(mode, WIDGET_PATHS),
38
+ sections,
39
+ getMinimizer(),
40
+ ];
41
+ const widgetConfig = merge(configSections);
42
+ const widgetArchivePath = path.resolve(WIDGET_PATHS.appBuildPath, WIDGET_ARCHIVE_FULL_NAME);
43
+ try {
44
+ yield build(widgetConfig);
45
+ console.log("");
46
+ yield build(yield getPackageBuildConfig({
47
+ mode,
48
+ PATHS: generatePackagePaths({
49
+ buildDirPath: buildDir,
50
+ packageDir,
51
+ packageManifest,
52
+ }),
53
+ isBuildDevMode,
54
+ entityArchivePath: widgetArchivePath,
55
+ }));
56
+ yield checkLatestLibsVersion();
57
+ }
58
+ catch (error) {
59
+ console.error(chalk.red("\nFailed to compile.\n"));
60
+ console.error(chalk.red(error));
61
+ process.exit(1);
62
+ }
63
+ });
64
+ function build(config) {
65
+ const compiler = webpack(config);
66
+ return new Promise((res, rej) => {
67
+ compiler.run((err, stats) => {
68
+ if (err) {
69
+ console.error(err.stack || err);
70
+ if (err === null || err === void 0 ? void 0 : err.details) {
71
+ console.error(err.details);
72
+ }
73
+ rej();
74
+ }
75
+ stats &&
76
+ console.log(stats === null || stats === void 0 ? void 0 : stats.toString({
77
+ chunks: false,
78
+ colors: true,
79
+ }));
80
+ res();
81
+ });
82
+ });
83
+ }
@@ -1,19 +1,21 @@
1
1
  import { __awaiter } from "tslib";
2
2
  import path from "node:path";
3
3
  import { getLatestVersionOfLibrary, safeWriteFile } from "../../../utils.js";
4
- import { PACKAGE_MANIFEST_TEMPLATE } from "../../../templates/package/packageManifest.js";
5
- import { PACKAGE_ICON_TEMPLATE } from "../../../templates/package/packageIcon.js";
6
- import { WIDGET_MANIFEST_TEMPLATE } from "../../../templates/widget/widgetManifest.js";
7
- import { WIDGET_BABEL_CONFIG, WIDGET_ESLINTIGNORE, WIDGET_ESLINTRC, WIDGET_GITIGNORE, WIDGET_JEST_CONFIG, WIDGET_TSCONFIG_JSON, } from "../../../templates/widget/widgetConfigs.js";
8
- import { WIDGET_INDEX_TEMPLATE } from "../../../templates/widget/src/widgetIndex.js";
9
- import { APP_D_TS_TEMPLATE } from "../../../templates/widget/src/widgetAppDTs.js";
10
- import { WIDGET_INDEX_CSS_TEMPLATE } from "../../../templates/widget/src/widgetIndexCSS.js";
11
- import { WIDGET_PACKAGE_JSON_TEMPLATE } from "../../../templates/widget/widgetPackageJson.js";
12
- import { CUSTOM_PACKAGE_CLI_LIB_NAME, WIDGET_SDK_LIB_NAME, MANIFEST_JSON_FILE_NAME, } from "../../../const.js";
13
- import { WIDGET_SETTINGS_TEMPLATE } from "../../../templates/widget/src/definition/settings.js";
14
- import { WIDGET_PANEL_TEMPLATE } from "../../../templates/widget/src/definition/panel.js";
15
- import { GET_CHANGELOG_MD, GET_DOC_MD, } from "../../../templates/package/additionalFiles.js";
16
- import { WIDGET_DEFINITION_TEMPLATE } from "../../../templates/widget/src/definition/definition.js";
4
+ import { PACKAGE_MANIFEST_TEMPLATE } from "../../../package/templates/packageManifest.js";
5
+ import { PACKAGE_ICON_TEMPLATE } from "../../../package/templates/packageIcon.js";
6
+ import { CUSTOM_PACKAGE_CLI_LIB_NAME, MANIFEST_JSON_FILE_NAME, } from "../../../const.js";
7
+ import { GET_CHANGELOG_MD, GET_DOC_MD, } from "../../../package/templates/additionalFiles.js";
8
+ import { WIDGET_MANIFEST_TEMPLATE } from "../../templates/widgetManifest.js";
9
+ import { WIDGET_INDEX_TEMPLATE } from "../../templates/src/widgetIndex.js";
10
+ import { APP_D_TS_TEMPLATE } from "../../templates/src/widgetAppDTs.js";
11
+ import { WIDGET_INDEX_CSS_TEMPLATE } from "../../templates/src/widgetIndexCSS.js";
12
+ import { WIDGET_DEFINITION_TEMPLATE } from "../../templates/src/definition/definition.js";
13
+ import { WIDGET_SETTINGS_TEMPLATE } from "../../templates/src/definition/settings.js";
14
+ import { WIDGET_PANEL_TEMPLATE } from "../../templates/src/definition/panel.js";
15
+ import { WIDGET_BABEL_CONFIG, WIDGET_ESLINTIGNORE, WIDGET_ESLINTRC, WIDGET_GITIGNORE, WIDGET_JEST_CONFIG, WIDGET_TSCONFIG_JSON, } from "../../templates/widgetConfigs.js";
16
+ import { WIDGET_PACKAGE_JSON_TEMPLATE } from "../../templates/widgetPackageJson.js";
17
+ import { WIDGET_SDK_LIB_NAME } from "../../const.js";
18
+ import { WIDGET_RC_CONFIG } from "../../templates/widgetRCConfig.js";
17
19
  const addIconActionName = "addIcon";
18
20
  const addInitActions = (basePath, plop) => {
19
21
  plop.setActionType(addIconActionName, function (answers, config, plop) {
@@ -94,6 +96,11 @@ const actions = ({ widgetSDKVersion, packageCliVersion }) => {
94
96
  path: "src/definition/panel.ts",
95
97
  template: WIDGET_PANEL_TEMPLATE,
96
98
  },
99
+ {
100
+ type: "add",
101
+ path: "widgetrc.json",
102
+ template: WIDGET_RC_CONFIG,
103
+ },
97
104
  {
98
105
  type: "add",
99
106
  path: "tsconfig.json",
@@ -1,10 +1,10 @@
1
1
  import { __awaiter } from "tslib";
2
2
  import { getInitWidgetActions } from "./actions.js";
3
3
  import { prompts } from "./prompts.js";
4
- import { addHelpers } from "./helpers.js";
4
+ import { addCommonHelpers } from "../../../plopHelpers.js";
5
5
  const generateWidgetGeneratorName = "widget-generate";
6
6
  const getInitWidgetGenerator = (basePath, plop) => __awaiter(void 0, void 0, void 0, function* () {
7
- addHelpers(plop);
7
+ addCommonHelpers(plop);
8
8
  const actions = yield getInitWidgetActions(basePath, plop);
9
9
  plop.setGenerator(generateWidgetGeneratorName, {
10
10
  prompts,
@@ -3,14 +3,8 @@ import path from "node:path";
3
3
  import nodePlop from "node-plop";
4
4
  import { getInitWidgetGenerator } from "./generators.js";
5
5
  import { spawnCommand } from "../../../utils.js";
6
- import chalk from "chalk";
7
- import { generatePaths } from "../../../paths.js";
8
6
  const runInitWidget = (dirName) => __awaiter(void 0, void 0, void 0, function* () {
9
7
  const createPath = path.join(process.cwd(), dirName);
10
- const PATHS = generatePaths({
11
- cwd: createPath,
12
- entryPath: createPath,
13
- });
14
8
  const plop = yield nodePlop(undefined, {
15
9
  destBasePath: createPath,
16
10
  force: false,
@@ -35,8 +29,5 @@ const runInitWidget = (dirName) => __awaiter(void 0, void 0, void 0, function* (
35
29
  catch (error) {
36
30
  console.error(error);
37
31
  }
38
- console.log(chalk.inverse(`\nCheck the package manifest (${chalk.underline(PATHS.packageManifest)}) and widget manifest (${chalk.underline(PATHS.manifestJson)}) ` +
39
- "and make the necessary changes. Also replace the " +
40
- "package icon with your own icon\n\n"));
41
32
  });
42
33
  export { runInitWidget };
@@ -1,19 +1,18 @@
1
1
  import { __awaiter } from "tslib";
2
2
  import _webpack, {} from "webpack";
3
- import { generatePaths } from "../../paths.js";
3
+ import {} from "../../paths.js";
4
4
  import WebpackDevServer from "webpack-dev-server";
5
- import { getDevServerConfig } from "../../configs/webpack/sections/devServer.js";
6
5
  import { merge } from "webpack-merge";
7
- import { getCommonWidgetConfig } from "../../configs/webpack/common.js";
8
- import { checkLatestLibsVersion } from "../../utils.js";
9
- import { getModifyManifestWidgetPlugin } from "../../configs/webpack/sections/plugins/modifyManifestWidget.js";
10
- import { getReactRefresh } from "../../configs/webpack/sections/plugins/reactRefresh.js";
11
- import { devtoolSection } from "../../configs/webpack/sections/devtool.js";
6
+ import { getModifyManifestWidgetPlugin } from "../configs/webpack/sections/plugins/modifyManifestWidget.js";
7
+ import { getReactRefresh } from "../configs/webpack/sections/plugins/reactRefresh.js";
8
+ import { getCommonWidgetConfig } from "../configs/webpack/common.js";
9
+ import { devtoolSection } from "../configs/webpack/sections/devtool.js";
10
+ import { getDevServerConfig } from "../configs/webpack/sections/devServer.js";
11
+ import { generateWidgetPaths } from "../widgetPaths.js";
12
+ import { checkLatestLibsVersion } from "../utils.js";
12
13
  const { webpack } = _webpack;
13
14
  export const runDevServer = (options) => __awaiter(void 0, void 0, void 0, function* () {
14
- const PATHS = generatePaths({
15
- entryPath: options.entry,
16
- });
15
+ const PATHS = generateWidgetPaths(options);
17
16
  try {
18
17
  yield run(PATHS, options);
19
18
  }
@@ -30,6 +29,7 @@ const run = (PATHS, options) => __awaiter(void 0, void 0, void 0, function* () {
30
29
  const pluginsSection = {
31
30
  plugins: [
32
31
  getModifyManifestWidgetPlugin({
32
+ isBuildDevMode: true,
33
33
  host,
34
34
  port,
35
35
  }),
@@ -44,7 +44,7 @@ const run = (PATHS, options) => __awaiter(void 0, void 0, void 0, function* () {
44
44
  const compiler = webpack(merge(configWebpack));
45
45
  const devServerConfig = getDevServerConfig({
46
46
  host,
47
- port,
47
+ port: String(port),
48
48
  });
49
49
  const devServer = new WebpackDevServer(devServerConfig, compiler);
50
50
  ["SIGINT", "SIGTERM"].forEach(function (sig) {
@@ -1,4 +1,4 @@
1
- import { WIDGET_SDK_LIB_NAME } from "../../../../const.js";
1
+ import { WIDGET_SDK_LIB_NAME } from "../../../../widget/const.js";
2
2
  export const WIDGET_DEFINITION_TEMPLATE = `\
3
3
  import type {
4
4
  IDefinition,
@@ -1,4 +1,4 @@
1
- import { WIDGET_SDK_LIB_NAME } from "../../../../const.js";
1
+ import { WIDGET_SDK_LIB_NAME } from "../../../const.js";
2
2
  export const WIDGET_PANEL_TEMPLATE = `\
3
3
  import {
4
4
  type IPanelDescriptionCreator,
@@ -1,4 +1,4 @@
1
- import { WIDGET_SDK_LIB_NAME } from "../../../../const.js";
1
+ import { WIDGET_SDK_LIB_NAME } from "../../../const.js";
2
2
  export const WIDGET_SETTINGS_TEMPLATE = `\
3
3
  import type {
4
4
  IBaseWidgetSettings,
@@ -1,4 +1,4 @@
1
- import { WIDGET_SDK_LIB_NAME } from "../../../const.js";
1
+ import { WIDGET_SDK_LIB_NAME } from "../../const.js";
2
2
  export const APP_D_TS_TEMPLATE = `\
3
3
  /* eslint-disable @typescript-eslint/triple-slash-reference */
4
4
  /// <reference types="@infomaximum/global-types" />
@@ -1,5 +1,6 @@
1
- import { MANIFEST_JSON_FILE_NAME, WIDGET_SDK_LIB_NAME, } from "../../../const.js";
2
- import { capitalizeHelperName } from "../../../scripts/widget/init/helpers.js";
1
+ import { MANIFEST_JSON_FILE_NAME } from "../../../const.js";
2
+ import { capitalizeHelperName } from "../../../plopHelpers.js";
3
+ import { WIDGET_SDK_LIB_NAME } from "../../const.js";
3
4
  export const WIDGET_INDEX_TEMPLATE = `\
4
5
  import React from "react";
5
6
  import ReactDOM from "react-dom/client";
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { capitalizeHelperName } from "../../scripts/widget/init/helpers.js";
3
2
  import { CUSTOM_PACKAGE_CLI_LIB_NAME } from "../../const.js";
3
+ import { capitalizeHelperName } from "../../plopHelpers.js";
4
4
  export const WIDGET_MANIFEST_TEMPLATE = `\
5
5
  {
6
6
  "$schema": "node_modules/${CUSTOM_PACKAGE_CLI_LIB_NAME}/schemas/widgetManifestSchema.json",
@@ -1,4 +1,5 @@
1
- import { CUSTOM_PACKAGE_CLI_LIB_NAME, WIDGET_SDK_LIB_NAME, } from "../../const.js";
1
+ import { CUSTOM_PACKAGE_CLI_LIB_NAME } from "../../const.js";
2
+ import { WIDGET_SDK_LIB_NAME } from "../const.js";
2
3
  export const WIDGET_PACKAGE_JSON_TEMPLATE = `\
3
4
  {
4
5
  "name": "template_widget",
@@ -0,0 +1,15 @@
1
+ import { CUSTOM_PACKAGE_CLI_LIB_NAME, DEFAULT_BUILD_DIR_NAME, MANIFEST_JSON_FILE_NAME, } from "../../const.js";
2
+ import { WIDGET_DEFAULT_HOST, WIDGET_DEFAULT_PORT } from "../const.js";
3
+ export const WIDGET_RC_CONFIG = `\
4
+ {
5
+ "$schema": "node_modules/${CUSTOM_PACKAGE_CLI_LIB_NAME}/schemas/widgetConfigSchema.json",
6
+ "entry": "src/index.tsx",
7
+ "widgetManifest": "${MANIFEST_JSON_FILE_NAME}",
8
+ "packageManifest": "package/${MANIFEST_JSON_FILE_NAME}",
9
+ "packageDir": "package",
10
+ "assetsDir": "_resources",
11
+ "buildDir": "${DEFAULT_BUILD_DIR_NAME}",
12
+ "port": ${+WIDGET_DEFAULT_PORT},
13
+ "host": "${WIDGET_DEFAULT_HOST}"
14
+ }
15
+ `;
@@ -0,0 +1,41 @@
1
+ import { __awaiter } from "tslib";
2
+ import semver from "semver";
3
+ import chalk from "chalk";
4
+ import { getLatestVersionOfLibrary, getLibraryVersionInProject, } from "../utils.js";
5
+ import { WIDGET_SDK_LIB_NAME } from "./const.js";
6
+ import { CUSTOM_PACKAGE_CLI_LIB_NAME } from "../const.js";
7
+ export function checkLatestVersion(libName) {
8
+ var _a, _b, _c;
9
+ return __awaiter(this, void 0, void 0, function* () {
10
+ const libVersionInProject = yield getLibraryVersionInProject(libName);
11
+ if (!libVersionInProject)
12
+ return;
13
+ const libVersionFromProject = (_c = (((_a = libVersionInProject === null || libVersionInProject === void 0 ? void 0 : libVersionInProject.dependencies) === null || _a === void 0 ? void 0 : _a[libName]) ||
14
+ ((_b = libVersionInProject === null || libVersionInProject === void 0 ? void 0 : libVersionInProject.devDependencies) === null || _b === void 0 ? void 0 : _b[libName]))) === null || _c === void 0 ? void 0 : _c.version;
15
+ if (!libVersionFromProject)
16
+ return;
17
+ const latestVersion = yield getLatestVersionOfLibrary(libName);
18
+ if (!latestVersion)
19
+ return;
20
+ const isOldVersion = semver.gt(latestVersion, libVersionFromProject);
21
+ if (isOldVersion) {
22
+ console.error(chalk.yellow(`\n\nA new version of the ${chalk.underline(`${libName}@${latestVersion}`)} library has been released,\n` +
23
+ `old version ${libVersionFromProject} is used in the project, it is recommended to ` +
24
+ `update to the latest version \n` +
25
+ chalk.green.bold(chalk.underline(`npm i --save ${libName}@${latestVersion}`) +
26
+ " or " +
27
+ chalk.underline(`yarn upgrade ${libName}@${latestVersion}\n\n`))));
28
+ }
29
+ });
30
+ }
31
+ export function checkLatestLibsVersion() {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ try {
34
+ yield Promise.allSettled([
35
+ checkLatestVersion(WIDGET_SDK_LIB_NAME),
36
+ checkLatestVersion(CUSTOM_PACKAGE_CLI_LIB_NAME),
37
+ ]);
38
+ }
39
+ catch (error) { }
40
+ });
41
+ }
@@ -0,0 +1,8 @@
1
+ import { _resolveApp, generateGlobalPaths, generateIndexPath, } from "../paths.js";
2
+ export function generateWidgetPaths({ entry, assetsDir, widgetManifest, buildDir, }) {
3
+ const globalPaths = generateGlobalPaths({ buildDirPath: buildDir });
4
+ const resolveApp = _resolveApp();
5
+ return Object.assign(Object.assign({}, globalPaths), { get moduleIndex() {
6
+ return generateIndexPath(entry);
7
+ }, widgetManifestJsonPath: resolveApp(widgetManifest), widgetResourcesPath: assetsDir ? resolveApp(assetsDir) : null, widgetBuildDirPath: resolveApp(buildDir) });
8
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infomaximum/package-cli",
3
- "version": "1.21.0",
3
+ "version": "2.0.0",
4
4
  "exports": "./dist/index.js",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@babel/core": "^7.23.6",
26
26
  "@babel/plugin-transform-runtime": "^7.23.6",
27
- "@infomaximum/assert": "1.1.2",
27
+ "@infomaximum/assert": "^1.1.3",
28
28
  "@infomaximum/json-modify-webpack-plugin": "^1.0.2",
29
29
  "@pmmmwh/react-refresh-webpack-plugin": "^0.5.11",
30
30
  "@svgr/webpack": "^8.1.0",
@@ -43,6 +43,7 @@
43
43
  "postcss": "^8.4.32",
44
44
  "postcss-loader": "^7.3.3",
45
45
  "postcss-preset-env": "^9.3.0",
46
+ "rc-config-loader": "^4.1.3",
46
47
  "react-refresh": "^0.14.0",
47
48
  "remove-files-webpack-plugin": "^1.5.0",
48
49
  "sass": "^1.69.5",
@@ -0,0 +1,48 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "type": "object",
4
+ "properties": {
5
+ "entry": {
6
+ "type": "string",
7
+ "description": "файл который является точкой входа"
8
+ },
9
+ "widgetManifest": {
10
+ "type": "string",
11
+ "description": "путь до файла манифеста виджета"
12
+ },
13
+ "packageManifest": {
14
+ "type": "string",
15
+ "description": "путь до файла манифеста пакета"
16
+ },
17
+ "packageDir": {
18
+ "type": "string",
19
+ "description": "директория с файлами пакета"
20
+ },
21
+ "assetsDir": {
22
+ "type": "string",
23
+ "description": "директория с файлами для динамической загрузки ресурсов виджета"
24
+ },
25
+ "buildDir": {
26
+ "type": "string",
27
+ "description": "директория в которую будет осуществляться сборка проекта"
28
+ },
29
+ "port": {
30
+ "type": "integer",
31
+ "minimum": 0,
32
+ "maximum": 65535,
33
+ "description": "порт по которому будет доступен сервер разработки"
34
+ },
35
+ "host": {
36
+ "type": "string",
37
+ "description": "хост по которому будет доступен сервер разработки"
38
+ }
39
+ },
40
+ "required": [
41
+ "entry",
42
+ "widgetManifest",
43
+ "packageManifest",
44
+ "packageDir",
45
+ "port",
46
+ "host"
47
+ ]
48
+ }
@@ -1,25 +0,0 @@
1
- import { JsonModifyWebpackPlugin } from "@infomaximum/json-modify-webpack-plugin";
2
- import { DEV_POSTFIX } from "../../../../const.js";
3
- import { removeServiceFieldsForDevelopment } from "../../../../utils.js";
4
- export const getModifyManifestWidgetPlugin = ({ host, port }) => {
5
- return new JsonModifyWebpackPlugin({
6
- matchers: [
7
- {
8
- matcher: /^manifest.json$/,
9
- action: (currentJsonContent) => {
10
- currentJsonContent.entry = `http://${host}:${port}/${currentJsonContent.entry}`;
11
- if ((currentJsonContent === null || currentJsonContent === void 0 ? void 0 : currentJsonContent.name) &&
12
- typeof currentJsonContent.name === "object") {
13
- Object.keys(currentJsonContent.name).forEach((lang) => {
14
- Object.assign(currentJsonContent.name, {
15
- [lang]: currentJsonContent.name[lang] + DEV_POSTFIX,
16
- });
17
- });
18
- }
19
- removeServiceFieldsForDevelopment(currentJsonContent);
20
- return currentJsonContent;
21
- },
22
- },
23
- ],
24
- });
25
- };
@@ -1,11 +0,0 @@
1
- import ZipPlugin from "zip-webpack-plugin";
2
- import { BUILD_ARCHIVE_EXT, MANIFEST_JSON_FILE_NAME, WIDGET_ARCHIVE_NAME, WIDGET_RESOURCES_DIR_NAME, } from "../../../../const.js";
3
- export const getZipWidgetPlugin = (isOnlyManifest) => {
4
- return new ZipPlugin({
5
- filename: WIDGET_ARCHIVE_NAME,
6
- extension: BUILD_ARCHIVE_EXT,
7
- include: isOnlyManifest
8
- ? [MANIFEST_JSON_FILE_NAME, WIDGET_RESOURCES_DIR_NAME]
9
- : undefined,
10
- });
11
- };
@@ -1,66 +0,0 @@
1
- import { __awaiter } from "tslib";
2
- import webpack, {} from "webpack";
3
- import { generatePaths } from "../../paths.js";
4
- import { getCommonWidgetConfig } from "../../configs/webpack/common.js";
5
- import { getPackageConfig } from "../../configs/webpack/buildPackage.js";
6
- import { checkLatestLibsVersion } from "../../utils.js";
7
- import { merge } from "webpack-merge";
8
- import { getModifyManifestWidgetPlugin } from "../../configs/webpack/sections/plugins/modifyManifestWidget.js";
9
- import { getMinimizer } from "../../configs/webpack/sections/plugins/minimizer.js";
10
- import { getZipWidgetPlugin } from "../../configs/webpack/sections/plugins/zipWidget.js";
11
- import chalk from "chalk";
12
- export const runBuild = (args) => __awaiter(void 0, void 0, void 0, function* () {
13
- const mode = "production";
14
- const { entry, host, port } = args;
15
- const isBuildDevMode = !!(host && port);
16
- const PATHS = generatePaths({
17
- entryPath: entry,
18
- });
19
- const sections = {
20
- plugins: [getZipWidgetPlugin(isBuildDevMode)],
21
- };
22
- if (isBuildDevMode) {
23
- sections.plugins.push(getModifyManifestWidgetPlugin({
24
- host,
25
- port,
26
- }));
27
- sections.entry = PATHS.manifestJson;
28
- }
29
- const configSections = [
30
- getCommonWidgetConfig(mode, PATHS),
31
- sections,
32
- getMinimizer(),
33
- ];
34
- const widgetConfig = merge(configSections);
35
- try {
36
- yield build(widgetConfig);
37
- console.log("");
38
- yield build(yield getPackageConfig(mode, PATHS, isBuildDevMode));
39
- yield checkLatestLibsVersion();
40
- }
41
- catch (error) {
42
- console.error(chalk.red("\nFailed to compile.\n"));
43
- console.error(chalk.red(error));
44
- process.exit(1);
45
- }
46
- });
47
- function build(config) {
48
- const compiler = webpack(config);
49
- return new Promise((res, rej) => {
50
- compiler.run((err, stats) => {
51
- if (err) {
52
- console.error(err.stack || err);
53
- if (err === null || err === void 0 ? void 0 : err.details) {
54
- console.error(err.details);
55
- }
56
- rej();
57
- }
58
- stats &&
59
- console.log(stats === null || stats === void 0 ? void 0 : stats.toString({
60
- chunks: false,
61
- colors: true,
62
- }));
63
- res();
64
- });
65
- });
66
- }
@@ -1,6 +0,0 @@
1
- import { capitalizeFirstLetter } from "../../../utils.js";
2
- const capitalizeHelperName = "capitalize";
3
- const addHelpers = (plop) => {
4
- plop.setHelper(capitalizeHelperName, capitalizeFirstLetter);
5
- };
6
- export { capitalizeHelperName, addHelpers };