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,181 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from '@vue/compiler-sfc';
4
+ import { transform as esbuildTransform } from 'esbuild';
5
+ import { compileStyleModule } from './style.js';
6
+ import { compileTemplate } from './template.js';
7
+ import { stripVueDefineComponentImport } from '../util/imports.js';
8
+ import { stripStaticComponentName } from '../util/component-name.js';
9
+ import { tokenizeStaticClasses } from '../util/class-tokenize.js';
10
+ export const SCRIPT_QUERY = 'falcon-script';
11
+ export const STYLE_QUERY = 'falcon-style';
12
+ function cleanUrl(id) {
13
+ const idx = id.indexOf('?');
14
+ return idx === -1 ? id : id.slice(0, idx);
15
+ }
16
+ function parseQuery(id) {
17
+ const idx = id.indexOf('?');
18
+ return new URLSearchParams(idx === -1 ? '' : id.slice(idx + 1));
19
+ }
20
+ function hasQuery(id, key) {
21
+ return id.includes('?') && parseQuery(id).has(key);
22
+ }
23
+ function isUnderSrc(ctx, fileId) {
24
+ return fileId.replace(/\\/g, '/').startsWith(ctx.srcDir.replace(/\\/g, '/'));
25
+ }
26
+ async function transformScript(code, lang, filename) {
27
+ const loader = lang === 'ts' || lang === 'tsx' ? 'ts' : lang === 'jsx' ? 'jsx' : 'js';
28
+ if (loader === 'js')
29
+ return code;
30
+ const result = await esbuildTransform(code, {
31
+ loader: loader === 'ts' ? 'ts' : 'jsx',
32
+ target: 'es2020',
33
+ format: 'esm',
34
+ sourcefile: filename
35
+ });
36
+ return result.code;
37
+ }
38
+ export function sfcPlugin(ctx, state) {
39
+ return {
40
+ name: 'falcon:sfc',
41
+ enforce: 'pre',
42
+ resolveId(id) {
43
+ if (hasQuery(id, SCRIPT_QUERY) || hasQuery(id, STYLE_QUERY)) {
44
+ if (path.isAbsolute(cleanUrl(id)))
45
+ return { id };
46
+ }
47
+ return null;
48
+ },
49
+ async load(id) {
50
+ const fileId = cleanUrl(id);
51
+ if (hasQuery(id, SCRIPT_QUERY)) {
52
+ const entry = state.descriptorCache.get(fileId);
53
+ const descriptor = entry?.descriptor;
54
+ const block = descriptor?.script;
55
+ if (!block)
56
+ return 'export default {}';
57
+ if (block.src) {
58
+ const src = path.resolve(path.dirname(fileId), block.src);
59
+ return `export { default } from ${JSON.stringify(src)}`;
60
+ }
61
+ let code = block.content;
62
+ const normalizedFile = fileId.replace(/\\/g, '/');
63
+ const normalizedSrc = ctx.srcDir.replace(/\\/g, '/');
64
+ const stripNames = !ctx.isDev &&
65
+ ctx.toolOptions.keepComponentNames !== true &&
66
+ normalizedFile.startsWith(normalizedSrc) &&
67
+ !ctx.pageFiles.has(path.resolve(fileId));
68
+ if (stripNames) {
69
+ const template = descriptor?.template?.content ?? '';
70
+ code = stripStaticComponentName(code, template, `${fileId}.ts`).code;
71
+ }
72
+ code = stripVueDefineComponentImport(code);
73
+ return transformScript(code, block.lang ?? 'js', fileId);
74
+ }
75
+ if (hasQuery(id, STYLE_QUERY)) {
76
+ const query = parseQuery(id);
77
+ const index = Number(query.get(STYLE_QUERY));
78
+ const scopeId = query.get('scopeId') ?? '';
79
+ const entry = state.descriptorCache.get(fileId);
80
+ if (!entry)
81
+ throw new Error(`[catchword] 缺失 SFC 缓存: ${fileId}`);
82
+ const style = entry.descriptor.styles[index];
83
+ if (!style)
84
+ throw new Error(`[catchword] 找不到 style[${index}]: ${fileId}`);
85
+ return compileStyleModule({
86
+ ctx,
87
+ state,
88
+ fileId,
89
+ index,
90
+ scopeId,
91
+ content: style.content,
92
+ lang: style.lang ?? 'css',
93
+ src: style.src,
94
+ tokenizeClasses: state.classTokensEnabled && !ctx.isDev && isUnderSrc(ctx, fileId),
95
+ tokens: state.classTokens
96
+ });
97
+ }
98
+ return null;
99
+ },
100
+ async transform(code, id) {
101
+ if (!id.endsWith('.vue'))
102
+ return null;
103
+ if (id !== cleanUrl(id))
104
+ return null;
105
+ const { descriptor, errors } = parse(code, { filename: id });
106
+ if (errors && errors.length) {
107
+ const msg = errors.map((e) => (typeof e === 'string' ? e : e.message)).join('\n');
108
+ this.error(`[catchword] SFC 解析失败 ${id}:\n${msg}`);
109
+ }
110
+ if (descriptor.scriptSetup) {
111
+ this.error(`[catchword] <script setup> 需要 runtime: 'vue3',当前设备运行时为 Vue 2.6:${id}`);
112
+ }
113
+ state.descriptorCache.set(id, { code, descriptor });
114
+ const scopeId = 'data-v-' + ctx.scopeIdFor(id);
115
+ const script = descriptor.script;
116
+ const isFunctional = Boolean(descriptor.template?.attrs?.functional);
117
+ const stripMetadata = !ctx.isDev && ctx.toolOptions.keepMetadata !== true;
118
+ const tokenizeClasses = state.classTokensEnabled && !ctx.isDev && isUnderSrc(ctx, id);
119
+ let scriptImport = 'const script = {}';
120
+ if (script) {
121
+ const lang = script.lang ?? 'js';
122
+ scriptImport = `import script from ${JSON.stringify(`${id}?${SCRIPT_QUERY}&scopeId=${scopeId}&lang=${lang}`)}`;
123
+ }
124
+ const styles = descriptor.styles ?? [];
125
+ const styleImports = [];
126
+ const styleNames = [];
127
+ styles.forEach((style, index) => {
128
+ const lang = style.lang ?? 'css';
129
+ styleNames.push(`style_${index}`);
130
+ styleImports.push(`import style_${index} from ${JSON.stringify(`${id}?${STYLE_QUERY}=${index}&scopeId=${scopeId}&lang=${lang}`)}`);
131
+ });
132
+ const styleOpts = ctx.styleOptions;
133
+ const themeKeys = ctx.getThemes();
134
+ let styleString = '';
135
+ let themesString = '';
136
+ if (styles.length > 0) {
137
+ if ((styleOpts.themes ?? []).length === 0) {
138
+ const merged = styleNames.map((name) => `${name}['_']`).join(' ,');
139
+ styleString = `Object.assign({}, ${merged})`;
140
+ }
141
+ else {
142
+ const merged = styleNames.map((name) => `${name}[cur]`).join(' ,');
143
+ themesString = `${JSON.stringify(themeKeys)}.reduce(function(acc, cur) { acc[cur] = ${merged}; return acc; }, {})`;
144
+ }
145
+ }
146
+ let templateCode = '';
147
+ let hasTemplate = false;
148
+ if (descriptor.template) {
149
+ let content = descriptor.template.content;
150
+ if (descriptor.template.src) {
151
+ const srcFile = path.resolve(path.dirname(id), descriptor.template.src);
152
+ content = fs.readFileSync(srcFile, 'utf8');
153
+ }
154
+ const compiled = compileTemplate(content, isFunctional, id, { stripMetadata });
155
+ templateCode = compiled.code;
156
+ hasTemplate = compiled.hasTemplate;
157
+ if (tokenizeClasses) {
158
+ templateCode = tokenizeStaticClasses(templateCode, state.classTokens);
159
+ }
160
+ }
161
+ const runtimeFile = stripMetadata ? '' : ctx.pathToRootUnix(id);
162
+ const out = `
163
+ import "virtual:falcon-shim";
164
+ ${scriptImport}
165
+ ${styleImports.join('\n')}
166
+ ${templateCode}
167
+ const __file = ${JSON.stringify(runtimeFile)};
168
+ const _scopeId = ${JSON.stringify(scopeId)};
169
+ const _exports = script;
170
+ ${isFunctional ? '_exports.functional = true;' : ''}
171
+ ${hasTemplate ? '_exports.render = render;\n_exports.staticRenderFns = staticRenderFns;\n_exports._compiled = true;' : ''}
172
+ _exports._scopeId = _scopeId;
173
+ _exports.themes = ${themesString || '{}'};
174
+ _exports.style = ${styleString || (themesString ? "_exports.themes['_']" : '{}')};
175
+ _exports.__file = __file;
176
+ export default _exports;
177
+ `;
178
+ return out;
179
+ }
180
+ };
181
+ }
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { AppContext } from './context.js';
3
+ export declare const SHIM_ID = "virtual:falcon-shim";
4
+ export declare function shimPlugin(ctx: AppContext): Plugin;
@@ -0,0 +1,68 @@
1
+ import { stripVueDefineComponentImport, transformRequireToImport } from '../util/imports.js';
2
+ export const SHIM_ID = 'virtual:falcon-shim';
3
+ const SHIM_RESOLVED = '\0falcon-shim';
4
+ const BS = String.fromCharCode(92);
5
+ const SCRIPT_RE = new RegExp(BS + '.(js|ts)$');
6
+ const DEFINE_RE = new RegExp(BS + 'bdefineComponent' + BS + 'b');
7
+ const REQUIRE_RE = new RegExp('require' + BS + 's*' + BS + '(');
8
+ const SHIM_CODE = `
9
+ const __g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this);
10
+ if (typeof __g.global === 'undefined') __g.global = __g;
11
+ if (typeof __g.self === 'undefined') __g.self = __g;
12
+ if (typeof __g.window === 'undefined') {
13
+ __g.window = __g;
14
+ if (typeof setTimeout === 'function' && typeof __g.requestAnimationFrame !== 'function') {
15
+ __g.requestAnimationFrame = function (cb) { return setTimeout(function () { cb(Date.now()); }, 16); };
16
+ __g.cancelAnimationFrame = function (id) { clearTimeout(id); };
17
+ }
18
+ }
19
+ if (typeof __g.defineComponent !== 'function') {
20
+ __g.defineComponent = function (options) { return options };
21
+ }
22
+ if (typeof __g.process === 'undefined') {
23
+ __g.process = { env: { NODE_ENV: 'production' } };
24
+ }
25
+ `;
26
+ function cleanUrl(id) {
27
+ const idx = id.indexOf('?');
28
+ return idx === -1 ? id : id.slice(0, idx);
29
+ }
30
+ export function shimPlugin(ctx) {
31
+ const SRC_POSIX = ctx.srcDir.split(String.fromCharCode(92)).join('/');
32
+ return {
33
+ name: 'falcon:shim',
34
+ enforce: 'pre',
35
+ resolveId(id) {
36
+ if (id === SHIM_ID || id === SHIM_RESOLVED)
37
+ return SHIM_RESOLVED;
38
+ return null;
39
+ },
40
+ load(id) {
41
+ if (id === SHIM_RESOLVED)
42
+ return SHIM_CODE;
43
+ return null;
44
+ },
45
+ transform(code, id) {
46
+ const file = cleanUrl(id);
47
+ if (id !== file)
48
+ return null;
49
+ if (!SCRIPT_RE.test(file))
50
+ return null;
51
+ if (!file.startsWith(SRC_POSIX))
52
+ return null;
53
+ let next = code;
54
+ let touched = false;
55
+ if (DEFINE_RE.test(next)) {
56
+ next = stripVueDefineComponentImport(next);
57
+ touched = true;
58
+ }
59
+ if (REQUIRE_RE.test(next)) {
60
+ next = transformRequireToImport(next);
61
+ touched = true;
62
+ }
63
+ if (!touched)
64
+ return null;
65
+ return `import ${JSON.stringify(SHIM_ID)};\n${next}`;
66
+ }
67
+ };
68
+ }
@@ -0,0 +1,31 @@
1
+ import type { SFCDescriptor } from '@vue/compiler-sfc';
2
+ export interface DescriptorEntry {
3
+ code: string;
4
+ descriptor: SFCDescriptor;
5
+ }
6
+ export declare class ClassTokenRegistry {
7
+ private readonly keep;
8
+ private map;
9
+ private index;
10
+ constructor(keep?: Set<string>);
11
+ tokenFor(name: string): string;
12
+ tokenForKey(key: string): string;
13
+ }
14
+ export declare class KeyframeTokenRegistry {
15
+ private readonly keep;
16
+ private map;
17
+ private index;
18
+ constructor(keep?: boolean);
19
+ tokenFor(name: string): string;
20
+ get(name: string): string;
21
+ }
22
+ export declare class BuildState {
23
+ keyframes: Array<Record<string, unknown>>;
24
+ internalModules: Set<string>;
25
+ descriptorCache: Map<string, DescriptorEntry>;
26
+ classTokens: ClassTokenRegistry;
27
+ classTokensEnabled: boolean;
28
+ keyframeTokens: KeyframeTokenRegistry;
29
+ encodedStrings: Set<string>;
30
+ constructor(keepKeyframeNames?: boolean);
31
+ }
@@ -0,0 +1,61 @@
1
+ export class ClassTokenRegistry {
2
+ keep;
3
+ map = new Map();
4
+ index = 0;
5
+ constructor(keep = new Set()) {
6
+ this.keep = keep;
7
+ }
8
+ tokenFor(name) {
9
+ if (this.keep.has(name))
10
+ return name;
11
+ const existing = this.map.get(name);
12
+ if (existing)
13
+ return existing;
14
+ const token = '__c' + this.index.toString(36);
15
+ this.index += 1;
16
+ this.map.set(name, token);
17
+ return token;
18
+ }
19
+ tokenForKey(key) {
20
+ if (key.startsWith('@'))
21
+ return key;
22
+ const colon = key.indexOf(':');
23
+ if (colon === -1)
24
+ return this.tokenFor(key);
25
+ return this.tokenFor(key.slice(0, colon)) + key.slice(colon);
26
+ }
27
+ }
28
+ export class KeyframeTokenRegistry {
29
+ keep;
30
+ map = new Map();
31
+ index = 0;
32
+ constructor(keep = false) {
33
+ this.keep = keep;
34
+ }
35
+ tokenFor(name) {
36
+ if (this.keep)
37
+ return name;
38
+ const existing = this.map.get(name);
39
+ if (existing)
40
+ return existing;
41
+ const token = '__k' + this.index.toString(36);
42
+ this.index += 1;
43
+ this.map.set(name, token);
44
+ return token;
45
+ }
46
+ get(name) {
47
+ return this.map.get(name) ?? name;
48
+ }
49
+ }
50
+ export class BuildState {
51
+ keyframes = [];
52
+ internalModules = new Set();
53
+ descriptorCache = new Map();
54
+ classTokens = new ClassTokenRegistry();
55
+ classTokensEnabled = false;
56
+ keyframeTokens;
57
+ encodedStrings = new Set();
58
+ constructor(keepKeyframeNames = false) {
59
+ this.keyframeTokens = new KeyframeTokenRegistry(keepKeyframeNames);
60
+ }
61
+ }
@@ -0,0 +1,7 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { AppContext } from './context.js';
3
+ import type { BuildState } from './state.js';
4
+ export declare function encodeStringValue(value: string, key: number): string;
5
+ export declare function decodeStringValue(encoded: string, key: number): string;
6
+ export declare function encodeChunk(code: string, key: number): string;
7
+ export declare function stringTablePlugin(ctx: AppContext, state: BuildState): Plugin;
@@ -0,0 +1,324 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseSync } from 'oxc-parser';
4
+ const DECODER = '__falconStr';
5
+ const DECODE_ONE = '__falconStrD';
6
+ const TABLE = '__falconStrT';
7
+ const KEY = '__falconStrK';
8
+ const SHARED_FILE = 'falcon-strings.js';
9
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
10
+ const CLASS_TOKEN_RE = /^__c[0-9a-z]+$/;
11
+ const SKIP_WORDS = new Set([
12
+ 'div',
13
+ 'text',
14
+ 'image',
15
+ 'a',
16
+ 'cell',
17
+ 'recycle-list',
18
+ 'list',
19
+ 'scroller',
20
+ 'slider',
21
+ 'indicator',
22
+ 'loading',
23
+ 'refresh',
24
+ 'header',
25
+ 'input',
26
+ 'textarea',
27
+ 'switch',
28
+ 'video',
29
+ 'web',
30
+ 'modal',
31
+ 'seekbar',
32
+ 'flex-start',
33
+ 'flex-end',
34
+ 'space-between',
35
+ 'space-around',
36
+ 'space-evenly',
37
+ 'row-reverse',
38
+ 'column-reverse',
39
+ 'center',
40
+ 'row',
41
+ 'column',
42
+ 'wrap',
43
+ 'nowrap',
44
+ 'hidden',
45
+ 'visible',
46
+ 'scroll',
47
+ 'auto',
48
+ 'none',
49
+ 'solid',
50
+ 'dashed',
51
+ 'dotted',
52
+ 'bold',
53
+ 'normal',
54
+ 'italic',
55
+ 'underline',
56
+ 'absolute',
57
+ 'relative',
58
+ 'fixed',
59
+ 'static',
60
+ 'left',
61
+ 'right',
62
+ 'top',
63
+ 'bottom',
64
+ 'middle',
65
+ 'cover',
66
+ 'contain',
67
+ 'repeat',
68
+ 'no-repeat',
69
+ 'stretch',
70
+ 'baseline',
71
+ 'inherit',
72
+ 'initial',
73
+ 'transparent',
74
+ 'pointer',
75
+ 'ellipsis'
76
+ ]);
77
+ function isSkipped(parent, key) {
78
+ if (!parent)
79
+ return false;
80
+ const type = parent.type;
81
+ if ((type === 'ImportDeclaration' ||
82
+ type === 'ExportNamedDeclaration' ||
83
+ type === 'ExportAllDeclaration') &&
84
+ key === 'source') {
85
+ return true;
86
+ }
87
+ if (type === 'ImportSpecifier' ||
88
+ type === 'ImportDefaultSpecifier' ||
89
+ type === 'ImportNamespaceSpecifier' ||
90
+ type === 'ExportSpecifier') {
91
+ return true;
92
+ }
93
+ if (type === 'Property' && key === 'key' && !parent.computed)
94
+ return true;
95
+ if ((type === 'MethodDefinition' || type === 'PropertyDefinition') &&
96
+ key === 'key' &&
97
+ !parent.computed) {
98
+ return true;
99
+ }
100
+ if (type === 'LabeledStatement' && key === 'label')
101
+ return true;
102
+ if (type === 'ExpressionStatement' && parent.directive)
103
+ return true;
104
+ if (type === 'TaggedTemplateExpression')
105
+ return true;
106
+ return false;
107
+ }
108
+ function isStyleValue(value) {
109
+ if (/^#[0-9a-f]{3,8}$/i.test(value))
110
+ return true;
111
+ if (/^-?\d+(?:\.\d+)?(?:px|em|rem|%|vw|vh|s|ms|deg)?$/i.test(value))
112
+ return true;
113
+ return SKIP_WORDS.has(value);
114
+ }
115
+ function collect(node, parent, key, refs) {
116
+ if (!node || typeof node !== 'object')
117
+ return;
118
+ if (Array.isArray(node)) {
119
+ for (const item of node)
120
+ collect(item, parent, key, refs);
121
+ return;
122
+ }
123
+ if (node.type === 'Literal' && typeof node.value === 'string') {
124
+ if (!isSkipped(parent, key) &&
125
+ typeof node.start === 'number' &&
126
+ typeof node.end === 'number') {
127
+ refs.push({ start: node.start, end: node.end, value: node.value });
128
+ }
129
+ return;
130
+ }
131
+ if (node.type === 'TemplateLiteral') {
132
+ const expressions = node.expressions ?? [];
133
+ const quasis = node.quasis ?? [];
134
+ const cooked = quasis[0]?.value?.cooked;
135
+ if (expressions.length === 0 &&
136
+ quasis.length === 1 &&
137
+ typeof cooked === 'string' &&
138
+ !isSkipped(parent, key) &&
139
+ typeof node.start === 'number' &&
140
+ typeof node.end === 'number') {
141
+ refs.push({ start: node.start, end: node.end, value: cooked });
142
+ }
143
+ return;
144
+ }
145
+ for (const childKey of Object.keys(node)) {
146
+ if (['type', 'start', 'end', 'loc', 'range', 'parent'].includes(childKey))
147
+ continue;
148
+ collect(node[childKey], node, childKey, refs);
149
+ }
150
+ }
151
+ function shouldEncode(value) {
152
+ if (value.length < 4)
153
+ return false;
154
+ if (CLASS_TOKEN_RE.test(value))
155
+ return false;
156
+ if (isStyleValue(value))
157
+ return false;
158
+ if (value === DECODER)
159
+ return false;
160
+ if (value.startsWith('data:'))
161
+ return false;
162
+ if (/^[a-z-]+\([^)]*\)$/i.test(value))
163
+ return false;
164
+ if (value.length >= 7)
165
+ return true;
166
+ if (/[\s㐀-鿿/:@?#&=]/.test(value))
167
+ return true;
168
+ if (/[A-Z]/.test(value))
169
+ return true;
170
+ return false;
171
+ }
172
+ function usableRefs(code) {
173
+ let parsed;
174
+ try {
175
+ parsed = parseSync('chunk.js', code);
176
+ }
177
+ catch {
178
+ return [];
179
+ }
180
+ const refs = [];
181
+ collect(parsed.program, null, null, refs);
182
+ return refs.filter((ref) => shouldEncode(ref.value));
183
+ }
184
+ export function encodeStringValue(value, key) {
185
+ const bytes = Buffer.from(value, 'utf16le');
186
+ for (let i = 0; i < bytes.length; i++)
187
+ bytes[i] ^= key;
188
+ return bytes.toString('base64');
189
+ }
190
+ export function decodeStringValue(encoded, key) {
191
+ const bytes = Buffer.from(encoded, 'base64');
192
+ const units = [];
193
+ for (let i = 0; i < bytes.length; i += 2) {
194
+ units.push(((bytes[i] ^ key) | (((bytes[i + 1] ?? 0) ^ key) << 8)) & 0xffff);
195
+ }
196
+ return String.fromCharCode(...units);
197
+ }
198
+ function decoderBody() {
199
+ return (`function ${DECODE_ONE}(s){var o="",n=0,x=0,b=[],c,j;` +
200
+ `for(j=0;j<s.length;j++){c="${ALPHABET}".indexOf(s[j]);if(c<0)continue;` +
201
+ `x=(x<<6)|c;n+=6;if(n>=8){n-=8;b.push((x>>n)&255)}}` +
202
+ `for(j=0;j<b.length;j+=2){o+=String.fromCharCode((((b[j]^${KEY})|` +
203
+ `((b[j+1]^${KEY})<<8))&65535))}return o}` +
204
+ `(function(){for(var i=0;i<${TABLE}.length;i++){${TABLE}[i]=${DECODE_ONE}(${TABLE}[i])}})();` +
205
+ `function ${DECODER}(i){return ${TABLE}[i]}`);
206
+ }
207
+ function inlineDecoder(table, key) {
208
+ return `var ${TABLE}=${JSON.stringify(table)},${KEY}=${key};${decoderBody()}\n`;
209
+ }
210
+ function isIdentifierChar(char) {
211
+ return !!char && /[A-Za-z0-9_$]/.test(char);
212
+ }
213
+ function replaceRefs(code, refs, indexByValue) {
214
+ const sorted = [...refs].sort((a, b) => b.start - a.start);
215
+ let output = code;
216
+ for (const ref of sorted) {
217
+ const before = code[ref.start - 1];
218
+ const after = code[ref.end];
219
+ const padBefore = isIdentifierChar(before) ? ' ' : '';
220
+ const padAfter = isIdentifierChar(after) ? ' ' : '';
221
+ output =
222
+ output.slice(0, ref.start) +
223
+ `${padBefore}${DECODER}(${indexByValue.get(ref.value)})${padAfter}` +
224
+ output.slice(ref.end);
225
+ }
226
+ return output;
227
+ }
228
+ function relativeImport(fileName) {
229
+ let rel = path.posix.relative(path.posix.dirname(fileName), SHARED_FILE);
230
+ if (!rel.startsWith('.'))
231
+ rel = './' + rel;
232
+ return rel;
233
+ }
234
+ function deriveKey(ctx) {
235
+ const seed = `${ctx.pkg.appid ?? ''}:${ctx.pkg.version ?? ''}:${ctx.pkg.name ?? ''}`;
236
+ let hash = 0;
237
+ for (let i = 0; i < seed.length; i++) {
238
+ hash = (hash * 31 + seed.charCodeAt(i)) & 0xffff;
239
+ }
240
+ return 1 + (hash % 250);
241
+ }
242
+ export function encodeChunk(code, key) {
243
+ const refs = usableRefs(code);
244
+ if (refs.length === 0)
245
+ return code;
246
+ const indexByValue = new Map();
247
+ const table = [];
248
+ for (const ref of refs) {
249
+ if (!indexByValue.has(ref.value)) {
250
+ indexByValue.set(ref.value, table.length);
251
+ table.push(encodeStringValue(ref.value, key));
252
+ }
253
+ }
254
+ return inlineDecoder(table, key) + replaceRefs(code, refs, indexByValue);
255
+ }
256
+ export function stringTablePlugin(ctx, state) {
257
+ let sharedSource = null;
258
+ return {
259
+ name: 'falcon:string-table',
260
+ apply: 'build',
261
+ enforce: 'post',
262
+ generateBundle(_options, bundle) {
263
+ sharedSource = null;
264
+ if (ctx.toolOptions.keepStrings === true)
265
+ return;
266
+ const key = deriveKey(ctx);
267
+ const plans = [];
268
+ for (const [fileName, item] of Object.entries(bundle)) {
269
+ if (item.type !== 'chunk' || typeof item.code !== 'string')
270
+ continue;
271
+ const refs = usableRefs(item.code);
272
+ if (refs.length > 0) {
273
+ plans.push({ fileName, code: item.code, refs });
274
+ for (const ref of refs)
275
+ state.encodedStrings.add(ref.value);
276
+ }
277
+ }
278
+ if (plans.length === 0)
279
+ return;
280
+ if (plans.length === 1) {
281
+ const plan = plans[0];
282
+ const indexByValue = new Map();
283
+ const table = [];
284
+ for (const ref of plan.refs) {
285
+ if (!indexByValue.has(ref.value)) {
286
+ indexByValue.set(ref.value, table.length);
287
+ table.push(encodeStringValue(ref.value, key));
288
+ }
289
+ }
290
+ const item = bundle[plan.fileName];
291
+ if (item.type === 'chunk') {
292
+ item.code =
293
+ inlineDecoder(table, key) + replaceRefs(plan.code, plan.refs, indexByValue);
294
+ }
295
+ return;
296
+ }
297
+ const indexByValue = new Map();
298
+ const table = [];
299
+ for (const plan of plans) {
300
+ for (const ref of plan.refs) {
301
+ if (!indexByValue.has(ref.value)) {
302
+ indexByValue.set(ref.value, table.length);
303
+ table.push(encodeStringValue(ref.value, key));
304
+ }
305
+ }
306
+ }
307
+ const shared = `var ${TABLE}=${JSON.stringify(table)},${KEY}=${key};` +
308
+ `${decoderBody()}export{${DECODER}};\n`;
309
+ sharedSource = shared;
310
+ for (const plan of plans) {
311
+ const item = bundle[plan.fileName];
312
+ if (item.type !== 'chunk')
313
+ continue;
314
+ const code = replaceRefs(plan.code, plan.refs, indexByValue);
315
+ item.code = `import{${DECODER}}from ${JSON.stringify(relativeImport(plan.fileName))};\n${code}`;
316
+ }
317
+ },
318
+ closeBundle() {
319
+ if (!sharedSource || !fs.existsSync(ctx.buildDir))
320
+ return;
321
+ fs.writeFileSync(path.join(ctx.buildDir, SHARED_FILE), sharedSource);
322
+ }
323
+ };
324
+ }