@airiot/cli 1.0.11 → 1.0.13

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.
package/config/envs.js CHANGED
@@ -1,16 +1,43 @@
1
1
  import paths from './paths.js';
2
2
  import { URL } from 'url';
3
+ import { resolve, dirname, basename } from 'path';
3
4
 
4
5
  let developConfig = {};
5
6
 
7
+ // attempt to load the developConfig file, if not found try parent directories up to root
6
8
  try {
7
- const module = await import(new URL(`file://${paths.developConfig}`));
8
- developConfig = module.default;
9
+ let filePath = resolve(paths.developConfig);
10
+ const fileName = basename(filePath);
11
+ let dir = dirname(filePath);
12
+
13
+ while (true) {
14
+ const candidate = resolve(dir, fileName);
15
+ // build a file:// URL compatible with Windows and POSIX
16
+ const fileUrl = new URL(`file://${process.platform === 'win32' ? '/' : ''}${candidate.replace(/\\/g, '/')}`).href;
17
+
18
+ try {
19
+ const module = await import(fileUrl);
20
+ developConfig = module.default;
21
+ break;
22
+ } catch (err) {
23
+ if (err && err.code !== 'ERR_MODULE_NOT_FOUND') {
24
+ throw err;
25
+ }
26
+ const parent = dirname(dir);
27
+ if (parent === dir) {
28
+ // reached filesystem root, stop searching
29
+ break;
30
+ }
31
+ dir = parent;
32
+ }
33
+ }
9
34
  } catch (err) {
10
- if (err.code !== 'ERR_MODULE_NOT_FOUND') {
35
+ // preserve original behavior: only rethrow unexpected errors
36
+ if (err && err.code !== 'ERR_MODULE_NOT_FOUND') {
11
37
  throw err;
12
38
  }
13
39
  }
40
+
14
41
  const getHost = () => {
15
42
  if (developConfig.host) {
16
43
  return developConfig.host;
@@ -65,6 +92,16 @@ const getBaseUrl = () => {
65
92
  return baseUrl;
66
93
  };
67
94
 
95
+ const getOpsInfo = () => {
96
+ if (developConfig.ops) {
97
+ return {
98
+ ...developConfig.ops,
99
+ ophost: developConfig.ops.host
100
+ };
101
+ }
102
+ return null;
103
+ }
104
+
68
105
  const getModule = () => {
69
106
  const envs = process.env;
70
107
  const args = process.argv;
@@ -81,6 +118,13 @@ const getModule = () => {
81
118
  return modules;
82
119
  };
83
120
 
121
+ const getProxy = () => {
122
+ if (developConfig.proxy) {
123
+ return developConfig.proxy;
124
+ }
125
+ return {};
126
+ }
127
+
84
128
  const translateKeys = () => {
85
129
  const envs = process.env;
86
130
  const args = process.argv;
@@ -102,4 +146,24 @@ const translateKeys = () => {
102
146
  return { appid, secret };
103
147
  }
104
148
 
105
- export { getHost, getBaseUrl, getModule, developConfig, translateKeys };
149
+ const getDllMode = () => {
150
+ const envs = process.env;
151
+ const args = process.argv;
152
+
153
+ let dllMode = "umd";
154
+
155
+ if (developConfig.dllMode) {
156
+ dllMode = developConfig.dllMode;
157
+ } else {
158
+ const dllArgs = args.filter(arg => arg.startsWith("--dllMode="));
159
+ if (dllArgs.length !== 0) {
160
+ dllMode = dllArgs[0].replace('--dllMode=', '');
161
+ } else if (envs.IOT_DLL_MODE) {
162
+ dllMode = envs.IOT_DLL_MODE;
163
+ }
164
+ }
165
+
166
+ return dllMode;
167
+ }
168
+
169
+ export { getHost, getBaseUrl, getModule, getOpsInfo, getProxy, getDllMode, developConfig, translateKeys };
@@ -28,8 +28,6 @@ export default defineConfig([
28
28
  sourceType: 'module',
29
29
  globals: {
30
30
  ...globals.browser,
31
- moment: "readonly",
32
- _: "readonly",
33
31
  _t1: "writable",
34
32
  _r: 'writable',
35
33
  _t: 'writable',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@airiot/cli",
3
- "version": "1.0.11",
3
+ "version": "1.0.13",
4
4
  "description": "AIRIOT平台前端包管理工具",
5
5
  "type": "module",
6
6
  "scripts": {},
@@ -7,6 +7,7 @@ import fs from "fs";
7
7
  import fetch from "node-fetch";
8
8
  import FormData from "form-data";
9
9
  import paths from "../config/paths.js";
10
+ import { getOpsInfo } from '../config/envs.js';
10
11
 
11
12
  const jsonData = fs.readFileSync(paths.appPackageJson, 'utf-8');
12
13
  const packageJson = JSON.parse(jsonData);
@@ -14,12 +15,15 @@ const packageJson = JSON.parse(jsonData);
14
15
  const envs = process.env;
15
16
  const args = process.argv;
16
17
  let packageName = packageJson.name;
18
+ const developOpsConfig = getOpsInfo();
17
19
 
18
20
  const getOption = (name, envName) => {
19
21
  let value;
20
22
  const optionArgs = args.filter((arg) => arg.startsWith(`--${name}=`));
21
23
  if (optionArgs.length != 0) {
22
24
  value = optionArgs[0].replace(`--${name}=`, "");
25
+ } else if (developOpsConfig && developOpsConfig[name]) {
26
+ value = developOpsConfig[name];
23
27
  } else if (envs[envName]) {
24
28
  value = envs[envName];
25
29
  }
@@ -34,7 +38,7 @@ const getOption = (name, envName) => {
34
38
  const questions = [];
35
39
  const forceQuestion = args.filter((arg) => arg.startsWith("-f")).length != 0;
36
40
  const options = {
37
- host: getOption("ophost", "IOT_OPURL"),
41
+ host: getOption("ophost", "IOT_OPHOST"),
38
42
  username: getOption("username", "IOT_OP_USER"),
39
43
  password: getOption("password", "IOT_OP_PASSWORD"),
40
44
  branch: getOption("branch", "IOT_BRANCH"),
@@ -61,6 +65,27 @@ inquirer
61
65
  let password = answers.password || options.password;
62
66
  let branch = answers.branch || options.branch;
63
67
 
68
+ console.log(chalk.yellow("[iot:install] 请确认以下参数:"));
69
+ console.log(chalk.yellow(` host: ${host || "(未提供)"}`));
70
+ console.log(chalk.yellow(` username: ${username || "(未提供)"}`));
71
+ console.log(chalk.yellow(` password: ${password ? "********" : "(未提供)"}`));
72
+ console.log(chalk.yellow(` branch: ${branch || "(未提供)"}`));
73
+ console.log(chalk.yellow(` package: ${packageName}\n`));
74
+
75
+ const { confirmProceed } = await inquirer.prompt([
76
+ {
77
+ name: "confirmProceed",
78
+ type: "confirm",
79
+ message: "确认以上参数并继续安装吗?",
80
+ default: true,
81
+ },
82
+ ]);
83
+
84
+ if (!confirmProceed) {
85
+ console.log(chalk.red("[iot:install] 操作已取消"));
86
+ return;
87
+ }
88
+
64
89
  host = host.endsWith("/") ? host : host + "/";
65
90
 
66
91
  try {
@@ -9,7 +9,7 @@ const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3030;
9
9
  const host = getHost();
10
10
  const baseUrl = getBaseUrl();
11
11
 
12
- console.log(chalk.green('[iot:envs] 请求 IOT_URL 为: ' + host));
12
+ console.log(chalk.green('[iot:envs] 请求 IOT_URL 为: ' + host + ', 基础路径为: ' + baseUrl));
13
13
 
14
14
  (async () => {
15
15
  const proxy = {
package/scripts/start.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import chalk from 'chalk';
2
2
  import {createServer} from 'vite';
3
- import { getHost, getBaseUrl } from '../config/envs.js';
3
+ import { getHost, getBaseUrl, getProxy } from '../config/envs.js';
4
4
  import paths from '../config/paths.js';
5
5
  import plugins from '../vite-plugin/index.js';
6
6
 
@@ -8,8 +8,9 @@ const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
8
8
 
9
9
  const host = getHost();
10
10
  const baseUrl = getBaseUrl();
11
+ const proxyConfig = getProxy();
11
12
 
12
- console.log(chalk.green('[iot:envs] 请求 IOT_URL 为: ' + host));
13
+ console.log(chalk.green('[iot:envs] 请求 IOT_URL 为: ' + host + ', 基础路径为: ' + baseUrl));
13
14
 
14
15
  (async () => {
15
16
  const proxy = {
@@ -29,6 +30,7 @@ console.log(chalk.green('[iot:envs] 请求 IOT_URL 为: ' + host));
29
30
  changeOrigin: true
30
31
  }
31
32
  }
33
+ Object.assign(proxy, proxyConfig);
32
34
 
33
35
  const server = await createServer({
34
36
  configFile: false,
@@ -1,6 +1,8 @@
1
1
  export default {
2
2
  "react": "React",
3
3
  "react-dom": "ReactDOM",
4
+ "react/jsx-runtime": "ReactJSXRuntime",
5
+ "react/jsx-dev-runtime": "ReactJSXDevRuntime",
4
6
  "react-dnd": "ReactDnD",
5
7
  "react-dnd-html5-backend": "ReactDnDHTML5Backend",
6
8
  "react-router": "ReactRouter",
@@ -1,4 +1,44 @@
1
1
  export default {
2
- "react-router": "https://esm.sh/react-router@6",
3
- "react-router-dom": "https://esm.sh/react-router-dom@6"
2
+ "react": "/node_modules/@airiot/dll/esm/react.js",
3
+ "react/jsx-runtime": "/node_modules/@airiot/dll/esm/react.js",
4
+ "react/jsx-dev-runtime": "/node_modules/@airiot/dll/esm/react.js",
5
+ "react-dom": "/node_modules/@airiot/dll/esm/react.js",
6
+ "react-dom/client": "/node_modules/@airiot/dll/esm/react.js",
7
+
8
+ // React Router
9
+ "history": "/node_modules/@airiot/dll/esm/history.js",
10
+ "react-router": "/node_modules/@airiot/dll/esm/react-router.js",
11
+ "react-router-dom": "/node_modules/@airiot/dll/esm/react-router-dom.js",
12
+
13
+ // React DnD
14
+ "react-dnd": "/node_modules/@airiot/dll/esm/react-dnd_.js",
15
+ "react-dnd-html5-backend": "/node_modules/@airiot/dll/esm/react-dnd-html5-backend.js",
16
+
17
+ // Utility Libraries
18
+ "lodash": "/node_modules/@airiot/dll/esm/lodash.js",
19
+ "async": "/node_modules/@airiot/dll/esm/async.js",
20
+ "moment": "/node_modules/@airiot/dll/esm/moment.js",
21
+ "dayjs": "/node_modules/@airiot/dll/esm/dayjs.js",
22
+
23
+ // Excel
24
+ "xlsx": "/node_modules/@airiot/dll/esm/xlsx_.js",
25
+
26
+ // Jotai State Management
27
+ "jotai": "/node_modules/@airiot/dll/esm/jotai.js",
28
+ "jotai/utils": "/node_modules/@airiot/dll/esm/jotai/utils.js",
29
+
30
+ // Ant Design
31
+ "antd": "/node_modules/@airiot/dll/esm/antd.js",
32
+ "@ant-design/icons": "/node_modules/@airiot/dll/esm/@ant-design/icons.js",
33
+ // "xui": "/node_modules/@airiot/dll/esm/xui.js",
34
+
35
+ // Xadmin Libraries
36
+ "xadmin": "/node_modules/@airiot/dll/esm/xadmin.js",
37
+ "xadmin-i18n": "/node_modules/@airiot/dll/esm/xadmin-i18n.js",
38
+ "xadmin-ui": "/node_modules/@airiot/dll/esm/xadmin-ui.js",
39
+ "xadmin-form": "/node_modules/@airiot/dll/esm/xadmin-form.js",
40
+ "xadmin-model": "/node_modules/@airiot/dll/esm/xadmin-model.js",
41
+ "xadmin-auth": "/node_modules/@airiot/dll/esm/xadmin-auth.js",
42
+ "xadmin-antd": "/node_modules/@airiot/dll/esm/xadmin-antd.js",
43
+ // "xadmin-xui": "/node_modules/@airiot/dll/esm/xadmin-xui.js"
4
44
  }
@@ -0,0 +1,108 @@
1
+ import path from "path";
2
+ import { emptyDirSync } from 'fs-extra';
3
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
4
+
5
+ export default function importMapPlugin(
6
+ options
7
+ ) {
8
+ const { imports, externals, autoRestart = false } = options;
9
+
10
+ let resolvedImports = imports ?? {};
11
+ const externalCacheDir = path.join(process.cwd(), 'node_modules', '.vite_external');
12
+
13
+ return {
14
+ name: "vite-plugin-import-map",
15
+ enforce: "pre",
16
+
17
+ config() {
18
+
19
+ resolvedImports = Object.fromEntries(
20
+ Object.entries(resolvedImports).map(([key, value]) => {
21
+ if (!value.startsWith("/") && !value.startsWith("http://") && !value.startsWith("https://") && !value.startsWith("//")) {
22
+ value = path.resolve(process.cwd(), value);
23
+ }
24
+
25
+ return [key, value];
26
+ })
27
+ );
28
+
29
+ if (!existsSync) {
30
+ mkdirSync(externalCacheDir);
31
+ }
32
+ else {
33
+ emptyDirSync(externalCacheDir);
34
+ }
35
+
36
+ return {
37
+ build: {
38
+ rollupOptions: {
39
+ external: Object.keys(resolvedImports),
40
+ },
41
+ },
42
+ optimizeDeps: {
43
+ //exclude: Object.keys(resolvedImports).filter(libName => !externals[libName]),
44
+ },
45
+ resolve: {
46
+ alias: Object.keys(resolvedImports).map((libName) => {
47
+ if(externals[libName]) {
48
+ const libPath = path.join(externalCacheDir, `${libName.replace(/\//g, '_')}.js`);
49
+ writeFileSync(libPath, `module.exports = ${externals[libName]};`);
50
+ return {
51
+ find: new RegExp(`^${libName}$`),
52
+ replacement: libPath
53
+ };
54
+ }
55
+ return null
56
+ }).filter(Boolean),
57
+ },
58
+ };
59
+ },
60
+
61
+ transformIndexHtml(html) {
62
+ // const importMapJson = JSON.stringify({ imports: resolvedImports });
63
+ // const scriptTag = `<script type="importmap">${importMapJson}</script>`;
64
+ const scriptTag = `<script type="module">${Object.keys(resolvedImports).map(libName => externals[libName] ? `import * as ${externals[libName]} from "${libName}";window.${externals[libName]} = ${externals[libName]}; ` : '').join(' ')}</script>`;
65
+ return html.replace("</head>", `${scriptTag}</head>`);
66
+ },
67
+
68
+ // handleHotUpdate({ file, server }) {
69
+ // if (
70
+ // importMapPath &&
71
+ // path.resolve(file) === path.resolve(process.cwd(), importMapPath)
72
+ // ) {
73
+ // try {
74
+ // const fileContents = fs.readFileSync(file, "utf-8");
75
+ // const parsedData = JSON.parse(fileContents);
76
+
77
+ // if (parsedData.imports) {
78
+ // resolvedImports = parsedData.imports;
79
+ // console.log(
80
+ // "[vite-plugin-import-map] Updated import map on the fly:",
81
+ // resolvedImports
82
+ // );
83
+ // }
84
+
85
+ // if (autoRestart) {
86
+ // console.log(
87
+ // "[vite-plugin-import-map] Restarting Vite server to apply changes..."
88
+ // );
89
+ // server.restart();
90
+ // } else {
91
+ // console.log(
92
+ // "[vite-plugin-import-map] Import map updated. Please restart Vite manually to apply changes."
93
+ // );
94
+ // }
95
+
96
+ // server.ws.send({
97
+ // type: "full-reload",
98
+ // });
99
+ // } catch (error) {
100
+ // console.error(
101
+ // "[vite-plugin-import-map] Error reading or parsing import-map.json:",
102
+ // error
103
+ // );
104
+ // }
105
+ // }
106
+ // },
107
+ };
108
+ }
@@ -9,12 +9,16 @@ import jsInJsxPlugin from './js-in-jsx.js'
9
9
  import svgInline from './svg-inline.js';
10
10
  import buildinfoPlugin from './buildinfo.js';
11
11
  import lazyImportPlugin from './lazyImport.js';
12
+ import importMapPlugin from "./importmaps.js";
12
13
 
13
14
  import externals from './externals.js'
15
+ import importmap from './importmap.js';
14
16
  import paths from '../config/paths.js';
15
17
 
18
+ import { getDllMode } from '../config/envs.js';
16
19
 
17
20
  const getPlugins = async (mode) => {
21
+ const dllMode = getDllMode() || "umd";
18
22
 
19
23
  const plugins = [
20
24
  react({
@@ -23,7 +27,11 @@ const getPlugins = async (mode) => {
23
27
  commonjs({
24
28
  requireReturnsDefault: 'preferred'
25
29
  }),
26
- createExternal({
30
+ dllMode == "esm" && importMapPlugin({
31
+ imports: importmap,
32
+ externals
33
+ }),
34
+ dllMode == "umd" && createExternal({
27
35
  externals
28
36
  }),
29
37
  cssInjectedByJsPlugin({
@@ -1,61 +1,24 @@
1
- import fs from "node:fs/promises";
2
- import url from "node:url";
3
- import react from "@vitejs/plugin-react";
4
1
  import * as vite from "vite";
5
2
 
6
- // Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
7
- function escapeRegExp(string) {
8
- // $& means the whole matched string
9
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10
- }
11
-
12
- // NOTE: Keep trailing slash to use resulting path in prefix matching.
13
- const srcDir = url.fileURLToPath(new URL("./src/", import.meta.url));
14
- // NOTE: Since ESBuild evaluates this regex using Go's engine, it is not
15
- // clear whether the JS-specific regex escape logic is sound.
16
- const srcJsRegex = new RegExp(`^${escapeRegExp(srcDir)}.*\\.js$`);
17
-
18
3
  const vitePlugin = () => ({
19
4
  name: "js-in-jsx",
20
- enforce: "pre",
5
+ enforce: "pre", // 必须在 Vite 核心插件之前运行
6
+
21
7
  config: () => ({
22
- build: {
23
- commonjsOptions: {
24
- transformMixedEsModules: true,
25
- },
26
- },
27
- esbuild: {
28
- loader: "jsx",
29
- include: /\/src\/.*\.js$|\/src\/.*\.jsx$/,
30
- exclude: [],
31
- },
32
- optimizeDeps: {
33
- esbuildOptions: {
34
- loader: {
35
- ".js": "jsx",
36
- ".ts": "tsx",
37
- ".svg": "text",
38
- },
8
+ esbuild: {
9
+ // 关键:使用对象映射,精确控制 .js 文件使用 jsx loader
10
+ // 而不影响 .ts 使用 ts loader
11
+ loader: "tsx", // 默认兜底(可选)
12
+ include: /src\/.*\.[tj]sx?$/, // 包含 .js, .ts, .jsx, .tsx
13
+ exclude: [],
14
+ },
15
+ optimizeDeps: {
16
+ esbuildOptions: {
17
+ loader: {
18
+ '.js': 'jsx',
39
19
  },
40
20
  },
41
- }),
42
- async transform(code, id) {
43
- // Ignore Rollup virtual modules.
44
- if (id.startsWith("\0")) {
45
- return;
46
- }
47
- // Strip off any "proxy id" component before testing against path.
48
- // See: https://github.com/vitejs/vite-plugin-react-swc/blob/a1bfc313612a8143a153ce87f52925059459aeb2/src/index.ts#L89
49
- // See: https://rollupjs.org/plugin-development/#inter-plugin-communication
50
- [id] = id.split("?");
51
- if (id.startsWith(srcDir) && id.endsWith(".js")) {
52
- return await vite.transformWithEsbuild(code, id, {
53
- loader: "jsx",
54
- jsx: "automatic",
55
- jsxDev: import.meta.env.DEV,
56
- });
57
- }
58
- }
21
+ }})
59
22
  });
60
23
 
61
- export default vitePlugin
24
+ export default vitePlugin;
@@ -1,7 +1,9 @@
1
1
  import paths from '../config/paths.js'
2
2
  import { promises as fsPromises } from 'fs';
3
3
  import fetch from 'node-fetch';
4
- import { getBaseUrl, getHost, developConfig } from '../config/envs.js';
4
+ import { getBaseUrl, getHost, developConfig, getDllMode } from '../config/envs.js';
5
+
6
+ import imports from './importmap.js'
5
7
 
6
8
  const jsonData = await fsPromises.readFile(paths.appPackageJson, 'utf-8');
7
9
  const htmlTpl = await fsPromises.readFile(paths.appHtml, 'utf-8');
@@ -15,15 +17,22 @@ const findModule = (scripts, packageName) => {
15
17
  const loadOnline = true
16
18
  const host = getHost()
17
19
  const basePath = getBaseUrl() + '/node_modules'
20
+ const baseUrl = getBaseUrl()
21
+
22
+ const importMap = Object.fromEntries(
23
+ Object.entries(imports).map(([key, value]) => {
24
+ return [key, baseUrl + value];
25
+ })
26
+ );
18
27
 
19
28
  const defaultModules = [
20
- '@airiot/i18n', '@airiot/theme', '@airiot/core'
29
+ '@airiot/i18n', '@airiot/core'
21
30
  ]
22
31
 
23
32
  let scripts, frontScripts;
24
33
 
25
- let dllScript = basePath + '/@airiot/dll/dist/iot.min.js',
26
- dllDevScript = basePath + '/@airiot/dll/dist/iot.js';
34
+ let dllScript = developConfig.dll?.url || (basePath + '/@airiot/dll/dist/iot.min.js'),
35
+ dllDevScript = developConfig.dll?.devUrl || (basePath + '/@airiot/dll/dist/iot.js');
27
36
 
28
37
  const filterDll = s => {
29
38
  if(s.indexOf("@airiot/dll") >= 0) {
@@ -133,9 +142,17 @@ const getHtmlScripts = async (html, isAdmin, mode) => {
133
142
  await loadPackageScripts()
134
143
  }
135
144
  const appendScripts = isAdmin ? scripts : frontScripts
145
+
146
+ const dllMod = getDllMode() || "umd";
147
+ const dllScripts = dllMod == "umd" ? [
148
+ { tag: 'script', attrs: { src: mode == 'dev' ? dllDevScript : dllScript }, injectTo: 'body' },
149
+ ] : ( dllMod == "esm" ? [
150
+ { tag: 'script', attrs: { type: 'importmap' }, children: JSON.stringify({ imports: importMap }), injectTo: 'head' },
151
+ ] : [] )
152
+
136
153
  return [
154
+ ...dllScripts,
137
155
  { tag: 'script', attrs: { }, children: 'window._r = s => s; window._t1 = s => s', injectTo: 'body-prepend' },
138
- { tag: 'script', attrs: { src: mode == 'dev' ? dllDevScript : dllScript }, injectTo: 'body' },
139
156
  ...appendScripts.map(script => ({ tag: 'script', attrs: { ...script }, injectTo: 'body' })),
140
157
  { tag: 'script', attrs: { type: 'module' }, children: '__app__.start()', injectTo: 'body' },
141
158
  ]
@@ -164,6 +181,8 @@ const airiotPlugin = (mode) => {
164
181
  return html.replace('<body>', '<body>' + makeScriptTag(script))
165
182
  } else if(script.injectTo == 'body') {
166
183
  return html.replace('</body>', makeScriptTag(script) + '</body>')
184
+ } else if(script.injectTo == 'head') {
185
+ return html.replace('</head>', makeScriptTag(script) + '</head>')
167
186
  }
168
187
  return html
169
188
  }, htmlTpl)