@lark-apaas/miaoda-cli 0.1.31 → 0.1.33-alpha.0e32e59
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 +24 -2
- package/dist/cli/commands/app/index.js +64 -0
- package/dist/cli/commands/deploy/modern.js +6 -5
- package/dist/cli/commands/registry/index.js +6 -6
- package/dist/cli/handlers/app/export-standalone.js +216 -0
- package/dist/cli/handlers/app/index.js +4 -1
- package/dist/cli/handlers/registry/add.js +3 -2
- package/dist/cli/handlers/registry/list.js +3 -8
- package/dist/cli/handlers/registry/shared.js +8 -4
- package/dist/services/app/export-standalone/archive.js +33 -0
- package/dist/services/app/export-standalone/copy-tree.js +51 -0
- package/dist/services/app/export-standalone/download.js +52 -0
- package/dist/services/app/export-standalone/index.js +23 -0
- package/dist/services/app/export-standalone/inline-babel.js +91 -0
- package/dist/services/app/export-standalone/naming.js +65 -0
- package/dist/services/app/export-standalone/rewrite.js +80 -0
- package/dist/services/app/export-standalone/scan.js +72 -0
- package/dist/services/app/export-standalone/strategies.js +214 -0
- package/dist/services/deploy/modern/patch/actions.js +6 -4
- package/dist/services/deploy/modern/patch/html-title.js +75 -0
- package/dist/services/deploy/modern/patch/index.js +1 -1
- package/dist/services/deploy/modern/patch/routes.js +13 -3
- package/dist/services/deploy/modern/patch/source-scan.js +3 -40
- package/dist/utils/exclude-patterns.js +49 -0
- package/dist/utils/sandbox-skills.js +13 -1
- package/package.json +1 -1
- package/upgrade/templates/nestjs-react-fullstack/templates/scripts/lint.js +43 -7
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.downloadImages = downloadImages;
|
|
7
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
8
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
+
const logger_1 = require("../../../utils/logger");
|
|
10
|
+
const naming_1 = require("./naming");
|
|
11
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
12
|
+
/**
|
|
13
|
+
* 经沙箱 dev server 代理批量下载图片。
|
|
14
|
+
*
|
|
15
|
+
* **单张失败不抛**——记进 `failed` 继续走。整体导出的成败判定由 handler 依据
|
|
16
|
+
* 「命中数 / 成功数」决定(设计文档「失败口径」:部分失败退 0,全失败退 1)。
|
|
17
|
+
*
|
|
18
|
+
* 串行下载:图片量级通常是个位数到几十,并发收益有限,而串行的日志与失败归因更清晰。
|
|
19
|
+
*/
|
|
20
|
+
async function downloadImages(urls, opts) {
|
|
21
|
+
const mapping = new Map();
|
|
22
|
+
const failed = [];
|
|
23
|
+
if (urls.length === 0)
|
|
24
|
+
return { mapping, failed };
|
|
25
|
+
node_fs_1.default.mkdirSync(opts.imagesDir, { recursive: true });
|
|
26
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
27
|
+
for (const url of urls) {
|
|
28
|
+
const target = `${opts.devServerBase}${url}`;
|
|
29
|
+
(0, logger_1.debug)(`export-standalone: GET ${target}`);
|
|
30
|
+
try {
|
|
31
|
+
// 刻意串行(见函数注释):图片量级通常个位数到几十,并发收益有限;
|
|
32
|
+
// 串行能让每张图的失败归因清晰,且不对沙箱 dev server 造成并发压力。
|
|
33
|
+
const resp = await fetch(target, { signal: AbortSignal.timeout(timeoutMs) });
|
|
34
|
+
if (!resp.ok) {
|
|
35
|
+
// resp.url 是**跟随重定向后**的最终地址。沙箱代理对存储图返回 302 指向签名 CDN,
|
|
36
|
+
// 失败发生在哪一跳,只看状态码分不出来,必须把最终地址带出来。
|
|
37
|
+
const finalUrl = resp.url && resp.url !== target ? ` (final: ${resp.url})` : '';
|
|
38
|
+
failed.push({ url, reason: `HTTP ${String(resp.status)}${finalUrl}` });
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const buf = Buffer.from(await resp.arrayBuffer());
|
|
42
|
+
const name = (0, naming_1.localImageName)(url, resp.headers.get('content-type') ?? undefined);
|
|
43
|
+
node_fs_1.default.writeFileSync(node_path_1.default.join(opts.imagesDir, name), buf);
|
|
44
|
+
mapping.set(url, name);
|
|
45
|
+
(0, logger_1.debug)(`export-standalone: downloaded ${url} -> images/${name} (${String(buf.length)}B)`);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
failed.push({ url, reason: err instanceof Error ? err.message : String(err) });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { mapping, failed };
|
|
52
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.STANDALONE_SUPPORTED_STACKS = exports.resolveStrategy = exports.buildStandaloneEnv = exports.scanSparkAppUrls = exports.TEXT_EXTENSIONS = exports.rewriteTree = exports.localImageName = exports.extFromContentType = exports.inlineBabelScripts = exports.downloadImages = exports.copyTree = exports.zipDir = void 0;
|
|
4
|
+
var archive_1 = require("./archive");
|
|
5
|
+
Object.defineProperty(exports, "zipDir", { enumerable: true, get: function () { return archive_1.zipDir; } });
|
|
6
|
+
var copy_tree_1 = require("./copy-tree");
|
|
7
|
+
Object.defineProperty(exports, "copyTree", { enumerable: true, get: function () { return copy_tree_1.copyTree; } });
|
|
8
|
+
var download_1 = require("./download");
|
|
9
|
+
Object.defineProperty(exports, "downloadImages", { enumerable: true, get: function () { return download_1.downloadImages; } });
|
|
10
|
+
var inline_babel_1 = require("./inline-babel");
|
|
11
|
+
Object.defineProperty(exports, "inlineBabelScripts", { enumerable: true, get: function () { return inline_babel_1.inlineBabelScripts; } });
|
|
12
|
+
var naming_1 = require("./naming");
|
|
13
|
+
Object.defineProperty(exports, "extFromContentType", { enumerable: true, get: function () { return naming_1.extFromContentType; } });
|
|
14
|
+
Object.defineProperty(exports, "localImageName", { enumerable: true, get: function () { return naming_1.localImageName; } });
|
|
15
|
+
var rewrite_1 = require("./rewrite");
|
|
16
|
+
Object.defineProperty(exports, "rewriteTree", { enumerable: true, get: function () { return rewrite_1.rewriteTree; } });
|
|
17
|
+
Object.defineProperty(exports, "TEXT_EXTENSIONS", { enumerable: true, get: function () { return rewrite_1.TEXT_EXTENSIONS; } });
|
|
18
|
+
var scan_1 = require("./scan");
|
|
19
|
+
Object.defineProperty(exports, "scanSparkAppUrls", { enumerable: true, get: function () { return scan_1.scanSparkAppUrls; } });
|
|
20
|
+
var strategies_1 = require("./strategies");
|
|
21
|
+
Object.defineProperty(exports, "buildStandaloneEnv", { enumerable: true, get: function () { return strategies_1.buildStandaloneEnv; } });
|
|
22
|
+
Object.defineProperty(exports, "resolveStrategy", { enumerable: true, get: function () { return strategies_1.resolveStrategy; } });
|
|
23
|
+
Object.defineProperty(exports, "STANDALONE_SUPPORTED_STACKS", { enumerable: true, get: function () { return strategies_1.STANDALONE_SUPPORTED_STACKS; } });
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.inlineBabelScripts = inlineBabelScripts;
|
|
7
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
8
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
+
const logger_1 = require("../../../utils/logger");
|
|
10
|
+
/**
|
|
11
|
+
* 匹配**完整的 `<script>` 元素**(含闭合标签),而不是只匹配开标签。
|
|
12
|
+
*
|
|
13
|
+
* 属性区用 `(?:"[^"]*"|'[^']*'|[^>])*` 而非 `[^>]*` —— 后者会被属性值里的 `>` 提前截断。
|
|
14
|
+
* 元素体用非贪婪 `[\s\S]*?` 配到最近的 `</script>`:带 `src` 的标签体按规范会被忽略,
|
|
15
|
+
* 整体替换掉最直白,不必去拼接原闭合标签。
|
|
16
|
+
*/
|
|
17
|
+
const SCRIPT_EL_RE = /<script((?:"[^"]*"|'[^']*'|[^>])*)>([\s\S]*?)<\/script\s*>/gi;
|
|
18
|
+
/** Babel Standalone 认这两种 type。 */
|
|
19
|
+
const BABEL_TYPE_RE = /\btype\s*=\s*["']text\/(?:babel|jsx)["']/i;
|
|
20
|
+
/** 取 src 属性值(带引号形式;Vite/手写产物里都是带引号的)。 */
|
|
21
|
+
const SRC_ATTR_RE = /\bsrc\s*=\s*["']([^"']+)["']/i;
|
|
22
|
+
/** 远端 / 内联数据源:不是本地文件,不内联。 */
|
|
23
|
+
const REMOTE_SRC_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
|
|
24
|
+
/** 需要处理的 HTML 扩展名。 */
|
|
25
|
+
const HTML_EXT = new Set(['.html', '.htm']);
|
|
26
|
+
function* walkHtml(dir, rel = '') {
|
|
27
|
+
for (const entry of node_fs_1.default.readdirSync(dir, { withFileTypes: true })) {
|
|
28
|
+
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
29
|
+
const abs = node_path_1.default.join(dir, entry.name);
|
|
30
|
+
if (entry.isDirectory())
|
|
31
|
+
yield* walkHtml(abs, childRel);
|
|
32
|
+
else if (HTML_EXT.has(node_path_1.default.extname(entry.name).toLowerCase()))
|
|
33
|
+
yield childRel;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* 把 `<script type="text/babel" src="x.jsx"></script>` 的外链内容内联进 HTML。
|
|
38
|
+
*
|
|
39
|
+
* **为什么必须做**:Babel Standalone 是用 **XHR** 去取 `src` 指向的文件的。`file://` 下
|
|
40
|
+
* 文档 origin 是 `null`,浏览器只允许 XHR 访问 chrome/data/http/https 等协议,file 被禁:
|
|
41
|
+
*
|
|
42
|
+
* ```
|
|
43
|
+
* Access to XMLHttpRequest at 'file:///.../app.jsx' from origin 'null' has been
|
|
44
|
+
* blocked by CORS policy: Cross origin requests are only supported for protocol
|
|
45
|
+
* schemes: chrome, ..., data, http, https, ...
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* 结果是 JSX 一个都没执行、页面白屏(`Uncaught ReferenceError: App is not defined`)。
|
|
49
|
+
* 内联之后 Babel 直接读标签内容,不发请求,`file://` 下正常渲染(已实测)。
|
|
50
|
+
*
|
|
51
|
+
* 只对 buildless 的 `design-html` / `html` 生效 —— vite 系产物已经打包过,不存在这种标签。
|
|
52
|
+
*
|
|
53
|
+
* 保留原 `.jsx` 文件不删:起 HTTP server 时两条路都能走,删了反而少一条。
|
|
54
|
+
*/
|
|
55
|
+
function inlineBabelScripts(root) {
|
|
56
|
+
const changed = [];
|
|
57
|
+
const rootResolved = node_path_1.default.resolve(root);
|
|
58
|
+
for (const rel of walkHtml(root)) {
|
|
59
|
+
const htmlPath = node_path_1.default.join(root, rel);
|
|
60
|
+
const htmlDir = node_path_1.default.dirname(htmlPath);
|
|
61
|
+
const original = node_fs_1.default.readFileSync(htmlPath, 'utf-8');
|
|
62
|
+
const next = original.replace(SCRIPT_EL_RE, (el, attrs) => {
|
|
63
|
+
if (!BABEL_TYPE_RE.test(attrs))
|
|
64
|
+
return el;
|
|
65
|
+
const m = SRC_ATTR_RE.exec(attrs);
|
|
66
|
+
if (!m)
|
|
67
|
+
return el; // 已是内联块
|
|
68
|
+
const src = m[1];
|
|
69
|
+
if (REMOTE_SRC_RE.test(src))
|
|
70
|
+
return el; // http(s) / 协议相对 / data:
|
|
71
|
+
const target = node_path_1.default.resolve(htmlDir, src);
|
|
72
|
+
// 防路径穿越:只内联产物树内的文件,否则可能把树外的内容打进产物
|
|
73
|
+
if (target !== rootResolved && !target.startsWith(rootResolved + node_path_1.default.sep))
|
|
74
|
+
return el;
|
|
75
|
+
if (!node_fs_1.default.existsSync(target))
|
|
76
|
+
return el;
|
|
77
|
+
// `</script` 出现在 JS 字符串里会提前闭合标签,必须转义
|
|
78
|
+
const code = node_fs_1.default.readFileSync(target, 'utf-8').replace(/<\/script/gi, '<\\/script');
|
|
79
|
+
const keptAttrs = attrs.replace(SRC_ATTR_RE, '').replace(/\s+/g, ' ').trimEnd();
|
|
80
|
+
(0, logger_1.debug)(`export-standalone: inlined ${src} into ${rel}`);
|
|
81
|
+
return `<script${keptAttrs} data-inlined-from="${src}">\n${code}\n</script>`;
|
|
82
|
+
});
|
|
83
|
+
// 用「文本是否变化」判定,不用外层 flag —— 回调里的赋值 TS 控制流分析看不到,
|
|
84
|
+
// 会把 `if (hit)` 判成恒假(@typescript-eslint/no-unnecessary-condition)。
|
|
85
|
+
if (next !== original) {
|
|
86
|
+
node_fs_1.default.writeFileSync(htmlPath, next, 'utf-8');
|
|
87
|
+
changed.push(rel);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return changed.sort();
|
|
91
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.extFromContentType = extFromContentType;
|
|
7
|
+
exports.localImageName = localImageName;
|
|
8
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
9
|
+
/**
|
|
10
|
+
* `Content-Type` → 文件扩展名。
|
|
11
|
+
*
|
|
12
|
+
* 存储 key 常常**不带扩展名**(线上真实形态 `static%2Fdemo_ve_miaoda`),
|
|
13
|
+
* URL 里推不出类型,只能以服务端响应为准。
|
|
14
|
+
* 未知类型返回空串 —— 宁可没后缀,也不猜一个错的(错后缀会让浏览器按错误类型解析)。
|
|
15
|
+
*/
|
|
16
|
+
const EXT_BY_MIME = {
|
|
17
|
+
'image/png': '.png',
|
|
18
|
+
'image/jpeg': '.jpg',
|
|
19
|
+
'image/jpg': '.jpg',
|
|
20
|
+
'image/gif': '.gif',
|
|
21
|
+
'image/webp': '.webp',
|
|
22
|
+
'image/svg+xml': '.svg',
|
|
23
|
+
'image/avif': '.avif',
|
|
24
|
+
'image/bmp': '.bmp',
|
|
25
|
+
'image/x-icon': '.ico',
|
|
26
|
+
'image/vnd.microsoft.icon': '.ico',
|
|
27
|
+
'image/tiff': '.tiff',
|
|
28
|
+
};
|
|
29
|
+
function extFromContentType(contentType) {
|
|
30
|
+
if (!contentType)
|
|
31
|
+
return '';
|
|
32
|
+
const mime = contentType.split(';')[0].trim().toLowerCase();
|
|
33
|
+
return EXT_BY_MIME[mime] ?? '';
|
|
34
|
+
}
|
|
35
|
+
/** 只保留文件名安全字符;其余折成 `_`。顺带挡掉 `/` 与 `..`(防 basename 逃出 images/)。 */
|
|
36
|
+
function sanitize(name) {
|
|
37
|
+
return name.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '');
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* URL → `images/` 下的本地文件名。
|
|
41
|
+
*
|
|
42
|
+
* 规则:
|
|
43
|
+
* 1. 剥掉 query/hash 后取 pathname
|
|
44
|
+
* 2. `decodeURIComponent` 还原(key 常被编码,如 `static%2Fx` → `static/x`)
|
|
45
|
+
* 3. 取 basename 并清洗危险字符
|
|
46
|
+
* 4. 追加 **完整 URL(含 query)** 的 8 位 hash —— 保证:
|
|
47
|
+
* - 同 URL 幂等(重跑导出不产生新文件)
|
|
48
|
+
* - 不同路径同名不互撞
|
|
49
|
+
* - 同图不同 `x-tos-process` 参数分开存(处理后的图内容不同)
|
|
50
|
+
* 5. 扩展名取自 `Content-Type`,URL 里自带的后缀不作数(服务端才是真相)
|
|
51
|
+
*/
|
|
52
|
+
function localImageName(url, contentType) {
|
|
53
|
+
const pathname = url.split('#')[0].split('?')[0];
|
|
54
|
+
let decoded = pathname;
|
|
55
|
+
try {
|
|
56
|
+
decoded = decodeURIComponent(pathname);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// 畸形 % 转义:退回原串,不抛
|
|
60
|
+
}
|
|
61
|
+
const rawBase = decoded.split('/').filter(Boolean).pop() ?? '';
|
|
62
|
+
const base = sanitize(rawBase).replace(/\.[^.]*$/, '') || 'image';
|
|
63
|
+
const hash = node_crypto_1.default.createHash('sha1').update(url).digest('hex').slice(0, 8);
|
|
64
|
+
return `${base}-${hash}${extFromContentType(contentType)}`;
|
|
65
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.TEXT_EXTENSIONS = void 0;
|
|
7
|
+
exports.rewriteTree = rewriteTree;
|
|
8
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
9
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
10
|
+
/**
|
|
11
|
+
* 需要扫描并改写的文本文件扩展名。
|
|
12
|
+
* 只列产物里真会出现 URL 的类型 —— `images/` 下的二进制不在其中,
|
|
13
|
+
* 避免把 PNG 当 UTF-8 读进来再写回去(会损坏文件)。
|
|
14
|
+
*/
|
|
15
|
+
exports.TEXT_EXTENSIONS = new Set([
|
|
16
|
+
'.html',
|
|
17
|
+
'.htm',
|
|
18
|
+
'.css',
|
|
19
|
+
'.js',
|
|
20
|
+
'.mjs',
|
|
21
|
+
'.cjs',
|
|
22
|
+
// buildless 栈(design-html / html)的源文件**就是产物**,JSX/TS 里的图片
|
|
23
|
+
// URL 同样要扫要改。漏了这几个扩展名会导致图片下载成功、但 .jsx 里的引用
|
|
24
|
+
// 仍指向线上绝对路径 —— 真机踩过(app.jsx 里 5 处未改写)。
|
|
25
|
+
'.jsx',
|
|
26
|
+
'.ts',
|
|
27
|
+
'.tsx',
|
|
28
|
+
'.mts',
|
|
29
|
+
'.cts',
|
|
30
|
+
'.json',
|
|
31
|
+
'.svg',
|
|
32
|
+
'.webmanifest',
|
|
33
|
+
]);
|
|
34
|
+
function* walk(dir, rel = '') {
|
|
35
|
+
for (const entry of node_fs_1.default.readdirSync(dir, { withFileTypes: true })) {
|
|
36
|
+
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
37
|
+
const abs = node_path_1.default.join(dir, entry.name);
|
|
38
|
+
if (entry.isDirectory())
|
|
39
|
+
yield* walk(abs, childRel);
|
|
40
|
+
else
|
|
41
|
+
yield childRel;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* 把产物树里所有命中的 URL 改写成 `./images/<name>`。
|
|
46
|
+
*
|
|
47
|
+
* **只改写 mapping 里有的 URL** —— 下载失败的原样保留。改成 `./images/xxx` 但文件不存在
|
|
48
|
+
* 反而制造死链,保留原绝对路径至少在联网访问平台时还能显示。
|
|
49
|
+
*
|
|
50
|
+
* 替换顺序按 URL **长度降序**:`/a/k.png` 是 `/a/k.png?x=1` 的前缀,若先替短的,
|
|
51
|
+
* 长 URL 会被替成 `./images/short.png?x=1` 这种半截产物。
|
|
52
|
+
*
|
|
53
|
+
* 用 `split().join()` 而非 `replace(new RegExp(...))`:URL 里含 `?`、`.`、`+`、`$` 等
|
|
54
|
+
* 正则元字符,转义容易出错;且 `$&` / `$1` 之类替换串语义也是坑。
|
|
55
|
+
*
|
|
56
|
+
* 返回实际发生改动的文件相对路径(posix 风格),用于 JSON 输出的 `rewrittenFiles`。
|
|
57
|
+
*/
|
|
58
|
+
function rewriteTree(root, mapping) {
|
|
59
|
+
if (mapping.size === 0)
|
|
60
|
+
return [];
|
|
61
|
+
const entries = [...mapping.entries()].sort((a, b) => b[0].length - a[0].length);
|
|
62
|
+
const changed = [];
|
|
63
|
+
for (const rel of walk(root)) {
|
|
64
|
+
if (!exports.TEXT_EXTENSIONS.has(node_path_1.default.extname(rel).toLowerCase()))
|
|
65
|
+
continue;
|
|
66
|
+
const abs = node_path_1.default.join(root, rel);
|
|
67
|
+
const original = node_fs_1.default.readFileSync(abs, 'utf-8');
|
|
68
|
+
let next = original;
|
|
69
|
+
for (const [url, name] of entries) {
|
|
70
|
+
if (!next.includes(url))
|
|
71
|
+
continue;
|
|
72
|
+
next = next.split(url).join(`./images/${name}`);
|
|
73
|
+
}
|
|
74
|
+
if (next !== original) {
|
|
75
|
+
node_fs_1.default.writeFileSync(abs, next, 'utf-8');
|
|
76
|
+
changed.push(rel);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return changed.sort();
|
|
80
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 从构建产物文本里扫出需要本地化的应用存储图片 URL。
|
|
4
|
+
*
|
|
5
|
+
* 匹配口径:**只认字面以 `/spark/app/` 开头的同源相对路径**。
|
|
6
|
+
*
|
|
7
|
+
* ⚠️ 这是刻意收窄的口径,会漏判其它挂载前缀(`/spark/p/`、`/spark/r/`、`/app/<appId>`、
|
|
8
|
+
* 反代场景等)。`miaoda-coding` 的 `cd-elements/src/core/tos.ts` 走的是「存储路径中段
|
|
9
|
+
* 子串匹配」,注释里明确记着「改成前缀匹配会让存储图静默跳过,这个错误犯过一次」。
|
|
10
|
+
* 本能力**明知该历史仍选择前缀匹配**(决策见设计文档「图片本地化」)。
|
|
11
|
+
* 若将来要扩范围,正确做法是**切子串匹配**,不是追加枚举前缀。
|
|
12
|
+
*/
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.scanSparkAppUrls = scanSparkAppUrls;
|
|
15
|
+
/**
|
|
16
|
+
* URL 终止字符:引号、反引号、空白、尖括号、圆括号、反斜杠。
|
|
17
|
+
* 刻意**不含逗号** —— `?x-tos-process=image/resize,w_400` 里逗号是 URL 的一部分,
|
|
18
|
+
* 排除它会把 query 截断成无效地址。
|
|
19
|
+
*
|
|
20
|
+
* 代价:`srcset="a.png 1x,b.png 2x"` 这种逗号后无空格的写法会把两个 URL 粘成一个。
|
|
21
|
+
* 实际产物里 srcset 由 cd-elements 生成,逗号后带空格,不触发。
|
|
22
|
+
*/
|
|
23
|
+
const SPARK_APP_URL_RE = /\/spark\/app\/[^"'`\s<>()\\]+/g;
|
|
24
|
+
/**
|
|
25
|
+
* URL 前必须是「token 起始位置」——字符串开头,或前一个字符是分隔符。
|
|
26
|
+
*
|
|
27
|
+
* 这条是为了排掉第三方绝对 URL:`https://example.com/spark/app/a/k.png` 里
|
|
28
|
+
* `/spark/app/` 的前一个字符是 `m`(`.com` 的 m),不是分隔符,因此不命中。
|
|
29
|
+
*
|
|
30
|
+
* ⚠️ 不能写成「前一个字符不是 `/`」—— 那个判据对绝对 URL 无效(prev 是 `m` 不是 `/`),
|
|
31
|
+
* 会把第三方地址误判成同源相对路径。
|
|
32
|
+
*/
|
|
33
|
+
const BOUNDARY_CHARS = new Set([
|
|
34
|
+
'"',
|
|
35
|
+
"'",
|
|
36
|
+
'`',
|
|
37
|
+
' ',
|
|
38
|
+
'\t',
|
|
39
|
+
'\n',
|
|
40
|
+
'\r',
|
|
41
|
+
'(',
|
|
42
|
+
'=',
|
|
43
|
+
',',
|
|
44
|
+
';',
|
|
45
|
+
':',
|
|
46
|
+
'{',
|
|
47
|
+
'[',
|
|
48
|
+
'<',
|
|
49
|
+
'>',
|
|
50
|
+
]);
|
|
51
|
+
function isSameOriginRelative(text, index) {
|
|
52
|
+
if (index === 0)
|
|
53
|
+
return true;
|
|
54
|
+
return BOUNDARY_CHARS.has(text[index - 1]);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* 扫出去重后的 URL 列表,保持首次出现的顺序(便于测试断言与日志可读)。
|
|
58
|
+
*/
|
|
59
|
+
function scanSparkAppUrls(text) {
|
|
60
|
+
const seen = new Set();
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const m of text.matchAll(SPARK_APP_URL_RE)) {
|
|
63
|
+
if (!isSameOriginRelative(text, m.index))
|
|
64
|
+
continue;
|
|
65
|
+
const url = m[0];
|
|
66
|
+
if (seen.has(url))
|
|
67
|
+
continue;
|
|
68
|
+
seen.add(url);
|
|
69
|
+
out.push(url);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.STANDALONE_SUPPORTED_STACKS = void 0;
|
|
7
|
+
exports.buildStandaloneEnv = buildStandaloneEnv;
|
|
8
|
+
exports.liftNestedEntry = liftNestedEntry;
|
|
9
|
+
exports.resolveStrategy = resolveStrategy;
|
|
10
|
+
const node_child_process_1 = require("node:child_process");
|
|
11
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
12
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
13
|
+
const error_1 = require("../../../utils/error");
|
|
14
|
+
const exclude_patterns_1 = require("../../../utils/exclude-patterns");
|
|
15
|
+
const logger_1 = require("../../../utils/logger");
|
|
16
|
+
const copy_tree_1 = require("./copy-tree");
|
|
17
|
+
const inline_babel_1 = require("./inline-babel");
|
|
18
|
+
exports.STANDALONE_SUPPORTED_STACKS = new Set([
|
|
19
|
+
'design-html',
|
|
20
|
+
'html',
|
|
21
|
+
'vite-react',
|
|
22
|
+
'nestjs-react-fullstack',
|
|
23
|
+
]);
|
|
24
|
+
/**
|
|
25
|
+
* standalone 构建 env。
|
|
26
|
+
*
|
|
27
|
+
* **不复用 `deploy/modern/atoms/build.ts` 的 `runBuild()`** —— 它的 `ensureHttpsScheme()`
|
|
28
|
+
* 会把 `'./'` 判成域名(含 `.` 且不以 `/` 开头)拼成 `https://./`,破掉 vite 的 base 替换。
|
|
29
|
+
*
|
|
30
|
+
* 删 `MIAODA_APP_ID` 是刻意的:`scripts/build.sh` 写的是
|
|
31
|
+
* `export CLIENT_BASE_PATH="${MIAODA_APP_ID:+/app/$MIAODA_APP_ID}"`,
|
|
32
|
+
* 变量为空时整个展开为空串,正好得到我们要的空 base path。
|
|
33
|
+
*/
|
|
34
|
+
function buildStandaloneEnv(base) {
|
|
35
|
+
const env = { ...base };
|
|
36
|
+
delete env.MIAODA_APP_ID;
|
|
37
|
+
delete env.CLIENT_BASE_PATH;
|
|
38
|
+
env.MIAODA_BUILD_TARGET = 'standalone';
|
|
39
|
+
env.NODE_ENV = 'production';
|
|
40
|
+
// vite-react 走 build.sh,由它把 MIAODA_RESOURCE_CDN_PREFIX 映射成 ASSETS_CDN_PATH
|
|
41
|
+
env.MIAODA_RESOURCE_CDN_PREFIX = './';
|
|
42
|
+
// nestjs 走 `npm run build:client` 直接调 vite,**没有 build.sh 那层映射** ——
|
|
43
|
+
// 必须直接给 preset 认的名字,否则 publicPath 为空 → base '/' → 产物里是
|
|
44
|
+
// `/assets/x.js` 绝对路径,file:// 下指向文件系统根,页面白屏(真机踩过)。
|
|
45
|
+
// vite-react 那边 build.sh 会用同样的值覆盖它,两条路结果一致。
|
|
46
|
+
env.ASSETS_CDN_PATH = './';
|
|
47
|
+
env.STATIC_ASSETS_BASE_URL = './static';
|
|
48
|
+
return env;
|
|
49
|
+
}
|
|
50
|
+
/** 把 `from` 目录内容并入 `into`(into 已存在,不清空)。from 不存在则静默跳过。 */
|
|
51
|
+
function mergeInto(from, into) {
|
|
52
|
+
if (!node_fs_1.default.existsSync(from))
|
|
53
|
+
return;
|
|
54
|
+
node_fs_1.default.mkdirSync(into, { recursive: true });
|
|
55
|
+
node_fs_1.default.cpSync(from, into, { recursive: true });
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 把 `<out>/client/index.html` 提到 `<out>/index.html`,并把资源引用降一级。
|
|
59
|
+
*
|
|
60
|
+
* **为什么会嵌一层**:vite 按 input 相对 root 的位置放产物 HTML。nestjs 模板的
|
|
61
|
+
* input 是 `client/index.html`、root 是项目根,所以 HTML 落在 `dist/client/client/`。
|
|
62
|
+
* 平台构建里 `vite-html-output` 插件负责把它提上来,但 standalone 下**刻意不挂**那个
|
|
63
|
+
* 插件——它的上移不修相对引用(平台模式 base 是绝对路径,不需要修)。
|
|
64
|
+
*
|
|
65
|
+
* **为什么必须同时改路径**:standalone 的 base 是 `./`,产物里写的是 `../assets/x`,
|
|
66
|
+
* 那是相对 `<out>/client/` 算的。提到 `<out>/` 后就多了一级,指向不存在的
|
|
67
|
+
* `<out>/../assets/`,页面白屏(实测确认)。层级差恒为 1,故 `../` → `./`。
|
|
68
|
+
*
|
|
69
|
+
* 只改 `src` / `href` 属性开头的 `../`,不做全文替换 —— 否则 inline 脚本里的字符串
|
|
70
|
+
* 常量(如 `var p = "../keep/me"`)会被误伤。
|
|
71
|
+
*/
|
|
72
|
+
function liftNestedEntry(outDir) {
|
|
73
|
+
const nestedDir = node_path_1.default.join(outDir, 'client');
|
|
74
|
+
const nestedHtml = node_path_1.default.join(nestedDir, 'index.html');
|
|
75
|
+
if (!node_fs_1.default.existsSync(nestedHtml))
|
|
76
|
+
return;
|
|
77
|
+
const target = node_path_1.default.join(outDir, 'index.html');
|
|
78
|
+
const html = node_fs_1.default.readFileSync(nestedHtml, 'utf-8');
|
|
79
|
+
const rebased = html.replace(/\b(src|href)=("|')\.\.\/(?!\.)/gi, (_m, attr, quote) => `${attr}=${quote}./`);
|
|
80
|
+
node_fs_1.default.writeFileSync(target, rebased, 'utf-8');
|
|
81
|
+
node_fs_1.default.rmSync(nestedHtml, { force: true });
|
|
82
|
+
// 只删空目录:嵌套目录里若还有别的文件,留着比静默丢弃安全
|
|
83
|
+
if (node_fs_1.default.readdirSync(nestedDir).length === 0)
|
|
84
|
+
node_fs_1.default.rmdirSync(nestedDir);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 从产物树里删掉 sourcemap(`*.map`)。
|
|
88
|
+
*
|
|
89
|
+
* preset 的 prod 配置是 `sourcemap: 'hidden'` —— map 文件会产出,但产物里**没有**
|
|
90
|
+
* `sourceMappingURL` 注释,即没人引用它。留在 standalone 包里有两个实打实的问题:
|
|
91
|
+
*
|
|
92
|
+
* 1. **体积**:实测真实应用 4.7MB map / 5.9MB 总体积,占 80%
|
|
93
|
+
* 2. **泄源码**:map 的 `sourcesContent` 内嵌原始源码(实测含 12 个业务文件,
|
|
94
|
+
* 如 `src/lib/utils.ts`)。standalone 包是拿来分发给人的,等于附赠全部源码
|
|
95
|
+
*
|
|
96
|
+
* 只对有编译步骤的 stack 调用;buildless 栈(design-html / html)的产物就是源码,
|
|
97
|
+
* 那里的 `.map`(若有)是用户自己的文件,不该动。
|
|
98
|
+
*/
|
|
99
|
+
function dropSourceMaps(outDir) {
|
|
100
|
+
const walk = (dir) => {
|
|
101
|
+
for (const entry of node_fs_1.default.readdirSync(dir, { withFileTypes: true })) {
|
|
102
|
+
const abs = node_path_1.default.join(dir, entry.name);
|
|
103
|
+
if (entry.isDirectory())
|
|
104
|
+
walk(abs);
|
|
105
|
+
else if (entry.name.toLowerCase().endsWith('.map'))
|
|
106
|
+
node_fs_1.default.rmSync(abs, { force: true });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
walk(outDir);
|
|
110
|
+
}
|
|
111
|
+
/** 从产物树里删掉 routes.json —— 平台/server 路由用,standalone 无人读取。 */
|
|
112
|
+
function dropRoutesJson(outDir) {
|
|
113
|
+
node_fs_1.default.rmSync(node_path_1.default.join(outDir, 'routes.json'), { force: true });
|
|
114
|
+
}
|
|
115
|
+
function runProjectBuild(projectDir, command) {
|
|
116
|
+
try {
|
|
117
|
+
(0, node_child_process_1.execSync)(command, {
|
|
118
|
+
cwd: projectDir,
|
|
119
|
+
stdio: 'inherit',
|
|
120
|
+
env: buildStandaloneEnv(process.env),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
throw new error_1.AppError('EXPORT_STANDALONE_BUILD_FAILED', `${command} failed: ${err.message}`, { next_actions: ['先手动跑一次该构建命令确认工程本身可构建'] });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** design-html:项目根纯拷贝,套 deploy 同一份 EXCLUDES。 */
|
|
128
|
+
const designHtmlStrategy = ({ projectDir, outDir }) => {
|
|
129
|
+
(0, logger_1.log)('export-standalone', 'Copying source (design-html)...');
|
|
130
|
+
(0, copy_tree_1.copyTree)(projectDir, outDir, exclude_patterns_1.EXCLUDES);
|
|
131
|
+
(0, inline_babel_1.inlineBabelScripts)(outDir);
|
|
132
|
+
dropRoutesJson(outDir);
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* html:拷 `src/`,**跳过 `coding-html-devserver build`**。
|
|
136
|
+
* 该命令会注入 slardar/tea 外链与 `{{appName}}` HBS 占位符,standalone 全要撤销,
|
|
137
|
+
* 调它再逐项撤销不如不调(设计文档「html 跳过 coding-html-devserver build」)。
|
|
138
|
+
*/
|
|
139
|
+
const htmlStrategy = ({ projectDir, outDir }) => {
|
|
140
|
+
(0, logger_1.log)('export-standalone', 'Copying src/ (html)...');
|
|
141
|
+
(0, copy_tree_1.copyTree)(node_path_1.default.join(projectDir, 'src'), outDir);
|
|
142
|
+
(0, inline_babel_1.inlineBabelScripts)(outDir);
|
|
143
|
+
dropRoutesJson(outDir);
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* vite-react:跑 `scripts/build.sh`,再把按上传通道拆的四个目录按可访问性合并。
|
|
147
|
+
* `output_capabilities` 丢弃 —— 平台侧注册用,运行时走已打进 bundle 的
|
|
148
|
+
* `virtual:capabilities` 虚拟模块,产物目录不引用它。
|
|
149
|
+
*/
|
|
150
|
+
const viteReactStrategy = ({ projectDir, outDir }) => {
|
|
151
|
+
(0, logger_1.log)('export-standalone', 'Building (vite-react)...');
|
|
152
|
+
runProjectBuild(projectDir, 'bash scripts/build.sh');
|
|
153
|
+
const dist = node_path_1.default.join(projectDir, 'dist');
|
|
154
|
+
node_fs_1.default.rmSync(outDir, { recursive: true, force: true });
|
|
155
|
+
node_fs_1.default.mkdirSync(outDir, { recursive: true });
|
|
156
|
+
mergeInto(node_path_1.default.join(dist, 'output'), outDir);
|
|
157
|
+
mergeInto(node_path_1.default.join(dist, 'output_resource', 'assets'), node_path_1.default.join(outDir, 'assets'));
|
|
158
|
+
mergeInto(node_path_1.default.join(dist, 'output_static'), node_path_1.default.join(outDir, 'static'));
|
|
159
|
+
dropSourceMaps(outDir);
|
|
160
|
+
dropRoutesJson(outDir);
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* nestjs-react-fullstack:只跑 `build:client`。
|
|
164
|
+
* 完整 `scripts/build.sh` 会跑 `action-plugin init` / `gen:openapi` / `nest build` /
|
|
165
|
+
* `prune-smart`,standalone 只要 client 那一半;且 `action-plugin init` 依赖平台 env,
|
|
166
|
+
* 是已知易失败点。
|
|
167
|
+
*
|
|
168
|
+
* 产物是单目录 `dist/client`,无需合并;但入口 HTML 嵌在 `dist/client/client/` 下
|
|
169
|
+
* (standalone 不挂 preset 的 vite-html-output 插件),需 `liftNestedEntry` 提到根。
|
|
170
|
+
*/
|
|
171
|
+
const nestjsStrategy = ({ projectDir, outDir }) => {
|
|
172
|
+
(0, logger_1.log)('export-standalone', 'Building client (nestjs-react-fullstack)...');
|
|
173
|
+
// 构建到**独立临时目录**,不碰 `dist/client`。
|
|
174
|
+
//
|
|
175
|
+
// 两个原因:
|
|
176
|
+
// 1. preset 设了 `emptyOutDir: false`(它指望 `scripts/build.sh` 先 `rm -rf dist`),
|
|
177
|
+
// 而我们绕过 build.sh 直接跑 `build:client`,没人清目录 —— 复用 `dist/client`
|
|
178
|
+
// 会把上次构建的 chunk 一起带进产物(真机见过新旧两个 index-<hash>.js 并存)。
|
|
179
|
+
// 2. `dist/client` 是平台链路的产物目录(dev 期 html-output 会往里写、NestJS 从
|
|
180
|
+
// 那儿取 HTML),导出这种旁路动作**不该清它**,否则破坏既有目录结构。
|
|
181
|
+
//
|
|
182
|
+
// vite CLI 的 `--outDir` 优先级高于 config,`--emptyOutDir` 覆盖 `emptyOutDir: false`。
|
|
183
|
+
// 放在 dist/ 下是为了留在 vite root 内(root 外 vite 会告警)。
|
|
184
|
+
const tmpDist = node_path_1.default.join(projectDir, 'dist', '.standalone-client');
|
|
185
|
+
try {
|
|
186
|
+
runProjectBuild(projectDir, `npm run build:client -- --outDir ${JSON.stringify(node_path_1.default.relative(projectDir, tmpDist))} --emptyOutDir`);
|
|
187
|
+
if (!node_fs_1.default.existsSync(tmpDist)) {
|
|
188
|
+
throw new error_1.AppError('EXPORT_STANDALONE_EMPTY_OUTPUT', `client 构建产物 ${node_path_1.default.relative(projectDir, tmpDist)} 不存在`);
|
|
189
|
+
}
|
|
190
|
+
node_fs_1.default.rmSync(outDir, { recursive: true, force: true });
|
|
191
|
+
node_fs_1.default.mkdirSync(outDir, { recursive: true });
|
|
192
|
+
mergeInto(tmpDist, outDir);
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
// 临时构建目录不留在用户项目里
|
|
196
|
+
node_fs_1.default.rmSync(tmpDist, { recursive: true, force: true });
|
|
197
|
+
}
|
|
198
|
+
liftNestedEntry(outDir);
|
|
199
|
+
dropSourceMaps(outDir);
|
|
200
|
+
dropRoutesJson(outDir);
|
|
201
|
+
};
|
|
202
|
+
const STRATEGY_BY_STACK = new Map([
|
|
203
|
+
['design-html', designHtmlStrategy],
|
|
204
|
+
['html', htmlStrategy],
|
|
205
|
+
['vite-react', viteReactStrategy],
|
|
206
|
+
['nestjs-react-fullstack', nestjsStrategy],
|
|
207
|
+
]);
|
|
208
|
+
function resolveStrategy(stack) {
|
|
209
|
+
const strategy = STRATEGY_BY_STACK.get(stack);
|
|
210
|
+
if (!strategy) {
|
|
211
|
+
throw new error_1.AppError('EXPORT_STANDALONE_STACK_UNSUPPORTED', `stack "${stack}" 不支持 standalone 导出`, { next_actions: [`支持的 stack:${[...exports.STANDALONE_SUPPORTED_STACKS].join(', ')}`] });
|
|
212
|
+
}
|
|
213
|
+
return strategy;
|
|
214
|
+
}
|
|
@@ -36,8 +36,10 @@ function isHtml(rel) {
|
|
|
36
36
|
/**
|
|
37
37
|
* 把 changeset 组成 TosFileAction[]:
|
|
38
38
|
* - create/update 读本地文件、自动编码;delete 仅 FilePath。
|
|
39
|
-
* - .html 被 create / delete
|
|
40
|
-
*
|
|
39
|
+
* - 任一 .html 被 create / update / delete 时,追加重算 routes.json 的 UPDATE action。
|
|
40
|
+
* update 也算:routes.json 的 name 取自 HTML 的 `<title>`,改方案名就是一次纯 update,
|
|
41
|
+
* 只按 create/delete 判定会让改名永远进不了 routes.json。
|
|
42
|
+
* - 纯非 .html 改动(js / css / 图片)不动 routes.json。
|
|
41
43
|
*/
|
|
42
44
|
function buildTosActions(projectDir, cs) {
|
|
43
45
|
const actions = [];
|
|
@@ -48,8 +50,8 @@ function buildTosActions(projectDir, cs) {
|
|
|
48
50
|
for (const rel of cs.deletes) {
|
|
49
51
|
actions.push({ actionType: index_1.TosActionType.DELETE, filePath: normalizeRel(rel) });
|
|
50
52
|
}
|
|
51
|
-
const
|
|
52
|
-
if (
|
|
53
|
+
const routesMayChange = [...cs.creates, ...cs.updates, ...cs.deletes].some(isHtml);
|
|
54
|
+
if (routesMayChange) {
|
|
53
55
|
actions.push({
|
|
54
56
|
actionType: index_1.TosActionType.UPDATE,
|
|
55
57
|
filePath: 'routes.json',
|