miaoda-react-devkit 0.1.1-beta.22 → 0.1.1-beta.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/lint.mjs ADDED
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { dirname, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const require = createRequire(import.meta.url);
10
+ const devkitRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
11
+
12
+ // 从 devkit 自己的依赖解析工具,兼容 pnpm 隔离安装与发布后的独立项目。
13
+ function resolveBin(packageName, binName) {
14
+ const packageJson = require.resolve(`${packageName}/package.json`, { paths: [devkitRoot] });
15
+ const metadata = JSON.parse(readFileSync(packageJson, 'utf8'));
16
+ const declaredBin = typeof metadata.bin === 'string' ? metadata.bin : metadata.bin?.[binName];
17
+ if (!declaredBin) {
18
+ throw new Error(`${packageName} 未声明 ${binName} 命令`);
19
+ }
20
+ return join(dirname(packageJson), declaredBin);
21
+ }
22
+
23
+ // lint 依赖 devkit 的构建产物(Oxlint 插件与 HTML 检查器)。发布包自带 dist;
24
+ // workspace 源码检出尚未构建时自动补一次构建,避免 lint 因产物缺失直接失败。
25
+ function ensureDevkitBuild() {
26
+ const artifacts = [
27
+ join(devkitRoot, 'dist/oxlint/index.js'),
28
+ join(devkitRoot, 'dist/html/check.js'),
29
+ ];
30
+ if (artifacts.every(path => existsSync(path))) {
31
+ return;
32
+ }
33
+ const build = spawnSync('pnpm', ['run', 'build'], { cwd: devkitRoot, stdio: 'inherit' });
34
+ if (build.error || build.status !== 0 || !artifacts.every(path => existsSync(path))) {
35
+ throw new Error('devkit 构建产物缺失,请先执行 pnpm --filter miaoda-react-devkit build');
36
+ }
37
+ }
38
+
39
+ try {
40
+ ensureDevkitBuild();
41
+ const result = spawnSync('bash', [join(devkitRoot, 'lint/lint.sh')], {
42
+ cwd: process.cwd(),
43
+ stdio: 'inherit',
44
+ env: {
45
+ ...process.env,
46
+ DEVKIT_ROOT: devkitRoot,
47
+ DEVKIT_TSGO: resolveBin('@typescript/native-preview', 'tsgo'),
48
+ DEVKIT_BIOME: resolveBin('@biomejs/biome', 'biome'),
49
+ DEVKIT_OXLINT: resolveBin('oxlint', 'oxlint'),
50
+ },
51
+ });
52
+ if (result.error) {
53
+ console.error(`无法启动 lint:${result.error.message}`);
54
+ }
55
+ process.exit(result.status ?? 1);
56
+ } catch (error) {
57
+ console.error(`无法启动 lint:${error.message}`);
58
+ process.exit(1);
59
+ }
package/bin/smoke.mjs ADDED
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+
3
+ // devkit-smoke 命令入口:只负责定位构建产物并转发调用,实际逻辑在 src/smoke(构建到 dist/smoke/cli.js)。
4
+ // 与 devkit-lint 一致:发布包自带 dist;workspace 源码检出尚未构建时自动补一次构建。
5
+
6
+ import { spawnSync } from 'node:child_process';
7
+ import { existsSync } from 'node:fs';
8
+ import { dirname, join, resolve } from 'node:path';
9
+ import { pathToFileURL, fileURLToPath } from 'node:url';
10
+
11
+ const devkitRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
12
+ const cliPath = join(devkitRoot, 'dist/smoke/cli.js');
13
+
14
+ function ensureCliBuild() {
15
+ if (existsSync(cliPath)) {
16
+ return;
17
+ }
18
+ // 发布包永远自带 dist,此分支只会在 workspace 源码检出中触发。
19
+ console.error(
20
+ '[startup-smoke] 尚未构建(缺少 dist/smoke/cli.js),正在自动构建 miaoda-react-devkit…',
21
+ );
22
+ const build = spawnSync('pnpm', ['run', 'build'], { cwd: devkitRoot, stdio: 'inherit' });
23
+ if (build.error || build.status !== 0 || !existsSync(cliPath)) {
24
+ console.error(
25
+ '[startup-smoke] 自动构建失败。请先安装依赖,再在仓库根目录手动执行:pnpm --filter miaoda-react-devkit build',
26
+ );
27
+ process.exit(1);
28
+ }
29
+ }
30
+
31
+ // 计时开关与 src/smoke/timing.ts 的约定一致:关闭时直接透传,不做包装。
32
+ // stages 数组贯穿 CLI 全生命周期,最终由 dist 侧写入 startup.timing.json;
33
+ // 这里只补齐 dist 加载之前无法在 CLI 内计时的阶段。
34
+ const verboseTiming = process.env.DEVKIT_SMOKE_TIMING === '1';
35
+ const stages = [];
36
+ if (verboseTiming) {
37
+ // exit 事件兜底打印 Node 总耗时(含进程退出前的同步清理):
38
+ // 用 shell `real` 减去它,可估算 pnpm 启动等 CLI 之外的耗时。
39
+ process.once('exit', () => {
40
+ console.error(`[startup-smoke:timing] Node elapsed ${Math.round(performance.now())}ms`);
41
+ });
42
+ }
43
+
44
+ // 与 SmokeTimings.measure 同构:找不到 dist(构建失败)时 CLI 层还没加载,
45
+ // 这两个前置阶段只能在这里记录;同样只在开启计时时才包装。
46
+ async function measure(stage, action) {
47
+ if (!verboseTiming) {
48
+ return action();
49
+ }
50
+ const startMs = Math.round(performance.now());
51
+ console.error(`[startup-smoke:timing] +${startMs}ms ${stage} start`);
52
+ let status = 'error';
53
+ try {
54
+ const result = await action();
55
+ status = 'completed';
56
+ return result;
57
+ } finally {
58
+ const durationMs = Math.round(performance.now()) - startMs;
59
+ stages.push({ stage, startMs, durationMs, status });
60
+ console.error(`[startup-smoke:timing] ${stage} ${status} ${durationMs}ms`);
61
+ }
62
+ }
63
+
64
+ try {
65
+ await measure('cli.ensure-build', ensureCliBuild);
66
+ // 应用侧依赖(vite)在 CLI 内部以应用目录为基准解析,此处无需注入任何路径。
67
+ const { runStartupSmokeCli } = await measure(
68
+ 'cli.import',
69
+ () => import(pathToFileURL(cliPath).href),
70
+ );
71
+ await runStartupSmokeCli(undefined, stages);
72
+ } catch (error) {
73
+ console.error(`[startup-smoke] FAIL: ${error instanceof Error ? error.message : String(error)}`);
74
+ process.exit(1);
75
+ }
@@ -0,0 +1,47 @@
1
+ {
2
+ "vcs": {
3
+ "enabled": true,
4
+ "clientKind": "git",
5
+ "useIgnoreFile": true
6
+ },
7
+ "linter": {
8
+ "enabled": true,
9
+ "rules": {
10
+ "recommended": false,
11
+ "correctness": {
12
+ "noUndeclaredDependencies": "error",
13
+ "useHookAtTopLevel": "error"
14
+ },
15
+ "suspicious": {
16
+ "noRedeclare": "error"
17
+ },
18
+ "style": {
19
+ "noCommonJs": "error"
20
+ }
21
+ }
22
+ },
23
+ "formatter": {
24
+ "enabled": false
25
+ },
26
+ "css": {
27
+ "parser": {
28
+ "cssModules": false,
29
+ "allowWrongLineComments": false,
30
+ "tailwindDirectives": true
31
+ }
32
+ },
33
+ "overrides": [
34
+ {
35
+ "includes": [
36
+ "tailwind.config.js"
37
+ ],
38
+ "linter": {
39
+ "rules": {
40
+ "style": {
41
+ "noCommonJs": "off"
42
+ }
43
+ }
44
+ }
45
+ }
46
+ ]
47
+ }
@@ -1,14 +1,15 @@
1
1
  // cloud/vite.config.ts
2
2
  import * as vite from "vite";
3
3
  import { loadConfigFromFile, mergeConfig } from "vite";
4
- import { hmrTogglePlugin, extractRouterPlugin } from "../dist/vite/index.js";
4
+ import { hmrTogglePlugin } from "../dist/vite/index.js";
5
5
  import {
6
6
  makeTagger,
7
7
  injectedGuiListenerPlugin,
8
8
  injectOnErrorPlugin,
9
9
  fontsCodePlugin,
10
10
  mdClickPlugin,
11
- patchSupabasePlugins
11
+ patchSupabasePlugins,
12
+ extractRouterPlugin
12
13
  } from "miaoda-sc-plugin";
13
14
  import path from "path";
14
15
  import fs from "fs";
@@ -16,9 +17,6 @@ var projectRoot = process.cwd();
16
17
  var appType = process.env.DEVKIT_APP_TYPE ?? "freestyle";
17
18
  var cdnHost = process.env.DEVKIT_CDN_HOST ?? "resource-static.cdn.bcebos.com";
18
19
  var env = process.env.DEVKIT_ENV ?? "";
19
- var sentryDsn = process.env.DEVKIT_SENTRY_DSN ?? "";
20
- var miaodaEnv = process.env.DEVKIT_MIAODA_ENV ?? "";
21
- var appId = process.env.DEVKIT_APP_ID ?? "";
22
20
  var isOnline = env === "online";
23
21
  var loaded = await loadConfigFromFile(
24
22
  { command: "serve", mode: "development" },
@@ -0,0 +1,9 @@
1
+ interface HtmlDiagnostic {
2
+ message: string;
3
+ line: number;
4
+ column: number;
5
+ }
6
+ declare function checkHtml(source: string): HtmlDiagnostic[];
7
+ declare function checkHtmlFile(filePath: string): HtmlDiagnostic[];
8
+
9
+ export { type HtmlDiagnostic, checkHtml, checkHtmlFile };
@@ -0,0 +1,54 @@
1
+ // src/html/check.ts
2
+ import { readFileSync } from "fs";
3
+ import { parse } from "parse5";
4
+ var FORBIDDEN_VALUES = /* @__PURE__ */ new Set([
5
+ "content-security-policy",
6
+ "content-security-policy-report-only",
7
+ "x-frame-options"
8
+ ]);
9
+ var MESSAGE = "\u7981\u6B62\u5728 index.html \u5199\u5B89\u5168\u54CD\u5E94\u5934 meta\u3002\u53D1\u5E03\u6001 CSP \u7531\u5E73\u53F0\u4EE5 HTTP \u54CD\u5E94\u5934\u7EDF\u4E00\u4E0B\u53D1\uFF1B\u5B89\u5168\u52A0\u56FA\u8BF7\u5728\u4EE3\u7801\u5C42\u505A\uFF1ARLS\u3001\u8F93\u5165\u6821\u9A8C\u3001\u8F93\u51FA\u8F6C\u4E49\u3002";
10
+ function locationForOffset(source, offset) {
11
+ const before = source.slice(0, offset);
12
+ const line = before.split("\n").length;
13
+ const lastNewline = before.lastIndexOf("\n");
14
+ return { line, column: offset - lastNewline };
15
+ }
16
+ function walk(node, callback) {
17
+ callback(node);
18
+ for (const child of node.childNodes ?? []) walk(child, callback);
19
+ }
20
+ function checkHtml(source) {
21
+ const document = parse(source, { sourceCodeLocationInfo: true });
22
+ const diagnostics = [];
23
+ walk(document, (node) => {
24
+ if (node.nodeName?.toLowerCase() !== "meta") return;
25
+ const httpEquiv = node.attrs?.find((attr) => attr.name.toLowerCase() === "http-equiv");
26
+ if (!httpEquiv || !FORBIDDEN_VALUES.has(httpEquiv.value.trim().toLowerCase())) return;
27
+ const offset = node.sourceCodeLocation?.startTag?.startOffset ?? node.sourceCodeLocation?.startOffset ?? 0;
28
+ const location = locationForOffset(source, offset);
29
+ diagnostics.push({ ...location, message: MESSAGE });
30
+ });
31
+ return diagnostics;
32
+ }
33
+ function checkHtmlFile(filePath) {
34
+ return checkHtml(readFileSync(filePath, "utf8"));
35
+ }
36
+ if (process.argv[1] && process.argv[1].endsWith("check.js")) {
37
+ const filePath = process.argv[2] ?? "index.html";
38
+ try {
39
+ const diagnostics = checkHtmlFile(filePath);
40
+ for (const diagnostic of diagnostics) {
41
+ process.stderr.write(`${filePath}:${diagnostic.line}:${diagnostic.column}: error: ${diagnostic.message}
42
+ `);
43
+ }
44
+ process.exitCode = diagnostics.length > 0 ? 1 : 0;
45
+ } catch (error) {
46
+ process.stderr.write(`\u65E0\u6CD5\u68C0\u67E5 HTML \u6587\u4EF6 ${filePath}: ${error instanceof Error ? error.message : String(error)}
47
+ `);
48
+ process.exitCode = 1;
49
+ }
50
+ }
51
+ export {
52
+ checkHtml,
53
+ checkHtmlFile
54
+ };
@@ -0,0 +1,5 @@
1
+ import { Plugin } from '@oxlint/plugins';
2
+
3
+ declare const plugin: Plugin;
4
+
5
+ export { plugin as default };
@@ -0,0 +1,226 @@
1
+ // src/oxlint/astUtils.ts
2
+ function nodeName(node) {
3
+ if (!node) return void 0;
4
+ if (typeof node.name === "string") return node.name;
5
+ if (node.name?.type === "JSXIdentifier" || node.name?.type === "Identifier") return node.name.name;
6
+ return node.name?.property?.name ?? node.property?.name;
7
+ }
8
+ function openingElement(node) {
9
+ return node?.type === "JSXElement" ? node.openingElement : node?.type === "JSXOpeningElement" ? node : void 0;
10
+ }
11
+ function attributes(node) {
12
+ return openingElement(node)?.attributes ?? [];
13
+ }
14
+ function attribute(node, name) {
15
+ return attributes(node).find((item) => item.type === "JSXAttribute" && nodeName(item.name) === name);
16
+ }
17
+ function hasAttribute(node, name) {
18
+ return attribute(node, name) !== void 0;
19
+ }
20
+ function staticString(value) {
21
+ if (!value) return void 0;
22
+ if (value.type === "Literal" && typeof value.value === "string") return value.value;
23
+ if (value.type === "TemplateLiteral" && value.expressions?.length === 0) {
24
+ return value.quasis?.[0]?.value?.cooked ?? value.quasis?.[0]?.value?.raw;
25
+ }
26
+ if (value.type === "JSXExpressionContainer") return staticString(value.expression);
27
+ return void 0;
28
+ }
29
+ function attributeString(node, name) {
30
+ return staticString(attribute(node, name)?.value);
31
+ }
32
+ function hasClassToken(value, token) {
33
+ return value?.split(/\s+/).includes(token) ?? false;
34
+ }
35
+ function hasClassPrefix(value, pattern) {
36
+ return value?.split(/\s+/).some((token) => pattern.test(token)) ?? false;
37
+ }
38
+ function ancestors(node) {
39
+ const result = [];
40
+ let current = node.parent;
41
+ while (current) {
42
+ result.push(current);
43
+ current = current.parent;
44
+ }
45
+ return result;
46
+ }
47
+ function report(context, node, message) {
48
+ context.report({ node, message });
49
+ }
50
+ function spreadMayProvideInteraction(node) {
51
+ for (const attr of attributes(node)) {
52
+ if (attr.type !== "JSXSpreadAttribute") continue;
53
+ const argument = attr.argument;
54
+ if (!argument || argument.type !== "ObjectExpression") return true;
55
+ for (const prop of argument.properties ?? []) {
56
+ if (prop.type !== "Property") return true;
57
+ if (prop.computed && prop.key?.type !== "Literal") return true;
58
+ const name = propertyName(prop);
59
+ if (name === "onClick" || name === "asChild") return true;
60
+ const value = propertyString(prop);
61
+ if (name === "type" && (value === "submit" || value === "reset")) return true;
62
+ }
63
+ }
64
+ return false;
65
+ }
66
+ function isJsxElementNamed(node, pattern) {
67
+ const opening = openingElement(node);
68
+ return pattern.test(nodeName(opening?.name) ?? "");
69
+ }
70
+ function directChildNamed(node, name) {
71
+ return (node.children ?? []).some((child) => isJsxElementNamed(child, new RegExp(`^${name}$`)));
72
+ }
73
+ function propertyName(node) {
74
+ if (!node) return void 0;
75
+ if (node.key?.type === "Identifier" && !node.computed) return node.key.name;
76
+ if (node.key?.type === "Literal" && typeof node.key.value === "string") return node.key.value;
77
+ return void 0;
78
+ }
79
+ function propertyString(node) {
80
+ return staticString(node?.value);
81
+ }
82
+ function isSupabaseInvoke(node) {
83
+ const callee = node.callee;
84
+ return callee?.type === "MemberExpression" && !callee.computed && callee.property?.name === "invoke" && callee.object?.type === "MemberExpression" && !callee.object.computed && callee.object.property?.name === "functions" && callee.object.object?.type === "Identifier" && callee.object.object.name === "supabase";
85
+ }
86
+
87
+ // src/oxlint/rules/index.ts
88
+ var BUTTON = /^Button$/;
89
+ var TRIGGER = /^(Popover|Dialog|DropdownMenu|AlertDialog|HoverCard|Menubar|NavigationMenu|ContextMenu|Tooltip)Trigger$/;
90
+ var ANY_TRIGGER = /Trigger$/;
91
+ function jsxRule(visitor) {
92
+ return { create: () => visitor };
93
+ }
94
+ function selectItemRule(context) {
95
+ return jsxRule({
96
+ JSXElement(node) {
97
+ const opening = openingElement(node);
98
+ if (!isJsxElementNamed(opening, /^SelectItem$/)) return;
99
+ const value = attribute(opening, "value");
100
+ if (value && staticString(value.value) === "") {
101
+ report(context, value, "\u68C0\u6D4B\u5230 SelectItem \u7EC4\u4EF6\u4F7F\u7528\u7A7A\u5B57\u7B26\u4E32 value\uFF0C\u8FD9\u662F\u9519\u8BEF\u7528\u6CD5\uFF0C\u8FD0\u884C\u65F6\u4F1A\u62A5\u9519\uFF0C\u8BF7\u4FEE\u6539\uFF1B\u5982\u679C\u60F3\u5B9E\u73B0\u5168\u9009\uFF0C\u5EFA\u8BAE\u4F7F\u7528 all \u4EE3\u66FF\u7A7A\u5B57\u7B26\u4E32\u3002");
102
+ }
103
+ }
104
+ });
105
+ }
106
+ function contrastRule(kind, context) {
107
+ return jsxRule({
108
+ JSXElement(node) {
109
+ const opening = openingElement(node);
110
+ if (!opening || !isJsxElementNamed(opening, BUTTON)) return;
111
+ const variant = attributeString(opening, "variant");
112
+ const className = attributeString(opening, "className");
113
+ if (kind === "foreground" && variant === "outline" && hasClassToken(className, "text-foreground")) {
114
+ report(context, opening, "Outline \u6309\u94AE\u4F7F\u7528 text-foreground class \u4F1A\u5BFC\u81F4\u6587\u5B57\u4E0D\u53EF\u89C1\u3002\u8BE5\u53D8\u4F53\u80CC\u666F\u900F\u660E\uFF0Ctext-foreground \u4F1A\u4E0E\u80CC\u666F\u878D\u5408\u800C\u65E0\u6CD5\u9605\u8BFB\u3002\u8BF7\u6539\u7528 text-primary \u6216\u5176\u4ED6\u6709\u8DB3\u591F\u5BF9\u6BD4\u5EA6\u7684\u989C\u8272\u3002");
115
+ }
116
+ if (kind === "primary" && !hasAttribute(opening, "variant") && hasClassToken(className, "text-primary")) {
117
+ report(context, opening, "Default \u6309\u94AE\u4F7F\u7528 text-primary class \u4F1A\u5BFC\u81F4\u5BF9\u6BD4\u5EA6\u4E0D\u8DB3\u3002\u8BE5\u53D8\u4F53\u4F7F\u7528\u4E3B\u8272\u80CC\u666F\uFF0Ctext-primary \u4F1A\u4E0E\u80CC\u666F\u878D\u5408\u800C\u96BE\u4EE5\u9605\u8BFB\u3002\u8BF7\u79FB\u9664 text-primary\uFF0C\u6216\u6539\u7528 outline\u3001ghost \u7B49\u53D8\u4F53\u3002");
118
+ }
119
+ if (kind === "white-gray" && variant === "outline" && hasClassPrefix(className, /^text-(white|gray)(?:-[0-9]+)?$/)) {
120
+ report(context, opening, "Outline \u6309\u94AE\u4F7F\u7528\u767D\u8272\u6216\u7070\u8272\u6587\u5B57\u65F6\u5BF9\u6BD4\u5EA6\u4E0D\u8DB3\u3002\u8BF7\u79FB\u9664\u6587\u5B57\u989C\u8272 class\uFF0C\u4F7F\u7528\u6309\u94AE\u9ED8\u8BA4\u6587\u5B57\u989C\u8272\u3002");
121
+ }
122
+ }
123
+ });
124
+ }
125
+ function slotNestingRule(context) {
126
+ return jsxRule({
127
+ JSXElement(node) {
128
+ const opening = openingElement(node);
129
+ if (!opening || !isJsxElementNamed(opening, TRIGGER) || !hasAttribute(opening, "asChild")) return;
130
+ if (directChildNamed(node, "FormControl")) {
131
+ report(context, opening, "\u68C0\u6D4B\u5230\u5371\u9669\u7684 Slot \u5D4C\u5957\uFF1ARadix UI Trigger (asChild) \u5185\u5305\u88F9 FormControl\u3002FormControl \u548C Trigger \u90FD\u4F7F\u7528 Radix \u7684 Slot \u673A\u5236\uFF0C\u53CC\u5C42\u5D4C\u5957\u4F1A\u5BFC\u81F4 ref \u4F20\u9012\u94FE\u65AD\u88C2\u3001\u70B9\u51FB\u4E8B\u4EF6\u4E22\u5931\uFF0C\u5185\u90E8\u7EC4\u4EF6\u65E0\u6CD5\u4EA4\u4E92\u3002");
132
+ }
133
+ }
134
+ });
135
+ }
136
+ function requireButtonInteractionRule(context) {
137
+ return jsxRule({
138
+ JSXElement(node) {
139
+ const opening = openingElement(node);
140
+ if (!opening || !isJsxElementNamed(opening, BUTTON)) return;
141
+ if (hasAttribute(opening, "onClick") || hasAttribute(opening, "asChild")) return;
142
+ const type = attributeString(opening, "type");
143
+ if (type === "submit" || type === "reset") return;
144
+ if (spreadMayProvideInteraction(opening)) return;
145
+ const exempt = ancestors(node).some((parent) => {
146
+ if (parent.type !== "JSXElement") return false;
147
+ return isJsxElementNamed(parent, ANY_TRIGGER) || isJsxElementNamed(parent, /^(Link|a)$/);
148
+ });
149
+ if (!exempt) {
150
+ report(context, opening, '<Button> \u5FC5\u987B\u662F\u53EF\u70B9\u51FB\u7684\uFF0C\u8BF7\u786E\u4FDD\u5176\u70B9\u51FB\u540E\u7684\u903B\u8F91\u5DF2\u7F16\u5199\u3002\u8BF7\u6DFB\u52A0 onClick\u3001type="submit"\u3001type="reset"\u3001asChild \u5C5E\u6027\uFF0C\u6216\u5C06\u5176\u5305\u88F9\u5728 *Trigger \u7EC4\u4EF6\u4E2D\uFF0C\u6216 <Link> \u6216 <a> \u4E2D\u3002');
151
+ }
152
+ }
153
+ });
154
+ }
155
+ function toastImportRule(context) {
156
+ return {
157
+ create: () => ({
158
+ ImportDeclaration(node) {
159
+ if (staticString(node.source) !== "@/hooks/use-toast") return;
160
+ if (node.specifiers?.some((item) => item.type === "ImportSpecifier")) {
161
+ report(context, node, '\u8BF7\u4F7F\u7528 import { toast } from "sonner"\uFF0C\u4E0D\u8981\u5BFC\u5165 "@/hooks/use-toast"\u3002');
162
+ }
163
+ }
164
+ })
165
+ };
166
+ }
167
+ function googleSsoRule(context) {
168
+ return {
169
+ create: () => ({
170
+ CallExpression(node) {
171
+ const callee = node.callee;
172
+ if (callee?.type !== "MemberExpression" || callee.computed || callee.property?.name !== "signInWithOAuth") return;
173
+ const arg = node.arguments?.[0];
174
+ if (!arg || arg.type !== "ObjectExpression") return;
175
+ const provider = arg.properties?.find((item) => propertyName(item) === "provider");
176
+ if (propertyString(provider) === "google") {
177
+ report(context, node, "Supabase Google \u767B\u5F55\u8BF7\u5C06 `signInWithOAuth` \u66FF\u6362\u4E3A `signInWithSSO`\u3002\u8BF7\u4F7F\u7528 domain: 'miaoda-gg.com'\uFF0C\u5E76\u786E\u4FDD window.open \u4F7F\u7528 `_self` \u76EE\u6807\u3002");
178
+ }
179
+ }
180
+ })
181
+ };
182
+ }
183
+ function edgeGetBodyRule(context) {
184
+ return {
185
+ create: () => ({
186
+ CallExpression(node) {
187
+ if (!isSupabaseInvoke(node)) return;
188
+ const options = node.arguments?.find((arg) => arg.type === "ObjectExpression");
189
+ if (!options) return;
190
+ const method = options.properties?.find((item) => propertyName(item) === "method");
191
+ const body = options.properties?.find((item) => propertyName(item) === "body");
192
+ if (propertyString(method)?.toUpperCase() === "GET" && body) {
193
+ report(context, node, "GET \u8BF7\u6C42\u4E0D\u80FD\u643A\u5E26 body\uFF1Asupabase.functions.invoke \u4F7F\u7528 method: 'GET' \u65F6\u53C2\u6570\u5FC5\u987B\u62FC\u63A5\u5728 URL \u91CC\u3002");
194
+ }
195
+ }
196
+ })
197
+ };
198
+ }
199
+ function makeRule(factory) {
200
+ return {
201
+ create(context) {
202
+ return factory(context).create();
203
+ }
204
+ };
205
+ }
206
+ var rules = {
207
+ "select-item-with-empty-value": makeRule(selectItemRule),
208
+ "button-outline-text-foreground-contrast": makeRule((context) => contrastRule("foreground", context)),
209
+ "button-default-text-primary-contrast": makeRule((context) => contrastRule("primary", context)),
210
+ "button-outline-white-gray-contrast": makeRule((context) => contrastRule("white-gray", context)),
211
+ "radix-trigger-formcontrol-nesting": makeRule(slotNestingRule),
212
+ "require-button-interaction": makeRule(requireButtonInteractionRule),
213
+ "use-toast-import": makeRule(toastImportRule),
214
+ "supabase-google-sso": makeRule(googleSsoRule),
215
+ "supabase-edge-function-get-with-body": makeRule(edgeGetBodyRule)
216
+ };
217
+
218
+ // src/oxlint/index.ts
219
+ var plugin = {
220
+ meta: { name: "miaoda" },
221
+ rules
222
+ };
223
+ var oxlint_default = plugin;
224
+ export {
225
+ oxlint_default as default
226
+ };
@@ -0,0 +1,501 @@
1
+ // src/smoke/cli.ts
2
+ import { mkdir, mkdtemp, writeFile as writeFile2 } from "fs/promises";
3
+ import { join as join3, relative as relative2 } from "path";
4
+
5
+ // src/smoke/findEntry.ts
6
+ import { readFile, stat } from "fs/promises";
7
+ import { join } from "path";
8
+ var SCRIPT_TAG_RE = /<script\b[^>]*>/gi;
9
+ function readAttr(tag, name) {
10
+ const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i"));
11
+ if (match === null) {
12
+ return void 0;
13
+ }
14
+ return match[1] ?? match[2] ?? match[3];
15
+ }
16
+ function isLocalSrc(src) {
17
+ return src !== "" && !src.startsWith("//") && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(src);
18
+ }
19
+ async function classifyEntry(root) {
20
+ let html;
21
+ try {
22
+ html = await readFile(join(root, "index.html"), "utf8");
23
+ } catch (error) {
24
+ if (error.code === "ENOENT") {
25
+ return { skip: "index.html was not found in the application directory" };
26
+ }
27
+ throw error;
28
+ }
29
+ const missing = [];
30
+ let hasLocalEntry = false;
31
+ for (const tag of html.match(SCRIPT_TAG_RE) ?? []) {
32
+ if (readAttr(tag, "type")?.trim().toLowerCase() !== "module") {
33
+ continue;
34
+ }
35
+ const src = readAttr(tag, "src");
36
+ if (src === void 0) {
37
+ hasLocalEntry = true;
38
+ continue;
39
+ }
40
+ const value = src.trim();
41
+ if (!isLocalSrc(value)) {
42
+ continue;
43
+ }
44
+ hasLocalEntry = true;
45
+ const entryPath = join(root, value);
46
+ try {
47
+ if (!(await stat(entryPath)).isFile()) {
48
+ missing.push(entryPath);
49
+ }
50
+ } catch (error) {
51
+ const code = error.code;
52
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
53
+ throw error;
54
+ }
55
+ missing.push(entryPath);
56
+ }
57
+ }
58
+ if (missing.length > 0) {
59
+ throw new Error(`index.html references missing module entries: ${missing.join(", ")}`);
60
+ }
61
+ return hasLocalEntry ? { entry: true } : { skip: "index.html does not declare a local module entry" };
62
+ }
63
+
64
+ // src/smoke/runStartupSmoke.ts
65
+ import { existsSync } from "fs";
66
+ import { writeFile } from "fs/promises";
67
+ import { createRequire } from "module";
68
+ import { join as join2, relative } from "path";
69
+ import { pathToFileURL } from "url";
70
+ import { chromium } from "playwright";
71
+
72
+ // src/smoke/inspectStartup.ts
73
+ import { setTimeout as delay } from "timers/promises";
74
+ var criticalResourceTypes = /* @__PURE__ */ new Set(["document", "script", "stylesheet", "fetch", "xhr"]);
75
+ var navigationTimeoutMs = 3e4;
76
+ var firstScreenTimeoutMs = 15e3;
77
+ var requestSettleTimeoutMs = 5e3;
78
+ function reportUrl(value) {
79
+ const url = new URL(value);
80
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin + url.pathname : url.protocol;
81
+ }
82
+ function describeRequest(request) {
83
+ return {
84
+ method: request.method(),
85
+ url: reportUrl(request.url()),
86
+ type: request.resourceType()
87
+ };
88
+ }
89
+ function hasVisibleContent() {
90
+ const inViewport = (rect) => rect.width > 0 && rect.height > 0 && rect.bottom > 0 && rect.right > 0 && rect.top < innerHeight && rect.left < innerWidth;
91
+ const visible = (element) => element.checkVisibility({ opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true });
92
+ const body = document.body;
93
+ if (body === null) {
94
+ return false;
95
+ }
96
+ const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
97
+ const range = document.createRange();
98
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
99
+ const parent = node.parentElement;
100
+ if (parent === null || node.textContent?.trim() === "") {
101
+ continue;
102
+ }
103
+ if (parent.closest("script,style,template,noscript,svg") !== null) {
104
+ continue;
105
+ }
106
+ if (!visible(parent) && getComputedStyle(parent).display !== "contents") {
107
+ continue;
108
+ }
109
+ range.selectNodeContents(node);
110
+ if (Array.from(range.getClientRects()).some(inViewport)) {
111
+ return true;
112
+ }
113
+ }
114
+ return Array.from(body.querySelectorAll(
115
+ "img, svg, canvas, video, iframe, button, input, select, textarea, [contenteditable]"
116
+ )).some(
117
+ (element) => (!(element instanceof HTMLImageElement) || element.naturalWidth > 0) && visible(element) && inViewport(element.getBoundingClientRect())
118
+ );
119
+ }
120
+ async function inspectPixels(screenshot) {
121
+ const bytes = Uint8Array.from(atob(screenshot), (char) => char.charCodeAt(0));
122
+ const image = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
123
+ const width = 160;
124
+ const height = 100;
125
+ const canvas = document.createElement("canvas");
126
+ canvas.width = width;
127
+ canvas.height = height;
128
+ const context = canvas.getContext("2d", { willReadFrequently: true });
129
+ if (context === null) {
130
+ throw new Error("Could not inspect screenshot pixels");
131
+ }
132
+ context.drawImage(image, 0, 0, width, height);
133
+ image.close();
134
+ const { data } = context.getImageData(0, 0, width, height);
135
+ const quantCounts = /* @__PURE__ */ new Map();
136
+ const exactColors = /* @__PURE__ */ new Set();
137
+ const total = width * height;
138
+ let dominant = 0;
139
+ for (let index = 0; index < data.length; index += 4) {
140
+ const r = data[index];
141
+ const g = data[index + 1];
142
+ const b = data[index + 2];
143
+ exactColors.add(r << 16 | g << 8 | b);
144
+ const bucket = r >> 4 << 8 | g >> 4 << 4 | b >> 4;
145
+ const next = (quantCounts.get(bucket) ?? 0) + 1;
146
+ quantCounts.set(bucket, next);
147
+ if (next > dominant) {
148
+ dominant = next;
149
+ }
150
+ }
151
+ const mainColorRatio = dominant / total;
152
+ const uniqColors = exactColors.size;
153
+ return { mainColorRatio, uniqColors, nearlyUniform: mainColorRatio >= 0.99 || uniqColors <= 12 };
154
+ }
155
+ async function inspectStartup(page, startUrl, timings) {
156
+ const pending = /* @__PURE__ */ new Set();
157
+ const navigationErrors = [];
158
+ const pageErrors = [];
159
+ const consoleErrors = [];
160
+ const consoleWarnings = [];
161
+ const networkErrors = [];
162
+ const networkObservations = [];
163
+ const reviewNotes = [];
164
+ page.on("request", (request) => {
165
+ if (request.resourceType() === "fetch" || request.resourceType() === "xhr") {
166
+ pending.add(request);
167
+ }
168
+ });
169
+ page.on("response", (response) => {
170
+ if (response.status() < 400) {
171
+ return;
172
+ }
173
+ const request = response.request();
174
+ const issues = criticalResourceTypes.has(request.resourceType()) ? networkErrors : networkObservations;
175
+ issues.push({ ...describeRequest(request), status: response.status() });
176
+ });
177
+ page.on("requestfinished", (request) => {
178
+ pending.delete(request);
179
+ });
180
+ page.on("requestfailed", (request) => {
181
+ pending.delete(request);
182
+ const reason = request.failure()?.errorText ?? "request failed";
183
+ const issues = reason === "net::ERR_ABORTED" || !criticalResourceTypes.has(request.resourceType()) ? networkObservations : networkErrors;
184
+ issues.push({ ...describeRequest(request), reason });
185
+ });
186
+ page.on("pageerror", (error) => {
187
+ pageErrors.push(error.stack ?? error.message);
188
+ });
189
+ page.on("crash", () => {
190
+ pageErrors.push("The browser page crashed");
191
+ });
192
+ page.on("console", (message) => {
193
+ if (message.type() === "warning") {
194
+ consoleWarnings.push(message.text());
195
+ }
196
+ if (message.type() !== "error" || message.args().length === 0) {
197
+ return;
198
+ }
199
+ const { url, lineNumber, columnNumber } = message.location();
200
+ consoleErrors.push({
201
+ text: message.text(),
202
+ source: url ? `${reportUrl(url)}:${lineNumber + 1}:${columnNumber + 1}` : ""
203
+ });
204
+ });
205
+ let documentStatus = null;
206
+ const navigationStartedAt = performance.now();
207
+ try {
208
+ const response = await timings.measure(
209
+ "page.navigate",
210
+ () => page.goto(startUrl, { waitUntil: "domcontentloaded", timeout: navigationTimeoutMs })
211
+ );
212
+ documentStatus = response?.status() ?? null;
213
+ } catch (error) {
214
+ navigationErrors.push(error instanceof Error ? error.message : String(error));
215
+ }
216
+ const navigationDurationMs = Math.round(performance.now() - navigationStartedAt);
217
+ if (documentStatus !== null && documentStatus < 400) {
218
+ await timings.measure(
219
+ "page.wait-visible",
220
+ () => page.waitForFunction(hasVisibleContent, void 0, { timeout: firstScreenTimeoutMs })
221
+ ).catch(() => {
222
+ });
223
+ await timings.measure("page.render-grace", () => delay(300));
224
+ await timings.measure("page.wait-requests", async () => {
225
+ const deadline = performance.now() + requestSettleTimeoutMs;
226
+ while (pending.size > 0 && performance.now() < deadline) {
227
+ await delay(50);
228
+ }
229
+ });
230
+ }
231
+ let visibleContent = false;
232
+ let pixels = null;
233
+ let screenshot;
234
+ try {
235
+ visibleContent = await timings.measure("page.check-visible", () => page.evaluate(hasVisibleContent));
236
+ screenshot = await timings.measure("page.screenshot", async () => {
237
+ const cdp = await page.context().newCDPSession(page);
238
+ const shot = await cdp.send("Page.captureScreenshot", { format: "png" });
239
+ return Buffer.from(shot.data, "base64");
240
+ });
241
+ pixels = await timings.measure("page.inspect-pixels", () => page.evaluate(inspectPixels, screenshot.toString("base64")));
242
+ } catch (error) {
243
+ reviewNotes.push(`First-screen capture: ${error instanceof Error ? error.message : String(error)}`);
244
+ }
245
+ if (!visibleContent && pixels !== null && !pixels.nearlyUniform) {
246
+ reviewNotes.push("The screenshot contains visual detail, but no visible text, control or media was detected.");
247
+ }
248
+ const firstScreen = { looksBlank: pixels?.nearlyUniform ?? !visibleContent, visibleContent, pixels };
249
+ let title = "";
250
+ let textHead = "";
251
+ try {
252
+ title = await page.title();
253
+ textHead = (await page.evaluate(() => document.body?.innerText ?? "")).trim().slice(0, 200);
254
+ } catch {
255
+ }
256
+ return {
257
+ screenshot,
258
+ diagnostics: {
259
+ startUrl: reportUrl(startUrl),
260
+ finalUrl: reportUrl(page.url()),
261
+ documentStatus,
262
+ navigationDurationMs,
263
+ firstScreen,
264
+ title,
265
+ textHead,
266
+ navigationErrors,
267
+ pageErrors,
268
+ consoleErrors,
269
+ networkErrors,
270
+ networkObservations,
271
+ pendingRequests: [...pending].map(describeRequest),
272
+ consoleWarnings,
273
+ reviewNotes
274
+ }
275
+ };
276
+ }
277
+
278
+ // src/smoke/runStartupSmoke.ts
279
+ var BROWSER_EXECUTABLE_CANDIDATES = [
280
+ "/usr/bin/chromium",
281
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
282
+ ];
283
+ function errorText(error) {
284
+ return error instanceof Error ? error.message : String(error);
285
+ }
286
+ function errorStack(error) {
287
+ return error instanceof Error ? error.stack ?? error.message : String(error);
288
+ }
289
+ async function resolveAppVite(root) {
290
+ let vitePath;
291
+ try {
292
+ vitePath = createRequire(join2(root, "package.json")).resolve("vite");
293
+ } catch {
294
+ throw new Error("\u672A\u80FD\u5728\u5E94\u7528\u76EE\u5F55\u89E3\u6790 vite\uFF0C\u8BF7\u786E\u8BA4\u5E94\u7528\u5DF2\u5B89\u88C5\u4F9D\u8D56\uFF08pnpm install\uFF09");
295
+ }
296
+ return import(pathToFileURL(vitePath).href);
297
+ }
298
+ async function launchChromium() {
299
+ const executablePath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH || BROWSER_EXECUTABLE_CANDIDATES.find((path) => existsSync(path));
300
+ return chromium.launch({
301
+ executablePath,
302
+ timeout: 15e3,
303
+ // 沙箱容器内常以 root 运行,Chromium 缺 --no-sandbox 会直接拒绝启动;
304
+ // --disable-dev-shm-usage 避开容器 /dev/shm 偏小的问题,--disable-gpu 免依赖 GPU。
305
+ args: ["--no-sandbox", "--disable-dev-shm-usage", "--disable-gpu"]
306
+ });
307
+ }
308
+ function collectStartupFailures(diagnostics) {
309
+ const failures = [];
310
+ if (diagnostics.documentStatus === null || diagnostics.documentStatus < 200 || diagnostics.documentStatus >= 300) {
311
+ failures.push({ check: "homepage document status", details: diagnostics.documentStatus });
312
+ }
313
+ if (diagnostics.firstScreen.looksBlank) {
314
+ failures.push({ check: "first screen appears blank" });
315
+ }
316
+ const collections = [
317
+ ["homepage navigation errors", diagnostics.navigationErrors],
318
+ ["uncaught page errors", diagnostics.pageErrors],
319
+ ["console.error during startup", diagnostics.consoleErrors],
320
+ ["failed startup network requests", diagnostics.networkErrors]
321
+ ];
322
+ for (const [check, details] of collections) {
323
+ if (details.length > 0) {
324
+ failures.push({ check, details });
325
+ }
326
+ }
327
+ return failures;
328
+ }
329
+ async function runStartupSmoke({ root, output, timings }) {
330
+ const failures = [];
331
+ let server;
332
+ let browser;
333
+ let context;
334
+ let diagnostics = null;
335
+ let screenshot;
336
+ let trace;
337
+ try {
338
+ const browserLaunching = timings.measure("browser.launch", launchChromium);
339
+ void browserLaunching.then(
340
+ (launched) => {
341
+ browser = launched;
342
+ },
343
+ () => {
344
+ }
345
+ // 失败由下方 Promise.all 抛出并统一记录,这里只防未处理拒绝
346
+ );
347
+ const [viteServer, chromiumBrowser] = await Promise.all([
348
+ timings.measure("vite.start", async () => {
349
+ const { createServer } = await timings.measure("vite.import", () => resolveAppVite(root));
350
+ const started = await timings.measure("vite.create-server", () => createServer({
351
+ root,
352
+ // 依赖预构建缓存指到本次运行目录,不污染应用自身的 node_modules/.vite。
353
+ cacheDir: join2(output, "vite-cache"),
354
+ server: { host: "127.0.0.1", port: 0, open: false, hmr: false }
355
+ }));
356
+ server = started;
357
+ await timings.measure("vite.listen", () => started.listen());
358
+ return started;
359
+ }),
360
+ browserLaunching
361
+ ]);
362
+ browser = chromiumBrowser;
363
+ const url = viteServer.resolvedUrls?.local[0];
364
+ if (url === void 0) {
365
+ throw new Error("Vite \u672A\u8FD4\u56DE\u672C\u5730\u8BBF\u95EE\u5730\u5740");
366
+ }
367
+ const browserContext = await timings.measure(
368
+ "browser.new-context",
369
+ () => chromiumBrowser.newContext({ viewport: { width: 1280, height: 800 } })
370
+ );
371
+ context = browserContext;
372
+ await timings.measure(
373
+ "trace.start",
374
+ () => browserContext.tracing.start({ screenshots: true, snapshots: true, sources: true })
375
+ );
376
+ const page = await timings.measure("browser.new-page", () => browserContext.newPage());
377
+ const result = await inspectStartup(page, url, timings);
378
+ diagnostics = result.diagnostics;
379
+ failures.push(...collectStartupFailures(diagnostics));
380
+ const screenshotBytes = result.screenshot;
381
+ if (screenshotBytes !== void 0) {
382
+ await timings.measure("artifact.write-screenshot", () => writeFile(join2(output, "startup.png"), screenshotBytes));
383
+ screenshot = relative(root, join2(output, "startup.png"));
384
+ }
385
+ } catch (error) {
386
+ failures.push({ check: "smoke runner error", details: errorStack(error) });
387
+ } finally {
388
+ const contextRef = context;
389
+ const browserRef = browser;
390
+ const serverRef = server;
391
+ const cleanupSteps = [];
392
+ if (contextRef !== void 0) {
393
+ cleanupSteps.push(["trace.stop", "save Playwright trace", async () => {
394
+ if (failures.length > 0) {
395
+ const tracePath = join2(output, "startup.trace.zip");
396
+ await contextRef.tracing.stop({ path: tracePath });
397
+ trace = relative(root, tracePath);
398
+ } else {
399
+ await contextRef.tracing.stop();
400
+ }
401
+ }]);
402
+ cleanupSteps.push(["browser.close-context", "close browser context", () => contextRef.close()]);
403
+ }
404
+ if (browserRef !== void 0) {
405
+ cleanupSteps.push(["browser.close", "close browser", () => browserRef.close()]);
406
+ }
407
+ if (serverRef !== void 0) {
408
+ cleanupSteps.push(["vite.close", "close Vite server", () => serverRef.close()]);
409
+ }
410
+ for (const [stage, check, action] of cleanupSteps) {
411
+ try {
412
+ await timings.measure(stage, action);
413
+ } catch (error) {
414
+ failures.push({ check, details: errorText(error) });
415
+ }
416
+ }
417
+ }
418
+ return { status: failures.length > 0 ? "failed" : "passed", failures, diagnostics, screenshot, trace };
419
+ }
420
+
421
+ // src/smoke/timing.ts
422
+ var SmokeTimings = class {
423
+ constructor(stages = [], enabled = process.env.DEVKIT_SMOKE_TIMING === "1") {
424
+ this.stages = stages;
425
+ this.enabled = enabled;
426
+ }
427
+ stages;
428
+ enabled;
429
+ /**
430
+ * 测量一个阶段:记录起点、终点与状态后原样返回动作结果。
431
+ * 实时日志在每个阶段开始前就打印,进程卡死时能直接看到停在哪个阶段。
432
+ */
433
+ async measure(stage, action) {
434
+ if (!this.enabled) {
435
+ return action();
436
+ }
437
+ const start = performance.now();
438
+ console.error(`[startup-smoke:timing] +${Math.round(start)}ms ${stage} start`);
439
+ let status = "error";
440
+ try {
441
+ const result = await action();
442
+ status = "completed";
443
+ return result;
444
+ } finally {
445
+ const durationMs = Math.round(performance.now() - start);
446
+ this.stages.push({ stage, startMs: Math.round(start), durationMs, status });
447
+ console.error(`[startup-smoke:timing] ${stage} ${status} ${durationMs}ms`);
448
+ }
449
+ }
450
+ };
451
+
452
+ // src/smoke/cli.ts
453
+ async function runStartupSmokeCli(root = process.cwd(), stages = []) {
454
+ const timings = new SmokeTimings(stages);
455
+ const entry = await timings.measure("cli.classify-entry", () => classifyEntry(root));
456
+ if ("skip" in entry) {
457
+ console.log(`[startup-smoke] SKIP: ${entry.skip}`);
458
+ return;
459
+ }
460
+ const output = await timings.measure("cli.prepare-output", async () => {
461
+ const resultsDir = join3(root, "test-results");
462
+ await mkdir(resultsDir, { recursive: true });
463
+ return mkdtemp(join3(resultsDir, "startup-"));
464
+ });
465
+ const result = await runStartupSmoke({ root, output, timings });
466
+ const reportPath = join3(output, "startup.json");
467
+ const report = { checkedAt: (/* @__PURE__ */ new Date()).toISOString(), ...result };
468
+ await timings.measure("cli.write-report", () => writeFile2(reportPath, `${JSON.stringify(report, null, 2)}
469
+ `));
470
+ if (timings.enabled) {
471
+ const timingReport = {
472
+ nodeStartedAt: new Date(performance.timeOrigin).toISOString(),
473
+ reportWrittenMs: Math.round(performance.now()),
474
+ stages
475
+ };
476
+ try {
477
+ await timings.measure(
478
+ "cli.write-timing",
479
+ () => writeFile2(join3(output, "startup.timing.json"), `${JSON.stringify(timingReport, null, 2)}
480
+ `)
481
+ );
482
+ } catch (error) {
483
+ console.error(`[startup-smoke:timing] ${error instanceof Error ? error.message : String(error)}`);
484
+ }
485
+ }
486
+ if (result.status === "passed") {
487
+ console.log("[startup-smoke] PASS: homepage loaded, painted content, and started without errors");
488
+ return;
489
+ }
490
+ process.exitCode = 1;
491
+ console.error("[startup-smoke] FAIL");
492
+ for (const { check, details } of result.failures) {
493
+ const suffix = details === void 0 ? "" : `: ${typeof details === "string" ? details : JSON.stringify(details)}`;
494
+ console.error(`- ${check}${suffix}`);
495
+ }
496
+ console.log("Startup smoke diagnostics for this failure:");
497
+ console.log(`- app report (page errors, console errors, failed network requests): ${relative2(root, reportPath)}`);
498
+ }
499
+ export {
500
+ runStartupSmokeCli
501
+ };
@@ -36,7 +36,7 @@ __export(vite_exports, {
36
36
  });
