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,77 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import { createContext } from '../plugin/context.js';
5
+ import { loadConfig } from '../config.js';
6
+ import { log } from '../util/log.js';
7
+ import { runBuild } from './build.js';
8
+ function launch(simPath, buildDir, page) {
9
+ const isWin = /^win/.test(process.platform);
10
+ const bin = isWin ? '.\\appx.exe' : './appx';
11
+ const args = [buildDir];
12
+ if (page)
13
+ args.push(page);
14
+ log.info(`启动模拟器: ${bin} ${args.join(' ')}`);
15
+ return spawn(bin, args, {
16
+ cwd: simPath,
17
+ stdio: ['pipe', 'inherit', 'inherit']
18
+ });
19
+ }
20
+ function deleteBinFiles(dir) {
21
+ if (!fs.existsSync(dir))
22
+ return;
23
+ for (const name of fs.readdirSync(dir)) {
24
+ if (name.endsWith('.bin'))
25
+ fs.unlinkSync(path.join(dir, name));
26
+ }
27
+ }
28
+ export async function runSimulator(opts) {
29
+ const config = opts.config ?? (await loadConfig(opts.dir, { mode: 'production' })).config;
30
+ const ctx = createContext({ dir: opts.dir, config });
31
+ const fromPkg = ctx.pkg.simulator ?? {};
32
+ const fromConfig = config.simulator ?? {};
33
+ const simPath = opts.simpath || fromConfig.path || fromPkg.path;
34
+ const page = opts.page || fromConfig.page || fromPkg.page;
35
+ if (!simPath) {
36
+ log.error(`请配置模拟器路径。可在工程 package.json 中配置:
37
+ {
38
+ "simulator": { "path": "/path/to/simulator/", "page": "index" }
39
+ }`);
40
+ return -1;
41
+ }
42
+ await runBuild({ dir: opts.dir, compress: false, mock: true, config });
43
+ let child = launch(simPath, ctx.buildDir, page);
44
+ let timer = null;
45
+ const watcher = fs.watch(ctx.srcDir, { recursive: true }, () => {
46
+ if (timer)
47
+ clearTimeout(timer);
48
+ timer = setTimeout(async () => {
49
+ try {
50
+ deleteBinFiles(ctx.buildDir);
51
+ await runBuild({
52
+ dir: opts.dir,
53
+ compress: false,
54
+ mock: true,
55
+ silent: true,
56
+ config
57
+ });
58
+ child.stdin?.write(`relaunch ${ctx.buildDir} ${page ?? ''}\n`);
59
+ log.success('已重新构建并通知模拟器刷新');
60
+ }
61
+ catch (err) {
62
+ log.error(`重新构建失败: ${String(err)}`);
63
+ }
64
+ timer = null;
65
+ }, 500);
66
+ });
67
+ process.on('SIGINT', () => {
68
+ watcher.close();
69
+ child.kill();
70
+ process.exit(0);
71
+ });
72
+ child.on('close', (code) => {
73
+ watcher.close();
74
+ log.info(`模拟器退出: ${code}`);
75
+ });
76
+ return 0;
77
+ }
@@ -0,0 +1,9 @@
1
+ export interface UploadOptions {
2
+ dir: string;
3
+ appPath?: string;
4
+ host: string;
5
+ port: string;
6
+ page: string;
7
+ noPath?: boolean;
8
+ }
9
+ export declare function runUpload(opts: UploadOptions): Promise<number>;
@@ -0,0 +1,135 @@
1
+ import fs from 'node:fs';
2
+ import http from 'node:http';
3
+ import path from 'node:path';
4
+ import { createContext } from '../plugin/context.js';
5
+ import { log } from '../util/log.js';
6
+ function requestJson(host, port, urlPath, payload) {
7
+ const data = Buffer.from(JSON.stringify(payload));
8
+ return new Promise((resolve, reject) => {
9
+ const req = http.request({
10
+ host,
11
+ port,
12
+ path: urlPath,
13
+ method: 'POST',
14
+ headers: {
15
+ 'Content-Type': 'application/json',
16
+ 'Content-Length': data.length
17
+ },
18
+ timeout: 5000
19
+ }, (res) => {
20
+ let body = '';
21
+ res.on('data', (chunk) => (body += chunk));
22
+ res.on('end', () => {
23
+ try {
24
+ resolve({ status: res.statusCode, data: JSON.parse(body) });
25
+ }
26
+ catch {
27
+ reject(new Error(`非法响应: ${body}`));
28
+ }
29
+ });
30
+ });
31
+ req.on('timeout', () => req.destroy(new Error('请求超时')));
32
+ req.on('error', reject);
33
+ req.end(data);
34
+ });
35
+ }
36
+ function requestFile(host, port, urlPath, field, file) {
37
+ return new Promise((resolve, reject) => {
38
+ const boundary = '----falcon' + Date.now().toString(16);
39
+ const pre = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${field}"; filename="${path.basename(file)}"\r\nContent-Type: application/octet-stream\r\n\r\n`);
40
+ const epi = Buffer.from(`\r\n--${boundary}--\r\n`);
41
+ const size = fs.statSync(file).size;
42
+ const req = http.request({
43
+ host,
44
+ port,
45
+ path: urlPath,
46
+ method: 'POST',
47
+ headers: {
48
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
49
+ 'Content-Length': pre.length + size + epi.length
50
+ },
51
+ timeout: 10000
52
+ }, (res) => {
53
+ let body = '';
54
+ res.on('data', (chunk) => (body += chunk));
55
+ res.on('end', () => {
56
+ try {
57
+ resolve({ status: res.statusCode, data: JSON.parse(body) });
58
+ }
59
+ catch {
60
+ reject(new Error(`非法响应: ${body}`));
61
+ }
62
+ });
63
+ });
64
+ req.on('timeout', () => req.destroy(new Error('请求超时')));
65
+ req.on('error', reject);
66
+ req.write(pre);
67
+ const stream = fs.createReadStream(file);
68
+ stream.on('error', reject);
69
+ stream.on('end', () => req.end(epi));
70
+ stream.pipe(req, { end: false });
71
+ });
72
+ }
73
+ export async function runUpload(opts) {
74
+ const ctx = createContext({ dir: opts.dir });
75
+ const amrPath = opts.appPath ?? ctx.amrPath;
76
+ if (!fs.existsSync(amrPath)) {
77
+ log.error(`本地 amr 包不存在: ${amrPath}\n请先执行构建`);
78
+ return -2;
79
+ }
80
+ const { host, port } = opts;
81
+ const loopback = /^(?:127\.0\.0\.1|localhost|::1|\[::1\])$/i.test(host);
82
+ if (!loopback) {
83
+ log.warn(`[catchword] upload 通过明文 HTTP 向 ${host}:${port} 传输 .amr,` +
84
+ `请仅在可信局域网使用;公网传输建议改用 adb/SSH 隧道。`);
85
+ }
86
+ log.step('STEP1: push');
87
+ let push;
88
+ try {
89
+ push = await requestFile(host, port, '/push', 'pkg', amrPath);
90
+ }
91
+ catch (err) {
92
+ log.error(`无法与设备建立连接: ${err.message}`);
93
+ return -3;
94
+ }
95
+ log.info(`push res ${JSON.stringify(push.data)}`);
96
+ if (push.status !== 200 || push.data?.ret !== 0) {
97
+ log.error('amr 包写入设备失败,请检查设备分区读写权限(如 chmod -R 777 /data)');
98
+ return -4;
99
+ }
100
+ log.success('push 成功');
101
+ log.step('STEP2: install');
102
+ let install;
103
+ try {
104
+ install = await requestJson(host, port, '/install', { path: push.data.fpath });
105
+ }
106
+ catch (err) {
107
+ log.error(`install 请求失败: ${err.message}`);
108
+ return -5;
109
+ }
110
+ log.info(`install res ${JSON.stringify(install.data)}`);
111
+ if (install.status !== 200 || install.data?.ret !== 0) {
112
+ log.error('install 失败');
113
+ return -6;
114
+ }
115
+ log.success('install 成功');
116
+ log.step('STEP3: start');
117
+ let start;
118
+ try {
119
+ start = await requestJson(host, port, '/start', {
120
+ appID: install.data.appid,
121
+ page: opts.page || undefined
122
+ });
123
+ }
124
+ catch (err) {
125
+ log.error(`start 请求失败: ${err.message}`);
126
+ return -7;
127
+ }
128
+ log.info(`start res ${JSON.stringify(start.data)}`);
129
+ if (start.status !== 200 || start.data?.ret !== 0) {
130
+ log.error('start 失败');
131
+ return -8;
132
+ }
133
+ log.success('安装完成');
134
+ return 0;
135
+ }
@@ -0,0 +1,8 @@
1
+ import type { AppContext } from '../plugin/context.js';
2
+ export declare function run(bin: string, args: string[]): Promise<{
3
+ ok: boolean;
4
+ stdout: string;
5
+ stderr: string;
6
+ }>;
7
+ export declare function prepareBuild(ctx: AppContext): void;
8
+ export declare function parseJsonLine(output: string): any | null;
@@ -0,0 +1,43 @@
1
+ import fs from 'node:fs';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { ensureDir, rmrf } from '../util/fs.js';
5
+ const execFileAsync = promisify(execFile);
6
+ export async function run(bin, args) {
7
+ try {
8
+ const { stdout, stderr } = await execFileAsync(bin, args, {
9
+ windowsHide: true,
10
+ maxBuffer: 10 * 1024 * 1024
11
+ });
12
+ return { ok: true, stdout, stderr };
13
+ }
14
+ catch (err) {
15
+ return {
16
+ ok: false,
17
+ stdout: err?.stdout ?? '',
18
+ stderr: err?.stderr ?? String(err)
19
+ };
20
+ }
21
+ }
22
+ export function prepareBuild(ctx) {
23
+ rmrf(ctx.buildDir);
24
+ ensureDir(ctx.buildDir);
25
+ rmrf(ctx.tmpDir);
26
+ ensureDir(ctx.tmpDir);
27
+ for (const stale of [ctx.amrPath, ctx.amrPath + '.tmp', ctx.amrPath + '.sha256']) {
28
+ if (fs.existsSync(stale))
29
+ fs.unlinkSync(stale);
30
+ }
31
+ }
32
+ export function parseJsonLine(output) {
33
+ for (const line of output.split(/\r?\n/)) {
34
+ const trimmed = line.trim();
35
+ if (!trimmed.startsWith('{'))
36
+ continue;
37
+ try {
38
+ return JSON.parse(trimmed);
39
+ }
40
+ catch { }
41
+ }
42
+ return null;
43
+ }
@@ -0,0 +1,17 @@
1
+ import type { FalconUserConfig } from './types.js';
2
+ export declare const CONFIG_FILES: string[];
3
+ export type ConfigFactory = (env: {
4
+ mode: string;
5
+ }) => FalconUserConfig;
6
+ export type ConfigExport = FalconUserConfig | ConfigFactory;
7
+ export interface LoadedConfig {
8
+ path: string | null;
9
+ config: FalconUserConfig;
10
+ mode?: string;
11
+ }
12
+ export declare function defineConfig(config: FalconUserConfig): FalconUserConfig;
13
+ export declare function defineConfig(config: ConfigFactory): ConfigFactory;
14
+ export declare function findConfigFile(dir: string): string | null;
15
+ export declare function loadConfig(dir: string, env?: {
16
+ mode?: string;
17
+ }): Promise<LoadedConfig>;
package/dist/config.js ADDED
@@ -0,0 +1,90 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { build as esbuild } from 'esbuild';
6
+ import { loadEnv } from 'vite';
7
+ export const CONFIG_FILES = [
8
+ 'catchword.config.ts',
9
+ 'catchword.config.mts',
10
+ 'catchword.config.js',
11
+ 'catchword.config.mjs',
12
+ 'falcon.config.ts',
13
+ 'falcon.config.mts',
14
+ 'falcon.config.js',
15
+ 'falcon.config.mjs'
16
+ ];
17
+ export function defineConfig(config) {
18
+ return config;
19
+ }
20
+ const cache = new Map();
21
+ let importSeq = 0;
22
+ export function findConfigFile(dir) {
23
+ const root = path.resolve(dir);
24
+ for (const name of CONFIG_FILES) {
25
+ const file = path.join(root, name);
26
+ if (fs.existsSync(file))
27
+ return file;
28
+ }
29
+ return null;
30
+ }
31
+ function stampOf(file) {
32
+ return createHash('sha1').update(fs.readFileSync(file)).digest('hex');
33
+ }
34
+ export async function loadConfig(dir, env = {}) {
35
+ const file = findConfigFile(dir);
36
+ if (!file)
37
+ return { path: null, config: {} };
38
+ const mode = env.mode ?? 'development';
39
+ const stamp = stampOf(file);
40
+ const cacheKey = `${file}::${mode}`;
41
+ const cached = cache.get(cacheKey);
42
+ if (cached && cached.stamp === stamp)
43
+ return cached.value;
44
+ try {
45
+ const envValues = loadEnv(mode, path.dirname(file), '');
46
+ for (const [key, value] of Object.entries(envValues)) {
47
+ if (process.env[key] === undefined)
48
+ process.env[key] = value;
49
+ }
50
+ }
51
+ catch (error) { }
52
+ const tmpDir = path.join(path.dirname(file), '.falcon_tmp');
53
+ fs.mkdirSync(tmpDir, { recursive: true });
54
+ const outfile = path.join(tmpDir, `catchword.config.${process.pid}.${++importSeq}.mjs`);
55
+ try {
56
+ await esbuild({
57
+ entryPoints: [file],
58
+ bundle: true,
59
+ platform: 'node',
60
+ format: 'esm',
61
+ target: 'node20',
62
+ outfile,
63
+ logLevel: 'silent',
64
+ external: ['catchword', 'falcon-vite']
65
+ });
66
+ }
67
+ catch (error) {
68
+ const message = error instanceof Error ? error.message : String(error);
69
+ throw new Error(`[catchword] 无法解析 ${path.basename(file)}: ${message}`);
70
+ }
71
+ let exported;
72
+ try {
73
+ const mod = (await import(pathToFileURL(outfile).href));
74
+ exported = mod.default;
75
+ }
76
+ finally {
77
+ fs.rmSync(outfile, { force: true });
78
+ }
79
+ if (exported === undefined || exported === null) {
80
+ throw new Error(`[catchword] ${path.basename(file)} 缺少默认导出,` +
81
+ `请使用 export default defineConfig({ ... })`);
82
+ }
83
+ if (typeof exported !== 'function' && typeof exported !== 'object') {
84
+ throw new Error(`[catchword] ${path.basename(file)} 的默认导出必须是对象或函数`);
85
+ }
86
+ const config = typeof exported === 'function' ? exported({ mode }) : exported;
87
+ const value = { path: file, config: config ?? {}, mode };
88
+ cache.set(cacheKey, { stamp, value });
89
+ return value;
90
+ }
@@ -0,0 +1,16 @@
1
+ import type { PluginOption } from 'vite';
2
+ import type { FalconOptions } from './types.js';
3
+ import { BuildState } from './plugin/state.js';
4
+ export type { FalconOptions, FalconUserConfig, CatchwordOptions, CatchwordUserConfig, AppToolOptions, DeviceProfile, BuildConfigOptions, PreviewConfigOptions, SimulatorConfigOptions, BuildHookContext, FalconHooks, QjscOptions } from './types.js';
5
+ export { createContext, AppContext } from './plugin/context.js';
6
+ export { defineConfig, loadConfig, findConfigFile, CONFIG_FILES } from './config.js';
7
+ export type { LoadedConfig, ConfigExport, ConfigFactory } from './config.js';
8
+ export declare function createCatchwordPlugins(options?: FalconOptions): {
9
+ ctx: import("./plugin/context.js").AppContext;
10
+ state: BuildState;
11
+ plugins: PluginOption[];
12
+ };
13
+ export declare function catchwordVite(options?: FalconOptions): PluginOption[];
14
+ export declare const createFalconPlugins: typeof createCatchwordPlugins;
15
+ export declare const falconVite: typeof catchwordVite;
16
+ export default catchwordVite;
package/dist/index.js ADDED
@@ -0,0 +1,51 @@
1
+ import { createContext } from './plugin/context.js';
2
+ import { BuildState, ClassTokenRegistry } from './plugin/state.js';
3
+ import { configPlugin } from './plugin/config.js';
4
+ import { themePlugin, jsapiPlugin } from './plugin/jsapi.js';
5
+ import { appEntryPlugin } from './plugin/app-entry.js';
6
+ import { sfcPlugin } from './plugin/sfc.js';
7
+ import { imagePlugin, mediaPlugin } from './plugin/assets.js';
8
+ import { fallbackPlugin } from './plugin/fallback.js';
9
+ import { shimPlugin } from './plugin/shim.js';
10
+ import { stringTablePlugin } from './plugin/string-table.js';
11
+ import { sanitizePlugin } from './plugin/sanitize.js';
12
+ import { outputPlugin } from './plugin/output.js';
13
+ import { securityPlugin } from './plugin/security.js';
14
+ import { previewPlugin, devRuntimePlugin } from './plugin/preview.js';
15
+ import { log } from './util/log.js';
16
+ export { createContext, AppContext } from './plugin/context.js';
17
+ export { defineConfig, loadConfig, findConfigFile, CONFIG_FILES } from './config.js';
18
+ export function createCatchwordPlugins(options = {}) {
19
+ const ctx = createContext(options);
20
+ const state = new BuildState(ctx.toolOptions.keepKeyframeNames === true);
21
+ state.classTokens = new ClassTokenRegistry(new Set(ctx.toolOptions.keepClassNames ?? []));
22
+ const tokenizeClasses = ctx.toolOptions.tokenizeClassNames !== false;
23
+ if (tokenizeClasses && ctx.hasDynamicClassBindings) {
24
+ log.warn('[catchword] 检测到 :class / v-bind:class,类名 token 化已禁用(动态类名无法安全重写)');
25
+ }
26
+ state.classTokensEnabled = tokenizeClasses && !ctx.hasDynamicClassBindings;
27
+ const plugins = [
28
+ configPlugin(ctx, options),
29
+ shimPlugin(ctx),
30
+ themePlugin(ctx),
31
+ jsapiPlugin(ctx, state),
32
+ appEntryPlugin(ctx),
33
+ sfcPlugin(ctx, state),
34
+ imagePlugin(ctx),
35
+ mediaPlugin(ctx),
36
+ fallbackPlugin(ctx, state),
37
+ stringTablePlugin(ctx, state),
38
+ sanitizePlugin(ctx),
39
+ outputPlugin(ctx, state),
40
+ securityPlugin(ctx, state),
41
+ devRuntimePlugin(ctx),
42
+ previewPlugin(ctx)
43
+ ];
44
+ return { ctx, state, plugins };
45
+ }
46
+ export function catchwordVite(options = {}) {
47
+ return createCatchwordPlugins(options).plugins;
48
+ }
49
+ export const createFalconPlugins = createCatchwordPlugins;
50
+ export const falconVite = catchwordVite;
51
+ export default catchwordVite;
@@ -0,0 +1,46 @@
1
+ import type { FalconUserConfig } from '../types.js';
2
+ export interface NativeMethod {
3
+ name: string;
4
+ async: boolean;
5
+ arity?: number;
6
+ style: 'proto' | 'raw';
7
+ }
8
+ export interface NativeModule {
9
+ name: string;
10
+ className: string;
11
+ file: string;
12
+ methods: NativeMethod[];
13
+ }
14
+ export interface NativeRegistryEntry {
15
+ name: string;
16
+ factory: string;
17
+ guard: string | null;
18
+ }
19
+ export interface NativeApiFile {
20
+ version: 1;
21
+ generatedBy: string;
22
+ sources: string[];
23
+ modules: NativeModule[];
24
+ registry: NativeRegistryEntry[];
25
+ }
26
+ export interface NativePaths {
27
+ root: string;
28
+ dir: string;
29
+ sourceDir: string;
30
+ registryFile: string;
31
+ apiFile: string;
32
+ typesFile: string;
33
+ overridesFile: string;
34
+ }
35
+ export declare function resolveNativePaths(root: string, config: FalconUserConfig): NativePaths;
36
+ export declare function collectSources(dir: string): string[];
37
+ export declare function parseModuleSource(source: string, file: string): NativeModule | null;
38
+ export declare function parseRegistry(source: string): NativeRegistryEntry[];
39
+ export declare function extractApi(options: {
40
+ sourceDir: string;
41
+ registryFile: string;
42
+ root: string;
43
+ }): NativeApiFile;
44
+ export declare function readApiFile(file: string): NativeApiFile;
45
+ export declare function writeJsonFile(file: string, value: unknown): void;
46
+ export declare function diffApi(previous: NativeApiFile, next: NativeApiFile): string[];
@@ -0,0 +1,185 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ const CLASS_RE = /JSValue\s+([A-Za-z0-9_]+)::CreateClass\s*\(/;
4
+ const TPL_NAME_RE = /JQFunctionTemplate::New\(\s*env\s*,\s*"([A-Za-z0-9_]+)"\s*\)/;
5
+ const PROTO_RE = /tpl->SetProtoMethod(Promise)?\(\s*"([A-Za-z0-9_]+)"\s*,\s*&([A-Za-z0-9_]+)::([A-Za-z0-9_]+)\s*\)\s*;/g;
6
+ const SET_PROP_RE = /JS_SetPropertyStr\(/g;
7
+ const CFUNC_RE = /JS_NewCFunction(?:2)?\(/;
8
+ export function resolveNativePaths(root, config) {
9
+ const native = config.native ?? {};
10
+ const dir = path.resolve(root, native.dir ?? 'jsapi');
11
+ return {
12
+ root,
13
+ dir,
14
+ sourceDir: path.resolve(dir, native.sourceDir ?? 'src'),
15
+ registryFile: path.resolve(dir, native.registry ?? 'src/bridge.cpp'),
16
+ apiFile: path.resolve(dir, native.api ?? 'api.json'),
17
+ typesFile: path.resolve(dir, native.types ?? 'api.d.ts'),
18
+ overridesFile: path.resolve(dir, native.overrides ?? 'api.override.json')
19
+ };
20
+ }
21
+ export function collectSources(dir) {
22
+ const out = [];
23
+ const walk = (current) => {
24
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
25
+ const full = path.join(current, entry.name);
26
+ if (entry.isDirectory()) {
27
+ if (entry.name === 'node_modules' || entry.name.startsWith('.'))
28
+ continue;
29
+ walk(full);
30
+ }
31
+ else if (/\.(cpp|cc|cxx)$/i.test(entry.name)) {
32
+ out.push(full);
33
+ }
34
+ }
35
+ };
36
+ if (fs.existsSync(dir))
37
+ walk(dir);
38
+ out.sort();
39
+ return out;
40
+ }
41
+ function parseRawMethods(source, bodyStart, into) {
42
+ SET_PROP_RE.lastIndex = bodyStart;
43
+ let match;
44
+ while ((match = SET_PROP_RE.exec(source))) {
45
+ const windowText = source.slice(match.index, match.index + 400);
46
+ const head = /^JS_SetPropertyStr\(\s*ctx\s*,\s*obj\s*,\s*"([A-Za-z0-9_]+)"\s*,/.exec(windowText);
47
+ if (!head)
48
+ continue;
49
+ const name = head[1];
50
+ if (into.has(name))
51
+ continue;
52
+ const tail = windowText.slice(head[0].length);
53
+ if (!CFUNC_RE.test(tail))
54
+ continue;
55
+ const arity = Number(/,?\s*"([A-Za-z0-9_]+)"\s*,\s*(\d+)\s*\)/.exec(tail)?.[2]);
56
+ into.set(name, {
57
+ name,
58
+ async: false,
59
+ arity: Number.isFinite(arity) && arity > 0 ? arity : undefined,
60
+ style: 'raw'
61
+ });
62
+ }
63
+ }
64
+ export function parseModuleSource(source, file) {
65
+ const classMatch = CLASS_RE.exec(source);
66
+ if (!classMatch)
67
+ return null;
68
+ const className = classMatch[1];
69
+ const body = source.slice(classMatch.index);
70
+ const moduleName = TPL_NAME_RE.exec(body)?.[1] ?? className.replace(/Bridge$/, '');
71
+ const methods = new Map();
72
+ PROTO_RE.lastIndex = 0;
73
+ let proto;
74
+ while ((proto = PROTO_RE.exec(body))) {
75
+ const name = proto[2];
76
+ if (methods.has(name))
77
+ continue;
78
+ methods.set(name, { name, async: proto[1] === 'Promise', style: 'proto' });
79
+ }
80
+ parseRawMethods(source, classMatch.index, methods);
81
+ return {
82
+ name: moduleName,
83
+ className,
84
+ file,
85
+ methods: [...methods.values()].sort((a, b) => a.name.localeCompare(b.name))
86
+ };
87
+ }
88
+ export function parseRegistry(source) {
89
+ const block = /const\s+std::vector\s*<\s*BridgeModule\s*>\s*kModules\s*=\s*\{([\s\S]*?)\n\};/.exec(source);
90
+ if (!block)
91
+ return [];
92
+ const entries = [];
93
+ const stack = [];
94
+ for (const line of block[1].split('\n')) {
95
+ const trimmed = line.trim();
96
+ const ifMatch = /^#\s*if(n?def)?\s+(.+)$/.exec(trimmed);
97
+ if (ifMatch) {
98
+ stack.push(ifMatch[2].trim());
99
+ continue;
100
+ }
101
+ if (/^#\s*endif/.test(trimmed)) {
102
+ stack.pop();
103
+ continue;
104
+ }
105
+ const entry = /^\{\s*"([A-Za-z0-9_]+)"\s*,\s*&?([A-Za-z0-9_:]+)\s*\}/.exec(trimmed);
106
+ if (!entry)
107
+ continue;
108
+ entries.push({
109
+ name: entry[1],
110
+ factory: entry[2],
111
+ guard: stack.length ? stack[stack.length - 1] : null
112
+ });
113
+ }
114
+ return entries;
115
+ }
116
+ export function extractApi(options) {
117
+ const files = collectSources(options.sourceDir);
118
+ const modules = [];
119
+ for (const file of files) {
120
+ const source = fs.readFileSync(file, 'utf8');
121
+ const parsed = parseModuleSource(source, path.relative(options.root, file).split(path.sep).join('/'));
122
+ if (parsed)
123
+ modules.push(parsed);
124
+ }
125
+ modules.sort((a, b) => a.name.localeCompare(b.name));
126
+ let registry = [];
127
+ if (fs.existsSync(options.registryFile)) {
128
+ registry = parseRegistry(fs.readFileSync(options.registryFile, 'utf8'));
129
+ }
130
+ return {
131
+ version: 1,
132
+ generatedBy: 'catchword',
133
+ sources: [path.relative(options.root, options.sourceDir).split(path.sep).join('/')],
134
+ modules,
135
+ registry
136
+ };
137
+ }
138
+ export function readApiFile(file) {
139
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
140
+ }
141
+ export function writeJsonFile(file, value) {
142
+ fs.mkdirSync(path.dirname(file), { recursive: true });
143
+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', 'utf8');
144
+ }
145
+ export function diffApi(previous, next) {
146
+ const diffs = [];
147
+ const prev = new Map(previous.modules.map((m) => [m.name, m]));
148
+ const cur = new Map(next.modules.map((m) => [m.name, m]));
149
+ for (const [name, before] of prev) {
150
+ const after = cur.get(name);
151
+ if (!after) {
152
+ diffs.push(`模块消失: ${name}`);
153
+ continue;
154
+ }
155
+ const beforeMethods = new Map(before.methods.map((m) => [m.name, m]));
156
+ const afterMethods = new Map(after.methods.map((m) => [m.name, m]));
157
+ for (const [method, oldMethod] of beforeMethods) {
158
+ const newMethod = afterMethods.get(method);
159
+ if (!newMethod)
160
+ diffs.push(`方法消失: ${name}.${method}`);
161
+ else if (newMethod.async !== oldMethod.async) {
162
+ diffs.push(`同步性变化: ${name}.${method} ${oldMethod.async ? 'async' : 'sync'} -> ${newMethod.async ? 'async' : 'sync'}`);
163
+ }
164
+ }
165
+ for (const method of afterMethods.keys()) {
166
+ if (!beforeMethods.has(method))
167
+ diffs.push(`新增方法: ${name}.${method}`);
168
+ }
169
+ }
170
+ for (const name of cur.keys()) {
171
+ if (!prev.has(name))
172
+ diffs.push(`新增模块: ${name}`);
173
+ }
174
+ const prevRegistry = new Set(previous.registry.map((r) => r.name));
175
+ const curRegistry = new Set(next.registry.map((r) => r.name));
176
+ for (const name of prevRegistry) {
177
+ if (!curRegistry.has(name))
178
+ diffs.push(`注册表移除: ${name}`);
179
+ }
180
+ for (const name of curRegistry) {
181
+ if (!prevRegistry.has(name))
182
+ diffs.push(`注册表新增: ${name}`);
183
+ }
184
+ return diffs;
185
+ }