@macrowing/inbiz-codegen 0.0.0-stage → 1.0.1
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/README.md +592 -2
- package/bin/inbiz-codegen.mjs +7 -0
- package/package.json +32 -4
- package/scripts/prepare-templates.mjs +35 -0
- package/src/backend/init.mjs +170 -0
- package/src/config.mjs +150 -0
- package/src/favicon.mjs +100 -0
- package/src/generate.mjs +935 -0
- package/src/generated-output.mjs +107 -0
- package/src/index.mjs +346 -0
- package/src/menu/build.mjs +252 -0
- package/src/menu/check.mjs +163 -0
- package/src/menu/command.mjs +179 -0
- package/src/migrate-runtime.mjs +106 -0
- package/src/platform/client.mjs +167 -0
- package/src/platform/command.mjs +386 -0
- package/src/platform/pack.mjs +591 -0
- package/src/platform/recover.mjs +236 -0
- package/src/platform/startup.mjs +343 -0
- package/src/platform/state.mjs +116 -0
- package/src/platform/update.mjs +157 -0
- package/src/platform/zip.mjs +134 -0
- package/src/pull.mjs +284 -0
- package/src/scaffold/commands.mjs +349 -0
- package/src/scaffold/init.mjs +392 -0
- package/src/scaffold/template-files.mjs +40 -0
- package/src/scaffold/template-source.mjs +235 -0
- package/src/scaffold/template-sync.mjs +335 -0
- package/src/transform/heaviness.mjs +380 -0
- package/src/transform/preview-props.mjs +108 -0
- package/src/transform/published-page-links.mjs +61 -0
- package/src/transform/published-script.mjs +110 -0
- package/src/transform/registry.mjs +781 -0
- package/src/transform/schema-to-jsx.mjs +1708 -0
- package/src/util/des.mjs +10 -0
- package/templates/README.md +34 -0
- package/templates/backend/Directory.Build.props +19 -0
- package/templates/backend/Directory.Packages.props +49 -0
- package/templates/backend/Macrowing.Scaffold.slnx +13 -0
- package/templates/backend/host/Macrowing.Start/Init/app.json +8 -0
- package/templates/backend/host/Macrowing.Start/Init/menus.json +4 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationDefinition.cs +245 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationEndpoints.cs +57 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationHostedService.cs +63 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationOptions.cs +44 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationRunner.cs +294 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationState.cs +72 -0
- package/templates/backend/host/Macrowing.Start/Initialization/MenuFactory.cs +118 -0
- package/templates/backend/host/Macrowing.Start/Initialization/PackageBuilder.cs +317 -0
- package/templates/backend/host/Macrowing.Start/Initialization/PlatformAppImporter.cs +371 -0
- package/templates/backend/host/Macrowing.Start/Macrowing.Start.csproj +26 -0
- package/templates/backend/host/Macrowing.Start/Program.cs +33 -0
- package/templates/backend/host/Macrowing.Start/StartModule.cs +67 -0
- package/templates/backend/host/Macrowing.Start/appsettings.json +38 -0
- package/templates/backend/modules/Macrowing.Generated/Application/GeneratedApplicationAutoMapperProfile.cs +42 -0
- package/templates/backend/modules/Macrowing.Generated/Domain/Entities/GeneratedEntityBase.cs +72 -0
- package/templates/backend/modules/Macrowing.Generated/Domain/GeneratedConsts.cs +50 -0
- package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContext.cs +55 -0
- package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContextModelBuilderExtensions.cs +61 -0
- package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/IGeneratedDbContext.cs +32 -0
- package/templates/backend/modules/Macrowing.Generated/GeneratedModule.cs +89 -0
- package/templates/backend/modules/Macrowing.Generated/Macrowing.Generated.csproj +22 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsClient.cs +95 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsModels.cs +81 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Dictionary/DictionaryClient.cs +44 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/InBizSdkModule.cs +16 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/InterfaceEngine/InterfaceEngineClient.cs +50 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Localization/LocalizationClient.cs +28 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Macrowing.InBiz.SDK.csproj +16 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageClient.cs +99 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageModels.cs +63 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelClient.cs +131 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelQuery.cs +108 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelWrite.cs +44 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Permission/PermissionClient.cs +86 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformException.cs +42 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformRegistration.cs +60 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformTransport.cs +96 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizRequestContext.cs +27 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/README.md +117 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsClient.cs +35 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsQuery.cs +20 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationRequests.cs +105 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationsClient.cs +53 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/README.md +132 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Tracking/WorkFlowTrackingClient.cs +50 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeClient.cs +78 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeModels.cs +34 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowContracts.cs +88 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowRegistration.cs +59 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowTransport.cs +163 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchClient.cs +59 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchModels.cs +76 -0
- package/templates/backend/modules/Macrowing.OC.SDK/Macrowing.OC.SDK.csproj +20 -0
- package/templates/backend/modules/Macrowing.OC.SDK/OcSdkModule.cs +18 -0
- package/templates/backend/modules/Macrowing.OC.SDK/Protos/README.md +22 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/Macrowing.InBiz.SDK.Tests.csproj +14 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformContractTests.cs +288 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformLiveTests.cs +173 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowHttpServer.cs +113 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowLiveTests.cs +269 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowOperationsTests.cs +80 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowQueryTests.cs +163 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowTransportTests.cs +111 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowUpgradeTests.cs +87 -0
- package/templates/frontend/components/README.md +39 -0
- package/templates/frontend/components/app-components/README.md +33 -0
- package/templates/frontend/components/app-components/common/.gitkeep +0 -0
- package/templates/frontend/components/app-components/components/.gitkeep +0 -0
- package/templates/frontend/components/app-components/package.json +20 -0
- package/templates/frontend/mgt/.umirc.ts +574 -0
- package/templates/frontend/mgt/package.json +96 -0
- package/templates/frontend/mgt/src/app-extends.ts +9 -0
- package/templates/frontend/mgt/src/app.tsx +20 -0
- package/templates/frontend/mgt/src/config/app.ts +31 -0
- package/templates/frontend/mgt/src/layout/header.tsx +14 -0
- package/templates/frontend/mgt/src/layout/index.tsx +11 -0
- package/templates/frontend/mgt/src/layout/sidebar.tsx +14 -0
- package/templates/frontend/mgt/src/locales.ts +8 -0
- package/templates/frontend/mgt/src/pages/.gitkeep +0 -0
- package/templates/frontend/mgt/src/root.tsx +12 -0
- package/templates/frontend/mgt/src/route-view.tsx +3 -0
- package/templates/frontend/mgt/src/runtime.ts +21 -0
- package/templates/frontend/mgt/src/styles/app.css +1 -0
- package/templates/frontend/mgt/src/styles/layout.less +79 -0
- package/templates/frontend/mgt/tsconfig.json +65 -0
- package/templates/frontend/mgt/typings.d.ts +57 -0
- package/templates/frontend/wap/.umirc.ts +574 -0
- package/templates/frontend/wap/package.json +73 -0
- package/templates/frontend/wap/src/app-extends.ts +9 -0
- package/templates/frontend/wap/src/app.tsx +28 -0
- package/templates/frontend/wap/src/config/app.ts +31 -0
- package/templates/frontend/wap/src/layout/header.tsx +14 -0
- package/templates/frontend/wap/src/layout/index.tsx +18 -0
- package/templates/frontend/wap/src/layout/sidebar.tsx +14 -0
- package/templates/frontend/wap/src/locales.ts +8 -0
- package/templates/frontend/wap/src/pages/.gitkeep +0 -0
- package/templates/frontend/wap/src/root.tsx +12 -0
- package/templates/frontend/wap/src/route-view.tsx +3 -0
- package/templates/frontend/wap/src/runtime.ts +21 -0
- package/templates/frontend/wap/src/styles/adaptation.less +190 -0
- package/templates/frontend/wap/src/styles/app.css +7 -0
- package/templates/frontend/wap/src/styles/global.less +81 -0
- package/templates/frontend/wap/src/styles/layout.less +92 -0
- package/templates/frontend/wap/tsconfig.json +66 -0
- package/templates/frontend/wap/typings.d.ts +24 -0
- package/templates/frontend/web/.umirc.ts +574 -0
- package/templates/frontend/web/package.json +26 -0
- package/templates/frontend/web/src/app-extends.ts +9 -0
- package/templates/frontend/web/src/app.tsx +25 -0
- package/templates/frontend/web/src/config/app.ts +31 -0
- package/templates/frontend/web/src/layout/header.tsx +14 -0
- package/templates/frontend/web/src/layout/index.tsx +11 -0
- package/templates/frontend/web/src/layout/sidebar.tsx +14 -0
- package/templates/frontend/web/src/locales.ts +8 -0
- package/templates/frontend/web/src/root.tsx +12 -0
- package/templates/frontend/web/src/route-view.tsx +3 -0
- package/templates/frontend/web/src/runtime.ts +21 -0
- package/templates/frontend/web/src/styles/app.css +104 -0
- package/templates/frontend/web/src/styles/layout.less +124 -0
- package/templates/frontend/web/tsconfig.json +91 -0
- package/templates/frontend/web/typings.d.ts +46 -0
- package/templates/package.json +14 -0
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `init`:用模板生成一套可开发的前端工程。
|
|
3
|
+
*
|
|
4
|
+
* 设计取舍:
|
|
5
|
+
* - 模板放在仓库的 `codegen/templates`,与 `codegen/framework` 平级,是独立可维护
|
|
6
|
+
* 的产物,不跟随 CLI 目录移动;
|
|
7
|
+
* - 只复制结构(`.umirc.ts` / `tsconfig` / 入口 / 样式 / 空白布局),**不复制**
|
|
8
|
+
* `src/pages`、`.inbiz`、`node_modules`、`dist` —— 那些是 pull + generate 的产物;
|
|
9
|
+
* - 模板必须纯净:不声明任何业务组件包、不写死平台地址与代理前缀,这些由 .env
|
|
10
|
+
* 和 generate 产物决定;
|
|
11
|
+
* - `packages/` 的相对路径按目标位置重新计算:模板里统一写成 `../../../packages`,
|
|
12
|
+
* 生成时替换成实际相对路径,换目录深度不会断。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import crypto from 'node:crypto';
|
|
18
|
+
import { CODEGEN_ROOT, TEMPLATES_ROOT, writeIfChanged } from '../config.mjs';
|
|
19
|
+
import { listTemplateFiles } from './template-files.mjs';
|
|
20
|
+
import { TEMPLATES_PACKAGE } from './template-source.mjs';
|
|
21
|
+
|
|
22
|
+
/** 前端模板根:与 demo/frontend 同构(web / mgt / wap / components)。 */
|
|
23
|
+
const FRONTEND_TEMPLATES = path.join(TEMPLATES_ROOT, 'frontend');
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 站点类型 → 模板目录名。
|
|
27
|
+
* 与 InBiz 的 SiteType 对齐:Web = 0,Wap = 1,Mgt = 2。
|
|
28
|
+
*/
|
|
29
|
+
const SITE_TEMPLATES = { 0: 'web', 1: 'wap', 2: 'mgt' };
|
|
30
|
+
|
|
31
|
+
/** 站点类型 → 默认开发端口。 */
|
|
32
|
+
const DEFAULT_PORTS = { 0: 8021, 2: 8022, 1: 8023 };
|
|
33
|
+
|
|
34
|
+
/** 内置模板包的版本(远程不可用时记录它,基线才有版本可比)。 */
|
|
35
|
+
function readLocalTemplatesVersion() {
|
|
36
|
+
try {
|
|
37
|
+
const file = path.join(TEMPLATES_ROOT, 'package.json');
|
|
38
|
+
return JSON.parse(fs.readFileSync(file, 'utf8')).version || '0.0.0';
|
|
39
|
+
} catch {
|
|
40
|
+
return '0.0.0';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 模板里代表「packages 根」的占位串。 */
|
|
45
|
+
const PACKAGES_PLACEHOLDER = /\.\.\/\.\.\/\.\.\/packages/g;
|
|
46
|
+
|
|
47
|
+
// 「哪些文件属于模板」与升级比对共用同一判定,见 template-files.mjs。
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
/** 新工程在 pull 之前的空路由表,保证 `generate` 之前也能编译。 */
|
|
51
|
+
function emptyRoutes() {
|
|
52
|
+
return `/**
|
|
53
|
+
* 页面清单(占位)。
|
|
54
|
+
*
|
|
55
|
+
* 由 \`inbiz-codegen generate\` 根据平台页面清单生成。首次运行 pull + generate 之前
|
|
56
|
+
* 保留空清单,保证工程可编译。
|
|
57
|
+
*/
|
|
58
|
+
import type { LayoutRegion } from '@macrowing/inbiz-runtime/web';
|
|
59
|
+
export type { LayoutRegion } from '@macrowing/inbiz-runtime/web';
|
|
60
|
+
|
|
61
|
+
export interface PageRoute {
|
|
62
|
+
dir: string;
|
|
63
|
+
route: string;
|
|
64
|
+
compName: string;
|
|
65
|
+
builtin?: boolean;
|
|
66
|
+
title?: string;
|
|
67
|
+
hideLayout: readonly LayoutRegion[];
|
|
68
|
+
hideLayoutInPage?: readonly LayoutRegion[];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const DEFAULT_HIDE_LAYOUT: readonly LayoutRegion[] = ['tools'];
|
|
72
|
+
|
|
73
|
+
export const PAGES: readonly PageRoute[] = [];
|
|
74
|
+
|
|
75
|
+
export function findPageRoute(route: string): PageRoute | undefined {
|
|
76
|
+
return PAGES.find((page) => page.route === route);
|
|
77
|
+
}
|
|
78
|
+
`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function envFile({ appId, siteType, siteOutId, dataVersionId, serverUrl, port, basePath, proxyPrefixes }) {
|
|
82
|
+
return `# 出码工程运行参数。由 inbiz-codegen init 生成,pull 会回填站点信息。
|
|
83
|
+
|
|
84
|
+
# 开发服务端口:固定,避免端口漂移导致代理 / 登录回调地址对不上
|
|
85
|
+
INBIZ_DEV_PORT=${port}
|
|
86
|
+
PORT=${port}
|
|
87
|
+
|
|
88
|
+
INBIZ_URL=${serverUrl}
|
|
89
|
+
|
|
90
|
+
# 生产部署的路径前缀(网关按应用域名挂载)。开发期留空即可。
|
|
91
|
+
INBIZ_BASE_PATH=${basePath}
|
|
92
|
+
|
|
93
|
+
# 需要转发到 InBiz 平台的路径前缀(逗号分隔)。
|
|
94
|
+
# 与平台同域是硬要求:Cookie 共享、静态资源绝对路径才能命中。
|
|
95
|
+
INBIZ_PROXY_PREFIXES=${proxyPrefixes.join(',')}
|
|
96
|
+
|
|
97
|
+
INBIZ_APP_ID=${appId}
|
|
98
|
+
INBIZ_SITE_TYPE=${siteType}
|
|
99
|
+
INBIZ_SITE_OUT_ID=${siteOutId}
|
|
100
|
+
INBIZ_DATA_VERSION_ID=${dataVersionId}
|
|
101
|
+
|
|
102
|
+
INBIZ_HOME_ROUTE=/
|
|
103
|
+
INBIZ_LOGIN_PATH=/login
|
|
104
|
+
|
|
105
|
+
# 本地预览自动登录(生产留空)
|
|
106
|
+
INBIZ_PREVIEW_ACCOUNT=
|
|
107
|
+
INBIZ_PREVIEW_PASSWORD=
|
|
108
|
+
`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 工程的 `.npmrc`。
|
|
113
|
+
*
|
|
114
|
+
* 必须由 init 生成,不能放模板文件里:**npm 打包时会强制排除 `.npmrc`**,
|
|
115
|
+
* 放模板里发布出去就丢了,生成的项目会缺 scoped registry 配置,
|
|
116
|
+
* 表现为装 `@macrowing/*` 时 404 或 EALLOWREMOTE。
|
|
117
|
+
*/
|
|
118
|
+
const NPMRC_CONTENT = `# 组件包与运行时包都发布在 npmjs 的 @macrowing scope 下,其余依赖走镜像。
|
|
119
|
+
@macrowing:registry=https://registry.npmjs.org/
|
|
120
|
+
registry=https://registry.npmmirror.com/
|
|
121
|
+
|
|
122
|
+
# 组件库大量依赖与工程 peer 版本不一致,按 npm 的 legacy 语义安装。
|
|
123
|
+
legacy-peer-deps=true
|
|
124
|
+
install-links=true
|
|
125
|
+
|
|
126
|
+
# npm 12 起 allow-remote 默认 none。@macrowing 的元数据取自 npmjs,
|
|
127
|
+
# 但镜像会把 dist.tarball 改写到 npmmirror 域名,跨源下载会被判定为
|
|
128
|
+
# "remote" 而拒绝(EALLOWREMOTE)。显式放开,避免重装时卡在这一步。
|
|
129
|
+
allow-remote=all
|
|
130
|
+
`;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 默认转发前缀:只保留平台自身的通用入口。
|
|
134
|
+
*
|
|
135
|
+
* 具体应用用到的子应用路径各不相同,由 `--proxy-prefixes` 或后续手改 .env 追加。
|
|
136
|
+
* 模板不预设任何业务前缀。
|
|
137
|
+
*/
|
|
138
|
+
const DEFAULT_PROXY = ['/inbiz', '/apps', '/login', '/portal'];
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @param {{
|
|
142
|
+
* out: string, appId?: string, siteType?: string|number, siteOutId?: string,
|
|
143
|
+
* dataVersionId?: string, serverUrl?: string, port?: number, basePath?: string,
|
|
144
|
+
* proxyPrefixes?: string[], force?: boolean, json?: boolean,
|
|
145
|
+
* }} options
|
|
146
|
+
*/
|
|
147
|
+
export function runInit(options) {
|
|
148
|
+
const {
|
|
149
|
+
out, appId = '', siteType = 0, siteOutId = '', dataVersionId = '',
|
|
150
|
+
serverUrl = '', port, basePath = '',
|
|
151
|
+
proxyPrefixes = DEFAULT_PROXY, force = false, json = false,
|
|
152
|
+
templatesRoot, templateLabel, templateVersion, quiet = false,
|
|
153
|
+
} = options;
|
|
154
|
+
|
|
155
|
+
const target = path.resolve(out);
|
|
156
|
+
const exists = fs.existsSync(target);
|
|
157
|
+
const entries = exists ? fs.readdirSync(target) : [];
|
|
158
|
+
if (exists && entries.length && !force) {
|
|
159
|
+
const message = `目标目录非空:${target}(确认要覆盖请加 --force)`;
|
|
160
|
+
if (json) console.log(JSON.stringify({ ok: false, command: 'init', errors: [{ code: 'TARGET_NOT_EMPTY', path: target, message }] }, null, 2));
|
|
161
|
+
else console.error(`✗ ${message}`);
|
|
162
|
+
return { code: 2, created: [] };
|
|
163
|
+
}
|
|
164
|
+
const siteKey = Number(siteType) || 0;
|
|
165
|
+
const siteName = SITE_TEMPLATES[siteKey] || SITE_TEMPLATES[0];
|
|
166
|
+
// 远程模板优先(npm 包 @macrowing/inbiz-templates),取不到就用 CLI 内置副本。
|
|
167
|
+
const remoteDir = templatesRoot ? path.join(templatesRoot, 'frontend', siteName) : '';
|
|
168
|
+
const localDir = path.join(FRONTEND_TEMPLATES, siteName);
|
|
169
|
+
const usingRemote = !!remoteDir && fs.existsSync(remoteDir);
|
|
170
|
+
const templateDir = usingRemote ? remoteDir : localDir;
|
|
171
|
+
const source = usingRemote ? (templateLabel || 'registry') : 'local';
|
|
172
|
+
// 端口未显式指定时按站点取默认值,三端同时跑不会互相抢端口。
|
|
173
|
+
const resolvedPort = Number(port) || DEFAULT_PORTS[siteKey] || DEFAULT_PORTS[0];
|
|
174
|
+
if (!fs.existsSync(templateDir)) {
|
|
175
|
+
const message = `缺少模板目录:${templateDir}(站点类型 ${siteType})`;
|
|
176
|
+
if (json) console.log(JSON.stringify({ ok: false, command: 'init', errors: [{ code: 'TEMPLATE_MISSING', path: templateDir, message }] }, null, 2));
|
|
177
|
+
else console.error(`✗ ${message}`);
|
|
178
|
+
return { code: 2, created: [] };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// 新工程 → packages 的相对路径(模板里写的是 ../../../packages)
|
|
182
|
+
const packagesRoot = path.join(CODEGEN_ROOT, 'packages');
|
|
183
|
+
const relativePackages = path.relative(target, packagesRoot).split(path.sep).join('/') || 'packages';
|
|
184
|
+
|
|
185
|
+
const created = [];
|
|
186
|
+
const templateRels = listTemplateFiles(templateDir);
|
|
187
|
+
for (const rel of templateRels) {
|
|
188
|
+
const from = path.join(templateDir, rel);
|
|
189
|
+
const to = path.join(target, rel);
|
|
190
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
191
|
+
const text = fs.readFileSync(from, 'utf8')
|
|
192
|
+
.replace(PACKAGES_PLACEHOLDER, relativePackages)
|
|
193
|
+
.replace(/__INBIZ_DEV_PORT__/g, String(resolvedPort));
|
|
194
|
+
fs.writeFileSync(to, text, 'utf8');
|
|
195
|
+
created.push(rel);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const extra = {
|
|
199
|
+
'.npmrc': NPMRC_CONTENT,
|
|
200
|
+
'.env': envFile({
|
|
201
|
+
appId, siteType, siteOutId, dataVersionId, serverUrl, port: resolvedPort, basePath, proxyPrefixes,
|
|
202
|
+
}),
|
|
203
|
+
'src/pages/routes.ts': emptyRoutes(),
|
|
204
|
+
};
|
|
205
|
+
for (const [rel, content] of Object.entries(extra)) {
|
|
206
|
+
const to = path.join(target, rel);
|
|
207
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
208
|
+
fs.writeFileSync(to, content, 'utf8');
|
|
209
|
+
created.push(rel);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 记录模板基线,供 `template status` / `template upgrade` 做三方比较。
|
|
214
|
+
*
|
|
215
|
+
* 只记模板文件:`.env` 是本机配置,`src/pages/routes.ts` 是 generate 的产物,
|
|
216
|
+
* 都不属于模板。哈希按**写入后的内容**算(端口等占位符已替换),
|
|
217
|
+
* 这样升级时用同样的替换规则比较才不会误判。
|
|
218
|
+
*/
|
|
219
|
+
const manifest = {
|
|
220
|
+
name: TEMPLATES_PACKAGE,
|
|
221
|
+
version: templateVersion || readLocalTemplatesVersion(),
|
|
222
|
+
source,
|
|
223
|
+
site: siteName,
|
|
224
|
+
siteType: siteKey,
|
|
225
|
+
createdAt: new Date().toISOString(),
|
|
226
|
+
files: Object.fromEntries(templateRels.map((rel) => [
|
|
227
|
+
rel,
|
|
228
|
+
`sha256:${crypto.createHash('sha256')
|
|
229
|
+
.update(fs.readFileSync(path.join(target, rel), 'utf8'), 'utf8')
|
|
230
|
+
.digest('hex')}`,
|
|
231
|
+
])),
|
|
232
|
+
};
|
|
233
|
+
writeIfChanged(path.join(target, '.inbiz', 'template.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
234
|
+
|
|
235
|
+
if (json) {
|
|
236
|
+
console.log(JSON.stringify({
|
|
237
|
+
ok: true, command: 'init', out: target, created, templateSource: source,
|
|
238
|
+
next: ['npm ci', 'inbiz-codegen pull', 'inbiz-codegen generate', 'npm run dev'],
|
|
239
|
+
}, null, 2));
|
|
240
|
+
} else if (!quiet) {
|
|
241
|
+
console.log(`✓ 已生成工程:${target}`);
|
|
242
|
+
console.log(` 文件 ${created.length} 个,模板来源 ${source},packages 相对路径 ${relativePackages}`);
|
|
243
|
+
console.log(' 下一步:');
|
|
244
|
+
console.log(' 1) npm ci');
|
|
245
|
+
console.log(` 2) inbiz-codegen pull --dir ${target}`);
|
|
246
|
+
console.log(` 3) inbiz-codegen generate --out-dir ${target}`);
|
|
247
|
+
console.log(' 4) npm run dev');
|
|
248
|
+
if (!appId) console.log(' ! 未提供 --app-id:pull 之前请把应用 id / 站点 id 填进 .env');
|
|
249
|
+
}
|
|
250
|
+
return { code: 0, created, out: target };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 项目级初始化:一次生成三端 + 组件包 + 后端,目录与 demo 同构。
|
|
255
|
+
*
|
|
256
|
+
* <out>/
|
|
257
|
+
* frontend/web|mgt|wap/ 三端(各自带 .env、页面清单占位、模板基线)
|
|
258
|
+
* frontend/components/ 应用定制组件包骨架
|
|
259
|
+
* backend/ ABP:host + modules + tests
|
|
260
|
+
*/
|
|
261
|
+
export function runInitProject(options) {
|
|
262
|
+
const { out, json = false, force = false } = options;
|
|
263
|
+
const target = path.resolve(out);
|
|
264
|
+
const exists = fs.existsSync(target);
|
|
265
|
+
const entries = exists ? fs.readdirSync(target) : [];
|
|
266
|
+
if (exists && entries.length && !force) {
|
|
267
|
+
const message = `目标目录非空:${target}(确认要覆盖请加 --force)`;
|
|
268
|
+
if (json) console.log(JSON.stringify({ ok: false, command: 'init --project', errors: [{ code: 'TARGET_NOT_EMPTY', path: target, message }] }, null, 2));
|
|
269
|
+
else console.error(`✗ ${message}`);
|
|
270
|
+
return { code: 2, created: [] };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const sites = [
|
|
274
|
+
{ siteType: 0, dir: 'frontend/web' },
|
|
275
|
+
{ siteType: 2, dir: 'frontend/mgt' },
|
|
276
|
+
{ siteType: 1, dir: 'frontend/wap' },
|
|
277
|
+
];
|
|
278
|
+
|
|
279
|
+
const created = [];
|
|
280
|
+
for (const site of sites) {
|
|
281
|
+
const result = runInit({
|
|
282
|
+
...options,
|
|
283
|
+
out: path.join(target, site.dir),
|
|
284
|
+
siteType: site.siteType,
|
|
285
|
+
force: true,
|
|
286
|
+
quiet: true,
|
|
287
|
+
json: false,
|
|
288
|
+
});
|
|
289
|
+
if (result.code !== 0) return result;
|
|
290
|
+
created.push(...result.created.map((rel) => `${site.dir}/${rel}`));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// 组件包与后端没有占位符,原样复制。
|
|
294
|
+
for (const part of ['frontend/components', 'backend']) {
|
|
295
|
+
const from = path.join(TEMPLATES_ROOT, part);
|
|
296
|
+
if (!fs.existsSync(from)) continue;
|
|
297
|
+
for (const rel of listTemplateFiles(from)) {
|
|
298
|
+
const to = path.join(target, part, rel);
|
|
299
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
300
|
+
fs.copyFileSync(path.join(from, rel), to);
|
|
301
|
+
created.push(`${part}/${rel}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const name = path.basename(target);
|
|
306
|
+
writeIfChanged(path.join(target, 'README.md'), projectReadme(name));
|
|
307
|
+
writeIfChanged(path.join(target, '.gitignore'), PROJECT_GITIGNORE);
|
|
308
|
+
created.push('README.md', '.gitignore');
|
|
309
|
+
|
|
310
|
+
if (json) {
|
|
311
|
+
console.log(JSON.stringify({
|
|
312
|
+
ok: true, command: 'init --project', out: target, created,
|
|
313
|
+
sites: sites.map((site) => site.dir),
|
|
314
|
+
next: [
|
|
315
|
+
'cd frontend/web && npm install && npm run dev',
|
|
316
|
+
'inbiz-codegen pull --dir frontend/web --app-id <ID>',
|
|
317
|
+
'inbiz-codegen generate --out-dir frontend/web',
|
|
318
|
+
],
|
|
319
|
+
}, null, 2));
|
|
320
|
+
} else {
|
|
321
|
+
console.log(`✓ 已生成项目:${target}`);
|
|
322
|
+
console.log(` 三端:${sites.map((site) => site.dir).join('、')}`);
|
|
323
|
+
console.log(' 组件:frontend/components 后端:backend');
|
|
324
|
+
console.log(` 文件 ${created.length} 个`);
|
|
325
|
+
console.log(' 下一步:');
|
|
326
|
+
console.log(` cd ${path.join(target, 'frontend/web')} && npm install && npm run dev`);
|
|
327
|
+
console.log(` inbiz-codegen pull --dir ${path.join(target, 'frontend/web')} --app-id <ID>`);
|
|
328
|
+
console.log(` inbiz-codegen generate --out-dir ${path.join(target, 'frontend/web')}`);
|
|
329
|
+
}
|
|
330
|
+
return { code: 0, created, out: target };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** 项目根 README,给接手的人一份目录说明。 */
|
|
334
|
+
function projectReadme(name) {
|
|
335
|
+
return `# ${name}
|
|
336
|
+
|
|
337
|
+
InBiz 出码工程(项目级),目录与 demo 同构。
|
|
338
|
+
|
|
339
|
+
\`\`\`
|
|
340
|
+
frontend/
|
|
341
|
+
web/ 桌面端(SiteType 0,端口 8021)
|
|
342
|
+
mgt/ 管理端(SiteType 2,端口 8022)
|
|
343
|
+
wap/ 移动端(SiteType 1,端口 8023)
|
|
344
|
+
components/ 应用定制组件包(一个包一个子目录)
|
|
345
|
+
backend/ ABP:host + modules + tests
|
|
346
|
+
\`\`\`
|
|
347
|
+
|
|
348
|
+
## 开发
|
|
349
|
+
|
|
350
|
+
\`\`\`bash
|
|
351
|
+
cd frontend/web
|
|
352
|
+
npm install
|
|
353
|
+
npm run dev
|
|
354
|
+
\`\`\`
|
|
355
|
+
|
|
356
|
+
三端各自独立安装、独立启动;端口写在各自的 \`.env\` 里。
|
|
357
|
+
|
|
358
|
+
## 接入平台
|
|
359
|
+
|
|
360
|
+
\`\`\`bash
|
|
361
|
+
inbiz-codegen pull --dir frontend/web --app-id <应用ID> --site-type 0
|
|
362
|
+
inbiz-codegen generate --out-dir frontend/web
|
|
363
|
+
\`\`\`
|
|
364
|
+
|
|
365
|
+
\`pull\` 只读平台接口,\`generate\` 离线且幂等;两者都不改动上手写的文件。
|
|
366
|
+
`;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** 项目根 .gitignore。模板文件里的忽略规则只管各自的工程。 */
|
|
370
|
+
const PROJECT_GITIGNORE = `# 依赖与构建产物
|
|
371
|
+
node_modules/
|
|
372
|
+
dist/
|
|
373
|
+
.umi/
|
|
374
|
+
.umi-production/
|
|
375
|
+
.cache/
|
|
376
|
+
|
|
377
|
+
# 本机配置与凭据
|
|
378
|
+
.env
|
|
379
|
+
.env.local
|
|
380
|
+
*.log
|
|
381
|
+
|
|
382
|
+
# 本地联调包
|
|
383
|
+
*.tgz
|
|
384
|
+
.packs/
|
|
385
|
+
|
|
386
|
+
# .NET / ABP
|
|
387
|
+
[Bb]in/
|
|
388
|
+
[Oo]bj/
|
|
389
|
+
*.user
|
|
390
|
+
`;
|
|
391
|
+
|
|
392
|
+
export { FRONTEND_TEMPLATES, SITE_TEMPLATES, DEFAULT_PROXY };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模板里「哪些文件属于模板」的唯一判定。
|
|
3
|
+
*
|
|
4
|
+
* init(复制)和 template upgrade(升级比对)必须用同一份清单,
|
|
5
|
+
* 否则会出现「init 复制了、升级却不认识」的漂移。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
/** 安装/构建产物与本机配置:永远不复制、也不算模板文件。 */
|
|
12
|
+
export const SKIP_DIRS = new Set(['node_modules', 'dist', '.umi', '.umi-production', '.umi-test', '.inbiz']);
|
|
13
|
+
export const SKIP_FILES = new Set(['.env', '.DS_Store', 'Thumbs.db', 'package-lock.json']);
|
|
14
|
+
|
|
15
|
+
/** 由 generate 产出的目录:模板不拥有,升级时一律不碰。 */
|
|
16
|
+
export const GENERATED_DIRS = new Set(['src/pages']);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 递归列出模板里要复制的文件(相对模板根,统一用 `/`)。
|
|
20
|
+
*
|
|
21
|
+
* @param {string} root 模板根(某个站点的目录)
|
|
22
|
+
* @param {string} [prefix]
|
|
23
|
+
* @returns {string[]}
|
|
24
|
+
*/
|
|
25
|
+
export function listTemplateFiles(root, prefix = '') {
|
|
26
|
+
const out = [];
|
|
27
|
+
const dir = path.join(root, prefix);
|
|
28
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
29
|
+
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
30
|
+
if (entry.isDirectory()) {
|
|
31
|
+
if (SKIP_DIRS.has(entry.name)) continue;
|
|
32
|
+
if (GENERATED_DIRS.has(rel)) continue;
|
|
33
|
+
out.push(...listTemplateFiles(root, rel));
|
|
34
|
+
} else {
|
|
35
|
+
if (SKIP_FILES.has(entry.name)) continue;
|
|
36
|
+
out.push(rel);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模板来源:优先从 npm registry 拉取 `@macrowing/inbiz-templates`,
|
|
3
|
+
* 失败时由调用方回退到 CLI 内置的 `codegen/templates`。
|
|
4
|
+
*
|
|
5
|
+
* 为什么是 npm 包而不是 git 仓库:
|
|
6
|
+
* - 公开包匿名可拉,不需要密钥,也不依赖内网 Git 的访问策略;
|
|
7
|
+
* - 版本天然对齐(dist-tags / 指定版本),不需要手工对 tag;
|
|
8
|
+
* - 只拉模板本身,不带仓库历史。
|
|
9
|
+
*
|
|
10
|
+
* 约束:CLI 零第三方运行时依赖。所以这里不引 tar/gzip 库:
|
|
11
|
+
* - 解压用 Node 自带 zlib;
|
|
12
|
+
* - tar 解析只覆盖 npm 产物实际会用到的格式(ustar + pax 长路径 + GNU longname)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import zlib from 'node:zlib';
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
|
|
21
|
+
/** 模板包名。 */
|
|
22
|
+
export const TEMPLATES_PACKAGE = '@macrowing/inbiz-templates';
|
|
23
|
+
|
|
24
|
+
/** 默认 registry:模板包和组件包一样在 npmjs。 */
|
|
25
|
+
export const DEFAULT_TEMPLATE_REGISTRY = 'https://registry.npmjs.org/';
|
|
26
|
+
|
|
27
|
+
/** 默认超时(下载大 tarball 时 30s 可能偏短,给 60s)。 */
|
|
28
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
29
|
+
|
|
30
|
+
/** 缓存根:~/.inbiz/templates。 */
|
|
31
|
+
function cacheRoot() {
|
|
32
|
+
return path.join(os.homedir(), '.inbiz', 'templates');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 把 registry 规范成以 `/` 结尾。 */
|
|
36
|
+
function normalizeRegistry(registry) {
|
|
37
|
+
const text = String(registry || DEFAULT_TEMPLATE_REGISTRY).trim() || DEFAULT_TEMPLATE_REGISTRY;
|
|
38
|
+
return text.endsWith('/') ? text : `${text}/`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 读取 tar 头里的定长字符串。 */
|
|
42
|
+
function readString(buffer, offset, length) {
|
|
43
|
+
const raw = buffer.subarray(offset, offset + length);
|
|
44
|
+
const end = raw.indexOf(0);
|
|
45
|
+
return raw.subarray(0, end === -1 ? raw.length : end).toString('utf8');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 越界路径直接拒绝,避免 tarball 里的 `../` 写到缓存目录之外。 */
|
|
49
|
+
function safeJoin(root, relative) {
|
|
50
|
+
const target = path.join(root, relative);
|
|
51
|
+
const rel = path.relative(root, target);
|
|
52
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
53
|
+
throw new Error(`模板包包含越界路径:${relative}`);
|
|
54
|
+
}
|
|
55
|
+
return target;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 解压 tar(已 gunzip)。npm 的 tarball 最外层统一是 `package/`,这里剥掉。
|
|
60
|
+
*
|
|
61
|
+
* @param {Buffer} buffer
|
|
62
|
+
* @param {string} destRoot
|
|
63
|
+
* @returns {number} 写出的文件数
|
|
64
|
+
*/
|
|
65
|
+
export function extractTar(buffer, destRoot) {
|
|
66
|
+
fs.mkdirSync(destRoot, { recursive: true });
|
|
67
|
+
let offset = 0;
|
|
68
|
+
let pendingName = '';
|
|
69
|
+
let written = 0;
|
|
70
|
+
|
|
71
|
+
while (offset + 512 <= buffer.length) {
|
|
72
|
+
const header = buffer.subarray(offset, offset + 512);
|
|
73
|
+
const name = readString(header, 0, 100);
|
|
74
|
+
// 两个连续的空块表示结束
|
|
75
|
+
if (!name) break;
|
|
76
|
+
|
|
77
|
+
const size = parseInt(readString(header, 124, 12).trim() || '0', 8) || 0;
|
|
78
|
+
const type = String.fromCharCode(header[156] || 48);
|
|
79
|
+
const prefix = readString(header, 345, 155);
|
|
80
|
+
const dataStart = offset + 512;
|
|
81
|
+
const data = buffer.subarray(dataStart, dataStart + size);
|
|
82
|
+
const next = dataStart + Math.ceil(size / 512) * 512;
|
|
83
|
+
|
|
84
|
+
// pax 扩展头:长路径写在下一条记录的 data 里
|
|
85
|
+
if (type === 'x' || type === 'g') {
|
|
86
|
+
const text = data.toString('utf8');
|
|
87
|
+
const match = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(text);
|
|
88
|
+
if (match) pendingName = match[1];
|
|
89
|
+
offset = next;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
// GNU 长文件名
|
|
93
|
+
if (type === 'L') {
|
|
94
|
+
pendingName = data.toString('utf8').replace(/\0.*$/, '').trim();
|
|
95
|
+
offset = next;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
// 链接(符号链接/硬链接)不落地:模板里不该有
|
|
99
|
+
if (type === 'K' || type === '1' || type === '2') {
|
|
100
|
+
offset = next;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let full = prefix ? `${prefix}/${name}` : name;
|
|
105
|
+
if (pendingName) {
|
|
106
|
+
full = pendingName;
|
|
107
|
+
pendingName = '';
|
|
108
|
+
}
|
|
109
|
+
// 剥掉 npm tarball 的 `package/` 前缀
|
|
110
|
+
full = full.replace(/^package\//, '').replace(/^\.\//, '');
|
|
111
|
+
if (!full) {
|
|
112
|
+
offset = next;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const target = safeJoin(destRoot, full);
|
|
117
|
+
if (type === '5') {
|
|
118
|
+
fs.mkdirSync(target, { recursive: true });
|
|
119
|
+
} else if (type === '0' || type === '\0' || type === '') {
|
|
120
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
121
|
+
fs.writeFileSync(target, data);
|
|
122
|
+
written += 1;
|
|
123
|
+
}
|
|
124
|
+
offset = next;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return written;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 校验 dist.integrity(sha512-/sha1-),不匹配直接报错。 */
|
|
131
|
+
function verifyIntegrity(buffer, integrity) {
|
|
132
|
+
if (!integrity) return;
|
|
133
|
+
const dash = integrity.indexOf('-');
|
|
134
|
+
if (dash < 0) return;
|
|
135
|
+
const algorithm = integrity.slice(0, dash);
|
|
136
|
+
const expected = integrity.slice(dash + 1);
|
|
137
|
+
let actual;
|
|
138
|
+
try {
|
|
139
|
+
actual = crypto.createHash(algorithm).update(buffer).digest('base64');
|
|
140
|
+
} catch {
|
|
141
|
+
return; // 不认识的算法:交给 registry 的传输层去保证
|
|
142
|
+
}
|
|
143
|
+
if (actual !== expected) {
|
|
144
|
+
throw new Error(`模板包校验失败:${TEMPLATES_PACKAGE} 的 ${algorithm} 摘要不匹配`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function fetchJson(url, timeoutMs) {
|
|
149
|
+
const controller = new AbortController();
|
|
150
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
151
|
+
try {
|
|
152
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
153
|
+
if (!res.ok) {
|
|
154
|
+
const code = res.status === 404 ? 'NOT_FOUND' : 'HTTP_ERROR';
|
|
155
|
+
const error = new Error(`读取 ${url} 失败:HTTP ${res.status}`);
|
|
156
|
+
error.code = code;
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
return await res.json();
|
|
160
|
+
} finally {
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function fetchBuffer(url, timeoutMs) {
|
|
166
|
+
const controller = new AbortController();
|
|
167
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
168
|
+
try {
|
|
169
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
170
|
+
if (!res.ok) throw new Error(`下载 ${url} 失败:HTTP ${res.status}`);
|
|
171
|
+
return Buffer.from(await res.arrayBuffer());
|
|
172
|
+
} finally {
|
|
173
|
+
clearTimeout(timer);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* 解析模板包,返回可直接使用(含 `frontend/`、`backend/`)的目录。
|
|
179
|
+
*
|
|
180
|
+
* @param {{
|
|
181
|
+
* version?: string, // 指定版本;缺省用 dist-tags.latest
|
|
182
|
+
* registry?: string,
|
|
183
|
+
* offline?: boolean,
|
|
184
|
+
* timeoutMs?: number,
|
|
185
|
+
* }} options
|
|
186
|
+
* @returns {Promise<{root: string, version: string, source: 'cache'|'registry'} | null>}
|
|
187
|
+
* 离线、包不存在、网络失败时返回 null,由调用方回退到内置模板。
|
|
188
|
+
*/
|
|
189
|
+
export async function resolveTemplatesRoot(options = {}) {
|
|
190
|
+
const { version, registry, offline = false, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
|
|
191
|
+
if (offline) return null;
|
|
192
|
+
|
|
193
|
+
const base = normalizeRegistry(registry);
|
|
194
|
+
const packumentUrl = `${base}${TEMPLATES_PACKAGE.replace('/', '%2f')}`;
|
|
195
|
+
|
|
196
|
+
let packument;
|
|
197
|
+
try {
|
|
198
|
+
packument = await fetchJson(packumentUrl, timeoutMs);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
// 包还没发布 / 网络不可达:都算「没有远程模板」,交给内置模板兜底
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const resolvedVersion = version || packument?.['dist-tags']?.latest;
|
|
205
|
+
const meta = resolvedVersion ? packument?.versions?.[resolvedVersion] : undefined;
|
|
206
|
+
if (!meta?.dist?.tarball) return null;
|
|
207
|
+
|
|
208
|
+
const cacheDir = path.join(cacheRoot(), `${TEMPLATES_PACKAGE.replace('/', '-')}@${resolvedVersion}`);
|
|
209
|
+
const marker = path.join(cacheDir, '.ready');
|
|
210
|
+
if (fs.existsSync(marker)) {
|
|
211
|
+
return { root: cacheDir, version: resolvedVersion, source: 'cache' };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
let buffer;
|
|
215
|
+
try {
|
|
216
|
+
buffer = await fetchBuffer(meta.dist.tarball, timeoutMs);
|
|
217
|
+
verifyIntegrity(buffer, meta.dist.integrity);
|
|
218
|
+
} catch {
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const staging = `${cacheDir}.tmp-${process.pid}`;
|
|
223
|
+
try {
|
|
224
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
225
|
+
extractTar(zlib.gunzipSync(buffer), staging);
|
|
226
|
+
fs.rmSync(cacheDir, { recursive: true, force: true });
|
|
227
|
+
fs.renameSync(staging, cacheDir);
|
|
228
|
+
fs.writeFileSync(marker, new Date().toISOString(), 'utf8');
|
|
229
|
+
} catch (error) {
|
|
230
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return { root: cacheDir, version: resolvedVersion, source: 'registry' };
|
|
235
|
+
}
|