@nasl/cli 0.3.3 → 0.3.5

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/README.md +24 -3
  2. package/dist/bin/nasl.mjs +192 -124
  3. package/dist/bin/nasl.mjs.map +1 -1
  4. package/dist/bin/naslc.mjs +38 -15
  5. package/dist/bin/naslc.mjs.map +1 -1
  6. package/dist/index.mjs +179 -97
  7. package/dist/index.mjs.map +1 -1
  8. package/out/apis/appApi.d.ts +17 -0
  9. package/out/apis/appApi.d.ts.map +1 -0
  10. package/out/apis/appApi.js +36 -0
  11. package/out/apis/appApi.js.map +1 -0
  12. package/out/apis/index.d.ts +1 -1
  13. package/out/apis/index.d.ts.map +1 -1
  14. package/out/apis/index.js +1 -1
  15. package/out/apis/index.js.map +1 -1
  16. package/out/bin/nasl.js +14 -61
  17. package/out/bin/nasl.js.map +1 -1
  18. package/out/commands/createAppInIde.d.ts +0 -3
  19. package/out/commands/createAppInIde.d.ts.map +1 -1
  20. package/out/commands/createAppInIde.js +26 -93
  21. package/out/commands/createAppInIde.js.map +1 -1
  22. package/out/commands/index.d.ts +1 -0
  23. package/out/commands/index.d.ts.map +1 -1
  24. package/out/commands/index.js +1 -0
  25. package/out/commands/index.js.map +1 -1
  26. package/out/commands/updateAppInIde.d.ts +3 -0
  27. package/out/commands/updateAppInIde.d.ts.map +1 -0
  28. package/out/commands/updateAppInIde.js +59 -0
  29. package/out/commands/updateAppInIde.js.map +1 -0
  30. package/out/constants/nasl-file-types.d.ts +1 -1
  31. package/out/constants/nasl-file-types.d.ts.map +1 -1
  32. package/out/constants/nasl-file-types.js +8 -1
  33. package/out/constants/nasl-file-types.js.map +1 -1
  34. package/out/services/compose.d.ts.map +1 -1
  35. package/out/services/compose.js +21 -8
  36. package/out/services/compose.js.map +1 -1
  37. package/out/services/resolve.d.ts.map +1 -1
  38. package/out/services/resolve.js +7 -5
  39. package/out/services/resolve.js.map +1 -1
  40. package/out/utils/appName.d.ts +8 -0
  41. package/out/utils/appName.d.ts.map +1 -0
  42. package/out/utils/appName.js +71 -0
  43. package/out/utils/appName.js.map +1 -0
  44. package/out/utils/prompt.d.ts +5 -0
  45. package/out/utils/prompt.d.ts.map +1 -0
  46. package/out/utils/prompt.js +54 -0
  47. package/out/utils/prompt.js.map +1 -0
  48. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -15,6 +15,7 @@ import crypto$1, { createHash } from 'crypto';
15
15
  import http2 from 'http2';
16
16
  import zlib from 'zlib';
17
17
  import { spawn, spawnSync } from 'child_process';
18
+ import * as readline from 'readline';
18
19
  import { realpath as realpath$1, stat as stat$2, lstat as lstat$1, open, readdir as readdir$1 } from 'fs/promises';
19
20
  import { lstat, stat as stat$1, readdir, realpath } from 'node:fs/promises';
20
21
  import { Readable as Readable$1 } from 'node:stream';
