vite-plugin-autojs6 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ /**
2
+ * AutoJs6 内置模块名.
3
+ *
4
+ * 这些名称在 `import ... from '<name>'` 时会被插件拦截, 转换成运行时的
5
+ * `require('<name>')` (若同名全局对象已存在则直接取全局), 不会被打包器
6
+ * 当成「找不到的依赖」而报错.
7
+ */
8
+ export declare const DEFAULT_BUILTIN_MODULES: readonly string[];
9
+ /** 判断标识符能否直接写成 JS 变量名 (用于读取同名全局对象) */
10
+ export declare function isIdentifier(name: string): boolean;
11
+ /**
12
+ * 生成内置模块的虚拟模块代码.
13
+ *
14
+ * 优先读取同名全局对象 (`ui` / `app` 等在 AutoJs6 中本身就是全局变量),
15
+ * 不存在的再走 `require()` (如 `fs` / `path` / `lodash`).
16
+ *
17
+ * 注意: 只支持默认导入 (`import ui from 'ui'`). 具名导入
18
+ * (`import { launch } from 'app'`) 无法在编译期枚举出真实的键,
19
+ * 需要具名 API 请使用 `vite-plugin-autojs6` 提供的运行时.
20
+ */
21
+ export declare function builtinModuleCode(name: string): string;
@@ -0,0 +1,44 @@
1
+ import type { DeployOptions } from "./options";
2
+ /**
3
+ * 通过 AutoJs6 VSCode 扩展把产物目录同步到手机.
4
+ *
5
+ * 扩展在激活时 (VSCode 启动即激活) 会监听一个本机 HTTP 命令桥,
6
+ * `GET /exec?cmd=saveProject&path=<项目目录>` 就能触发它的「保存项目到设备」命令.
7
+ * 这条通道是「发完立即返回 200」的语义, 拿不到同步结果, 所以这里只承诺
8
+ * 「请求已送达扩展」, 失败原因也只在变化时上报一次, 免得 watch 模式刷屏.
9
+ */
10
+ /** 扩展 HTTP 命令桥的默认端口 (`autojs6.http.port` 的默认值). */
11
+ export declare const DEFAULT_HTTP_PORT = 10347;
12
+ /** 选项名 → 扩展命令名. 两者都在扩展的 HTTP 白名单里. */
13
+ declare const COMMANDS: {
14
+ readonly save: "saveProject";
15
+ readonly run: "runProject";
16
+ };
17
+ /** 规范化后的同步配置. */
18
+ export interface DeploySettings {
19
+ command: (typeof COMMANDS)[keyof typeof COMMANDS];
20
+ host: string;
21
+ port: number;
22
+ timeout: number;
23
+ silent: boolean;
24
+ }
25
+ export interface DeployLogger {
26
+ info(message: string): void;
27
+ warn(message: string): void;
28
+ }
29
+ export interface Deployer {
30
+ /**
31
+ * 触发一次同步. 返回值用于拼接构建日志, `null` 表示本次跳过.
32
+ * 请求是 fire-and-forget, 不会阻塞构建.
33
+ */
34
+ trigger(projectDir: string): string | null;
35
+ }
36
+ /** 规范化 `deploy` 选项; 未启用或当前模式不命中时返回 `null`. */
37
+ export declare function resolveDeploy(options: DeployOptions | false | undefined, root: string, mode: string): DeploySettings | null;
38
+ /**
39
+ * 读取工作区 `.vscode/settings.json` 里的 `autojs6.http.port`.
40
+ * settings.json 允许注释, 用正则取值而不是 JSON.parse.
41
+ */
42
+ export declare function readExtensionPort(root: string): number | undefined;
43
+ export declare function createDeployer(settings: DeploySettings, logger: DeployLogger): Deployer;
44
+ export {};
@@ -0,0 +1,341 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const http = require("node:http");
6
+ const DEFAULT_BUILTIN_MODULES = [
7
+ // AutoJs6 augmentable API (既可作为全局对象使用, 也可 require 载入)
8
+ "app",
9
+ "auto",
10
+ "automator",
11
+ "barcode",
12
+ "base64",
13
+ "canvas",
14
+ "colors",
15
+ "console",
16
+ "continuation",
17
+ "crypto",
18
+ "device",
19
+ "dialogs",
20
+ "engines",
21
+ "events",
22
+ "files",
23
+ "floaty",
24
+ "flow",
25
+ "http",
26
+ "i18n",
27
+ "images",
28
+ "media",
29
+ "mediainfo",
30
+ "notice",
31
+ "ocr",
32
+ "opencc",
33
+ "pinyin",
34
+ "qrcode",
35
+ "sensors",
36
+ "shell",
37
+ "shizuku",
38
+ "speech",
39
+ "sqlite",
40
+ "storages",
41
+ "threads",
42
+ "timers",
43
+ "toast",
44
+ "tts",
45
+ "ui",
46
+ "util",
47
+ "web",
48
+ "zip",
49
+ // Node.js 兼容模块 (6.8.0 起由「脚本库」插件提供)
50
+ "fs",
51
+ "path",
52
+ "os",
53
+ "process",
54
+ "buffer",
55
+ "nodejs",
56
+ "lodash",
57
+ "axios",
58
+ "cheerio",
59
+ "dayjs",
60
+ "pangu",
61
+ // 其他内置资源模块
62
+ "result-adapter"
63
+ ];
64
+ function isIdentifier(name2) {
65
+ return /^[A-Za-z_$][\w$]*$/.test(name2);
66
+ }
67
+ function builtinModuleCode(name2) {
68
+ const fallback = `require(${JSON.stringify(name2)})`;
69
+ if (!isIdentifier(name2)) {
70
+ return `export default ${fallback};`;
71
+ }
72
+ return [
73
+ `/* AutoJs6 内置模块: ${name2} */`,
74
+ `var __autojs6Module = typeof ${name2} !== 'undefined' ? ${name2} : ${fallback};`,
75
+ "export default __autojs6Module;"
76
+ ].join("\n");
77
+ }
78
+ const name = "vite-plugin-autojs6";
79
+ const DEFAULT_HTTP_PORT = 10347;
80
+ const COMMANDS = {
81
+ save: "saveProject",
82
+ run: "runProject"
83
+ };
84
+ const TAG = `\x1B[36m[${name}]\x1B[0m`;
85
+ function resolveDeploy(options, root, mode) {
86
+ if (!options || options.enabled === false || !matchMode(options.modes, mode)) {
87
+ return null;
88
+ }
89
+ return {
90
+ command: COMMANDS[options.command ?? "save"],
91
+ host: options.host ?? "127.0.0.1",
92
+ port: options.port ?? readExtensionPort(root) ?? DEFAULT_HTTP_PORT,
93
+ timeout: options.timeout ?? 1500,
94
+ silent: options.onError === "silent"
95
+ };
96
+ }
97
+ function matchMode(modes, mode) {
98
+ if (!modes || modes === "dev") {
99
+ return mode.startsWith("development");
100
+ }
101
+ return modes === "all" || modes.includes(mode);
102
+ }
103
+ function readExtensionPort(root) {
104
+ try {
105
+ const text = fs.readFileSync(path.join(root, ".vscode", "settings.json"), "utf8");
106
+ const matched = /"autojs6\.http\.port"\s*:\s*(\d+)/.exec(text);
107
+ return matched ? Number(matched[1]) : void 0;
108
+ } catch {
109
+ return void 0;
110
+ }
111
+ }
112
+ function createDeployer(settings, logger) {
113
+ const target = `${settings.host}:${settings.port}`;
114
+ let inflight = false;
115
+ let lastError = "";
116
+ function report(message) {
117
+ if (settings.silent || message === lastError) {
118
+ return;
119
+ }
120
+ lastError = message;
121
+ logger.warn(`${TAG} ${message}`);
122
+ }
123
+ return {
124
+ trigger(projectDir) {
125
+ if (!fs.existsSync(path.join(projectDir, "project.json"))) {
126
+ report(
127
+ "产物目录缺少 project.json, 已跳过同步到设备.\n AutoJs6 依赖它识别项目, 请确认 assets 选项包含 project.json."
128
+ );
129
+ return null;
130
+ }
131
+ if (inflight) {
132
+ return null;
133
+ }
134
+ inflight = true;
135
+ void (async () => {
136
+ try {
137
+ await sendProject(settings, projectDir);
138
+ if (lastError) {
139
+ lastError = "";
140
+ logger.info(`${TAG} 已恢复与 VSCode 扩展的连接 (${target})`);
141
+ }
142
+ } catch (error) {
143
+ report(describeError(error, settings, target));
144
+ } finally {
145
+ inflight = false;
146
+ }
147
+ })();
148
+ return `已请求同步到设备 (${target})`;
149
+ }
150
+ };
151
+ }
152
+ function sendProject(settings, projectDir) {
153
+ const query = `cmd=${encodeURIComponent(settings.command)}&path=${encodeURIComponent(projectDir)}`;
154
+ return new Promise((resolve, reject) => {
155
+ const request = http.request(
156
+ {
157
+ host: settings.host,
158
+ port: settings.port,
159
+ path: `/exec?${query}`,
160
+ method: "GET",
161
+ agent: false,
162
+ timeout: settings.timeout
163
+ },
164
+ (response) => {
165
+ response.resume();
166
+ response.on("end", () => resolve());
167
+ }
168
+ );
169
+ request.on("timeout", () => {
170
+ request.destroy(new Error(`timeout after ${settings.timeout}ms`));
171
+ });
172
+ request.on("error", reject);
173
+ request.end();
174
+ });
175
+ }
176
+ function describeError(error, settings, target) {
177
+ if (error.code === "ECONNREFUSED") {
178
+ return `无法连接 VSCode 扩展的 HTTP 命令桥 (${target}): 端口无人监听.
179
+ 请确认 VSCode 已打开且 AutoJs6 扩展已连接设备;
180
+ 不需要自动同步时把 deploy 设为 false (或删掉 deploy 选项).`;
181
+ }
182
+ if (error.code === "ETIMEDOUT" || /timeout/i.test(error.message ?? "")) {
183
+ return `VSCode 扩展响应超时 (${target}, ${settings.timeout}ms), 本次同步可能未完成.`;
184
+ }
185
+ return `同步到设备失败 (${target}): ${error.message || String(error)}`;
186
+ }
187
+ const VIRTUAL_PREFIX = `\0${name}:builtin:`;
188
+ const DEFAULT_ASSETS = ["project.json", "res", "images"];
189
+ function autojs6(options = {}) {
190
+ const {
191
+ entry = "src/main.ts",
192
+ uiEntry,
193
+ outDir = "dist",
194
+ fileName = "main.js",
195
+ uiMode = false,
196
+ assets = DEFAULT_ASSETS,
197
+ builtinModules = [],
198
+ target = "es2018",
199
+ banner = "",
200
+ define = {},
201
+ strict = false,
202
+ log = true,
203
+ deploy
204
+ } = options;
205
+ const builtinSet = /* @__PURE__ */ new Set([...DEFAULT_BUILTIN_MODULES, ...builtinModules]);
206
+ let resolved;
207
+ let isDev = false;
208
+ let entryFile = entry;
209
+ let deployer = null;
210
+ return {
211
+ name,
212
+ // 必须先于 vite:resolve 拦截内置模块名
213
+ enforce: "pre",
214
+ config(userConfig, env) {
215
+ const root = path.resolve(userConfig.root ?? process.cwd());
216
+ isDev = !env.mode.startsWith("production");
217
+ const useUiEntry = uiMode && !!uiEntry && fs.existsSync(path.resolve(root, uiEntry));
218
+ entryFile = useUiEntry ? uiEntry : entry;
219
+ return {
220
+ build: {
221
+ outDir,
222
+ emptyOutDir: true,
223
+ target,
224
+ minify: options.minify ?? !isDev,
225
+ sourcemap: options.sourcemap ?? false,
226
+ reportCompressedSize: false,
227
+ // 产物是给移动端脚本引擎用的, 体积警告没有意义
228
+ chunkSizeWarningLimit: 4096,
229
+ lib: {
230
+ entry: path.resolve(root, entryFile),
231
+ formats: ["cjs"],
232
+ fileName: () => fileName
233
+ },
234
+ rollupOptions: {
235
+ output: {
236
+ format: "cjs",
237
+ entryFileNames: fileName,
238
+ // 运行时没有 import() 能力, 动态导入必须内联
239
+ inlineDynamicImports: true,
240
+ exports: "auto",
241
+ // 默认不写 "use strict": AutoJs6 脚本不需要它, 产物保持干净
242
+ strict
243
+ }
244
+ }
245
+ },
246
+ define: {
247
+ ...define
248
+ }
249
+ };
250
+ },
251
+ configResolved(config) {
252
+ resolved = config;
253
+ const settings = resolveDeploy(deploy, config.root, config.mode);
254
+ deployer = settings ? createDeployer(settings, config.logger) : null;
255
+ },
256
+ buildStart() {
257
+ const file = path.resolve(resolved.root, entryFile);
258
+ if (!fs.existsSync(file)) {
259
+ this.error(
260
+ `找不到入口脚本: ${path.relative(resolved.root, file)}
261
+ 请检查 autojs6() 的 entry 选项.`
262
+ );
263
+ }
264
+ },
265
+ resolveId(source) {
266
+ if (builtinSet.has(source)) {
267
+ return VIRTUAL_PREFIX + source;
268
+ }
269
+ return null;
270
+ },
271
+ load(id) {
272
+ if (id.startsWith(VIRTUAL_PREFIX)) {
273
+ return builtinModuleCode(id.slice(VIRTUAL_PREFIX.length));
274
+ }
275
+ return null;
276
+ },
277
+ /**
278
+ * 产物头部由这里写入, 而不是用 `output.banner`.
279
+ *
280
+ * 原因: `"ui";` 必须是脚本的第一个有效语句, 并且要在压缩之后写入,
281
+ * 否则头部注释会被 minifier 删掉. 没有 `"ui";` 和自定义 banner 时
282
+ * 不写任何头部, 产物第一行就是代码.
283
+ */
284
+ generateBundle(_outputOptions, bundle) {
285
+ const prefix = buildBanner({ uiMode, banner });
286
+ for (const chunk of Object.values(bundle)) {
287
+ if (chunk.type === "chunk" && chunk.isEntry) {
288
+ if (prefix) {
289
+ chunk.code = prefix + "\n" + chunk.code;
290
+ }
291
+ if (!uiMode && /\bui\.(layout|layoutFile)\s*\(/.test(chunk.code)) {
292
+ resolved.logger.warn(
293
+ '检测到 ui.layout* 调用, 但当前不是 UI 模式 (产物缺少首行 "ui";).\n 请用 npm run dev:ui / npm run build:ui 构建, 或在 autojs6() 里设置 uiMode: true.',
294
+ { timestamp: true }
295
+ );
296
+ }
297
+ break;
298
+ }
299
+ }
300
+ },
301
+ writeBundle(_outputOptions, bundle) {
302
+ const root = resolved.root;
303
+ const outDirAbs = path.resolve(root, resolved.build.outDir);
304
+ const copied = [];
305
+ for (const asset of assets === false ? [] : assets) {
306
+ const from = path.resolve(root, asset);
307
+ const to = path.resolve(outDirAbs, asset);
308
+ if (to === from || from.startsWith(outDirAbs + path.sep)) continue;
309
+ if (!fs.existsSync(from)) continue;
310
+ fs.cpSync(from, to, { recursive: true, dereference: true, preserveTimestamps: true });
311
+ copied.push(asset);
312
+ }
313
+ const deployHint = deployer?.trigger(outDirAbs) ?? null;
314
+ if (!log) {
315
+ return;
316
+ }
317
+ const mainAsset = bundle[fileName];
318
+ const size = mainAsset && "code" in mainAsset ? Buffer.byteLength(mainAsset.code) : 0;
319
+ const kb = (size / 1024).toFixed(1);
320
+ const tag = isDev ? "dev" : "build";
321
+ const ui = uiMode ? " · UI 模式" : "";
322
+ resolved.logger.info(
323
+ `\x1B[36m[${name}]\x1B[0m ${tag} 产物 → ${path.relative(root, path.join(outDirAbs, fileName))} (${kb} kB)${ui}` + (copied.length ? ` · 已同步 ${copied.join(", ")}` : "") + (deployHint ? ` · ${deployHint}` : ""),
324
+ { timestamp: true }
325
+ );
326
+ }
327
+ };
328
+ }
329
+ function buildBanner(input) {
330
+ const lines = [];
331
+ if (input.uiMode) {
332
+ lines.push('"ui";');
333
+ }
334
+ if (input.banner) {
335
+ lines.push(input.banner);
336
+ }
337
+ return lines.join("\n");
338
+ }
339
+ exports.DEFAULT_BUILTIN_MODULES = DEFAULT_BUILTIN_MODULES;
340
+ exports.autojs6 = autojs6;
341
+ exports.default = autojs6;
@@ -0,0 +1,13 @@
1
+ /// <reference types="@sm003/autojs6-dts" />
2
+ /**
3
+ * vite-plugin-autojs6
4
+ *
5
+ * AutoJs6 的 Vite 构建插件: 把 TypeScript + ESM 源码打成 AutoJs6 可直接执行的单文件脚本.
6
+ *
7
+ * 脚本里不需要从这里 import 任何东西 —— `device` / `app` / `ocr` / `images` 等都是
8
+ * AutoJs6 的全局对象, 直接使用即可; 代码提示由 `@sm003/autojs6-dts` 提供.
9
+ */
10
+ export { autojs6 } from "./autojs6";
11
+ export { autojs6 as default } from "./autojs6";
12
+ export { DEFAULT_BUILTIN_MODULES } from "./builtin";
13
+ export type { AutoJs6Options, DeployOptions } from "./options";