37
37
  module.exports = __toCommonJS(vite_exports);
38
38
 
39
- // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.26_typescript@5.9.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js
39
+ // node_modules/tsup/assets/cjs_shims.js
40
40
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
41
41
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
42
42
 
package/lint/check.sh ADDED
@@ -0,0 +1,33 @@
1
+ #!/bin/bash
2
+
3
+ # 执行 Oxlint 自定义规则和 index.html 安全响应头检查。
4
+
5
+ # 默认使用 devkit 内置的 Oxlint 配置;应用根目录放置 .oxlintrc.json 可覆盖。
6
+ if [ -f "$PWD/.oxlintrc.json" ]; then
7
+ OX_CONFIG="$PWD/.oxlintrc.json"
8
+ else
9
+ OX_CONFIG="$DEVKIT_ROOT/oxlint-config.json"
10
+ fi
11
+
12
+ OX_BIN="${DEVKIT_OXLINT:-$(command -v oxlint || true)}"
13
+ if [ -z "$OX_BIN" ]; then
14
+ echo "无法找到 oxlint 可执行文件。"
15
+ OX_STATUS=1
16
+ else
17
+ "$OX_BIN" --config "$OX_CONFIG" "$PWD/src"
18
+ OX_STATUS=$?
19
+ fi
20
+
21
+ HTML_CHECKER="$DEVKIT_ROOT/dist/html/check.js"
22
+ if [ ! -f "$HTML_CHECKER" ]; then
23
+ echo "无法找到 HTML 检查器:$HTML_CHECKER"
24
+ HTML_STATUS=1
25
+ else
26
+ node "$HTML_CHECKER" "$PWD/index.html"
27
+ HTML_STATUS=$?
28
+ fi
29
+
30
+ if [ "$OX_STATUS" -ne 0 ] || [ "$HTML_STATUS" -ne 0 ]; then
31
+ exit 1
32
+ fi
33
+ exit 0
package/lint/lint.sh ADDED
@@ -0,0 +1,97 @@
1
+ #!/bin/bash
2
+ # 按原有顺序执行类型、Biome、自定义规则、Tailwind、构建和包体积检查。
3
+ # 即使某个阶段失败,仍执行后续阶段,最后汇总并输出 SUCCESS / ERROR 标记。
4
+
5
+ FAILED=""
6
+ SUMMARY=""
7
+
8
+ record() {
9
+ local name="$1" ok="$2"
10
+ if [ "$ok" -eq 0 ]; then
11
+ SUMMARY="$SUMMARY$name: OK
12
+ "
13
+ else
14
+ SUMMARY="$SUMMARY$name: FAIL
15
+ "
16
+ FAILED="$FAILED $name"
17
+ fi
18
+ }
19
+
20
+ "$DEVKIT_TSGO" -p tsconfig.check.json
21
+ record "tsgo" $?
22
+
23
+ "$DEVKIT_BIOME" lint
24
+ record "biome" $?
25
+
26
+ # check.sh 统一执行 Oxlint 与 HTML 检查器,依据退出码判断阶段结果。
27
+ bash "$DEVKIT_ROOT/lint/check.sh"
28
+ record "customRules" $?
29
+
30
+ CSS_OUTPUT=$(tailwindcss -i ./src/index.css -o /dev/null 2>&1)
31
+ CSS_STATUS=$?
32
+ CSS_ERRORS=$(printf '%s' "$CSS_OUTPUT" | grep -E '^(CssSyntaxError|Error):.*')
33
+ [ -n "$CSS_ERRORS" ] && echo "$CSS_ERRORS"
34
+ [ "$CSS_STATUS" -ne 0 ] && [ -z "$CSS_ERRORS" ] && echo "$CSS_OUTPUT"
35
+ [ -z "$CSS_ERRORS" ] && [ "$CSS_STATUS" -eq 0 ]
36
+ record "tailwind" $?
37
+
38
+ bash "$DEVKIT_ROOT/lint/testBuild.sh"
39
+ record "testBuild" $?
40
+
41
+ # 发布包体积守卫:tracked + 未忽略的 untracked 文件总大小不超过 100 MB。
42
+ PKG_LIMIT_KB=$((100 * 1024))
43
+
44
+ if stat -c %s . >/dev/null 2>&1; then
45
+ PKG_STAT=(stat -c %s) # GNU coreutils
46
+ else
47
+ PKG_STAT=(stat -f %z) # BSD/macOS
48
+ fi
49
+
50
+ if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
51
+ # 统计 git 可见的全部路径:tracked 文件加上未被 .gitignore 排除的 untracked
52
+ # 文件。按磁盘实际大小统计,未暂存的修改也会计入。
53
+ DISK_BYTES=$(git ls-files -co --exclude-standard -z 2>/dev/null \
54
+ | xargs -0 "${PKG_STAT[@]}" 2>/dev/null \
55
+ | awk '{s+=$1} END{printf "%d", s+0}')
56
+ # 已从磁盘删除但仍留在 .git 中的 tracked 文件也计入。
57
+ if [ -n "$(git ls-files -d 2>/dev/null)" ]; then
58
+ DELETED_BYTES=$(git ls-files -d -z 2>/dev/null \
59
+ | xargs -0 git ls-files -s -z -- 2>/dev/null \
60
+ | tr '\0' '\n' \
61
+ | awk 'NF {print $2}' \
62
+ | git cat-file --batch-check='%(objectsize)' 2>/dev/null \
63
+ | awk '$1 ~ /^[0-9]+$/ {s+=$1} END{printf "%d", s+0}')
64
+ else
65
+ DELETED_BYTES=0
66
+ fi
67
+ PKG_BYTES=$(( ${DISK_BYTES:-0} + ${DELETED_BYTES:-0} ))
68
+ PKG_KB=$(( (PKG_BYTES + 1023) / 1024 ))
69
+ [ "$PKG_KB" -le "$PKG_LIMIT_KB" ]
70
+ PKG_OK=$?
71
+ else
72
+ PKG_KB=0
73
+ PKG_OK=1
74
+ echo "packageSize: FAIL - not a git repository, cannot measure tracked files"
75
+ fi
76
+
77
+ echo "packageSize: tracked+untracked (non-ignored) $(awk -v k="$PKG_KB" 'BEGIN{printf "%.1f", k/1024}')MB / 100MB"
78
+ if [ "$PKG_OK" -ne 0 ]; then
79
+ echo "packageSize: FAIL - tracked + untracked (non-ignored) files exceed 100MB. Remediation (ask the user for confirmation before deleting anything):"
80
+ echo " 1. Large files under public/: upload them to a Supabase Storage bucket first, then delete the local copies and commit. Ask the user for explicit confirmation before deleting."
81
+ echo " 2. Files already deleted but still held in .git history: locate the large files and their commits with git rev-list --objects --all, then use git filter-repo to remove only those large-file paths, followed by git reflog expire --expire=now --all and git gc --prune=now. Ask the user for explicit confirmation before executing."
82
+ echo " 3. Oversized non-code files: move files needed at runtime to a Supabase Storage bucket; add files unrelated to the build/runtime environment to .gitignore."
83
+ fi
84
+ record "packageSize" "$PKG_OK"
85
+
86
+ echo ""
87
+ echo "--------- LINT SUMMARY ---------"
88
+ printf '%s' "$SUMMARY"
89
+ echo "-------------------------------"
90
+ echo ""
91
+
92
+ if [ -n "$FAILED" ]; then
93
+ echo "ERROR: lint failed ->$FAILED"
94
+ exit 1
95
+ fi
96
+
97
+ echo "SUCCESS"
@@ -0,0 +1,26 @@
1
+ #!/bin/bash
2
+
3
+ VITE_TEMP="node_modules/.vite-temp"
4
+ if [ -L "$VITE_TEMP" ]; then
5
+ rm "$VITE_TEMP"
6
+ mkdir -p "$VITE_TEMP"
7
+ elif [ ! -e "$VITE_TEMP" ]; then
8
+ mkdir -p "$VITE_TEMP"
9
+ fi
10
+
11
+ # 平台继续使用原来的 /workspace/.dist;本地检查回退到应用内的 .dist。
12
+ if [ -d /workspace ] && [ -w /workspace ]; then
13
+ BUILD_OUT_DIR="/workspace/.dist"
14
+ else
15
+ BUILD_OUT_DIR=".dist"
16
+ fi
17
+ BUILD_OUT_DIR="${DEVKIT_BUILD_OUT_DIR:-$BUILD_OUT_DIR}"
18
+
19
+ OUTPUT=$(vite build --minify false --logLevel error --outDir "$BUILD_OUT_DIR" 2>&1)
20
+ EXIT_CODE=$?
21
+
22
+ if [ $EXIT_CODE -ne 0 ]; then
23
+ echo "$OUTPUT"
24
+ fi
25
+
26
+ exit $EXIT_CODE
@@ -0,0 +1,26 @@
1
+ {
2
+ "jsPlugins": ["miaoda-react-devkit/oxlint-plugin"],
3
+ "categories": {
4
+ "correctness": "off",
5
+ "nursery": "off",
6
+ "pedantic": "off",
7
+ "perf": "off",
8
+ "restriction": "off",
9
+ "style": "off",
10
+ "suspicious": "off"
11
+ },
12
+ "rules": {
13
+ "miaoda/select-item-with-empty-value": "error",
14
+ "miaoda/button-outline-text-foreground-contrast": "warn",
15
+ "miaoda/button-default-text-primary-contrast": "warn",
16
+ "miaoda/button-outline-white-gray-contrast": "warn",
17
+ "miaoda/radix-trigger-formcontrol-nesting": "error",
18
+ "miaoda/require-button-interaction": "error",
19
+ "miaoda/use-toast-import": "error",
20
+ "miaoda/supabase-google-sso": "warn",
21
+ "miaoda/supabase-edge-function-get-with-body": "error"
22
+ },
23
+ "options": {
24
+ "denyWarnings": true
25
+ }
26
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "miaoda-react-devkit",
3
- "version": "0.1.1-beta.22",
3
+ "version": "0.1.1-beta.25",
4
4
  "description": "React admin 应用开发工具集",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -19,19 +19,36 @@
19
19
  "require": "./dist/vite/index.cjs"
20
20
  },