@@ -38,7 +39,18 @@ const DEFAULT_CONFIG = {
38
39
  const CONFIG_FILE_NAME = 'nasl.config.json';
39
40
 
40
41
  function createSorter() {
41
- const priorityOrder = ['app.dataSources', 'app.enums', 'app.structures', 'app.logics', 'app.frontendTypes'];
42
+ const priorityOrder = [
43
+ 'extensions',
44
+ 'apis',
45
+ 'connectors',
46
+ 'app.backend.variables',
47
+ 'app.roles',
48
+ 'app.enums',
49
+ 'app.dataSources',
50
+ 'app.structures',
51
+ 'app.logics',
52
+ 'app.frontendTypes',
53
+ ];
42
54
  // 获取优先级索引
43
55
  const getPriority = (str) => {
44
56
  const prefixIndex = priorityOrder.findIndex((p) => str.startsWith(p));
@@ -52,13 +64,11 @@ function createSorter() {
52
64
  return aPriority - bPriority;
53
65
  }
54
66
  // 如果是frontendTypes,按字母顺序排序
55
- if (aPriority === 4) {
67
+ if (a.startsWith('app.frontendTypes') && b.startsWith('app.frontendTypes')) {
56
68
  return a.localeCompare(b);
57
69
  }
58
- else {
59
- // 其他情况保持原顺序
60
- return 0;
61
- }
70
+ // 其他情况保持原顺序
71
+ return 0;
62
72
  };
63
73
  }
64
74
  const sorter = createSorter();
@@ -126,11 +136,15 @@ function composeToString(files, options) {
126
136
  const isVariablesFile = nameFromPath === 'variables';
127
137
  const isExtensionsFile = arr[0] === 'extensions';
128
138
  const isThemeCss = ext === 'css' && nameFromPath === 'theme';
129
- const isSpecialFile = isVariablesFile || isExtensionsFile || isThemeCss;
139
+ const isRolesJson = file.path === 'app.roles.json';
140
+ const isSpecialFile = isVariablesFile || isExtensionsFile || isThemeCss || isRolesJson;
130
141
  // 特殊文件的 namespace ${包含文件名,普通文件不包含
131
142
  const namespace = isSpecialFile ? [...arr, nameFromPath].join('.') : arr.join('.');
132
143
  let content = file.content;
133
- if (['ts', 'tsx'].includes(ext)) {
144
+ if (isRolesJson) {
145
+ content = ` $roles(${content});`;
146
+ }
147
+ else if (['ts', 'tsx'].includes(ext)) {
134
148
  if (isVariablesFile) {
135
149
  validateVariablesFile(file, errors);
136
150
  }
@@ -13753,6 +13767,13 @@ function writeFileWithLog(filePath, content, logger) {
13753
13767
  * NASL 支持的所有文件类型配置
13754
13768
  */
13755
13769
  const NASL_FILE_TYPES = [
13770
+ {
13771
+ name: 'roles',
13772
+ description: '角色',
13773
+ fileNamePattern: 'app\\.roles\\.json',
13774
+ codeRefPattern: '',
13775
+ extension: 'json',
13776
+ },
13756
13777
  {
13757
13778
  name: 'theme-css',
13758
13779
  description: '主题样式',
@@ -13849,7 +13870,7 @@ const fileNamePatterns = getFileNamePatterns();
13849
13870
  * 获取用于提取代码引用的正则表达式数组
13850
13871
  */
13851
13872
  function getCodeRefPatterns() {
13852
- return NASL_FILE_TYPES.map((type) => new RegExp(type.codeRefPattern, 'g'));
13873
+ return NASL_FILE_TYPES.filter((type) => type.codeRefPattern).map((type) => new RegExp(type.codeRefPattern, 'g'));
13853
13874
  }
13854
13875
  const codeRefPatterns = getCodeRefPatterns();
13855
13876
  /**
@@ -13884,7 +13905,7 @@ function shouldSkipDependencyTraversal(depPath) {
13884
13905
  async function scanNASLFiles(srcDir, representation, logger) {
13885
13906
  try {
13886
13907
  const pattern = representation === 'NaturalTS' ? '**/*.{ts,tsx}' : '**/*.nasl';
13887
- const files = await globby([pattern, '**/app.frontendTypes.pc.frontends.pc.theme.css'], {
13908
+ const files = await globby([pattern, 'app.frontendTypes.pc.frontends.pc.theme.css', 'app.roles.json'], {
13888
13909
  cwd: srcDir,
13889
13910
  onlyFiles: true,
13890
13911
  absolute: false,
@@ -14118,9 +14139,9 @@ function buildExternalDependencies(refs, mergedDeps, logger) {
14118
14139
  function replaceViewAsSignature(content, hasSubViews = false) {
14119
14140
  if (hasSubViews) {
14120
14141
  // 如果有子页面,替换为返回 ElRouterView 的函数
14121
- return content.replace(/export function ((\w+)\([^)]*\)) \{[\s\S]+$/, 'export function $1 {\n return <ElRouterView />\n}');
14142
+ return content.replace(/export function ((\w+)\([\s\S]*?\)) \{[\s\S]+$/, 'export function $1 {\n return <ElRouterView />\n}');
14122
14143
  }
14123
- return content.replace(/export function ((\w+)\([^)]*\)) \{[\s\S]+$/, 'export declare function $1;');
14144
+ return content.replace(/export function ((\w+)\([\s\S]*?\)) \{[\s\S]+$/, 'export declare function $1;');
14124
14145
  }
14125
14146
  /**
14126
14147
  * 处理单个文件的依赖
@@ -14162,8 +14183,10 @@ function processFileDeps(pathRelativeToSrc, srcDir, matchedFileSet, processedFil
14162
14183
  processedFileMap.set(pathRelativeToSrc, fileInfo);
14163
14184
  // 提取依赖
14164
14185
  // extensions/connectors/apis/uilibs 作为叶子节点,不再向下递归查找依赖
14186
+ // JSON 文件(如 app.roles.json)无代码引用,跳过依赖分析
14165
14187
  const isExternalDep = shouldSkipDependencyTraversal(pathRelativeToSrc);
14166
- const deps = isExternalDep ? [] : extractDeps(fileInfo.content);
14188
+ const isRolesJson = pathRelativeToSrc === 'app.roles.json';
14189
+ const deps = isExternalDep || isRolesJson ? [] : extractDeps(fileInfo.content);
14167
14190
  // 查找依赖文件
14168
14191
  if (isView) {
14169
14192
  const pathArr = pathRelativeToSrc.split('.');
@@ -14289,7 +14312,7 @@ async function resolveNASLFiles(entry, logger, depMode, verbose) {
14289
14312
  }
14290
14313
  let externalRefs = null;
14291
14314
  if (!entry && depMode)
14292
- entry = 'src/**/app.*.{ts,tsx,css}';
14315
+ entry = ['src/**/app.*.{ts,tsx,css}', 'src/app.roles.json'];
14293
14316
  if (entry) {
14294
14317
  // 检查入口路径是否在源代码目录外面
14295
14318
  // if (entry.startsWith('..')) throw new Error('入口路径不能在源代码目录外面');
@@ -35191,41 +35214,33 @@ async function parseApi(fullNaturalTS, options) {
35191
35214
  }
35192
35215
 
35193
35216
  /**
35194
- * 创建应用同步
35217
+ * 创建应用(POST /nasl/app/create)
35195
35218
  */
35196
- async function createAppSyncApi(fullNaturalTS, options) {
35197
- const url = new URL(options.serverBaseURL);
35198
- const origin = url.origin + '/app-ai-creator';
35199
- const axios = await createAxios({ serverBaseURL: origin, ideVersion: options.ideVersion });
35200
- try {
35201
- const res = await axios.post('/api/createAppSync', {
35202
- fullNaturalTS,
35203
- packageName: options.packageName,
35204
- appName: options.appName,
35205
- hostname: url.hostname,
35206
- enableAuthTemplate: false,
35207
- ideVersion: options.ideVersion,
35208
- fullVersion: `${options.ideVersion}.0`,
35209
- });
35210
- if (res.data.success) {
35211
- return {
35212
- success: true,
35213
- appId: res.data.data?.appId,
35214
- appURL: res.data.data?.appURL,
35215
- message: res.data.data?.message,
35216
- };
35217
- }
35218
- else {
35219
- return {
35220
- success: false,
35221
- error: res.data.message || '应用创建失败',
35222
- };
35223
- }
35224
- }
35225
- catch (error) {
35226
- console.log(error);
35227
- throw error;
35228
- }
35219
+ async function createApp(fullNaturalTS, options, appName, packageName) {
35220
+ const axiosInstance = await createAxios(options);
35221
+ const res = await axiosInstance.post('/app/create', {
35222
+ fullNaturalTS,
35223
+ packageName,
35224
+ appName,
35225
+ ideVersion: options.ideVersion,
35226
+ }, {
35227
+ headers: { ...buildNaslHeaders(options), 'Content-Type': 'application/json' },
35228
+ });
35229
+ return res.data.result;
35230
+ }
35231
+ /**
35232
+ * 更新应用(POST /nasl/app/update)
35233
+ */
35234
+ async function updateApp(fullNaturalTS, options, appId) {
35235
+ const axiosInstance = await createAxios(options);
35236
+ const res = await axiosInstance.post('/app/update', {
35237
+ fullNaturalTS,
35238
+ appId,
35239
+ ideVersion: options.ideVersion,
35240
+ }, {
35241
+ headers: { ...buildNaslHeaders(options), 'Content-Type': 'application/json' },
35242
+ });
35243
+ return res.data.result;
35229
35244
  }
35230
35245
 
35231
35246
  async function installDependenciesApi(dependenciesJSON, options) {
@@ -35632,78 +35647,94 @@ async function build(entry, options) {
35632
35647
  }
35633
35648
 
35634
35649
  /**
35635
- * 获取 specs 下第1个文件夹的名字
35650
+ * specs/ 目录取第一个子文件夹名;若无则退回项目根目录名
35636
35651
  */
35637
- function getFirstSpecFolderName(projectRoot) {
35638
- const dirname = path$1.basename(projectRoot);
35652
+ function getSpecBaseName(projectRoot) {
35639
35653
  const specsDir = path$1.join(projectRoot, 'specs');
35640
- if (!libExports.existsSync(specsDir))
35641
- return dirname;
35642
- const entries = libExports.readdirSync(specsDir, { withFileTypes: true });
35643
- const folders = entries
35644
- .filter(entry => entry.isDirectory())
35645
- .map(entry => entry.name);
35646
- if (folders.length === 0)
35647
- return dirname;
35648
- return folders[0];
35654
+ if (libExports.existsSync(specsDir)) {
35655
+ const folders = libExports.readdirSync(specsDir, { withFileTypes: true })
35656
+ .filter(e => e.isDirectory())
35657
+ .map(e => e.name);
35658
+ if (folders.length > 0)
35659
+ return folders[0];
35660
+ }
35661
+ return path$1.basename(projectRoot);
35662
+ }
35663
+ /**
35664
+ * 从项目目录推导出合法的应用名称和包名
35665
+ */
35666
+ function deriveAppNames(projectRoot) {
35667
+ const baseName = getSpecBaseName(projectRoot);
35668
+ const suffix = dayjs().format('MMDDHHmmss');
35669
+ let cleaned = baseName.replace(/[^a-zA-Z0-9]/g, '').replace(/^\d+/, '').slice(0, 12);
35670
+ if (!cleaned)
35671
+ cleaned = 'app';
35672
+ return {
35673
+ appName: `${cleaned}_${suffix}`,
35674
+ packageName: `${cleaned}${suffix}`,
35675
+ };
35649
35676
  }
35677
+
35650
35678
  /**
35651
- * 创建应用在 IDE
35679
+ * 使用 readline 询问用户确认
35652
35680
  */
35681
+ function askForConfirmation(question) {
35682
+ const rl = readline.createInterface({
35683
+ input: process.stdin,
35684
+ output: process.stdout,
35685
+ });
35686
+ return new Promise((resolve) => {
35687
+ rl.question(question, (answer) => {
35688
+ rl.close();
35689
+ const a = answer.trim().toLowerCase();
35690
+ resolve(!a || a === 'y' || a === 'yes' || a === '是');
35691
+ });
35692
+ });
35693
+ }
35694
+
35653
35695
  async function createAppInIde(entry, options) {
35654
35696
  const logger = options?.logger || defaultLogger;
35655
- logger.info('开始创建应用在 IDE 中...');
35656
- // 收集需要处理的文件
35657
- const { collectedFiles, config } = await resolveNASLFiles(entry, logger, false, options?.verbose);
35658
- if (config.useOPENAPI) {
35659
- logger.error('create-app-in-ide 暂不支持 useOPENAPI 模式');
35660
- logger.exit(1);
35697
+ // ── 扫描 ─────────────────────────────────────────────
35698
+ const { collectedFiles, config, mergedDependencies } = await resolveNASLFiles(entry, logger, false, options?.verbose);
35699
+ // ── 展示参数 ──────────────────────────────────────────
35700
+ const { appName, packageName } = deriveAppNames(getProjectRoot());
35701
+ logger.newLine();
35702
+ logger.info(`应用名称: ${appName}`);
35703
+ logger.info(`包名: ${packageName}`);
35704
+ logger.info(`IDE 版本: ${config.ideVersion}`);
35705
+ logger.info(`租户名称: ${config.tenantName || 'defaulttenant'}`);
35706
+ // ── 确认 ──────────────────────────────────────────────
35707
+ if (!options?.quiet) {
35708
+ logger.newLine();
35709
+ const confirmed = await askForConfirmation('即将在 IDE 中创建新的应用,请确认是否继续?(Y/n): ');
35710
+ if (!confirmed) {
35711
+ logger.info('已取消操作');
35712
+ process.exit(0);
35713
+ }
35661
35714
  }
35662
- // 生成 fullNaturalTS
35715
+ // ── 执行 ──────────────────────────────────────────────
35663
35716
  logger.newLine();
35664
35717
  logger.info('正在生成 NaturalTS 代码...');
35665
- let fullNaturalTS = '';
35718
+ let fullNaturalTS;
35666
35719
  try {
35667
35720
  fullNaturalTS = composeToString(collectedFiles);
35721
+ fullNaturalTS = prependDependencies(fullNaturalTS, mergedDependencies);
35668
35722
  }
35669
35723
  catch (error) {
35670
35724
  logger.error(`生成 NaturalTS 代码失败: ${error.message}`);
35671
35725
  throw error;
35672
35726
  }
35673
- // 获取 specs 下第1个文件夹
35674
- const projectRoot = getProjectRoot();
35675
- const firstSpecFolderName = getFirstSpecFolderName(projectRoot);
35676
- const suffix = dayjs().format('MMDDHHmmss');
35677
- let cleaned = firstSpecFolderName.replace(/[^a-zA-Z0-9]/g, '').replace(/^\d+/, '').slice(0, 12);
35678
- if (!cleaned)
35679
- cleaned = 'app';
35680
- const appName = `${cleaned}_${suffix}`;
35681
- const packageName = `${cleaned}${suffix}`;
35682
- logger.info(`应用名称: ${appName}`);
35683
- logger.info(`包名: ${packageName}`);
35684
- logger.info(`IDE 版本: ${config.ideVersion}`);
35685
- logger.info(`完整版本: ${config.ideVersion}.0`);
35686
- // 调用创建应用 API
35687
- logger.newLine();
35688
35727
  logger.info('正在调用创建应用服务...');
35689
35728
  try {
35690
- const result = await createAppSyncApi(fullNaturalTS, {
35691
- packageName: packageName,
35692
- appName: appName,
35693
- serverBaseURL: config.serverBaseURL,
35694
- ideVersion: config.ideVersion,
35695
- });
35729
+ const result = await createApp(fullNaturalTS, config, appName, packageName);
35696
35730
  if (result.success) {
35697
35731
  logger.success('应用创建成功!');
35698
- if (result.appURL) {
35732
+ if (result.appURL)
35699
35733
  logger.info(`应用 URL: ${result.appURL}`);
35700
- }
35701
- if (result.appId) {
35734
+ if (result.appId)
35702
35735
  logger.info(`应用 ID: ${result.appId}`);
35703
- }
35704
- if (result.message) {
35736
+ if (result.message)
35705
35737
  logger.info(result.message);
35706
- }
35707
35738
  }
35708
35739
  else {
35709
35740
  logger.error(`应用创建失败: ${result.error || '未知错误'}`);
@@ -35716,6 +35747,57 @@ async function createAppInIde(entry, options) {
35716
35747
  }
35717
35748
  }
35718
35749
 
35750
+ async function updateAppInIde(appId, entry, options) {
35751
+ const logger = options?.logger || defaultLogger;
35752
+ // ── 扫描 ─────────────────────────────────────────────
35753
+ const { collectedFiles, config, mergedDependencies } = await resolveNASLFiles(entry, logger, false, options?.verbose);
35754
+ // ── 展示参数 ──────────────────────────────────────────
35755
+ logger.newLine();
35756
+ logger.info(`应用 ID: ${appId}`);
35757
+ logger.info(`IDE 版本: ${config.ideVersion}`);
35758
+ logger.info(`租户名称: ${config.tenantName || 'defaulttenant'}`);
35759
+ // ── 确认 ──────────────────────────────────────────────
35760
+ if (!options?.quiet) {
35761
+ logger.newLine();
35762
+ const confirmed = await askForConfirmation(`即将更新应用 ${appId},请确认是否继续?(Y/n): `);
35763
+ if (!confirmed) {
35764
+ logger.info('已取消操作');
35765
+ process.exit(0);
35766
+ }
35767
+ }
35768
+ // ── 执行 ──────────────────────────────────────────────
35769
+ logger.newLine();
35770
+ logger.info('正在生成 NaturalTS 代码...');
35771
+ let fullNaturalTS;
35772
+ try {
35773
+ fullNaturalTS = composeToString(collectedFiles);
35774
+ fullNaturalTS = prependDependencies(fullNaturalTS, mergedDependencies);
35775
+ }
35776
+ catch (error) {
35777
+ logger.error(`生成 NaturalTS 代码失败: ${error.message}`);
35778
+ throw error;
35779
+ }
35780
+ logger.info('正在调用更新应用服务...');
35781
+ try {
35782
+ const result = await updateApp(fullNaturalTS, config, appId);
35783
+ if (result.success) {
35784
+ logger.success('应用更新成功!');
35785
+ if (result.appURL)
35786
+ logger.info(`应用 URL: ${result.appURL}`);
35787
+ if (result.message)
35788
+ logger.info(result.message);
35789
+ }
35790
+ else {
35791
+ logger.error(`应用更新失败: ${result.error || '未知错误'}`);
35792
+ throw new Error(result.error || '应用更新失败');
35793
+ }
35794
+ }
35795
+ catch (error) {
35796
+ logger.error(`调用更新应用服务失败: ${error.message}`);
35797
+ throw error;
35798
+ }
35799
+ }
35800
+
35719
35801
  /**
35720
35802
  * 编译 NASL 代码
35721
35803
  * TODO: 实现具体的 API 调用逻辑
@@ -37764,5 +37846,5 @@ var index$1 = /*#__PURE__*/Object.freeze({
37764
37846
  watch: watch
37765
37847
  });
37766
37848
 
37767
- export { BaseLogger, CONFIG_FILE_NAME, ConsoleLogger, ConsoleLoggerWithoutExit, DEFAULT_CONFIG, MemoryLogger, build, check, compile, composeToString, createAppInIde, createSorter, defaultLogger, dep, dev, docCheck, extractFullNaturalTS, fastAppendLogToFile, fastLogToFile, init, installAuto, installByJSON, installByKind, loadAppDependencies, loadMergedDependencies, mergeDependenciesIntoApp, prependDependencies, resolveNASLFiles, scanEntryFiles, scanNASLFiles, sorter, transform, tryCompile };
37849
+ export { BaseLogger, CONFIG_FILE_NAME, ConsoleLogger, ConsoleLoggerWithoutExit, DEFAULT_CONFIG, MemoryLogger, build, check, compile, composeToString, createAppInIde, createSorter, defaultLogger, dep, dev, docCheck, extractFullNaturalTS, fastAppendLogToFile, fastLogToFile, init, installAuto, installByJSON, installByKind, loadAppDependencies, loadMergedDependencies, mergeDependenciesIntoApp, prependDependencies, resolveNASLFiles, scanEntryFiles, scanNASLFiles, sorter, transform, tryCompile, updateAppInIde };
37768
37850
  //# sourceMappingURL=index.mjs.map