@macrowing/inbiz-codegen 0.0.0-stage → 1.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 (163) hide show
  1. package/README.md +592 -2
  2. package/bin/inbiz-codegen.mjs +7 -0
  3. package/package.json +32 -4
  4. package/scripts/prepare-templates.mjs +35 -0
  5. package/src/backend/init.mjs +170 -0
  6. package/src/config.mjs +150 -0
  7. package/src/favicon.mjs +100 -0
  8. package/src/generate.mjs +935 -0
  9. package/src/generated-output.mjs +107 -0
  10. package/src/index.mjs +346 -0
  11. package/src/menu/build.mjs +252 -0
  12. package/src/menu/check.mjs +163 -0
  13. package/src/menu/command.mjs +179 -0
  14. package/src/migrate-runtime.mjs +106 -0
  15. package/src/platform/client.mjs +167 -0
  16. package/src/platform/command.mjs +386 -0
  17. package/src/platform/pack.mjs +591 -0
  18. package/src/platform/recover.mjs +236 -0
  19. package/src/platform/startup.mjs +343 -0
  20. package/src/platform/state.mjs +116 -0
  21. package/src/platform/update.mjs +157 -0
  22. package/src/platform/zip.mjs +134 -0
  23. package/src/pull.mjs +284 -0
  24. package/src/scaffold/commands.mjs +349 -0
  25. package/src/scaffold/init.mjs +370 -0
  26. package/src/scaffold/template-files.mjs +40 -0
  27. package/src/scaffold/template-source.mjs +235 -0
  28. package/src/scaffold/template-sync.mjs +335 -0
  29. package/src/transform/heaviness.mjs +380 -0
  30. package/src/transform/preview-props.mjs +108 -0
  31. package/src/transform/published-page-links.mjs +61 -0
  32. package/src/transform/published-script.mjs +110 -0
  33. package/src/transform/registry.mjs +781 -0
  34. package/src/transform/schema-to-jsx.mjs +1708 -0
  35. package/src/util/des.mjs +10 -0
  36. package/templates/README.md +34 -0
  37. package/templates/backend/Directory.Build.props +19 -0
  38. package/templates/backend/Directory.Packages.props +49 -0
  39. package/templates/backend/Macrowing.Scaffold.slnx +13 -0
  40. package/templates/backend/host/Macrowing.Start/Init/app.json +8 -0
  41. package/templates/backend/host/Macrowing.Start/Init/menus.json +4 -0
  42. package/templates/backend/host/Macrowing.Start/Initialization/InitializationDefinition.cs +245 -0
  43. package/templates/backend/host/Macrowing.Start/Initialization/InitializationEndpoints.cs +57 -0
  44. package/templates/backend/host/Macrowing.Start/Initialization/InitializationHostedService.cs +63 -0
  45. package/templates/backend/host/Macrowing.Start/Initialization/InitializationOptions.cs +44 -0
  46. package/templates/backend/host/Macrowing.Start/Initialization/InitializationRunner.cs +294 -0
  47. package/templates/backend/host/Macrowing.Start/Initialization/InitializationState.cs +72 -0
  48. package/templates/backend/host/Macrowing.Start/Initialization/MenuFactory.cs +118 -0
  49. package/templates/backend/host/Macrowing.Start/Initialization/PackageBuilder.cs +317 -0
  50. package/templates/backend/host/Macrowing.Start/Initialization/PlatformAppImporter.cs +371 -0
  51. package/templates/backend/host/Macrowing.Start/Macrowing.Start.csproj +26 -0
  52. package/templates/backend/host/Macrowing.Start/Program.cs +33 -0
  53. package/templates/backend/host/Macrowing.Start/StartModule.cs +67 -0
  54. package/templates/backend/host/Macrowing.Start/appsettings.json +38 -0
  55. package/templates/backend/modules/Macrowing.Generated/Application/GeneratedApplicationAutoMapperProfile.cs +42 -0
  56. package/templates/backend/modules/Macrowing.Generated/Domain/Entities/GeneratedEntityBase.cs +72 -0
  57. package/templates/backend/modules/Macrowing.Generated/Domain/GeneratedConsts.cs +50 -0
  58. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContext.cs +55 -0
  59. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContextModelBuilderExtensions.cs +61 -0
  60. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/IGeneratedDbContext.cs +32 -0
  61. package/templates/backend/modules/Macrowing.Generated/GeneratedModule.cs +89 -0
  62. package/templates/backend/modules/Macrowing.Generated/Macrowing.Generated.csproj +22 -0
  63. package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsClient.cs +95 -0
  64. package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsModels.cs +81 -0
  65. package/templates/backend/modules/Macrowing.InBiz.SDK/Dictionary/DictionaryClient.cs +44 -0
  66. package/templates/backend/modules/Macrowing.InBiz.SDK/InBizSdkModule.cs +16 -0
  67. package/templates/backend/modules/Macrowing.InBiz.SDK/InterfaceEngine/InterfaceEngineClient.cs +50 -0
  68. package/templates/backend/modules/Macrowing.InBiz.SDK/Localization/LocalizationClient.cs +28 -0
  69. package/templates/backend/modules/Macrowing.InBiz.SDK/Macrowing.InBiz.SDK.csproj +16 -0
  70. package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageClient.cs +99 -0
  71. package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageModels.cs +63 -0
  72. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelClient.cs +131 -0
  73. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelQuery.cs +108 -0
  74. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelWrite.cs +44 -0
  75. package/templates/backend/modules/Macrowing.InBiz.SDK/Permission/PermissionClient.cs +86 -0
  76. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformException.cs +42 -0
  77. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformRegistration.cs +60 -0
  78. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformTransport.cs +96 -0
  79. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizRequestContext.cs +27 -0
  80. package/templates/backend/modules/Macrowing.InBiz.SDK/README.md +117 -0
  81. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsClient.cs +35 -0
  82. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsQuery.cs +20 -0
  83. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationRequests.cs +105 -0
  84. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationsClient.cs +53 -0
  85. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/README.md +132 -0
  86. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Tracking/WorkFlowTrackingClient.cs +50 -0
  87. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeClient.cs +78 -0
  88. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeModels.cs +34 -0
  89. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowContracts.cs +88 -0
  90. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowRegistration.cs +59 -0
  91. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowTransport.cs +163 -0
  92. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchClient.cs +59 -0
  93. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchModels.cs +76 -0
  94. package/templates/backend/modules/Macrowing.OC.SDK/Macrowing.OC.SDK.csproj +20 -0
  95. package/templates/backend/modules/Macrowing.OC.SDK/OcSdkModule.cs +18 -0
  96. package/templates/backend/modules/Macrowing.OC.SDK/Protos/README.md +22 -0
  97. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/Macrowing.InBiz.SDK.Tests.csproj +14 -0
  98. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformContractTests.cs +288 -0
  99. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformLiveTests.cs +173 -0
  100. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowHttpServer.cs +113 -0
  101. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowLiveTests.cs +269 -0
  102. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowOperationsTests.cs +80 -0
  103. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowQueryTests.cs +163 -0
  104. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowTransportTests.cs +111 -0
  105. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowUpgradeTests.cs +87 -0
  106. package/templates/frontend/components/README.md +39 -0
  107. package/templates/frontend/components/app-components/README.md +33 -0
  108. package/templates/frontend/components/app-components/common/.gitkeep +0 -0
  109. package/templates/frontend/components/app-components/components/.gitkeep +0 -0
  110. package/templates/frontend/components/app-components/package.json +20 -0
  111. package/templates/frontend/mgt/.umirc.ts +574 -0
  112. package/templates/frontend/mgt/package.json +96 -0
  113. package/templates/frontend/mgt/src/app-extends.ts +9 -0
  114. package/templates/frontend/mgt/src/app.tsx +20 -0
  115. package/templates/frontend/mgt/src/config/app.ts +31 -0
  116. package/templates/frontend/mgt/src/layout/header.tsx +14 -0
  117. package/templates/frontend/mgt/src/layout/index.tsx +11 -0
  118. package/templates/frontend/mgt/src/layout/sidebar.tsx +14 -0
  119. package/templates/frontend/mgt/src/locales.ts +8 -0
  120. package/templates/frontend/mgt/src/pages/.gitkeep +0 -0
  121. package/templates/frontend/mgt/src/root.tsx +12 -0
  122. package/templates/frontend/mgt/src/route-view.tsx +3 -0
  123. package/templates/frontend/mgt/src/runtime.ts +21 -0
  124. package/templates/frontend/mgt/src/styles/app.css +1 -0
  125. package/templates/frontend/mgt/src/styles/layout.less +79 -0
  126. package/templates/frontend/mgt/tsconfig.json +65 -0
  127. package/templates/frontend/mgt/typings.d.ts +57 -0
  128. package/templates/frontend/wap/.umirc.ts +574 -0
  129. package/templates/frontend/wap/package.json +73 -0
  130. package/templates/frontend/wap/src/app-extends.ts +9 -0
  131. package/templates/frontend/wap/src/app.tsx +28 -0
  132. package/templates/frontend/wap/src/config/app.ts +31 -0
  133. package/templates/frontend/wap/src/layout/header.tsx +14 -0
  134. package/templates/frontend/wap/src/layout/index.tsx +18 -0
  135. package/templates/frontend/wap/src/layout/sidebar.tsx +14 -0
  136. package/templates/frontend/wap/src/locales.ts +8 -0
  137. package/templates/frontend/wap/src/pages/.gitkeep +0 -0
  138. package/templates/frontend/wap/src/root.tsx +12 -0
  139. package/templates/frontend/wap/src/route-view.tsx +3 -0
  140. package/templates/frontend/wap/src/runtime.ts +21 -0
  141. package/templates/frontend/wap/src/styles/adaptation.less +190 -0
  142. package/templates/frontend/wap/src/styles/app.css +7 -0
  143. package/templates/frontend/wap/src/styles/global.less +81 -0
  144. package/templates/frontend/wap/src/styles/layout.less +92 -0
  145. package/templates/frontend/wap/tsconfig.json +66 -0
  146. package/templates/frontend/wap/typings.d.ts +24 -0
  147. package/templates/frontend/web/.umirc.ts +574 -0
  148. package/templates/frontend/web/package.json +26 -0
  149. package/templates/frontend/web/src/app-extends.ts +9 -0
  150. package/templates/frontend/web/src/app.tsx +25 -0
  151. package/templates/frontend/web/src/config/app.ts +31 -0
  152. package/templates/frontend/web/src/layout/header.tsx +14 -0
  153. package/templates/frontend/web/src/layout/index.tsx +11 -0
  154. package/templates/frontend/web/src/layout/sidebar.tsx +14 -0
  155. package/templates/frontend/web/src/locales.ts +8 -0
  156. package/templates/frontend/web/src/root.tsx +12 -0
  157. package/templates/frontend/web/src/route-view.tsx +3 -0
  158. package/templates/frontend/web/src/runtime.ts +21 -0
  159. package/templates/frontend/web/src/styles/app.css +104 -0
  160. package/templates/frontend/web/src/styles/layout.less +124 -0
  161. package/templates/frontend/web/tsconfig.json +91 -0
  162. package/templates/frontend/web/typings.d.ts +46 -0
  163. package/templates/package.json +14 -0
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * prepack:把仓库里的 `codegen/templates` 复制进 CLI 包内。
4
+ *
5
+ * 为什么要带一份:`init` 的模板是「远程优先、失败回退」。发布到 npmjs 之后
6
+ * 仓库结构不存在了,包内这份就是离线/网络不可达时的兜底。
7
+ *
8
+ * 不进版本库:它是打包产物(`.gitignore` 已忽略 `cli/templates/`)。
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ const CLI_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
16
+ const SOURCE = path.resolve(CLI_ROOT, '../../templates');
17
+ const DEST = path.join(CLI_ROOT, 'templates');
18
+
19
+ if (!fs.existsSync(SOURCE)) {
20
+ console.error(`✗ 找不到模板源目录:${SOURCE}`);
21
+ process.exit(1);
22
+ }
23
+
24
+ fs.rmSync(DEST, { recursive: true, force: true });
25
+ fs.cpSync(SOURCE, DEST, { recursive: true });
26
+
27
+ const count = (function walk(dir) {
28
+ let total = 0;
29
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
30
+ total += entry.isDirectory() ? walk(path.join(dir, entry.name)) : 1;
31
+ }
32
+ return total;
33
+ })(DEST);
34
+
35
+ console.log(`✓ 已复制模板:${SOURCE} → ${DEST}(${count} 个文件)`);
@@ -0,0 +1,170 @@
1
+ /**
2
+ * 把平台数据落成后端的初始化文件(`Macrowing.Start/Init/*.json`)。
3
+ *
4
+ * 出码时顺带产出,保证「后端启动时导入的那份应用包」和「前端出码用的那份数据」
5
+ * 来自同一次 pull —— 否则两边各维护一份菜单,线上迟早对不上。
6
+ *
7
+ * 输出:
8
+ * Init/app.json 应用身份(appName / domain / tableNamePrefix)+ 端
9
+ * Init/menus.json 菜单期望态(保留平台 OutId,用于改名/改图标时命中同一条)
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ const GROUP_ROUTE_PREFIX = 'xinjiancaidan_';
16
+
17
+ /**
18
+ * 词条 key → 文本。
19
+ *
20
+ * 平台菜单的 Name 存的是 `{multilingual}global.i18n-xxxx` 这种占位串,
21
+ * 前端运行时才解析。初始化文件是给后端导入平台用的 —— 写回占位串会变成
22
+ * 一条名字叫 `{multilingual}...` 的菜单,必须在这里解析成真实文本。
23
+ */
24
+ export function createTextResolver(messages) {
25
+ const table = messages && typeof messages === 'object' ? messages : {};
26
+ return function resolve(value) {
27
+ const text = String(value || '');
28
+ if (!text.startsWith('{multilingual}')) return text;
29
+ const key = text.slice('{multilingual}'.length).split('.').pop();
30
+ return table[key] ?? table[`i18n-${key}`] ?? text;
31
+ };
32
+ }
33
+
34
+ /**
35
+ * 平台图标字段是 `{"type":"icon-x","typeActive":""}` 这样的对象(有时是它的
36
+ * JSON 字符串)。初始化文件里只保留 `type`;对象序列化后直接写进去,
37
+ * 导入平台就变成一个非法图标名。
38
+ */
39
+ export function normalizeIcon(icon) {
40
+ if (!icon) return '';
41
+ if (typeof icon === 'string') {
42
+ const text = icon.trim();
43
+ if (text.startsWith('{')) {
44
+ try {
45
+ return normalizeIcon(JSON.parse(text));
46
+ } catch {
47
+ return text;
48
+ }
49
+ }
50
+ return text;
51
+ }
52
+ if (typeof icon === 'object') {
53
+ const type = icon.type || icon.Type || '';
54
+ return String(type || '').trim();
55
+ }
56
+ return '';
57
+ }
58
+
59
+ /** 平台菜单项 → 初始化文件的菜单定义(保留 outId)。 */
60
+ export function toMenuDefinitions(menuList = [], { resolve } = {}) {
61
+ const resolveText = resolve || ((value) => String(value || ''));
62
+ const items = Array.isArray(menuList) ? menuList : [];
63
+ const byOutId = new Map();
64
+ for (const item of items) {
65
+ if (item?.OutId) byOutId.set(String(item.OutId), item);
66
+ }
67
+
68
+ const routeOf = (item) => {
69
+ const route = String(item?.Route || '').trim();
70
+ return route.startsWith(GROUP_ROUTE_PREFIX) ? route.slice(GROUP_ROUTE_PREFIX.length) : route;
71
+ };
72
+
73
+ return items
74
+ .filter((item) => item && (item.Route || item.Name))
75
+ .map((item) => {
76
+ const isGroup = item.IsHaveChild === true || String(item.Route || '').startsWith(GROUP_ROUTE_PREFIX);
77
+ const parent = item.ParentId ? byOutId.get(String(item.ParentId)) : undefined;
78
+ const route = routeOf(item);
79
+ if (!route) return null;
80
+
81
+ const name = resolveText(item.Name || item.DisplayName || route);
82
+ const displayName = item.DisplayName ? resolveText(item.DisplayName) : '';
83
+ const icon = normalizeIcon(item.Icon);
84
+
85
+ return {
86
+ // 关键:保留平台 id,重新导入时命中同一条菜单
87
+ ...(item.OutId ? { outId: String(item.OutId) } : {}),
88
+ route,
89
+ name,
90
+ ...(displayName && displayName !== name ? { displayName } : {}),
91
+ ...(parent ? { parent: routeOf(parent) } : {}),
92
+ ...(isGroup ? { type: 'group' } : {}),
93
+ // 图标:只保留 type;平台给什么写什么,新菜单不要凭经验编
94
+ ...(icon ? { icon } : {}),
95
+ ...(item.Sort !== undefined ? { order: Number(item.Sort) || undefined } : {}),
96
+ ...(item.IsVisible === false ? { visible: false } : {}),
97
+ ...(item.IsInternalLink === false ? { external: true, url: String(item.LinkUrl || '') } : {}),
98
+ ...(!isGroup && item.PageOutId ? { pageOutId: String(item.PageOutId) } : {}),
99
+ };
100
+ })
101
+ .filter(Boolean);
102
+ }
103
+
104
+ /** 应用身份。平台在 app 对象上给的字段名不止一种,按候选顺序取。 */
105
+ export function toAppDefinition(app = {}, { end = 'web', siteType = 0, site = null, resolve } = {}) {
106
+ const domain = app.Domain || app.AppDomain || app.DomainName || '';
107
+ const src = site || {};
108
+ return {
109
+ app: {
110
+ appName: app.AppName || app.Name || '',
111
+ domain,
112
+ tableNamePrefix: app.TableNamePrefix || app.TablePrefix || 'app_',
113
+ },
114
+ /**
115
+ * 站点元数据随应用一起写。导入包里的 `standard/<end>/info.json` 必须有
116
+ * `AppTemplateId`(平台规则校验缺它就是 Error),值和主题都是**平台侧数据**,
117
+ * 只能在出码时从源应用读下来,运行时猜不出来。
118
+ */
119
+ sites: [{
120
+ end,
121
+ siteType,
122
+ appTemplateId: src.AppTemplateId || src.appTemplateId || '',
123
+ theme: src.Theme || src.theme || '',
124
+ layoutType: src.LayoutType ?? src.layoutType ?? 0,
125
+ // 默认页名同样是词条占位串({multilingual}global.i18n-xxx),要按语言包解析
126
+ defaultPageName: (resolve || String)(src.DefaultPageName || src.defaultPageName || ''),
127
+ defaultPageRoute: src.DefaultPageRoute || src.defaultPageRoute || '',
128
+ defaultPageId: src.DefaultPageId || src.defaultPageId || '',
129
+ isSkipMenuPerm: Boolean(src.IsSkipMenuPerm ?? src.isSkipMenuPerm ?? false),
130
+ }],
131
+ // domain 是导入/恢复的匹配键,缺了就没法「按域名判断应用是否存在」
132
+ warning: domain ? undefined : '平台未返回 Domain,后端初始化前必须手工补上 Init/app.json 的 domain',
133
+ };
134
+ }
135
+
136
+ /**
137
+ * @param {{ codegenRoot: string, snapshot: object, end?: string, siteType?: number,
138
+ * write?: (file: string, content: string) => boolean }} options
139
+ */
140
+ export function emitBackendInit({ codegenRoot, snapshot, end = 'web', siteType = 0, write }) {
141
+ const hostDir = path.join(codegenRoot, 'scaffolds/backend/host/Macrowing.Start');
142
+ if (!fs.existsSync(hostDir)) return { written: false, reason: '后端宿主目录不存在' };
143
+
144
+ const initDir = path.join(hostDir, 'Init');
145
+ // 菜单名/默认页名里是词条占位串,必须用同一次 pull 的语言包解析成真实文本
146
+ const resolve = createTextResolver(snapshot?.language?.messages);
147
+ const appDef = toAppDefinition(snapshot?.app || {}, { end, siteType, site: snapshot?.site, resolve });
148
+ const menus = toMenuDefinitions(snapshot?.menu || [], { resolve });
149
+
150
+ const appFile = path.join(initDir, 'app.json');
151
+ const menusFile = path.join(initDir, 'menus.json');
152
+
153
+ const writeFile = write || ((file, content) => {
154
+ fs.mkdirSync(path.dirname(file), { recursive: true });
155
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === content) return false;
156
+ fs.writeFileSync(file, content, 'utf8');
157
+ return true;
158
+ });
159
+
160
+ writeFile(appFile, JSON.stringify({ app: appDef.app, sites: appDef.sites }, null, 2) + '\n');
161
+ writeFile(menusFile, JSON.stringify({ end, menus }, null, 2) + '\n');
162
+
163
+ return {
164
+ written: true,
165
+ appFile: path.relative(codegenRoot, appFile),
166
+ menusFile: path.relative(codegenRoot, menusFile),
167
+ menus: menus.length,
168
+ warning: appDef.warning,
169
+ };
170
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,150 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { createRequire } from 'module';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ /** codegen/ 根目录(cli/ 的上一层) */
9
+ export const CODEGEN_ROOT = path.resolve(__dirname, '../..');
10
+
11
+ /**
12
+ * 模板根目录。
13
+ *
14
+ * 两种存在形态都认:
15
+ * - 开发态:`codegen/templates`(与 `codegen/framework` 平级);
16
+ * - 发布态:`cli/templates`(`prepack` 从开发态复制进来,随包发布)。
17
+ * 发布包里没有仓库结构,所以必须先看包内,再看仓库。
18
+ */
19
+ export const TEMPLATES_ROOT = (() => {
20
+ // __dirname = <repo>/codegen/framework/cli/src
21
+ const bundled = path.resolve(__dirname, '../templates'); // <cli>/templates
22
+ return fs.existsSync(bundled) ? bundled : path.resolve(__dirname, '../../../templates'); // <repo>/codegen/templates
23
+ })();
24
+
25
+ /** 前端出码工程目录 */
26
+ export const WEB_DIR = path.join(CODEGEN_ROOT, 'scaffolds/frontend/web');
27
+
28
+ /** 拉取下来的原始数据目录(不参与构建) */
29
+ export const DATA_DIR = path.join(WEB_DIR, '.inbiz');
30
+
31
+ /**
32
+ * 组件包(`@macrowing/inbiz-components`)的物理目录。
33
+ *
34
+ * 组件包按普通 npm 依赖装进出码工程,出码只消费它的公共入口:
35
+ * 目录在 `scaffolds/frontend/web/node_modules/` 下,内容是编译产物
36
+ * (`core/`、`basic/`、`*.d.ts`)。**不再**从 `codegen/packages/inbiz-components`
37
+ * 读源码 —— 那份目录已删除,且发布包与源码包的结构本来就不同。
38
+ *
39
+ * 找不到时直接报错:出码的组件注册表、重型判定、props 裁剪全都依赖这个目录,
40
+ * 静默回退只会得到一张空表,最后表现成「所有组件都解析不到」。
41
+ *
42
+ * @param {string} [dir] 出码工程目录(默认 scaffolds/frontend/web)
43
+ * @returns {string} 组件包绝对路径
44
+ */
45
+ export function resolveComponentsPackageDir(dir = WEB_DIR) {
46
+ const manual = path.join(dir, 'node_modules/@macrowing/inbiz-components');
47
+ if (fs.existsSync(path.join(manual, 'package.json'))) return manual;
48
+ try {
49
+ const req = createRequire(path.join(dir, 'package.json'));
50
+ return path.dirname(req.resolve('@macrowing/inbiz-components/package.json'));
51
+ } catch {
52
+ throw new Error(
53
+ `找不到 @macrowing/inbiz-components。请先在 ${dir} 执行 npm install `
54
+ + '(该包按 npm 依赖安装,不再从 codegen/packages 下读取)。',
55
+ );
56
+ }
57
+ }
58
+
59
+ /** 组件包路径(模块加载时解析一次,CLI 全程复用) */
60
+ export const COMPONENTS_PKG_DIR = resolveComponentsPackageDir();
61
+
62
+ /** 组件扫描根:`<组件包>/core/components` */
63
+ export const COMPONENTS_ROOT = path.join(COMPONENTS_PKG_DIR, 'core/components');
64
+
65
+ /** 基础组件候选目录,顺序与组件包 tsconfig paths 一致 */
66
+ export const COMPONENTS_BASIC_ROOTS = [
67
+ path.join(COMPONENTS_PKG_DIR, 'basic'),
68
+ path.join(COMPONENTS_PKG_DIR, 'basic/SyncComponents'),
69
+ path.join(COMPONENTS_PKG_DIR, 'basic/SyncDesignerComponents'),
70
+ ];
71
+
72
+ /**
73
+ * 读取 .env。
74
+ *
75
+ * 不用 dotenv:少一个依赖,且要避免把值做任何隐式转换
76
+ * (曾经踩过把 appId 序列化成带引号字符串的坑)。
77
+ */
78
+ export function readEnv(file = path.join(WEB_DIR, '.env')) {
79
+ const env = {};
80
+ if (!fs.existsSync(file)) return env;
81
+ for (const raw of fs.readFileSync(file, 'utf8').split('\n')) {
82
+ const line = raw.trim();
83
+ if (!line || line.startsWith('#')) continue;
84
+ const eq = line.indexOf('=');
85
+ if (eq < 0) continue;
86
+ const key = line.slice(0, eq).trim();
87
+ let val = line.slice(eq + 1).trim();
88
+ if (val.length > 1 && (val[0] === '"' || val[0] === "'")) val = val.slice(1, -1);
89
+ env[key] = val;
90
+ }
91
+ return env;
92
+ }
93
+
94
+ /**
95
+ * 读取工程配置。
96
+ *
97
+ * @param {string} [dir] 工程目录(默认 scaffolds/frontend/web)。
98
+ * 支持指定目录是为了「一个仓库里并存多个出码工程」:每个工程一份 .env,
99
+ * 互不干扰。显式参数优先于 .env(方便临时对某个应用出码)。
100
+ * @param {{ appId?: string, appName?: string, siteType?: number, siteOutId?: string,
101
+ * dataVersionId?: string, account?: string, password?: string }} [override]
102
+ */
103
+ export function loadConfig(dir = WEB_DIR, override = {}) {
104
+ const env = readEnv(path.join(dir, '.env'));
105
+ const cfg = {
106
+ dir,
107
+ baseUrl: env.INBIZ_URL,
108
+ appId: override.appId || env.INBIZ_APP_ID,
109
+ // `--app-name` 用于「只知道应用名、不知道 id」的场景,pull 时按名字解析
110
+ appName: override.appName || '',
111
+ siteType: Number(override.siteType ?? env.INBIZ_SITE_TYPE ?? 0),
112
+ siteOutId: override.siteOutId || env.INBIZ_SITE_OUT_ID,
113
+ dataVersionId: override.dataVersionId || env.INBIZ_DATA_VERSION_ID,
114
+ homeRoute: env.INBIZ_HOME_ROUTE || '/',
115
+ basePath: env.INBIZ_BASE_PATH || '',
116
+ account: override.account || env.INBIZ_PREVIEW_ACCOUNT || '',
117
+ password: override.password || env.INBIZ_PREVIEW_PASSWORD || '',
118
+ };
119
+
120
+ if (!cfg.baseUrl || !cfg.appId) {
121
+ throw new Error(
122
+ '缺少配置:请检查 ' + path.join(dir, '.env') + ' 中的 INBIZ_URL / INBIZ_APP_ID'
123
+ + '(也可以用 --app-id 临时指定)',
124
+ );
125
+ }
126
+ return cfg;
127
+ }
128
+
129
+ export function ensureDir(dir) {
130
+ fs.mkdirSync(dir, { recursive: true });
131
+ return dir;
132
+ }
133
+
134
+ export function writeIfChanged(file, content) {
135
+ ensureDir(path.dirname(file));
136
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === content) return false;
137
+ fs.writeFileSync(file, content, 'utf8');
138
+ return true;
139
+ }
140
+
141
+ /** 生成文件头,标明来源,避免别人手改后被覆盖时困惑 */
142
+ export function header(extra = '') {
143
+ return [
144
+ '/* eslint-disable */',
145
+ '// 本文件由 inbiz-codegen 生成,请勿手工修改。',
146
+ '// 需要定制请写在同目录的 *.custom.tsx 或对应 *.custom.ts 中。',
147
+ ...(extra ? ['// ' + extra] : []),
148
+ '',
149
+ ].join('\n');
150
+ }
@@ -0,0 +1,100 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const DEFAULT_ICON = new URL('../assets/inbiz-favicon.ico', import.meta.url);
5
+ const UMI_ICON_EXTENSIONS = ['ico', 'gif', 'png', 'jpg', 'jpeg', 'svg', 'avif', 'webp'];
6
+ const MAX_ICON_BYTES = 2 * 1024 * 1024;
7
+ const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
8
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
9
+
10
+ function detectFormat(bytes) {
11
+ if (bytes.length >= 22 && bytes.readUInt32LE(0) === 0x00010000 && bytes.readUInt16LE(4) > 0) return 'ico';
12
+ if (bytes.length >= 24 && bytes.subarray(0, 8).equals(PNG_SIGNATURE) && bytes.toString('ascii', 12, 16) === 'IHDR') return 'png';
13
+ if (bytes.length >= 4 && bytes.subarray(0, 3).toString('hex') === 'ffd8ff') return 'jpg';
14
+ if (bytes.length >= 13 && /^(?:GIF87a|GIF89a)$/.test(bytes.toString('ascii', 0, 6))) return 'gif';
15
+ if (bytes.length >= 16 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return 'webp';
16
+ if (bytes.length >= 16 && bytes.toString('ascii', 4, 8) === 'ftyp' && /^(?:avif|avis)$/.test(bytes.toString('ascii', 8, 12))) return 'avif';
17
+ if (/^\s*(?:<\?xml\b[^?]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/.test(bytes.toString('utf8'))) return 'svg';
18
+ throw new Error('expected an icon image, not a login page or unsupported response');
19
+ }
20
+
21
+ async function readIcon(response) {
22
+ const chunks = [];
23
+ let size = 0;
24
+ for await (const chunk of response.body ?? []) {
25
+ size += chunk.length;
26
+ if (size > MAX_ICON_BYTES) throw new Error('image exceeds 2 MiB');
27
+ chunks.push(chunk);
28
+ }
29
+ return Buffer.concat(chunks, size);
30
+ }
31
+
32
+ export async function pullFavicon({ logoPath, baseUrl, appId, cookie }) {
33
+ if (!logoPath) return undefined;
34
+ try {
35
+ const platform = new URL(baseUrl);
36
+ let url = new URL(logoPath.replaceAll('{AppId}', () => appId), new URL('/inbiz/web/', platform));
37
+ let platformRequest = true;
38
+ const signal = AbortSignal.timeout(15_000);
39
+ for (let hop = 0; hop <= 5; hop++) {
40
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
41
+ throw new Error('expected an HTTP(S) URL without embedded credentials');
42
+ }
43
+ platformRequest &&= url.origin === platform.origin;
44
+ const response = await fetch(url, {
45
+ headers: {
46
+ Accept: 'image/*',
47
+ ...(platformRequest ? { appId, ...(cookie ? { cookie } : {}) } : {}),
48
+ },
49
+ redirect: 'manual',
50
+ signal,
51
+ });
52
+ if (REDIRECTS.has(response.status)) {
53
+ await response.body?.cancel();
54
+ const location = response.headers.get('location');
55
+ if (!location) throw new Error(`HTTP ${response.status} without a redirect location`);
56
+ url = new URL(location, url);
57
+ continue;
58
+ }
59
+ if (!response.ok) {
60
+ await response.body?.cancel();
61
+ throw new Error(`HTTP ${response.status}`);
62
+ }
63
+ const bytes = await readIcon(response);
64
+ return { format: detectFormat(bytes), base64: bytes.toString('base64') };
65
+ }
66
+ throw new Error('too many redirects');
67
+ } catch (error) {
68
+ throw new Error(`Could not pull App.LogoPath: ${error.message}`);
69
+ }
70
+ }
71
+
72
+ function snapshotIcon(data) {
73
+ if (!data.app?.LogoPath) return { format: 'ico', bytes: fs.readFileSync(DEFAULT_ICON) };
74
+ const { format, base64 } = data.favicon ?? {};
75
+ if (typeof base64 !== 'string' || base64.length > Math.ceil(MAX_ICON_BYTES / 3) * 4) {
76
+ throw new Error('App.LogoPath is configured but its icon is missing or invalid; run inbiz-codegen pull again');
77
+ }
78
+ const bytes = Buffer.from(base64, 'base64');
79
+ if (bytes.toString('base64') !== base64 || bytes.length > MAX_ICON_BYTES || detectFormat(bytes) !== format) {
80
+ throw new Error('Invalid favicon in the snapshot; run inbiz-codegen pull again');
81
+ }
82
+ if (format === 'svg') {
83
+ // Keep uploaded SVG in image mode even when the local asset is opened as a document.
84
+ return { format, bytes: Buffer.from(
85
+ '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">' +
86
+ `<image width="64" height="64" href="data:image/svg+xml;base64,${base64}"/></svg>\n`,
87
+ ) };
88
+ }
89
+ return { format, bytes };
90
+ }
91
+
92
+ export function emitFavicon(data, srcDir, add, retire) {
93
+ const { format, bytes } = snapshotIcon(data);
94
+ add(path.join(srcDir, `favicon.${format}`), bytes);
95
+ // Umi picks up every src/favicon.* it recognizes. Do not silently combine a
96
+ // generated icon with a competing untracked file, or remove a changed one.
97
+ for (const ext of UMI_ICON_EXTENSIONS) {
98
+ if (ext !== format) retire.set(`src/favicon.${ext}`, undefined);
99
+ }
100
+ }