catchword 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 (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +314 -2
  3. package/bin/catchword.js +8 -0
  4. package/bin/falcon.js +5 -0
  5. package/dist/cli/adb.d.ts +6 -0
  6. package/dist/cli/adb.js +52 -0
  7. package/dist/cli/audit.d.ts +4 -0
  8. package/dist/cli/audit.js +91 -0
  9. package/dist/cli/build.d.ts +13 -0
  10. package/dist/cli/build.js +139 -0
  11. package/dist/cli/clean.d.ts +1 -0
  12. package/dist/cli/clean.js +15 -0
  13. package/dist/cli/create.d.ts +4 -0
  14. package/dist/cli/create.js +60 -0
  15. package/dist/cli/dev.d.ts +10 -0
  16. package/dist/cli/dev.js +23 -0
  17. package/dist/cli/index.d.ts +3 -0
  18. package/dist/cli/index.js +243 -0
  19. package/dist/cli/native.d.ts +18 -0
  20. package/dist/cli/native.js +232 -0
  21. package/dist/cli/simulator.d.ts +8 -0
  22. package/dist/cli/simulator.js +77 -0
  23. package/dist/cli/upload.d.ts +9 -0
  24. package/dist/cli/upload.js +135 -0
  25. package/dist/cli/util.d.ts +8 -0
  26. package/dist/cli/util.js +43 -0
  27. package/dist/config.d.ts +17 -0
  28. package/dist/config.js +90 -0
  29. package/dist/index.d.ts +16 -0
  30. package/dist/index.js +51 -0
  31. package/dist/native/api.d.ts +46 -0
  32. package/dist/native/api.js +185 -0
  33. package/dist/native/build.d.ts +47 -0
  34. package/dist/native/build.js +407 -0
  35. package/dist/native/elf.d.ts +15 -0
  36. package/dist/native/elf.js +200 -0
  37. package/dist/native/types.d.ts +9 -0
  38. package/dist/native/types.js +91 -0
  39. package/dist/native/wsl.d.ts +7 -0
  40. package/dist/native/wsl.js +29 -0
  41. package/dist/plugin/app-entry.d.ts +6 -0
  42. package/dist/plugin/app-entry.js +115 -0
  43. package/dist/plugin/assets.d.ts +4 -0
  44. package/dist/plugin/assets.js +84 -0
  45. package/dist/plugin/config.d.ts +14 -0
  46. package/dist/plugin/config.js +80 -0
  47. package/dist/plugin/context.d.ts +58 -0
  48. package/dist/plugin/context.js +255 -0
  49. package/dist/plugin/fallback.d.ts +4 -0
  50. package/dist/plugin/fallback.js +81 -0
  51. package/dist/plugin/image-service.d.ts +17 -0
  52. package/dist/plugin/image-service.js +138 -0
  53. package/dist/plugin/jsapi.d.ts +6 -0
  54. package/dist/plugin/jsapi.js +82 -0
  55. package/dist/plugin/output.d.ts +4 -0
  56. package/dist/plugin/output.js +75 -0
  57. package/dist/plugin/preview.d.ts +34 -0
  58. package/dist/plugin/preview.js +459 -0
  59. package/dist/plugin/sanitize.d.ts +5 -0
  60. package/dist/plugin/sanitize.js +48 -0
  61. package/dist/plugin/security.d.ts +4 -0
  62. package/dist/plugin/security.js +18 -0
  63. package/dist/plugin/sfc.d.ts +6 -0
  64. package/dist/plugin/sfc.js +181 -0
  65. package/dist/plugin/shim.d.ts +4 -0
  66. package/dist/plugin/shim.js +68 -0
  67. package/dist/plugin/state.d.ts +31 -0
  68. package/dist/plugin/state.js +61 -0
  69. package/dist/plugin/string-table.d.ts +7 -0
  70. package/dist/plugin/string-table.js +324 -0
  71. package/dist/plugin/style.d.ts +15 -0
  72. package/dist/plugin/style.js +114 -0
  73. package/dist/plugin/template.d.ts +7 -0
  74. package/dist/plugin/template.js +39 -0
  75. package/dist/steps/manifest.d.ts +9 -0
  76. package/dist/steps/manifest.js +60 -0
  77. package/dist/steps/pack.d.ts +3 -0
  78. package/dist/steps/pack.js +46 -0
  79. package/dist/steps/qjsc.d.ts +9 -0
  80. package/dist/steps/qjsc.js +186 -0
  81. package/dist/steps/report.d.ts +2 -0
  82. package/dist/steps/report.js +50 -0
  83. package/dist/steps/security.d.ts +17 -0
  84. package/dist/steps/security.js +310 -0
  85. package/dist/types.d.ts +158 -0
  86. package/dist/types.js +1 -0
  87. package/dist/util/class-tokenize.d.ts +2 -0
  88. package/dist/util/class-tokenize.js +56 -0
  89. package/dist/util/component-name.d.ts +6 -0
  90. package/dist/util/component-name.js +120 -0
  91. package/dist/util/fs.d.ts +14 -0
  92. package/dist/util/fs.js +70 -0
  93. package/dist/util/imports.d.ts +2 -0
  94. package/dist/util/imports.js +173 -0
  95. package/dist/util/log.d.ts +8 -0
  96. package/dist/util/log.js +24 -0
  97. package/package.json +61 -4
  98. package/template/README.md +38 -0
  99. package/template/catchword.config.ts +18 -0
  100. package/template/native/CMakeLists.txt +33 -0
  101. package/template/native/README.md +34 -0
  102. package/template/native/api.override.json +7 -0
  103. package/template/native/include/jsapi_demo.h +10 -0
  104. package/template/native/lib/README.md +10 -0
  105. package/template/native/sdk/README.md +6 -0
  106. package/template/native/src/bridge.cpp +9 -0
  107. package/template/native/src/jsapi_demo.cpp +11 -0
  108. package/template/package.json +38 -0
  109. package/template/src/app.js +45 -0
  110. package/template/src/app.json +11 -0
  111. package/template/src/base-page.js +150 -0
  112. package/template/src/components/HelloWorld.vue +20 -0
  113. package/template/src/mocks/$jsapi.test.js +5 -0
  114. package/template/src/mocks/test-module.js +5 -0
  115. package/template/src/pages/index/index.vue +41 -0
  116. package/template/src/pages/page/page.vue +63 -0
  117. package/template/src/shims.d.ts +21 -0
  118. package/template/src/styles/base.less +23 -0
  119. package/template/src/styles/mixin.less +32 -0
  120. package/template/src/styles/var.less +15 -0
  121. package/template/tsconfig.json +14 -0
  122. package/vendor/README.md +16 -0
  123. package/vendor/falcon-styler/.jscsrc +31 -0
  124. package/vendor/falcon-styler/LICENSE +21 -0
  125. package/vendor/falcon-styler/README.md +124 -0
  126. package/vendor/falcon-styler/index.js +273 -0
  127. package/vendor/falcon-styler/lib/shorthand-parser.js +78 -0
  128. package/vendor/falcon-styler/lib/util.js +30 -0
  129. package/vendor/falcon-styler/lib/validator.js +846 -0
  130. package/vendor/falcon-styler/package.json +32 -0
  131. package/vendor/licenses/falcon-styler.LICENSE +21 -0
  132. package/vendor/licenses/weex-template-compiler.README.md +3 -0
  133. package/vendor/package.json +5 -0
  134. package/vendor/qjsc/SHA256SUMS +11 -0
  135. package/vendor/qjsc/bin/darwin/arm64/qjsc20200705 +0 -0
  136. package/vendor/qjsc/bin/darwin/x64/qjsc20200412 +0 -0
  137. package/vendor/qjsc/bin/darwin/x64/qjsc20200705 +0 -0
  138. package/vendor/qjsc/bin/darwin/x64/qjsc20200906 +0 -0
  139. package/vendor/qjsc/bin/darwin/x64/qjscbn20200412 +0 -0
  140. package/vendor/qjsc/bin/darwin/x64/qjscbn20200705 +0 -0
  141. package/vendor/qjsc/bin/darwin/x64/qjscbn20200906 +0 -0
  142. package/vendor/qjsc/bin/linux/qjsc20200705 +0 -0
  143. package/vendor/qjsc/bin/win32/libgcc_s_dw2-1.dll +0 -0
  144. package/vendor/qjsc/bin/win32/pthreadGC-3.dll +0 -0
  145. package/vendor/qjsc/bin/win32/qjsc20200705.exe +0 -0
  146. package/vendor/web/falcon-js-web.js +863 -0
  147. package/vendor/web/falcon-jsapi-web.js +479 -0
  148. package/vendor/web/falcon-vue-render.js +11323 -0
  149. package/vendor/web/falcon-web-boot.js +4 -0
  150. package/vendor/web/falcon-web-hud.js +119 -0
  151. package/vendor/web/falcon-web-style.js +235 -0
  152. package/vendor/web/vue.runtime.common.dev.js +8467 -0
  153. package/vendor/web/vue.runtime.common.js +5 -0
  154. package/vendor/weex-template-compiler/README.md +3 -0
  155. package/vendor/weex-template-compiler/build.js +4824 -0
  156. package/vendor/weex-template-compiler/index.js +17 -0
  157. package/vendor/weex-template-compiler/package.json +25 -0
@@ -0,0 +1,15 @@
1
+ import type { AppContext } from './context.js';
2
+ import type { BuildState, ClassTokenRegistry } from './state.js';
3
+ export interface StyleBlockInput {
4
+ ctx: AppContext;
5
+ state: BuildState;
6
+ fileId: string;
7
+ index: number;
8
+ scopeId: string;
9
+ content: string;
10
+ lang: string;
11
+ src?: string;
12
+ tokenizeClasses?: boolean;
13
+ tokens?: ClassTokenRegistry;
14
+ }
15
+ export declare function compileStyleModule(input: StyleBlockInput): Promise<string>;
@@ -0,0 +1,114 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { processImage } from './image-service.js';
5
+ import { log } from '../util/log.js';
6
+ const require = createRequire(import.meta.url);
7
+ const styler = require('../../vendor/falcon-styler/index.js');
8
+ const less = require('less');
9
+ const REG_BACKGROUND = /\burl\s*\(\s*["']?([^"'\r\n,]+)["']?\s*\)/;
10
+ function printLog(fileId, logs) {
11
+ if (!logs || logs.length === 0)
12
+ return;
13
+ const rel = path.relative(path.dirname(fileId), fileId);
14
+ for (const item of logs) {
15
+ log.warn(`${rel}:${item.line}-${item.column}\n${item.reason}`);
16
+ }
17
+ }
18
+ async function replaceBackgroundImageUrl(ctx, fileId, styleList) {
19
+ for (const className of Object.keys(styleList)) {
20
+ const style = styleList[className];
21
+ if (!style || typeof style !== 'object')
22
+ continue;
23
+ for (const prop of Object.keys(style)) {
24
+ if (!prop.startsWith('backgroundImage'))
25
+ continue;
26
+ const value = style[prop];
27
+ if (typeof value !== 'string')
28
+ continue;
29
+ const match = REG_BACKGROUND.exec(value);
30
+ if (!match || !match[1])
31
+ continue;
32
+ const raw = match[1];
33
+ const abs = /^https?:\/\//.test(raw)
34
+ ? raw
35
+ : path.resolve(path.dirname(fileId), raw.split('?')[0]) +
36
+ (raw.includes('?') ? raw.slice(raw.indexOf('?')) : '');
37
+ const url = await processImage(ctx, abs);
38
+ if (url)
39
+ style[prop] = `url("${url}")`;
40
+ }
41
+ }
42
+ }
43
+ function extractKeyframes(state, scopeId, result) {
44
+ const keyframes = result['@KEYFRAME'];
45
+ if (keyframes) {
46
+ delete result['@KEYFRAME'];
47
+ for (const name of Object.keys(keyframes)) {
48
+ const scoped = name + scopeId;
49
+ state.keyframes.push({ [state.keyframeTokens.tokenFor(scoped)]: keyframes[name] });
50
+ }
51
+ }
52
+ for (const name of Object.keys(result)) {
53
+ const style = result[name];
54
+ if (style && typeof style === 'object' && style.animationName) {
55
+ const scoped = String(style.animationName) + scopeId;
56
+ style.animationName = state.keyframeTokens.tokenFor(scoped);
57
+ }
58
+ }
59
+ }
60
+ async function compileOne(ctx, state, fileId, code, lang, scopeId, themeName) {
61
+ let css = code;
62
+ if (lang === 'less') {
63
+ const modifyVars = ctx.getLessModifyVars();
64
+ if (themeName)
65
+ modifyVars.theme = themeName;
66
+ const rendered = await less.render(code, {
67
+ modifyVars,
68
+ paths: [path.dirname(fileId), ...ctx.getLessPaths()]
69
+ });
70
+ css = rendered.css;
71
+ }
72
+ else if (lang && lang !== 'css') {
73
+ throw new Error(`[catchword] 暂不支持的样式语言: ${lang} (${fileId})`);
74
+ }
75
+ let jsonStyle = {};
76
+ let parsedLogs;
77
+ styler.parse(css, (_err, data) => {
78
+ if (data?.jsonStyle)
79
+ jsonStyle = data.jsonStyle;
80
+ parsedLogs = data?.log;
81
+ });
82
+ printLog(fileId, parsedLogs);
83
+ await replaceBackgroundImageUrl(ctx, fileId, jsonStyle);
84
+ extractKeyframes(state, scopeId, jsonStyle);
85
+ return jsonStyle;
86
+ }
87
+ function tokenizeStyleKeys(style, tokens) {
88
+ for (const key of Object.keys(style)) {
89
+ const token = tokens.tokenForKey(key);
90
+ if (token === key)
91
+ continue;
92
+ style[token] = style[key];
93
+ delete style[key];
94
+ }
95
+ }
96
+ export async function compileStyleModule(input) {
97
+ const { ctx, state, fileId, scopeId } = input;
98
+ let code = input.content;
99
+ if (input.src) {
100
+ const srcFile = path.resolve(path.dirname(fileId), input.src);
101
+ code = fs.readFileSync(srcFile, 'utf8');
102
+ }
103
+ const themes = ctx.getThemes();
104
+ const themeItems = [];
105
+ for (const key of themes) {
106
+ const themeName = key === '_' ? undefined : key;
107
+ const json = await compileOne(ctx, state, fileId, code, input.lang || 'css', scopeId, themeName);
108
+ if (input.tokenizeClasses && input.tokens) {
109
+ tokenizeStyleKeys(json, input.tokens);
110
+ }
111
+ themeItems.push(`${JSON.stringify(key)}: ${JSON.stringify(json, null, 2)}`);
112
+ }
113
+ return `export default { ${themeItems.join(', ')} }`;
114
+ }
@@ -0,0 +1,7 @@
1
+ export interface CompiledTemplate {
2
+ code: string;
3
+ hasTemplate: boolean;
4
+ }
5
+ export declare function compileTemplate(content: string, isFunctional: boolean, fileIdForError?: string, options?: {
6
+ stripMetadata?: boolean;
7
+ }): CompiledTemplate;
@@ -0,0 +1,39 @@
1
+ import { createRequire } from 'node:module';
2
+ import { transformRequireToImport } from '../util/imports.js';
3
+ const require = createRequire(import.meta.url);
4
+ const templateCompiler = require('../../vendor/weex-template-compiler/index.js');
5
+ const transpile = require('vue-template-es2015-compiler');
6
+ const beautify = require('js-beautify').js_beautify;
7
+ function compileAsProduction(content) {
8
+ const previous = process.env.NODE_ENV;
9
+ process.env.NODE_ENV = 'production';
10
+ try {
11
+ return templateCompiler.compile(content);
12
+ }
13
+ finally {
14
+ if (previous === undefined)
15
+ delete process.env.NODE_ENV;
16
+ else
17
+ process.env.NODE_ENV = previous;
18
+ }
19
+ }
20
+ export function compileTemplate(content, isFunctional, fileIdForError = '', options = {}) {
21
+ const compiled = compileAsProduction(content);
22
+ if (compiled.errors && compiled.errors.length) {
23
+ const messages = compiled.errors.map((e) => typeof e === 'string' ? e : (e.message ?? JSON.stringify(e)));
24
+ throw new Error(`[catchword] 模板编译失败 ${fileIdForError}:\n${messages.join('\n')}`);
25
+ }
26
+ const toFunction = (code) => `function (${isFunctional ? '_h,_vm' : ''}){\n${beautify(code, { indent_size: 2 })}}`;
27
+ const renderMarker = compiled['@render'] ? `"@render": ${toFunction(compiled['@render'])},` : '';
28
+ const stripped = options.stripMetadata ? '' : 'render._withStripped = true;';
29
+ const code = `
30
+ let render = ${toFunction(compiled.render)};
31
+ ${renderMarker}
32
+ let staticRenderFns = [${compiled.staticRenderFns.map(toFunction).join(',')}];
33
+ ${stripped}
34
+ `;
35
+ const transpiled = transpile(code, {
36
+ transforms: { stripWithFunctional: isFunctional }
37
+ });
38
+ return { code: transformRequireToImport(transpiled), hasTemplate: true };
39
+ }
@@ -0,0 +1,9 @@
1
+ import type { AppContext } from '../plugin/context.js';
2
+ declare function isPackable(relPath: string): boolean;
3
+ export interface ManifestCertEntry {
4
+ size: number;
5
+ md5: string;
6
+ }
7
+ export type ManifestCert = Record<string, ManifestCertEntry>;
8
+ export declare function generateManifest(ctx: AppContext): ManifestCert;
9
+ export { isPackable };
@@ -0,0 +1,60 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { log } from '../util/log.js';
4
+ import { md5File, walkSync } from '../util/fs.js';
5
+ function isPackable(relPath) {
6
+ if (!relPath)
7
+ return false;
8
+ const base = path.basename(relPath);
9
+ if (base.startsWith('.'))
10
+ return false;
11
+ if (base.endsWith('.amr'))
12
+ return false;
13
+ return true;
14
+ }
15
+ export function generateManifest(ctx) {
16
+ const distDir = ctx.buildDir;
17
+ const pkg = ctx.pkg;
18
+ const appJson = ctx.appJson;
19
+ if (!pkg.appid) {
20
+ log.error('ERROR: 未在 package.json 中配置应用的 appid');
21
+ }
22
+ const info = {
23
+ appName: pkg.appName ?? pkg.name,
24
+ version: pkg.version
25
+ };
26
+ if (pkg.appid)
27
+ info.appid = pkg.appid;
28
+ if (pkg.icon) {
29
+ const iconFile = path.resolve(ctx.root, pkg.icon);
30
+ if (fs.existsSync(iconFile)) {
31
+ fs.copyFileSync(iconFile, path.resolve(distDir, path.basename(pkg.icon)));
32
+ info.icon = path.basename(pkg.icon);
33
+ }
34
+ else {
35
+ log.warn(`WARNING: 找不到应用 icon: ${iconFile}`);
36
+ }
37
+ }
38
+ else {
39
+ log.warn('WARNING: 未在 package.json 中配置应用 icon 路径');
40
+ }
41
+ if (pkg.quickjs)
42
+ info.quickjs = pkg.quickjs;
43
+ if (appJson.meta)
44
+ info.meta = appJson.meta;
45
+ if (appJson.props)
46
+ info.props = appJson.props;
47
+ const cert = {};
48
+ const files = walkSync(distDir, { skipDotFiles: true });
49
+ for (const file of files) {
50
+ const rel = path.relative(distDir, file).replace(/\\/g, '/');
51
+ if (!isPackable(rel))
52
+ continue;
53
+ cert[rel] = { size: fs.statSync(file).size, md5: md5File(file) };
54
+ }
55
+ info.cert = cert;
56
+ fs.writeFileSync(path.resolve(distDir, 'manifest.json'), JSON.stringify(info, null, 2));
57
+ log.success(`manifest.json 生成成功 (${Object.keys(cert).length} 个文件)`);
58
+ return cert;
59
+ }
60
+ export { isPackable };
@@ -0,0 +1,3 @@
1
+ import type { AppContext } from '../plugin/context.js';
2
+ export declare function packAmr(ctx: AppContext): Promise<string>;
3
+ export declare function writeSha256Sidecar(amrPath: string): string;
@@ -0,0 +1,46 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pipeline } from 'node:stream/promises';
4
+ import { createRequire } from 'node:module';
5
+ import { isPackable } from './manifest.js';
6
+ import { log } from '../util/log.js';
7
+ import { sha256File } from '../util/fs.js';
8
+ const require = createRequire(import.meta.url);
9
+ const compressing = require('compressing');
10
+ export async function packAmr(ctx) {
11
+ const distDir = ctx.buildDir;
12
+ const destFile = ctx.amrPath;
13
+ const tmpFile = destFile + '.tmp';
14
+ if (fs.existsSync(destFile))
15
+ fs.unlinkSync(destFile);
16
+ if (fs.existsSync(tmpFile))
17
+ fs.unlinkSync(tmpFile);
18
+ const entries = fs
19
+ .readdirSync(distDir)
20
+ .filter((name) => isPackable(name))
21
+ .map((name) => path.resolve(distDir, name));
22
+ if (entries.length === 0)
23
+ throw new Error(`[catchword] 构建目录为空: ${distDir}`);
24
+ const zipStream = new compressing.zip.Stream();
25
+ for (const entry of entries)
26
+ zipStream.addEntry(entry);
27
+ try {
28
+ const destStream = fs.createWriteStream(tmpFile);
29
+ await pipeline(zipStream, destStream);
30
+ fs.renameSync(tmpFile, destFile);
31
+ }
32
+ catch (error) {
33
+ if (fs.existsSync(tmpFile))
34
+ fs.unlinkSync(tmpFile);
35
+ throw error;
36
+ }
37
+ const size = fs.statSync(destFile).size;
38
+ log.success(`打包成功: ${destFile} (${(size / 1024).toFixed(1)} KB)`);
39
+ return destFile;
40
+ }
41
+ export function writeSha256Sidecar(amrPath) {
42
+ const digest = sha256File(amrPath);
43
+ fs.writeFileSync(amrPath + '.sha256', `${digest} ${path.basename(amrPath)}\n`);
44
+ log.success(`校验和: ${path.basename(amrPath)}.sha256 ${digest.slice(0, 16)}…`);
45
+ return digest;
46
+ }
@@ -0,0 +1,9 @@
1
+ import type { AppContext } from '../plugin/context.js';
2
+ import type { BuildState } from '../plugin/state.js';
3
+ export declare function compileJs(jsFile: string, binFile: string, cfg: {
4
+ version: string;
5
+ bigNum: boolean;
6
+ internal: string[];
7
+ skipVerify?: boolean;
8
+ }): Promise<void>;
9
+ export declare function compileAll(ctx: AppContext, state: BuildState): Promise<void>;
@@ -0,0 +1,186 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { log } from '../util/log.js';
6
+ import { sha256File, walkSync } from '../util/fs.js';
7
+ const here = path.dirname(fileURLToPath(import.meta.url));
8
+ const QJSC_ROOT = path.resolve(here, '../../vendor/qjsc');
9
+ const QJSC_BIN_ROOT = path.join(QJSC_ROOT, 'bin');
10
+ const QJSC_SUMS_FILE = path.join(QJSC_ROOT, 'SHA256SUMS');
11
+ let sums;
12
+ const verifiedFiles = new Set();
13
+ const warnedMissing = new Set();
14
+ function loadQjscSums() {
15
+ if (sums !== undefined)
16
+ return sums;
17
+ if (!fs.existsSync(QJSC_SUMS_FILE)) {
18
+ log.warn(`[catchword] 未找到 qjsc 校验清单,跳过二进制完整性校验: ${QJSC_SUMS_FILE}`);
19
+ sums = null;
20
+ return sums;
21
+ }
22
+ const map = new Map();
23
+ for (const line of fs.readFileSync(QJSC_SUMS_FILE, 'utf8').split(/\r?\n/)) {
24
+ const match = /^([0-9a-f]{64})\s+\*?(.+)$/i.exec(line.trim());
25
+ if (!match)
26
+ continue;
27
+ const rel = match[2].replace(/\\/g, '/');
28
+ if (!rel.startsWith('bin/') || rel.includes('..'))
29
+ continue;
30
+ map.set(rel, match[1].toLowerCase());
31
+ }
32
+ sums = map.size > 0 ? map : null;
33
+ if (!sums)
34
+ log.warn('[catchword] qjsc 校验清单为空,跳过二进制完整性校验');
35
+ return sums;
36
+ }
37
+ function verifyQjscFiles(qjscPath, skip) {
38
+ if (skip)
39
+ return;
40
+ const map = loadQjscSums();
41
+ if (!map)
42
+ return;
43
+ const rel = path.relative(QJSC_ROOT, qjscPath).replace(/\\/g, '/');
44
+ const relDir = path.posix.dirname(rel);
45
+ const entries = [...map].filter(([file]) => {
46
+ if (path.posix.dirname(file) !== relDir)
47
+ return false;
48
+ if (file === rel)
49
+ return true;
50
+ return /\.(?:dll|so|dylib)$/i.test(file);
51
+ });
52
+ if (!entries.some(([file]) => file === rel)) {
53
+ if (!warnedMissing.has(rel)) {
54
+ warnedMissing.add(rel);
55
+ log.warn(`[catchword] qjsc 校验清单中没有 ${rel},跳过完整性校验`);
56
+ }
57
+ return;
58
+ }
59
+ for (const [file, expected] of entries) {
60
+ const abs = path.join(QJSC_ROOT, file);
61
+ if (!fs.existsSync(abs))
62
+ continue;
63
+ if (verifiedFiles.has(abs))
64
+ continue;
65
+ const actual = sha256File(abs);
66
+ if (actual !== expected) {
67
+ throw new Error(`[catchword] qjsc 二进制校验失败: ${file}\n` +
68
+ `期望 sha256 ${expected}\n实际 sha256 ${actual}\n` +
69
+ `请重新获取官方 vendor/qjsc 二进制;确认是本地可信构建时可设置 catchword.skipQjscVerify: true。`);
70
+ }
71
+ verifiedFiles.add(abs);
72
+ }
73
+ }
74
+ let currentId = 0;
75
+ function nextId() {
76
+ return ++currentId;
77
+ }
78
+ function getQjscPath(version, bigNum) {
79
+ const platform = process.platform;
80
+ let dir;
81
+ if (platform === 'win32') {
82
+ dir = path.join(QJSC_BIN_ROOT, 'win32');
83
+ }
84
+ else if (platform === 'darwin') {
85
+ dir = path.join(QJSC_BIN_ROOT, 'darwin', process.arch === 'arm64' ? 'arm64' : 'x64');
86
+ }
87
+ else {
88
+ dir = path.join(QJSC_BIN_ROOT, platform);
89
+ }
90
+ const ext = platform === 'win32' ? '.exe' : '';
91
+ return path.join(dir, `qjsc${bigNum ? 'bn' : ''}${version}${ext}`);
92
+ }
93
+ function exec(bin, args, cwd) {
94
+ return new Promise((resolve) => {
95
+ const child = spawn(bin, args, { cwd, windowsHide: true });
96
+ let output = '';
97
+ child.stdout.on('data', (d) => (output += d.toString()));
98
+ child.stderr.on('data', (d) => (output += d.toString()));
99
+ child.on('error', (err) => resolve({ ok: false, output: String(err) }));
100
+ child.on('close', (code) => resolve({ ok: code === 0, output }));
101
+ });
102
+ }
103
+ function convertCppToBin(cpp, cname) {
104
+ const text = cpp.toString('utf8');
105
+ const re = new RegExp(`const uint8_t ${cname}\\[\\d+\\] = {([^}]+)}`);
106
+ const match = re.exec(text);
107
+ if (!match)
108
+ throw new Error(`qjsc: 无法从 C 输出中提取 ${cname}`);
109
+ const bytes = [];
110
+ for (const item of match[1].replace(/[\r\n]/g, '').split(',')) {
111
+ const hex = item.trim().slice(2);
112
+ if (hex)
113
+ bytes.push(parseInt(hex, 16));
114
+ }
115
+ return Buffer.from(bytes);
116
+ }
117
+ export async function compileJs(jsFile, binFile, cfg) {
118
+ const qjsc = getQjscPath(cfg.version, cfg.bigNum);
119
+ if (!fs.existsSync(qjsc)) {
120
+ throw new Error(`[catchword] 找不到 qjsc: ${qjsc}\n` +
121
+ `请确认设备固件使用的 QuickJS 版本,或把对应二进制放入 vendor/qjsc/bin/`);
122
+ }
123
+ verifyQjscFiles(qjsc, cfg.skipVerify === true);
124
+ if (process.platform !== 'win32') {
125
+ try {
126
+ fs.chmodSync(qjsc, 0o755);
127
+ }
128
+ catch { }
129
+ }
130
+ const cname = `qjsc_convert_c_v_${nextId()}`;
131
+ const cFile = jsFile + '.c';
132
+ const args = ['-N', cname, '-o', cFile, '-c', path.basename(jsFile), '-m'];
133
+ for (const item of cfg.internal) {
134
+ if (!item)
135
+ continue;
136
+ args.unshift(item);
137
+ args.unshift('-M');
138
+ }
139
+ const { ok, output } = await exec(qjsc, args, path.dirname(jsFile));
140
+ if (!ok || !fs.existsSync(cFile)) {
141
+ throw new Error(`[catchword] qjsc 编译失败: ${jsFile}\n${output}`);
142
+ }
143
+ try {
144
+ const cpp = fs.readFileSync(cFile);
145
+ fs.writeFileSync(binFile, convertCppToBin(cpp, cname));
146
+ }
147
+ finally {
148
+ fs.unlinkSync(cFile);
149
+ }
150
+ }
151
+ export async function compileAll(ctx, state) {
152
+ if (!fs.existsSync(ctx.buildDir)) {
153
+ throw new Error(`[catchword] 构建目录不存在: ${ctx.buildDir}`);
154
+ }
155
+ const { version, bigNum, concurrency } = ctx.quickjsOptions;
156
+ const files = walkSync(ctx.buildDir).filter((file) => file.endsWith('.js'));
157
+ if (files.length === 0)
158
+ return;
159
+ log.step(`qjsc 预编译 (${files.length} 个文件, QuickJS ${version}${bigNum ? ' bignum' : ''})`);
160
+ const internal = [...state.internalModules];
161
+ const limit = Math.max(1, concurrency ?? 4);
162
+ const skipVerify = ctx.toolOptions.skipQjscVerify === true;
163
+ let cursor = 0;
164
+ let failed = null;
165
+ await Promise.all(Array.from({ length: Math.min(limit, files.length) }, async () => {
166
+ while (cursor < files.length && !failed) {
167
+ const index = cursor++;
168
+ const file = files[index];
169
+ try {
170
+ await compileJs(file, file + '.bin', { version, bigNum, internal, skipVerify });
171
+ }
172
+ catch (err) {
173
+ failed = err;
174
+ }
175
+ }
176
+ }));
177
+ if (failed)
178
+ throw failed;
179
+ for (const file of files) {
180
+ const bin = file + '.bin';
181
+ if (!fs.existsSync(bin))
182
+ throw new Error(`[catchword] 缺少产物: ${bin}`);
183
+ fs.unlinkSync(file);
184
+ }
185
+ log.success(`qjsc 完成: ${files.length} 个 .js -> .js.bin`);
186
+ }
@@ -0,0 +1,2 @@
1
+ import type { AppContext } from '../plugin/context.js';
2
+ export declare function reportBuildSize(ctx: AppContext): void;
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { walkSync } from '../util/fs.js';
4
+ import { log } from '../util/log.js';
5
+ function kb(size) {
6
+ return (size / 1024).toFixed(1) + ' KB';
7
+ }
8
+ export function reportBuildSize(ctx) {
9
+ if (!fs.existsSync(ctx.buildDir))
10
+ return;
11
+ const files = walkSync(ctx.buildDir);
12
+ const buckets = new Map();
13
+ const list = [];
14
+ for (const file of files) {
15
+ const rel = path.relative(ctx.buildDir, file).replace(/\\/g, '/');
16
+ const size = fs.statSync(file).size;
17
+ list.push({ rel, size });
18
+ const category = rel.startsWith('images/')
19
+ ? 'images'
20
+ : rel.startsWith('assets/')
21
+ ? 'assets'
22
+ : rel.endsWith('.js.bin')
23
+ ? 'bytecode'
24
+ : rel.endsWith('.js')
25
+ ? 'js'
26
+ : rel === 'manifest.json'
27
+ ? 'manifest'
28
+ : 'other';
29
+ const bucket = buckets.get(category) ?? { count: 0, size: 0 };
30
+ bucket.count += 1;
31
+ bucket.size += size;
32
+ buckets.set(category, bucket);
33
+ }
34
+ const total = list.reduce((sum, item) => sum + item.size, 0);
35
+ log.step('产物体积');
36
+ for (const [category, bucket] of [...buckets].sort((a, b) => b[1].size - a[1].size)) {
37
+ log.info(` ${category.padEnd(9)} ${String(bucket.count).padStart(3)} 个 ${kb(bucket.size)}`);
38
+ }
39
+ log.info(` 合计 ${kb(total)}`);
40
+ const top = [...list].sort((a, b) => b.size - a.size).slice(0, 8);
41
+ if (top.length) {
42
+ log.info(' 最大的文件:');
43
+ for (const item of top) {
44
+ log.info(` ${kb(item.size).padStart(10)} ${item.rel}`);
45
+ }
46
+ }
47
+ if (fs.existsSync(ctx.amrPath)) {
48
+ log.info(` .amr ${kb(fs.statSync(ctx.amrPath).size)}`);
49
+ }
50
+ }
@@ -0,0 +1,17 @@
1
+ import type { AppContext } from '../plugin/context.js';
2
+ import type { BuildState } from '../plugin/state.js';
3
+ export interface SecretPattern {
4
+ name: string;
5
+ re: RegExp;
6
+ }
7
+ export declare const DEFAULT_SECRET_PATTERNS: SecretPattern[];
8
+ export declare function assertNoSourceMaps(ctx: AppContext): void;
9
+ export declare function assertNoSensitiveFiles(ctx: AppContext): void;
10
+ export declare function assertNoBuildPathLeak(ctx: AppContext, state?: BuildState): void;
11
+ export declare function assertNoSourcePathLeak(ctx: AppContext, state?: BuildState): void;
12
+ export declare function warnNativeLeaks(ctx: AppContext): void;
13
+ export declare function verifyManifestCert(ctx: AppContext, cert: Record<string, {
14
+ size: number;
15
+ md5: string;
16
+ }>): void;
17
+ export declare function scanSecrets(ctx: AppContext, state?: BuildState): void;