21
21
  "./cloud/vite.config": "./cloud/vite.config.js",
22
- "./tsconfig-base": "./tsconfig-base.json"
22
+ "./tsconfig-base": "./tsconfig-base.json",
23
+ "./biome": "./biome-config.json",
24
+ "./oxlint": "./oxlint-config.json",
25
+ "./oxlint-plugin": {
26
+ "types": "./dist/oxlint/index.d.ts",
27
+ "import": "./dist/oxlint/index.js"
28
+ }
23
29
  },
24
30
  "files": [
25
31
  "dist",
26
32
  "cloud",
27
33
  "!cloud/**/*.ts",
28
34
  "tsconfig-base.json",
29
- "!dist/**/*.map"
35
+ "!dist/**/*.map",
36
+ "bin",
37
+ "lint",
38
+ "biome-config.json",
39
+ "oxlint-config.json"
30
40
  ],
31
41
  "dependencies": {
32
42
  "@babel/parser": "^7.28.0",
33
43
  "@babel/traverse": "^7.28.0",
34
- "@babel/types": "^7.28.0"
44
+ "@babel/types": "^7.28.0",
45
+ "@biomejs/biome": "2.4.5",
46
+ "@oxlint/plugins": "1.90.0",
47
+ "@typescript/native-preview": "7.0.0-dev.20260514.1",
48
+ "oxc-walker": "^1.1.1",
49
+ "oxlint": "1.90.0",
50
+ "parse5": "7.3.0",
51
+ "playwright": "1.65.0"
35
52
  },
36
53
  "peerDependencies": {
37
54
  "@sentry/core": ">=8.0.0",
@@ -56,5 +73,9 @@
56
73
  "publishConfig": {
57
74
  "registry": "https://registry.npmjs.org/",
58
75
  "access": "public"
76
+ },
77
+ "bin": {
78
+ "devkit-lint": "./bin/lint.mjs",
79
+ "devkit-smoke": "./bin/smoke.mjs"
59
80
  }
60
81
  }