resuxjs 0.2.43 → 0.3.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.
- package/README.md +993 -666
- package/dist/cli.js +1990 -355
- package/dist/cli.js.map +1 -1
- package/dist/compiler/adapter.d.ts +17 -0
- package/dist/compiler/adapter.js +106 -0
- package/dist/compiler/adapter.js.map +1 -0
- package/dist/compiler/dev-warnings.d.ts +11 -0
- package/dist/compiler/dev-warnings.js +360 -0
- package/dist/compiler/dev-warnings.js.map +1 -0
- package/dist/compiler/directives.d.ts +13 -0
- package/dist/compiler/directives.js +167 -0
- package/dist/compiler/directives.js.map +1 -0
- package/dist/compiler/implementation.d.ts +129 -0
- package/dist/compiler/implementation.js +3745 -0
- package/dist/compiler/implementation.js.map +1 -0
- package/dist/compiler/index.d.ts +9 -103
- package/dist/compiler/index.js +74 -1971
- package/dist/compiler/index.js.map +1 -1
- package/dist/core/config.d.ts +8 -0
- package/dist/core/config.js +21 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/hooks.d.ts +133 -0
- package/dist/core/hooks.js +54 -0
- package/dist/core/hooks.js.map +1 -0
- package/dist/core/index.d.ts +4 -0
- package/dist/core/index.js +5 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/module-container.d.ts +100 -0
- package/dist/core/module-container.js +171 -0
- package/dist/core/module-container.js.map +1 -0
- package/dist/core/resux.d.ts +18 -0
- package/dist/core/resux.js +18 -0
- package/dist/core/resux.js.map +1 -0
- package/dist/create.d.ts +1 -0
- package/dist/create.js +878 -22
- package/dist/create.js.map +1 -1
- package/dist/deploy/cloudflare.js +17 -3
- package/dist/deploy/cloudflare.js.map +1 -1
- package/dist/deploy/common.js +4 -3
- package/dist/deploy/common.js.map +1 -1
- package/dist/fonts/index.d.ts +16 -0
- package/dist/fonts/index.js +154 -0
- package/dist/fonts/index.js.map +1 -0
- package/dist/globals.d.ts +27 -2
- package/dist/halal-core/ai/classifyProject.d.ts +4 -0
- package/dist/halal-core/ai/classifyProject.js +104 -0
- package/dist/halal-core/ai/classifyProject.js.map +1 -0
- package/dist/halal-core/ai/createProjectSummary.d.ts +39 -0
- package/dist/halal-core/ai/createProjectSummary.js +42 -0
- package/dist/halal-core/ai/createProjectSummary.js.map +1 -0
- package/dist/halal-core/ai/halalClassifierPrompt.d.ts +1 -0
- package/dist/halal-core/ai/halalClassifierPrompt.js +20 -0
- package/dist/halal-core/ai/halalClassifierPrompt.js.map +1 -0
- package/dist/halal-core/ai/redactSensitiveData.d.ts +1 -0
- package/dist/halal-core/ai/redactSensitiveData.js +139 -0
- package/dist/halal-core/ai/redactSensitiveData.js.map +1 -0
- package/dist/halal-core/ai/validateAiResponse.d.ts +2 -0
- package/dist/halal-core/ai/validateAiResponse.js +97 -0
- package/dist/halal-core/ai/validateAiResponse.js.map +1 -0
- package/dist/halal-core/cli/check.d.ts +1 -0
- package/dist/halal-core/cli/check.js +36 -0
- package/dist/halal-core/cli/check.js.map +1 -0
- package/dist/halal-core/cli/explain.d.ts +1 -0
- package/dist/halal-core/cli/explain.js +35 -0
- package/dist/halal-core/cli/explain.js.map +1 -0
- package/dist/halal-core/cli/report.d.ts +1 -0
- package/dist/halal-core/cli/report.js +15 -0
- package/dist/halal-core/cli/report.js.map +1 -0
- package/dist/halal-core/cli/submitReview.d.ts +1 -0
- package/dist/halal-core/cli/submitReview.js +12 -0
- package/dist/halal-core/cli/submitReview.js.map +1 -0
- package/dist/halal-core/cli/verifyReview.d.ts +1 -0
- package/dist/halal-core/cli/verifyReview.js +19 -0
- package/dist/halal-core/cli/verifyReview.js.map +1 -0
- package/dist/halal-core/config.d.ts +40 -0
- package/dist/halal-core/config.js +128 -0
- package/dist/halal-core/config.js.map +1 -0
- package/dist/halal-core/crypto/integrity.d.ts +9 -0
- package/dist/halal-core/crypto/integrity.js +101 -0
- package/dist/halal-core/crypto/integrity.js.map +1 -0
- package/dist/halal-core/enforce.d.ts +5 -0
- package/dist/halal-core/enforce.js +119 -0
- package/dist/halal-core/enforce.js.map +1 -0
- package/dist/halal-core/index.d.ts +14 -0
- package/dist/halal-core/index.js +17 -0
- package/dist/halal-core/index.js.map +1 -0
- package/dist/halal-core/lifecycle.d.ts +1 -0
- package/dist/halal-core/lifecycle.js +15 -0
- package/dist/halal-core/lifecycle.js.map +1 -0
- package/dist/halal-core/policy.d.ts +2 -0
- package/dist/halal-core/policy.js +5 -0
- package/dist/halal-core/policy.js.map +1 -0
- package/dist/halal-core/report/formatBrowserOverlay.d.ts +2 -0
- package/dist/halal-core/report/formatBrowserOverlay.js +41 -0
- package/dist/halal-core/report/formatBrowserOverlay.js.map +1 -0
- package/dist/halal-core/report/formatTerminalReport.d.ts +2 -0
- package/dist/halal-core/report/formatTerminalReport.js +39 -0
- package/dist/halal-core/report/formatTerminalReport.js.map +1 -0
- package/dist/halal-core/report/generateHalalReport.d.ts +7 -0
- package/dist/halal-core/report/generateHalalReport.js +46 -0
- package/dist/halal-core/report/generateHalalReport.js.map +1 -0
- package/dist/halal-core/report/signReport.d.ts +3 -0
- package/dist/halal-core/report/signReport.js +17 -0
- package/dist/halal-core/report/signReport.js.map +1 -0
- package/dist/halal-core/report/verifyReport.d.ts +11 -0
- package/dist/halal-core/report/verifyReport.js +45 -0
- package/dist/halal-core/report/verifyReport.js.map +1 -0
- package/dist/halal-core/review/createReviewRequest.d.ts +2 -0
- package/dist/halal-core/review/createReviewRequest.js +21 -0
- package/dist/halal-core/review/createReviewRequest.js.map +1 -0
- package/dist/halal-core/review/reviewPolicy.d.ts +3 -0
- package/dist/halal-core/review/reviewPolicy.js +21 -0
- package/dist/halal-core/review/reviewPolicy.js.map +1 -0
- package/dist/halal-core/review/signedReviewFile.d.ts +13 -0
- package/dist/halal-core/review/signedReviewFile.js +28 -0
- package/dist/halal-core/review/signedReviewFile.js.map +1 -0
- package/dist/halal-core/review/verifyReviewApproval.d.ts +10 -0
- package/dist/halal-core/review/verifyReviewApproval.js +68 -0
- package/dist/halal-core/review/verifyReviewApproval.js.map +1 -0
- package/dist/halal-core/rules/adultContentRules.d.ts +2 -0
- package/dist/halal-core/rules/adultContentRules.js +26 -0
- package/dist/halal-core/rules/adultContentRules.js.map +1 -0
- package/dist/halal-core/rules/alcoholDrugVapeRules.d.ts +2 -0
- package/dist/halal-core/rules/alcoholDrugVapeRules.js +25 -0
- package/dist/halal-core/rules/alcoholDrugVapeRules.js.map +1 -0
- package/dist/halal-core/rules/childSafetyRules.d.ts +2 -0
- package/dist/halal-core/rules/childSafetyRules.js +22 -0
- package/dist/halal-core/rules/childSafetyRules.js.map +1 -0
- package/dist/halal-core/rules/coreCategories.d.ts +7 -0
- package/dist/halal-core/rules/coreCategories.js +112 -0
- package/dist/halal-core/rules/coreCategories.js.map +1 -0
- package/dist/halal-core/rules/cyberAbuseRules.d.ts +2 -0
- package/dist/halal-core/rules/cyberAbuseRules.js +30 -0
- package/dist/halal-core/rules/cyberAbuseRules.js.map +1 -0
- package/dist/halal-core/rules/defaultBlockedRules.d.ts +20 -0
- package/dist/halal-core/rules/defaultBlockedRules.js +216 -0
- package/dist/halal-core/rules/defaultBlockedRules.js.map +1 -0
- package/dist/halal-core/rules/dependencyRules.d.ts +9 -0
- package/dist/halal-core/rules/dependencyRules.js +59 -0
- package/dist/halal-core/rules/dependencyRules.js.map +1 -0
- package/dist/halal-core/rules/endpointRules.d.ts +6 -0
- package/dist/halal-core/rules/endpointRules.js +26 -0
- package/dist/halal-core/rules/endpointRules.js.map +1 -0
- package/dist/halal-core/rules/environmentalHarmRules.d.ts +2 -0
- package/dist/halal-core/rules/environmentalHarmRules.js +20 -0
- package/dist/halal-core/rules/environmentalHarmRules.js.map +1 -0
- package/dist/halal-core/rules/financeRibaRules.d.ts +2 -0
- package/dist/halal-core/rules/financeRibaRules.js +23 -0
- package/dist/halal-core/rules/financeRibaRules.js.map +1 -0
- package/dist/halal-core/rules/gamblingRules.d.ts +2 -0
- package/dist/halal-core/rules/gamblingRules.js +25 -0
- package/dist/halal-core/rules/gamblingRules.js.map +1 -0
- package/dist/halal-core/rules/generalHarmRules.d.ts +2 -0
- package/dist/halal-core/rules/generalHarmRules.js +18 -0
- package/dist/halal-core/rules/generalHarmRules.js.map +1 -0
- package/dist/halal-core/rules/healthHarmRules.d.ts +2 -0
- package/dist/halal-core/rules/healthHarmRules.js +22 -0
- package/dist/halal-core/rules/healthHarmRules.js.map +1 -0
- package/dist/halal-core/rules/keywordRules.d.ts +10 -0
- package/dist/halal-core/rules/keywordRules.js +41 -0
- package/dist/halal-core/rules/keywordRules.js.map +1 -0
- package/dist/halal-core/rules/privacyAbuseRules.d.ts +2 -0
- package/dist/halal-core/rules/privacyAbuseRules.js +24 -0
- package/dist/halal-core/rules/privacyAbuseRules.js.map +1 -0
- package/dist/halal-core/rules/scamFraudRules.d.ts +2 -0
- package/dist/halal-core/rules/scamFraudRules.js +32 -0
- package/dist/halal-core/rules/scamFraudRules.js.map +1 -0
- package/dist/halal-core/rules/selfHarmRules.d.ts +2 -0
- package/dist/halal-core/rules/selfHarmRules.js +20 -0
- package/dist/halal-core/rules/selfHarmRules.js.map +1 -0
- package/dist/halal-core/rules/violenceExtremismRules.d.ts +2 -0
- package/dist/halal-core/rules/violenceExtremismRules.js +33 -0
- package/dist/halal-core/rules/violenceExtremismRules.js.map +1 -0
- package/dist/halal-core/scanner/scanApiRoutes.d.ts +1 -0
- package/dist/halal-core/scanner/scanApiRoutes.js +40 -0
- package/dist/halal-core/scanner/scanApiRoutes.js.map +1 -0
- package/dist/halal-core/scanner/scanComponents.d.ts +1 -0
- package/dist/halal-core/scanner/scanComponents.js +17 -0
- package/dist/halal-core/scanner/scanComponents.js.map +1 -0
- package/dist/halal-core/scanner/scanContent.d.ts +5 -0
- package/dist/halal-core/scanner/scanContent.js +302 -0
- package/dist/halal-core/scanner/scanContent.js.map +1 -0
- package/dist/halal-core/scanner/scanDependencies.d.ts +1 -0
- package/dist/halal-core/scanner/scanDependencies.js +19 -0
- package/dist/halal-core/scanner/scanDependencies.js.map +1 -0
- package/dist/halal-core/scanner/scanDomains.d.ts +4 -0
- package/dist/halal-core/scanner/scanDomains.js +14 -0
- package/dist/halal-core/scanner/scanDomains.js.map +1 -0
- package/dist/halal-core/scanner/scanEnvNames.d.ts +1 -0
- package/dist/halal-core/scanner/scanEnvNames.js +30 -0
- package/dist/halal-core/scanner/scanEnvNames.js.map +1 -0
- package/dist/halal-core/scanner/scanMetadata.d.ts +6 -0
- package/dist/halal-core/scanner/scanMetadata.js +33 -0
- package/dist/halal-core/scanner/scanMetadata.js.map +1 -0
- package/dist/halal-core/scanner/scanPages.d.ts +1 -0
- package/dist/halal-core/scanner/scanPages.js +19 -0
- package/dist/halal-core/scanner/scanPages.js.map +1 -0
- package/dist/halal-core/scanner/scanProject.d.ts +13 -0
- package/dist/halal-core/scanner/scanProject.js +62 -0
- package/dist/halal-core/scanner/scanProject.js.map +1 -0
- package/dist/halal-core/scanner/scanRoutes.d.ts +1 -0
- package/dist/halal-core/scanner/scanRoutes.js +43 -0
- package/dist/halal-core/scanner/scanRoutes.js.map +1 -0
- package/dist/halal-core/scanner/scanTranslations.d.ts +1 -0
- package/dist/halal-core/scanner/scanTranslations.js +32 -0
- package/dist/halal-core/scanner/scanTranslations.js.map +1 -0
- package/dist/halal-core/status.d.ts +14 -0
- package/dist/halal-core/status.js +2 -0
- package/dist/halal-core/status.js.map +1 -0
- package/dist/halal-core/tamper/verifyCoreIntegrity.d.ts +1 -0
- package/dist/halal-core/tamper/verifyCoreIntegrity.js +28 -0
- package/dist/halal-core/tamper/verifyCoreIntegrity.js.map +1 -0
- package/dist/halal-core/tamper/verifyLifecycleHooks.d.ts +1 -0
- package/dist/halal-core/tamper/verifyLifecycleHooks.js +14 -0
- package/dist/halal-core/tamper/verifyLifecycleHooks.js.map +1 -0
- package/dist/halal-core/tamper/verifyReportSignature.d.ts +5 -0
- package/dist/halal-core/tamper/verifyReportSignature.js +18 -0
- package/dist/halal-core/tamper/verifyReportSignature.js.map +1 -0
- package/dist/i18n/index.d.ts +45 -0
- package/dist/i18n/index.js +284 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/i18n/shared.d.ts +35 -0
- package/dist/i18n/shared.js +270 -0
- package/dist/i18n/shared.js.map +1 -0
- package/dist/icons/index.d.ts +159 -0
- package/dist/icons/index.js +286 -0
- package/dist/icons/index.js.map +1 -0
- package/dist/kit/index.d.ts +29 -0
- package/dist/kit/index.js +72 -0
- package/dist/kit/index.js.map +1 -0
- package/dist/nitro-server/index.d.ts +7 -0
- package/dist/nitro-server/index.js +4 -0
- package/dist/nitro-server/index.js.map +1 -0
- package/dist/reactivity/computed.js +9 -4
- package/dist/reactivity/computed.js.map +1 -1
- package/dist/reactivity/effect.d.ts +3 -1
- package/dist/reactivity/effect.js +56 -6
- package/dist/reactivity/effect.js.map +1 -1
- package/dist/reactivity/reactive.js +64 -15
- package/dist/reactivity/reactive.js.map +1 -1
- package/dist/reactivity/ref.d.ts +1 -0
- package/dist/reactivity/ref.js +13 -6
- package/dist/reactivity/ref.js.map +1 -1
- package/dist/reactivity/scheduler.js +36 -4
- package/dist/reactivity/scheduler.js.map +1 -1
- package/dist/reactivity/watch.js +27 -5
- package/dist/reactivity/watch.js.map +1 -1
- package/dist/runtime/index.d.ts +226 -3
- package/dist/runtime/index.js +13344 -6395
- package/dist/runtime/index.js.map +1 -1
- package/dist/ui/index.d.ts +1828 -0
- package/dist/ui/index.js +938 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/vite-builder/index.d.ts +6 -0
- package/dist/vite-builder/index.js +4 -0
- package/dist/vite-builder/index.js.map +1 -0
- package/package.json +150 -105
- package/templates/default/.env.example +1 -0
- package/templates/default/README.md +18 -14
- package/templates/default/_gitignore +8 -5
- package/templates/default/assets/css/main.css +4 -0
- package/templates/default/nitro.config.ts +9 -5
- package/templates/default/pages/index.vue +102 -87
- package/templates/default/public/favicon.svg +4 -0
- package/templates/default/types/app.d.ts +3 -0
- package/templates/default/.resux-nitro/handler.ts +0 -21
|
@@ -0,0 +1,3745 @@
|
|
|
1
|
+
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { existsSync, statSync, writeFileSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import { NodeTypes, parse as parseTemplate } from "@vue/compiler-dom";
|
|
7
|
+
import { compileStyle, parse as parseSfc } from "@vue/compiler-sfc";
|
|
8
|
+
import vuePlugin from "@vitejs/plugin-vue";
|
|
9
|
+
import ts from "typescript";
|
|
10
|
+
import { build as viteBuild } from "vite";
|
|
11
|
+
import { createResux } from "../core/resux.js";
|
|
12
|
+
import { ResuxModuleContainer } from "../core/module-container.js";
|
|
13
|
+
import { buildLocalePath, normalizeI18nRuntimeConfig } from "../i18n/shared.js";
|
|
14
|
+
import { withResuxKitContext } from "../kit/index.js";
|
|
15
|
+
import { getClientRuntimeSource, } from "../runtime/index.js";
|
|
16
|
+
const require = createRequire(import.meta.url);
|
|
17
|
+
export class ResuxCompileError extends Error {
|
|
18
|
+
location;
|
|
19
|
+
constructor(message, location) {
|
|
20
|
+
super(location ? `${message} (${location.file}:${location.line}:${location.column})` : message);
|
|
21
|
+
this.name = "ResuxCompileError";
|
|
22
|
+
this.location = location;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const RESUMABLE_HANDLER_ALLOWED_GLOBALS = new Set([
|
|
26
|
+
"Math",
|
|
27
|
+
"Number",
|
|
28
|
+
"String",
|
|
29
|
+
"Boolean",
|
|
30
|
+
"Array",
|
|
31
|
+
"Object",
|
|
32
|
+
"Date",
|
|
33
|
+
"JSON",
|
|
34
|
+
"Intl",
|
|
35
|
+
"Promise",
|
|
36
|
+
"console",
|
|
37
|
+
"undefined",
|
|
38
|
+
"globalThis",
|
|
39
|
+
"performance",
|
|
40
|
+
"fetch",
|
|
41
|
+
"Headers",
|
|
42
|
+
"Request",
|
|
43
|
+
"Response",
|
|
44
|
+
"URL",
|
|
45
|
+
"URLSearchParams",
|
|
46
|
+
"AbortController",
|
|
47
|
+
"setTimeout",
|
|
48
|
+
"clearTimeout",
|
|
49
|
+
"setInterval",
|
|
50
|
+
"clearInterval",
|
|
51
|
+
"queueMicrotask",
|
|
52
|
+
"ref",
|
|
53
|
+
"reactive",
|
|
54
|
+
"computed",
|
|
55
|
+
"watch",
|
|
56
|
+
"watchEffect",
|
|
57
|
+
"readonly",
|
|
58
|
+
"toRef",
|
|
59
|
+
"toRefs",
|
|
60
|
+
"unref",
|
|
61
|
+
"isRef",
|
|
62
|
+
"isReactive",
|
|
63
|
+
"isReadonly",
|
|
64
|
+
"nextTick",
|
|
65
|
+
"useState",
|
|
66
|
+
"useGlobalState",
|
|
67
|
+
"useAsyncData",
|
|
68
|
+
"useRoute",
|
|
69
|
+
"useRouter",
|
|
70
|
+
"useHead",
|
|
71
|
+
"useSeoMeta",
|
|
72
|
+
"useRuntimeConfig",
|
|
73
|
+
"useResuxApp",
|
|
74
|
+
"useResuxImage",
|
|
75
|
+
"useI18n",
|
|
76
|
+
"useLocalePath",
|
|
77
|
+
"useSwitchLocalePath",
|
|
78
|
+
"useDevice",
|
|
79
|
+
"$device",
|
|
80
|
+
"apiURL",
|
|
81
|
+
"useFetch",
|
|
82
|
+
"$fetch",
|
|
83
|
+
"useError",
|
|
84
|
+
"clearError",
|
|
85
|
+
"showError",
|
|
86
|
+
"createError",
|
|
87
|
+
"useLazyPackage",
|
|
88
|
+
"useClientPackage",
|
|
89
|
+
"usePackageReady",
|
|
90
|
+
"defineLazyPackage",
|
|
91
|
+
"defineClientOnlyPackage",
|
|
92
|
+
"definePackageAdapter",
|
|
93
|
+
"defineClientEnhancement",
|
|
94
|
+
"useClientEnhancement",
|
|
95
|
+
"onMounted",
|
|
96
|
+
"definePageMeta",
|
|
97
|
+
"defineProps"
|
|
98
|
+
]);
|
|
99
|
+
const BUILTIN_AUTO_IMPORTS = [
|
|
100
|
+
{ from: "resuxjs", name: "useRoute" },
|
|
101
|
+
{ from: "resuxjs", name: "useRouter" },
|
|
102
|
+
{ from: "resuxjs", name: "useLocalePath" },
|
|
103
|
+
{ from: "resuxjs", name: "useSwitchLocalePath" },
|
|
104
|
+
{ from: "resuxjs", name: "useI18n" },
|
|
105
|
+
{ from: "resuxjs", name: "useResuxApp" },
|
|
106
|
+
{ from: "resuxjs", name: "useDevice" },
|
|
107
|
+
{ from: "resuxjs", name: "navigateTo" },
|
|
108
|
+
{ from: "resuxjs", name: "abortNavigation" },
|
|
109
|
+
{ from: "resuxjs", name: "useHead" },
|
|
110
|
+
{ from: "resuxjs", name: "useSeoMeta" },
|
|
111
|
+
{ from: "resuxjs", name: "useRuntimeConfig" },
|
|
112
|
+
{ from: "resuxjs", name: "useState" },
|
|
113
|
+
{ from: "resuxjs", name: "useGlobalState" },
|
|
114
|
+
{ from: "resuxjs", name: "useFetch" },
|
|
115
|
+
{ from: "resuxjs", name: "useAsyncData" },
|
|
116
|
+
{ from: "resuxjs", name: "$fetch" },
|
|
117
|
+
{ from: "resuxjs", name: "useError" },
|
|
118
|
+
{ from: "resuxjs", name: "clearError" },
|
|
119
|
+
{ from: "resuxjs", name: "showError" },
|
|
120
|
+
{ from: "resuxjs", name: "createError" },
|
|
121
|
+
{ from: "resuxjs", name: "useLazyPackage" },
|
|
122
|
+
{ from: "resuxjs", name: "useClientPackage" },
|
|
123
|
+
{ from: "resuxjs", name: "usePackageReady" },
|
|
124
|
+
{ from: "resuxjs", name: "defineLazyPackage" },
|
|
125
|
+
{ from: "resuxjs", name: "defineClientOnlyPackage" },
|
|
126
|
+
{ from: "resuxjs", name: "definePackageAdapter" },
|
|
127
|
+
{ from: "resuxjs", name: "defineClientEnhancement" },
|
|
128
|
+
{ from: "resuxjs", name: "useClientEnhancement" }
|
|
129
|
+
];
|
|
130
|
+
const SUPPORT_CLIENT_RUNTIME_HELPERS = [
|
|
131
|
+
"useLazyPackage",
|
|
132
|
+
"useClientPackage",
|
|
133
|
+
"usePackageReady",
|
|
134
|
+
"defineLazyPackage",
|
|
135
|
+
"defineClientOnlyPackage",
|
|
136
|
+
"definePackageAdapter",
|
|
137
|
+
"defineClientEnhancement",
|
|
138
|
+
"useClientEnhancement",
|
|
139
|
+
];
|
|
140
|
+
const CLIENT_ENHANCEMENT_DIR_CANDIDATES = [
|
|
141
|
+
"client-enhancements",
|
|
142
|
+
"enhancements",
|
|
143
|
+
path.join("app", "client-enhancements"),
|
|
144
|
+
path.join("app", "enhancements"),
|
|
145
|
+
];
|
|
146
|
+
export async function buildProject(appRoot, outDir = path.join(appRoot, ".resux"), options = {}) {
|
|
147
|
+
const absoluteRoot = path.resolve(appRoot);
|
|
148
|
+
const absoluteOut = path.resolve(outDir);
|
|
149
|
+
const buildOptions = {
|
|
150
|
+
vite: options.vite ?? "build",
|
|
151
|
+
server: options.server ?? (options.vite === "dev" ? "modules" : "bundle"),
|
|
152
|
+
hooks: options.hooks,
|
|
153
|
+
traceBuild: options.traceBuild === true
|
|
154
|
+
};
|
|
155
|
+
const mode = buildOptions.vite === "dev" ? "dev" : "build";
|
|
156
|
+
const incrementalDevBuild = mode === "dev" && typeof options.changedPath === "string" && options.changedPath.length > 0;
|
|
157
|
+
const hooks = buildOptions.hooks ?? createResux({ rootDir: absoluteRoot, buildDir: absoluteOut, config: {} }).hooks;
|
|
158
|
+
try {
|
|
159
|
+
await hooks.callHook("build:before", { appRoot: absoluteRoot, outDir: absoluteOut, mode });
|
|
160
|
+
if (!incrementalDevBuild) {
|
|
161
|
+
await cleanGeneratedOutput(absoluteOut);
|
|
162
|
+
}
|
|
163
|
+
await ensureGeneratedDirs(absoluteOut, buildOptions.vite === "dev");
|
|
164
|
+
const { config: runtimeConfig, moduleContainer } = await readRuntimeConfig(absoluteRoot, absoluteOut, hooks);
|
|
165
|
+
const contributions = moduleContainer.contributions;
|
|
166
|
+
await hooks.callHook("config:resolved", { rootDir: absoluteRoot, buildDir: absoluteOut, config: runtimeConfig });
|
|
167
|
+
await hooks.callHook("app:resolve", { appRoot: absoluteRoot, outDir: absoluteOut });
|
|
168
|
+
const routeRules = createRouteRules(runtimeConfig);
|
|
169
|
+
const componentDirs = unique([
|
|
170
|
+
path.join(absoluteRoot, "components"),
|
|
171
|
+
path.join(absoluteRoot, "app", "components"),
|
|
172
|
+
...contributions.componentDirs.map((entry) => path.resolve(absoluteRoot, entry.path))
|
|
173
|
+
]);
|
|
174
|
+
await hooks.callHook("components:dirs", { dirs: componentDirs });
|
|
175
|
+
const componentFiles = await discoverVueFilesFromDirs(componentDirs);
|
|
176
|
+
componentFiles.push(...contributions.components.map((entry) => path.resolve(absoluteRoot, entry.file)));
|
|
177
|
+
const uniqueComponentFiles = unique(componentFiles).sort((left, right) => normalizePath(left).localeCompare(normalizePath(right)));
|
|
178
|
+
const pageFiles = await discoverAppVueFiles(absoluteRoot, "pages");
|
|
179
|
+
const layoutFiles = await discoverAppVueFiles(absoluteRoot, "layouts");
|
|
180
|
+
const appFile = await optionalFile(path.join(absoluteRoot, "app.vue"))
|
|
181
|
+
?? await optionalFile(path.join(absoluteRoot, "app", "app.vue"));
|
|
182
|
+
const errorFile = await optionalFile(path.join(absoluteRoot, "error.vue"))
|
|
183
|
+
?? await optionalFile(path.join(absoluteRoot, "app", "error.vue"));
|
|
184
|
+
const pluginDirs = [
|
|
185
|
+
path.join(absoluteRoot, "plugins"),
|
|
186
|
+
path.join(absoluteRoot, "app", "plugins"),
|
|
187
|
+
path.join(absoluteRoot, "enhancements"),
|
|
188
|
+
path.join(absoluteRoot, "client-enhancements"),
|
|
189
|
+
path.join(absoluteRoot, "app", "enhancements"),
|
|
190
|
+
path.join(absoluteRoot, "app", "client-enhancements"),
|
|
191
|
+
];
|
|
192
|
+
await hooks.callHook("plugins:dirs", { dirs: pluginDirs });
|
|
193
|
+
const pluginFiles = await discoverSupportTsFiles(absoluteRoot, "plugins");
|
|
194
|
+
const modulePluginEntries = contributions.plugins.map((entry) => ({
|
|
195
|
+
file: path.resolve(absoluteRoot, entry.src),
|
|
196
|
+
mode: entry.mode ?? "all"
|
|
197
|
+
}));
|
|
198
|
+
const pluginModeByFile = new Map();
|
|
199
|
+
for (const entry of modulePluginEntries) {
|
|
200
|
+
pluginModeByFile.set(entry.file, entry.mode);
|
|
201
|
+
pluginFiles.push(entry.file);
|
|
202
|
+
}
|
|
203
|
+
const clientEnhancementFiles = await discoverClientEnhancementFiles(absoluteRoot);
|
|
204
|
+
for (const file of clientEnhancementFiles) {
|
|
205
|
+
if (!pluginModeByFile.has(file)) {
|
|
206
|
+
pluginModeByFile.set(file, "client");
|
|
207
|
+
}
|
|
208
|
+
pluginFiles.push(file);
|
|
209
|
+
}
|
|
210
|
+
const clientEnhancementFileSet = new Set(clientEnhancementFiles.map((file) => normalizePath(path.resolve(file))));
|
|
211
|
+
const middlewareDirs = [path.join(absoluteRoot, "middleware"), path.join(absoluteRoot, "app", "middleware")];
|
|
212
|
+
await hooks.callHook("middleware:dirs", { dirs: middlewareDirs });
|
|
213
|
+
const middlewareFiles = await discoverSupportTsFiles(absoluteRoot, "middleware");
|
|
214
|
+
const moduleMiddlewareEntries = contributions.middleware.map((entry) => ({
|
|
215
|
+
file: path.resolve(absoluteRoot, entry.src),
|
|
216
|
+
mode: entry.mode ?? "all",
|
|
217
|
+
global: entry.global === true,
|
|
218
|
+
name: entry.name
|
|
219
|
+
}));
|
|
220
|
+
const middlewareMetaByFile = new Map();
|
|
221
|
+
for (const entry of moduleMiddlewareEntries) {
|
|
222
|
+
middlewareMetaByFile.set(entry.file, entry);
|
|
223
|
+
middlewareFiles.push(entry.file);
|
|
224
|
+
}
|
|
225
|
+
const serverMiddlewareFiles = await discoverSupportTsFiles(absoluteRoot, path.join("server", "middleware"));
|
|
226
|
+
const serverHandlerFiles = [
|
|
227
|
+
...await discoverServerFiles(path.join(absoluteRoot, "server", "api"), "/api"),
|
|
228
|
+
...await discoverServerFiles(path.join(absoluteRoot, "server", "routes"), "")
|
|
229
|
+
];
|
|
230
|
+
for (const handler of contributions.serverHandlers) {
|
|
231
|
+
serverHandlerFiles.push({
|
|
232
|
+
file: path.resolve(absoluteRoot, handler.handler),
|
|
233
|
+
path: normalizeRoutePath(handler.route)
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
const vueIslands = await discoverVueIslands(absoluteRoot);
|
|
237
|
+
const allFiles = [...uniqueComponentFiles, ...layoutFiles, ...pageFiles, ...(appFile ? [appFile] : []), ...(errorFile ? [errorFile] : [])];
|
|
238
|
+
const idByFile = new Map();
|
|
239
|
+
const compiledByFile = new Map();
|
|
240
|
+
let index = 0;
|
|
241
|
+
for (const file of allFiles) {
|
|
242
|
+
idByFile.set(file, `m${index++}`);
|
|
243
|
+
}
|
|
244
|
+
for (const file of allFiles) {
|
|
245
|
+
const component = await compileVueFile(file, {
|
|
246
|
+
id: idByFile.get(file),
|
|
247
|
+
name: inferComponentName(absoluteRoot, file, componentDirs)
|
|
248
|
+
});
|
|
249
|
+
compiledByFile.set(file, component);
|
|
250
|
+
await writeFile(path.join(absoluteOut, "server", `${component.id}.mjs`), component.serverSource, "utf8");
|
|
251
|
+
await writeFile(path.join(absoluteOut, "vite-client", "handlers", `${component.id}.mjs`), component.clientSource, "utf8");
|
|
252
|
+
}
|
|
253
|
+
const baseRoutes = createRouteManifest(absoluteRoot, pageFiles, idByFile, compiledByFile);
|
|
254
|
+
for (const extender of contributions.pagesExtenders) {
|
|
255
|
+
await extender(baseRoutes);
|
|
256
|
+
}
|
|
257
|
+
await hooks.callHook("pages:extend", { pages: baseRoutes });
|
|
258
|
+
const routes = localizeRouteManifest(baseRoutes, runtimeConfig);
|
|
259
|
+
await hooks.callHook("pages:resolved", { pages: routes });
|
|
260
|
+
const components = allFiles.map((file) => compiledByFile.get(file));
|
|
261
|
+
const layouts = layoutFiles.map((file) => compiledByFile.get(file));
|
|
262
|
+
const plugins = unique(pluginFiles).sort((left, right) => normalizePath(left).localeCompare(normalizePath(right))).map((file, pluginIndex) => {
|
|
263
|
+
const compiled = compilePluginFile(file, pluginIndex);
|
|
264
|
+
const mode = pluginModeByFile.get(file);
|
|
265
|
+
if (mode) {
|
|
266
|
+
compiled.mode = mode;
|
|
267
|
+
}
|
|
268
|
+
return compiled;
|
|
269
|
+
});
|
|
270
|
+
const clientEnhancements = plugins
|
|
271
|
+
.filter((plugin) => (plugin.mode !== "server"
|
|
272
|
+
&& clientEnhancementFileSet.has(normalizePath(path.resolve(plugin.file)))))
|
|
273
|
+
.map((plugin) => ({
|
|
274
|
+
name: supportFileBaseName(plugin.file),
|
|
275
|
+
id: plugin.id,
|
|
276
|
+
file: plugin.file,
|
|
277
|
+
src: `/__resux/plugins/${plugin.id}.mjs`,
|
|
278
|
+
}))
|
|
279
|
+
.sort((left, right) => left.name.localeCompare(right.name) || normalizePath(left.file).localeCompare(normalizePath(right.file)));
|
|
280
|
+
const middleware = unique(middlewareFiles).sort((left, right) => normalizePath(left).localeCompare(normalizePath(right))).map((file, middlewareIndex) => {
|
|
281
|
+
const compiled = compileMiddlewareFile(file, middlewareIndex);
|
|
282
|
+
const meta = middlewareMetaByFile.get(file);
|
|
283
|
+
if (meta) {
|
|
284
|
+
compiled.mode = meta.mode;
|
|
285
|
+
compiled.global = meta.global;
|
|
286
|
+
compiled.name = kebabCase(meta.name);
|
|
287
|
+
}
|
|
288
|
+
return compiled;
|
|
289
|
+
});
|
|
290
|
+
const serverMiddleware = serverMiddlewareFiles.map((file, middlewareIndex) => compileServerMiddlewareFile(file, middlewareIndex));
|
|
291
|
+
const serverHandlers = uniqueServerHandlers(serverHandlerFiles).map((record, handlerIndex) => compileServerHandlerFile(record.file, handlerIndex, record.path));
|
|
292
|
+
const app = appFile ? compiledByFile.get(appFile) : undefined;
|
|
293
|
+
const error = errorFile ? compiledByFile.get(errorFile) : undefined;
|
|
294
|
+
await hooks.callHook("components:extend", { components: components });
|
|
295
|
+
await hooks.callHook("plugins:extend", { plugins: plugins });
|
|
296
|
+
await hooks.callHook("middleware:extend", { middleware: middleware });
|
|
297
|
+
for (const plugin of plugins) {
|
|
298
|
+
if (plugin.mode !== "client") {
|
|
299
|
+
await writeFile(path.join(absoluteOut, "server", "resux-plugins", `${plugin.id}.mjs`), plugin.serverSource, "utf8");
|
|
300
|
+
}
|
|
301
|
+
if (plugin.mode !== "server") {
|
|
302
|
+
await writeFile(path.join(absoluteOut, "vite-client", "plugins", `${plugin.id}.mjs`), plugin.clientSource, "utf8");
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
await writeClientEnhancementManifests(absoluteOut, clientEnhancements);
|
|
306
|
+
for (const entry of middleware) {
|
|
307
|
+
if (entry.mode !== "client") {
|
|
308
|
+
await writeFile(path.join(absoluteOut, "server", "resux-middleware", `${entry.id}.mjs`), entry.serverSource, "utf8");
|
|
309
|
+
}
|
|
310
|
+
if (entry.mode !== "server") {
|
|
311
|
+
await writeFile(path.join(absoluteOut, "vite-client", "middleware", `${entry.id}.mjs`), entry.clientSource, "utf8");
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
for (const entry of serverMiddleware) {
|
|
315
|
+
await writeFile(path.join(absoluteOut, "server", "request-middleware", `${entry.id}.mjs`), entry.source, "utf8");
|
|
316
|
+
}
|
|
317
|
+
for (const handler of serverHandlers) {
|
|
318
|
+
await writeFile(path.join(absoluteOut, "server", "handlers", `${handler.id}.mjs`), handler.source, "utf8");
|
|
319
|
+
}
|
|
320
|
+
for (const island of vueIslands) {
|
|
321
|
+
const islandEntryDir = path.join(absoluteOut, "vite-client", "vue-islands");
|
|
322
|
+
await writeFile(path.join(islandEntryDir, `${island.name}.mjs`), createVueIslandClientSource(island, islandEntryDir), "utf8");
|
|
323
|
+
}
|
|
324
|
+
const importDirs = unique([
|
|
325
|
+
path.join(absoluteRoot, "composables"),
|
|
326
|
+
path.join(absoluteRoot, "utils"),
|
|
327
|
+
path.join(absoluteRoot, "shared"),
|
|
328
|
+
path.join(absoluteRoot, "server", "utils"),
|
|
329
|
+
...contributions.importDirs.map((dir) => path.resolve(absoluteRoot, dir))
|
|
330
|
+
]);
|
|
331
|
+
await hooks.callHook("imports:dirs", { dirs: importDirs });
|
|
332
|
+
const discoveredAutoImports = await discoverAutoImportsFromDirs(absoluteRoot, importDirs);
|
|
333
|
+
const mergedImports = dedupeImports([...contributions.imports, ...discoveredAutoImports]);
|
|
334
|
+
await hooks.callHook("imports:extend", { imports: mergedImports });
|
|
335
|
+
await hooks.callHook("app:templates", { outDir: absoluteOut, templatesDir: path.join(absoluteOut, "templates") });
|
|
336
|
+
const generatedTemplateFiles = await writeModuleTemplates(absoluteOut, contributions);
|
|
337
|
+
await hooks.callHook("app:templatesGenerated", { outDir: absoluteOut, files: generatedTemplateFiles });
|
|
338
|
+
const additionalSharedPackageFiles = unique([
|
|
339
|
+
...await discoverSupportTsFiles(absoluteRoot, "composables"),
|
|
340
|
+
...await discoverSupportTsFiles(absoluteRoot, "utils"),
|
|
341
|
+
...await discoverSupportTsFiles(absoluteRoot, "shared"),
|
|
342
|
+
]);
|
|
343
|
+
const additionalServerPackageFiles = unique([
|
|
344
|
+
...await discoverSupportTsFiles(absoluteRoot, path.join("server", "utils")),
|
|
345
|
+
...await discoverSupportTsFiles(absoluteRoot, path.join("server", "plugins")),
|
|
346
|
+
]);
|
|
347
|
+
const packageSources = uniquePackageSourceFiles([
|
|
348
|
+
...components.map((component) => ({ file: component.file, mode: "all" })),
|
|
349
|
+
...plugins.map((plugin) => ({ file: plugin.file, mode: plugin.mode })),
|
|
350
|
+
...middleware.map((entry) => ({ file: entry.file, mode: entry.mode })),
|
|
351
|
+
...serverMiddleware.map((entry) => ({ file: entry.file, mode: "server" })),
|
|
352
|
+
...serverHandlers.map((entry) => ({ file: entry.file, mode: "server" })),
|
|
353
|
+
...additionalSharedPackageFiles.map((file) => ({ file, mode: "all" })),
|
|
354
|
+
...additionalServerPackageFiles.map((file) => ({ file, mode: "server" })),
|
|
355
|
+
]);
|
|
356
|
+
const packageDiagnostics = await analyzePackageUsage(absoluteRoot, packageSources, runtimeConfig);
|
|
357
|
+
const packageRegistry = createClientRuntimePackageRegistry(absoluteRoot, readConfiguredPackages(runtimeConfig), packageDiagnostics);
|
|
358
|
+
if (buildOptions.vite === "dev") {
|
|
359
|
+
await writeViteClientRuntime(absoluteOut, packageRegistry);
|
|
360
|
+
await hooks.callHook("vite:compiled", { outDir: absoluteOut, dev: true });
|
|
361
|
+
}
|
|
362
|
+
else {
|
|
363
|
+
await buildClientAssets(absoluteRoot, absoluteOut, components, plugins, middleware, vueIslands, packageRegistry, hooks, contributions);
|
|
364
|
+
await hooks.callHook("vite:compiled", { outDir: absoluteOut, dev: false });
|
|
365
|
+
}
|
|
366
|
+
await ensureServerComponentModules(absoluteOut, components);
|
|
367
|
+
const runtimeArtifacts = buildRuntimeArtifacts({
|
|
368
|
+
routes,
|
|
369
|
+
components,
|
|
370
|
+
layouts,
|
|
371
|
+
plugins,
|
|
372
|
+
clientEnhancements,
|
|
373
|
+
middleware,
|
|
374
|
+
serverMiddleware,
|
|
375
|
+
serverHandlers,
|
|
376
|
+
vueIslands,
|
|
377
|
+
app,
|
|
378
|
+
error,
|
|
379
|
+
runtimeConfig,
|
|
380
|
+
routeRules,
|
|
381
|
+
packages: packageDiagnostics,
|
|
382
|
+
buildOptions: { vite: buildOptions.vite, server: buildOptions.server },
|
|
383
|
+
contributions: {
|
|
384
|
+
...contributions,
|
|
385
|
+
imports: mergedImports
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
await hooks.callHook("build:manifest", { manifest: runtimeArtifacts.manifest, outDir: absoluteOut });
|
|
389
|
+
await writeFile(path.join(absoluteOut, "server", "manifest.mjs"), createServerManifestSource(routes, components, layouts, plugins, middleware, serverMiddleware, serverHandlers, vueIslands, app, error, runtimeConfig, buildOptions), "utf8");
|
|
390
|
+
await writeGeneratedArtifacts(absoluteOut, runtimeArtifacts, buildOptions.vite === "dev");
|
|
391
|
+
await hooks.callHook("prepare:types", {
|
|
392
|
+
outDir: absoluteOut,
|
|
393
|
+
files: [
|
|
394
|
+
path.join(absoluteOut, "resux.d.ts"),
|
|
395
|
+
path.join(absoluteOut, "imports.d.ts"),
|
|
396
|
+
path.join(absoluteOut, "components.d.ts"),
|
|
397
|
+
path.join(absoluteOut, "server-routes.d.ts")
|
|
398
|
+
]
|
|
399
|
+
});
|
|
400
|
+
if (buildOptions.server === "bundle") {
|
|
401
|
+
await buildServerBundle(absoluteRoot, absoluteOut);
|
|
402
|
+
}
|
|
403
|
+
await hooks.callHook("build:done", { appRoot: absoluteRoot, outDir: absoluteOut, mode });
|
|
404
|
+
return {
|
|
405
|
+
appRoot: absoluteRoot,
|
|
406
|
+
outDir: absoluteOut,
|
|
407
|
+
routes,
|
|
408
|
+
components,
|
|
409
|
+
layouts,
|
|
410
|
+
plugins,
|
|
411
|
+
clientEnhancements,
|
|
412
|
+
middleware,
|
|
413
|
+
serverMiddleware,
|
|
414
|
+
serverHandlers,
|
|
415
|
+
vueIslands,
|
|
416
|
+
routeRules,
|
|
417
|
+
app,
|
|
418
|
+
error
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
catch (error) {
|
|
422
|
+
await hooks.callHook("build:error", { appRoot: absoluteRoot, outDir: absoluteOut, mode, error });
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async function cleanGeneratedOutput(outDir) {
|
|
427
|
+
const directoryRmOptions = {
|
|
428
|
+
recursive: true,
|
|
429
|
+
force: true,
|
|
430
|
+
maxRetries: 6,
|
|
431
|
+
retryDelay: 40,
|
|
432
|
+
};
|
|
433
|
+
await mkdir(outDir, { recursive: true });
|
|
434
|
+
await rm(path.join(outDir, "server"), directoryRmOptions);
|
|
435
|
+
await rm(path.join(outDir, "server-bundle"), directoryRmOptions);
|
|
436
|
+
await rm(path.join(outDir, "client"), directoryRmOptions);
|
|
437
|
+
await rm(path.join(outDir, "vite-client"), directoryRmOptions);
|
|
438
|
+
await rm(path.join(outDir, "manifest"), directoryRmOptions);
|
|
439
|
+
await rm(path.join(outDir, "types"), directoryRmOptions);
|
|
440
|
+
await rm(path.join(outDir, "cache"), directoryRmOptions);
|
|
441
|
+
await rm(path.join(outDir, "dev"), directoryRmOptions);
|
|
442
|
+
await rm(path.join(outDir, "templates"), directoryRmOptions);
|
|
443
|
+
await rm(path.join(outDir, "app.mjs"), { force: true });
|
|
444
|
+
await rm(path.join(outDir, "routes.mjs"), { force: true });
|
|
445
|
+
await rm(path.join(outDir, "plugins.mjs"), { force: true });
|
|
446
|
+
await rm(path.join(outDir, "middleware.mjs"), { force: true });
|
|
447
|
+
await rm(path.join(outDir, "components.mjs"), { force: true });
|
|
448
|
+
await rm(path.join(outDir, "imports.mjs"), { force: true });
|
|
449
|
+
await rm(path.join(outDir, "resux.d.ts"), { force: true });
|
|
450
|
+
await rm(path.join(outDir, "imports.d.ts"), { force: true });
|
|
451
|
+
await rm(path.join(outDir, "components.d.ts"), { force: true });
|
|
452
|
+
await rm(path.join(outDir, "server-routes.d.ts"), { force: true });
|
|
453
|
+
await rm(path.join(outDir, "manifest.json"), { force: true });
|
|
454
|
+
await rm(path.join(outDir, "client-enhancements.mjs"), { force: true });
|
|
455
|
+
}
|
|
456
|
+
async function ensureGeneratedDirs(outDir, _dev) {
|
|
457
|
+
await mkdir(path.join(outDir, "server"), { recursive: true });
|
|
458
|
+
await mkdir(path.join(outDir, "server", "resux-plugins"), { recursive: true });
|
|
459
|
+
await mkdir(path.join(outDir, "server", "resux-middleware"), { recursive: true });
|
|
460
|
+
await mkdir(path.join(outDir, "server", "request-middleware"), { recursive: true });
|
|
461
|
+
await mkdir(path.join(outDir, "server", "handlers"), { recursive: true });
|
|
462
|
+
await mkdir(path.join(outDir, "server", "config-modules"), { recursive: true });
|
|
463
|
+
await mkdir(path.join(outDir, "client", "handlers"), { recursive: true });
|
|
464
|
+
await mkdir(path.join(outDir, "client", "vue-islands"), { recursive: true });
|
|
465
|
+
await mkdir(path.join(outDir, "client", "plugins"), { recursive: true });
|
|
466
|
+
await mkdir(path.join(outDir, "client", "middleware"), { recursive: true });
|
|
467
|
+
await mkdir(path.join(outDir, "vite-client", "handlers"), { recursive: true });
|
|
468
|
+
await mkdir(path.join(outDir, "vite-client", "vue-islands"), { recursive: true });
|
|
469
|
+
await mkdir(path.join(outDir, "vite-client", "plugins"), { recursive: true });
|
|
470
|
+
await mkdir(path.join(outDir, "vite-client", "middleware"), { recursive: true });
|
|
471
|
+
await mkdir(path.join(outDir, "manifest"), { recursive: true });
|
|
472
|
+
await mkdir(path.join(outDir, "types"), { recursive: true });
|
|
473
|
+
await mkdir(path.join(outDir, "cache"), { recursive: true });
|
|
474
|
+
await mkdir(path.join(outDir, "templates"), { recursive: true });
|
|
475
|
+
await mkdir(path.join(outDir, "dev"), { recursive: true });
|
|
476
|
+
}
|
|
477
|
+
async function buildServerBundle(root, outDir) {
|
|
478
|
+
try {
|
|
479
|
+
await viteBuild({
|
|
480
|
+
root,
|
|
481
|
+
configFile: false,
|
|
482
|
+
publicDir: false,
|
|
483
|
+
appType: "custom",
|
|
484
|
+
clearScreen: false,
|
|
485
|
+
logLevel: "warn",
|
|
486
|
+
build: {
|
|
487
|
+
ssr: path.join(outDir, "server", "manifest.mjs"),
|
|
488
|
+
outDir: path.join(outDir, "server-bundle"),
|
|
489
|
+
emptyOutDir: true,
|
|
490
|
+
minify: "oxc",
|
|
491
|
+
sourcemap: false,
|
|
492
|
+
manifest: false,
|
|
493
|
+
rollupOptions: {
|
|
494
|
+
external: (id) => {
|
|
495
|
+
if (id === "resuxjs" || id.startsWith("resuxjs/"))
|
|
496
|
+
return true;
|
|
497
|
+
if (id.includes("node_modules") || (!id.startsWith(".") && !path.isAbsolute(id)))
|
|
498
|
+
return true;
|
|
499
|
+
return false;
|
|
500
|
+
},
|
|
501
|
+
output: {
|
|
502
|
+
format: "es",
|
|
503
|
+
entryFileNames: "index.mjs",
|
|
504
|
+
chunkFileNames: "chunks/[name]-[hash].mjs"
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
catch (error) {
|
|
511
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
512
|
+
throw new Error(`Vite server build failed. Ensure vite is installed. ${message}`);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
async function buildClientAssets(root, outDir, components, plugins, middleware, vueIslands, packageRegistry, hooks, contributions) {
|
|
516
|
+
const inputRoot = path.join(outDir, "vite-client");
|
|
517
|
+
const runtimeInput = await writeViteClientRuntime(outDir, packageRegistry);
|
|
518
|
+
const input = {
|
|
519
|
+
"runtime-client": runtimeInput
|
|
520
|
+
};
|
|
521
|
+
for (const component of components) {
|
|
522
|
+
input[`handlers/${component.id}`] = path.join(inputRoot, "handlers", `${component.id}.mjs`);
|
|
523
|
+
}
|
|
524
|
+
for (const plugin of plugins.filter((entry) => entry.mode !== "server")) {
|
|
525
|
+
input[`plugins/${plugin.id}`] = path.join(inputRoot, "plugins", `${plugin.id}.mjs`);
|
|
526
|
+
}
|
|
527
|
+
for (const entry of middleware.filter((candidate) => candidate.mode !== "server")) {
|
|
528
|
+
input[`middleware/${entry.id}`] = path.join(inputRoot, "middleware", `${entry.id}.mjs`);
|
|
529
|
+
}
|
|
530
|
+
for (const island of vueIslands) {
|
|
531
|
+
input[`vue-islands/${island.name}`] = path.join(inputRoot, "vue-islands", `${island.name}.mjs`);
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
const viteConfig = {
|
|
535
|
+
root,
|
|
536
|
+
configFile: false,
|
|
537
|
+
publicDir: false,
|
|
538
|
+
base: "/__resux/",
|
|
539
|
+
appType: "custom",
|
|
540
|
+
clearScreen: false,
|
|
541
|
+
logLevel: "warn",
|
|
542
|
+
plugins: [vuePlugin(), ...(contributions?.vitePlugins ?? [])],
|
|
543
|
+
resolve: {
|
|
544
|
+
alias: {
|
|
545
|
+
vue: require.resolve("vue"),
|
|
546
|
+
"@": normalizePath(root),
|
|
547
|
+
"~": normalizePath(root)
|
|
548
|
+
}
|
|
549
|
+
},
|
|
550
|
+
build: {
|
|
551
|
+
outDir: path.join(outDir, "client"),
|
|
552
|
+
emptyOutDir: false,
|
|
553
|
+
minify: "oxc",
|
|
554
|
+
sourcemap: false,
|
|
555
|
+
manifest: false,
|
|
556
|
+
rollupOptions: {
|
|
557
|
+
input,
|
|
558
|
+
preserveEntrySignatures: "strict",
|
|
559
|
+
external: (id) => id === "/__resux/runtime-client.mjs",
|
|
560
|
+
output: {
|
|
561
|
+
format: "es",
|
|
562
|
+
entryFileNames: "[name].mjs",
|
|
563
|
+
chunkFileNames: "chunks/[name]-[hash].mjs",
|
|
564
|
+
assetFileNames: "assets/[name]-[hash][extname]"
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
console.log("resux build client viteConfig:", JSON.stringify(viteConfig, null, 2));
|
|
570
|
+
for (const extender of contributions?.viteConfigExtenders ?? []) {
|
|
571
|
+
await extender(viteConfig);
|
|
572
|
+
}
|
|
573
|
+
if (hooks) {
|
|
574
|
+
await hooks.callHook("vite:extendConfig", { config: viteConfig, dev: false });
|
|
575
|
+
}
|
|
576
|
+
await viteBuild(viteConfig);
|
|
577
|
+
}
|
|
578
|
+
catch (error) {
|
|
579
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
580
|
+
throw new Error(`Vite client build failed. Ensure vite is installed. ${message}`);
|
|
581
|
+
}
|
|
582
|
+
finally {
|
|
583
|
+
await rm(inputRoot, { recursive: true, force: true });
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
async function writeViteClientRuntime(outDir, packageRegistry) {
|
|
587
|
+
const runtimeInput = path.join(outDir, "vite-client", "runtime-client.mjs");
|
|
588
|
+
await writeFile(runtimeInput, getClientRuntimeSource({
|
|
589
|
+
packageRegistry: {
|
|
590
|
+
importers: packageRegistry.importers,
|
|
591
|
+
css: packageRegistry.cssByPackage,
|
|
592
|
+
declared: packageRegistry.declared,
|
|
593
|
+
},
|
|
594
|
+
}), "utf8");
|
|
595
|
+
return runtimeInput;
|
|
596
|
+
}
|
|
597
|
+
function createClientEnhancementManifestSource(entries) {
|
|
598
|
+
const imports = entries
|
|
599
|
+
.map((entry) => `import ${JSON.stringify(entry.src)};`)
|
|
600
|
+
.join("\n");
|
|
601
|
+
const names = [...new Set(entries.map((entry) => entry.name))];
|
|
602
|
+
if (imports) {
|
|
603
|
+
return `${imports}\n\nexport const clientEnhancements = ${JSON.stringify(names, null, 2)};\n`;
|
|
604
|
+
}
|
|
605
|
+
return `export const clientEnhancements = ${JSON.stringify(names, null, 2)};\n`;
|
|
606
|
+
}
|
|
607
|
+
async function writeClientEnhancementManifests(outDir, entries) {
|
|
608
|
+
const source = createClientEnhancementManifestSource(entries);
|
|
609
|
+
await writeFile(path.join(outDir, "client-enhancements.mjs"), source, "utf8");
|
|
610
|
+
await writeFile(path.join(outDir, "vite-client", "client-enhancements.mjs"), source, "utf8");
|
|
611
|
+
await writeFile(path.join(outDir, "client", "client-enhancements.mjs"), source, "utf8");
|
|
612
|
+
}
|
|
613
|
+
export async function compileVueFile(file, options) {
|
|
614
|
+
const source = await readFile(file, "utf8");
|
|
615
|
+
return compileVueSource(source, {
|
|
616
|
+
file,
|
|
617
|
+
id: options.id,
|
|
618
|
+
name: options.name ?? pascalCase(path.basename(file, ".vue"))
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
export function compileVueSource(source, options) {
|
|
622
|
+
const parsed = parseSfc(source, { filename: options.file });
|
|
623
|
+
const descriptor = parsed.descriptor;
|
|
624
|
+
if (!descriptor.template) {
|
|
625
|
+
throw new ResuxCompileError("Resux components need a <template> block.", locationFromOffset(options.file, source, 0));
|
|
626
|
+
}
|
|
627
|
+
const script = descriptor.scriptSetup?.content ?? "";
|
|
628
|
+
const templateRefBindings = inferTemplateRefBindings(script, options.file);
|
|
629
|
+
const template = compileTemplate(descriptor.template.content, options.file, templateRefBindings);
|
|
630
|
+
const analysis = analyzeScript(script, options.file, template.inlineHandlers);
|
|
631
|
+
const compiledStyles = compileSfcStyles(descriptor.styles, {
|
|
632
|
+
id: options.id,
|
|
633
|
+
file: options.file
|
|
634
|
+
});
|
|
635
|
+
validateTemplateHandlers(template.handlers, analysis, options.file, source, template.allLocals);
|
|
636
|
+
const serverSource = createComponentModuleSource({
|
|
637
|
+
id: options.id,
|
|
638
|
+
name: options.name,
|
|
639
|
+
file: options.file,
|
|
640
|
+
template: template.nodes,
|
|
641
|
+
analysis,
|
|
642
|
+
styles: compiledStyles.styles,
|
|
643
|
+
styleScopeId: compiledStyles.styleScopeId,
|
|
644
|
+
client: false,
|
|
645
|
+
expressions: template.expressions
|
|
646
|
+
});
|
|
647
|
+
const clientSource = createComponentModuleSource({
|
|
648
|
+
id: options.id,
|
|
649
|
+
name: options.name,
|
|
650
|
+
file: options.file,
|
|
651
|
+
template: template.nodes,
|
|
652
|
+
analysis,
|
|
653
|
+
styles: compiledStyles.styles,
|
|
654
|
+
styleScopeId: compiledStyles.styleScopeId,
|
|
655
|
+
client: true,
|
|
656
|
+
expressions: template.expressions
|
|
657
|
+
});
|
|
658
|
+
return {
|
|
659
|
+
id: options.id,
|
|
660
|
+
name: options.name,
|
|
661
|
+
file: options.file,
|
|
662
|
+
serverSource,
|
|
663
|
+
clientSource,
|
|
664
|
+
template: template.nodes,
|
|
665
|
+
handlers: [...new Set(template.handlers.map((event) => event.handler))],
|
|
666
|
+
styles: compiledStyles.styles,
|
|
667
|
+
styleScopeId: compiledStyles.styleScopeId,
|
|
668
|
+
meta: analysis.pageMeta,
|
|
669
|
+
expressions: template.expressions
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function compileSfcStyles(styleBlocks, options) {
|
|
673
|
+
const scopeId = `rx-s-${options.id}`;
|
|
674
|
+
const styles = [];
|
|
675
|
+
let hasScopedStyles = false;
|
|
676
|
+
for (let index = 0; index < styleBlocks.length; index++) {
|
|
677
|
+
const style = styleBlocks[index];
|
|
678
|
+
const lang = style.lang ?? (typeof style.attrs.lang === "string" ? style.attrs.lang : undefined);
|
|
679
|
+
if (lang && lang !== "css") {
|
|
680
|
+
throw new ResuxCompileError(`Resux <style> only supports plain CSS in resumable components. Unsupported lang "${lang}".`, styleBlockLocation(options.file, style));
|
|
681
|
+
}
|
|
682
|
+
if (style.module) {
|
|
683
|
+
throw new ResuxCompileError("Resux <style module> is not supported in resumable components yet.", styleBlockLocation(options.file, style));
|
|
684
|
+
}
|
|
685
|
+
if (style.src) {
|
|
686
|
+
throw new ResuxCompileError("Resux <style src> is not supported in resumable components yet.", styleBlockLocation(options.file, style));
|
|
687
|
+
}
|
|
688
|
+
const result = compileStyle({
|
|
689
|
+
id: scopeId,
|
|
690
|
+
filename: options.file,
|
|
691
|
+
source: style.content,
|
|
692
|
+
scoped: Boolean(style.scoped),
|
|
693
|
+
isProd: true
|
|
694
|
+
});
|
|
695
|
+
if (result.errors.length > 0) {
|
|
696
|
+
const error = result.errors[0];
|
|
697
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
698
|
+
throw new ResuxCompileError(message, styleBlockLocation(options.file, style));
|
|
699
|
+
}
|
|
700
|
+
const css = result.code.trim();
|
|
701
|
+
if (!css) {
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
hasScopedStyles ||= Boolean(style.scoped);
|
|
705
|
+
styles.push({
|
|
706
|
+
id: `${options.id}-${index}`,
|
|
707
|
+
css,
|
|
708
|
+
scoped: Boolean(style.scoped)
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
return {
|
|
712
|
+
styles,
|
|
713
|
+
styleScopeId: hasScopedStyles ? `data-v-${scopeId}` : undefined
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
function styleBlockLocation(file, style) {
|
|
717
|
+
return {
|
|
718
|
+
file,
|
|
719
|
+
line: style.loc.start.line,
|
|
720
|
+
column: style.loc.start.column
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
export function createRouteManifest(root, files, idByFile, compiledByFile) {
|
|
724
|
+
return files
|
|
725
|
+
.map((file, index) => {
|
|
726
|
+
const normalizedRoot = normalizePath(path.resolve(root));
|
|
727
|
+
const normalizedFile = normalizePath(path.resolve(file));
|
|
728
|
+
const appPagesRoot = `${normalizedRoot}/app/pages/`;
|
|
729
|
+
const pagesRoot = `${normalizedRoot}/pages/`;
|
|
730
|
+
const relative = normalizedFile.startsWith(appPagesRoot)
|
|
731
|
+
? normalizedFile.slice(appPagesRoot.length)
|
|
732
|
+
: normalizedFile.startsWith(pagesRoot)
|
|
733
|
+
? normalizedFile.slice(pagesRoot.length)
|
|
734
|
+
: normalizePath(path.relative(path.join(root, "pages"), file));
|
|
735
|
+
const withoutExtension = relative.replace(/\.vue$/, "");
|
|
736
|
+
const parts = withoutExtension.split("/");
|
|
737
|
+
const params = [];
|
|
738
|
+
const routeParts = parts
|
|
739
|
+
.filter((part, partIndex) => !(part === "index" && partIndex === parts.length - 1))
|
|
740
|
+
.map((part) => {
|
|
741
|
+
const catchAllMatch = /^\[\.\.\.([A-Za-z0-9_]+)\]$/.exec(part);
|
|
742
|
+
if (catchAllMatch) {
|
|
743
|
+
params.push(catchAllMatch[1]);
|
|
744
|
+
return `:${catchAllMatch[1]}*`;
|
|
745
|
+
}
|
|
746
|
+
const match = /^\[([A-Za-z0-9_]+)\]$/.exec(part);
|
|
747
|
+
if (match) {
|
|
748
|
+
params.push(match[1]);
|
|
749
|
+
return `:${match[1]}`;
|
|
750
|
+
}
|
|
751
|
+
return part;
|
|
752
|
+
});
|
|
753
|
+
const routePath = `/${routeParts.join("/")}`.replace(/\/$/, "") || "/";
|
|
754
|
+
return {
|
|
755
|
+
id: `r${index}`,
|
|
756
|
+
path: routePath,
|
|
757
|
+
file,
|
|
758
|
+
params,
|
|
759
|
+
componentId: idByFile?.get(file) ?? `m${index}`,
|
|
760
|
+
meta: compiledByFile?.get(file)?.meta
|
|
761
|
+
};
|
|
762
|
+
})
|
|
763
|
+
.sort((a, b) => routeScore(b.path) - routeScore(a.path) || a.path.localeCompare(b.path));
|
|
764
|
+
}
|
|
765
|
+
async function ensureServerComponentModules(outDir, components) {
|
|
766
|
+
for (const component of components) {
|
|
767
|
+
const file = path.join(outDir, "server", `${component.id}.mjs`);
|
|
768
|
+
if (await existsFile(file)) {
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
await writeFile(file, component.serverSource, "utf8");
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
function localizeRouteManifest(routes, runtimeConfig) {
|
|
775
|
+
const i18n = readRuntimeI18nConfig(runtimeConfig);
|
|
776
|
+
if (!i18n) {
|
|
777
|
+
return routes;
|
|
778
|
+
}
|
|
779
|
+
const localeCodes = i18n.strategy === "no_prefix"
|
|
780
|
+
? [i18n.defaultLocale]
|
|
781
|
+
: i18n.locales.map((locale) => locale.code);
|
|
782
|
+
const localized = [];
|
|
783
|
+
const seenPaths = new Set();
|
|
784
|
+
for (const route of routes) {
|
|
785
|
+
for (const localeCode of localeCodes) {
|
|
786
|
+
const localizedPath = buildLocalePath(route.path, localeCode, i18n);
|
|
787
|
+
if (seenPaths.has(localizedPath)) {
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
seenPaths.add(localizedPath);
|
|
791
|
+
localized.push({
|
|
792
|
+
...route,
|
|
793
|
+
path: localizedPath,
|
|
794
|
+
id: route.id
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
return localized
|
|
799
|
+
.sort((a, b) => routeScore(b.path) - routeScore(a.path) || a.path.localeCompare(b.path))
|
|
800
|
+
.map((route, index) => ({
|
|
801
|
+
...route,
|
|
802
|
+
id: `r${index}`
|
|
803
|
+
}));
|
|
804
|
+
}
|
|
805
|
+
function readRuntimeI18nConfig(runtimeConfig) {
|
|
806
|
+
const directPublicConfig = isPlainObject(runtimeConfig.public)
|
|
807
|
+
? runtimeConfig.public
|
|
808
|
+
: null;
|
|
809
|
+
const nestedRuntimeConfig = isPlainObject(runtimeConfig.runtimeConfig)
|
|
810
|
+
? runtimeConfig.runtimeConfig
|
|
811
|
+
: null;
|
|
812
|
+
const nestedPublicConfig = nestedRuntimeConfig && isPlainObject(nestedRuntimeConfig.public)
|
|
813
|
+
? nestedRuntimeConfig.public
|
|
814
|
+
: null;
|
|
815
|
+
const publicConfig = directPublicConfig ?? nestedPublicConfig;
|
|
816
|
+
if (!publicConfig) {
|
|
817
|
+
return null;
|
|
818
|
+
}
|
|
819
|
+
const i18n = publicConfig.i18n;
|
|
820
|
+
return normalizeI18nRuntimeConfig(i18n);
|
|
821
|
+
}
|
|
822
|
+
function compileTemplate(template, file, templateRefBindings = new Set()) {
|
|
823
|
+
const ast = parseTemplate(template, { comments: false });
|
|
824
|
+
const state = {
|
|
825
|
+
file,
|
|
826
|
+
templateRefBindings,
|
|
827
|
+
bindingIndex: 0,
|
|
828
|
+
inlineHandlerIndex: 0,
|
|
829
|
+
handlers: [],
|
|
830
|
+
inlineHandlers: [],
|
|
831
|
+
expressions: [],
|
|
832
|
+
activeLocals: [],
|
|
833
|
+
allLocals: new Set()
|
|
834
|
+
};
|
|
835
|
+
const nodes = compileTemplateChildren(ast.children, state);
|
|
836
|
+
return {
|
|
837
|
+
nodes,
|
|
838
|
+
handlers: state.handlers,
|
|
839
|
+
inlineHandlers: state.inlineHandlers,
|
|
840
|
+
expressions: state.expressions,
|
|
841
|
+
allLocals: Array.from(state.allLocals)
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
function compileTemplateChildren(children, state) {
|
|
845
|
+
const nodes = [];
|
|
846
|
+
let conditionalChainExpressions = null;
|
|
847
|
+
for (const child of children) {
|
|
848
|
+
if (child.type === NodeTypes.ELEMENT) {
|
|
849
|
+
const conditionalDirective = resolveConditionalDirective(child, state);
|
|
850
|
+
if (!conditionalDirective) {
|
|
851
|
+
conditionalChainExpressions = null;
|
|
852
|
+
const compiledNode = compileTemplateNode(child, state);
|
|
853
|
+
if (compiledNode) {
|
|
854
|
+
nodes.push(compiledNode);
|
|
855
|
+
}
|
|
856
|
+
continue;
|
|
857
|
+
}
|
|
858
|
+
if (conditionalDirective.kind === "if") {
|
|
859
|
+
const expressionResult = transformTemplateExpressionCode(conditionalDirective.expression, state.templateRefBindings, state.file, conditionalDirective.directive);
|
|
860
|
+
conditionalChainExpressions = [expressionResult.transformed];
|
|
861
|
+
const compiledNode = compileTemplateNode(child, state, { ifExpressionOverride: expressionResult.transformed });
|
|
862
|
+
if (compiledNode) {
|
|
863
|
+
nodes.push(compiledNode);
|
|
864
|
+
}
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
if (!conditionalChainExpressions || conditionalChainExpressions.length === 0) {
|
|
868
|
+
throw new ResuxCompileError(`v-${conditionalDirective.kind} must follow a sibling with v-if or v-else-if.`, locationFromVueNode(state.file, conditionalDirective.directive));
|
|
869
|
+
}
|
|
870
|
+
if (conditionalDirective.kind === "else-if") {
|
|
871
|
+
const branchExpressionResult = transformTemplateExpressionCode(conditionalDirective.expression, state.templateRefBindings, state.file, conditionalDirective.directive);
|
|
872
|
+
const expression = `${buildConditionalChainGuard(conditionalChainExpressions)} && (${branchExpressionResult.transformed})`;
|
|
873
|
+
conditionalChainExpressions.push(branchExpressionResult.transformed);
|
|
874
|
+
const compiledNode = compileTemplateNode(child, state, { ifExpressionOverride: expression });
|
|
875
|
+
if (compiledNode) {
|
|
876
|
+
nodes.push(compiledNode);
|
|
877
|
+
}
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
const expression = buildConditionalChainGuard(conditionalChainExpressions);
|
|
881
|
+
conditionalChainExpressions = null;
|
|
882
|
+
const compiledNode = compileTemplateNode(child, state, { ifExpressionOverride: expression });
|
|
883
|
+
if (compiledNode) {
|
|
884
|
+
nodes.push(compiledNode);
|
|
885
|
+
}
|
|
886
|
+
continue;
|
|
887
|
+
}
|
|
888
|
+
if (child.type !== NodeTypes.TEXT || child.content.trim().length > 0) {
|
|
889
|
+
conditionalChainExpressions = null;
|
|
890
|
+
}
|
|
891
|
+
const compiledNode = compileTemplateNode(child, state);
|
|
892
|
+
if (compiledNode) {
|
|
893
|
+
nodes.push(compiledNode);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
return nodes;
|
|
897
|
+
}
|
|
898
|
+
function buildConditionalChainGuard(expressions) {
|
|
899
|
+
return expressions.map((expression) => `!(${expression})`).join(" && ");
|
|
900
|
+
}
|
|
901
|
+
function resolveConditionalDirective(node, state) {
|
|
902
|
+
let conditional = null;
|
|
903
|
+
for (const prop of node.props) {
|
|
904
|
+
if (prop.type !== NodeTypes.DIRECTIVE) {
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
if (prop.name !== "if" && prop.name !== "else-if" && prop.name !== "else") {
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
910
|
+
if (conditional) {
|
|
911
|
+
throw new ResuxCompileError("Only one conditional directive is allowed per element.", locationFromVueNode(state.file, prop));
|
|
912
|
+
}
|
|
913
|
+
const expression = expressionContent(prop.exp).trim();
|
|
914
|
+
if ((prop.name === "if" || prop.name === "else-if") && expression.length === 0) {
|
|
915
|
+
throw new ResuxCompileError(`v-${prop.name} needs an expression.`, locationFromVueNode(state.file, prop));
|
|
916
|
+
}
|
|
917
|
+
if (prop.name === "else" && expression.length > 0) {
|
|
918
|
+
throw new ResuxCompileError("v-else does not accept an expression.", locationFromVueNode(state.file, prop));
|
|
919
|
+
}
|
|
920
|
+
conditional = {
|
|
921
|
+
kind: prop.name,
|
|
922
|
+
directive: prop,
|
|
923
|
+
expression: expression.length > 0 ? expression : undefined,
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
return conditional;
|
|
927
|
+
}
|
|
928
|
+
function expressionContent(node) {
|
|
929
|
+
if (node && typeof node === "object" && "content" in node && typeof node.content === "string") {
|
|
930
|
+
return node.content;
|
|
931
|
+
}
|
|
932
|
+
return "";
|
|
933
|
+
}
|
|
934
|
+
function compileTemplateNode(node, state, options = {}) {
|
|
935
|
+
if (node.type === NodeTypes.TEXT) {
|
|
936
|
+
return {
|
|
937
|
+
type: "text",
|
|
938
|
+
value: node.content
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
if (node.type === NodeTypes.INTERPOLATION) {
|
|
942
|
+
return {
|
|
943
|
+
type: "interpolation",
|
|
944
|
+
expression: registerTemplateExpression(expressionContent(node.content), state.templateRefBindings, state.file, node, state),
|
|
945
|
+
bindingId: nextBindingId(state)
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
if (node.type !== NodeTypes.ELEMENT) {
|
|
949
|
+
return null;
|
|
950
|
+
}
|
|
951
|
+
// Find v-for to track locals for children
|
|
952
|
+
const forProp = node.props.find((prop) => prop.type === NodeTypes.DIRECTIVE && prop.name === "for");
|
|
953
|
+
let addedLocals = 0;
|
|
954
|
+
if (forProp) {
|
|
955
|
+
const expression = expressionContent(forProp.exp);
|
|
956
|
+
if (expression) {
|
|
957
|
+
const parsedFor = parseForExpression(expression, state.file, forProp, state);
|
|
958
|
+
state.activeLocals.push(parsedFor.value);
|
|
959
|
+
state.allLocals.add(parsedFor.value);
|
|
960
|
+
addedLocals++;
|
|
961
|
+
if (parsedFor.index) {
|
|
962
|
+
state.activeLocals.push(parsedFor.index);
|
|
963
|
+
state.allLocals.add(parsedFor.index);
|
|
964
|
+
addedLocals++;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
// Find slot props to track locals for children
|
|
969
|
+
const slotProp = node.props.find((prop) => prop.type === NodeTypes.DIRECTIVE && prop.name === "slot");
|
|
970
|
+
if (slotProp) {
|
|
971
|
+
const expression = expressionContent(slotProp.exp);
|
|
972
|
+
if (expression) {
|
|
973
|
+
const slotLocals = parseBindingNames(expression);
|
|
974
|
+
for (const local of slotLocals) {
|
|
975
|
+
state.activeLocals.push(local);
|
|
976
|
+
state.allLocals.add(local);
|
|
977
|
+
addedLocals++;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
const attrs = [];
|
|
982
|
+
const events = [];
|
|
983
|
+
const element = {
|
|
984
|
+
type: "element",
|
|
985
|
+
tag: node.tag,
|
|
986
|
+
attrs,
|
|
987
|
+
events,
|
|
988
|
+
children: compileTemplateChildren(node.children, state)
|
|
989
|
+
};
|
|
990
|
+
for (const prop of node.props) {
|
|
991
|
+
if (prop.type === NodeTypes.ATTRIBUTE) {
|
|
992
|
+
attrs.push({
|
|
993
|
+
kind: "static",
|
|
994
|
+
name: prop.name,
|
|
995
|
+
value: prop.value?.content ?? ""
|
|
996
|
+
});
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
if (prop.type !== NodeTypes.DIRECTIVE) {
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
if (prop.name === "bind") {
|
|
1003
|
+
const arg = expressionContent(prop.arg);
|
|
1004
|
+
const expression = expressionContent(prop.exp);
|
|
1005
|
+
if (!arg || !expression) {
|
|
1006
|
+
throw new ResuxCompileError("Dynamic bindings need an argument and expression.", locationFromVueNode(state.file, prop));
|
|
1007
|
+
}
|
|
1008
|
+
attrs.push({
|
|
1009
|
+
kind: "dynamic",
|
|
1010
|
+
name: arg,
|
|
1011
|
+
value: registerTemplateExpression(expression, state.templateRefBindings, state.file, prop, state),
|
|
1012
|
+
bindingId: nextBindingId(state)
|
|
1013
|
+
});
|
|
1014
|
+
continue;
|
|
1015
|
+
}
|
|
1016
|
+
if (prop.name === "on") {
|
|
1017
|
+
const arg = expressionContent(prop.arg);
|
|
1018
|
+
const expression = expressionContent(prop.exp);
|
|
1019
|
+
const modifiers = normalizeEventModifiers(prop.modifiers ?? [], state.file, prop);
|
|
1020
|
+
if (!arg || !expression) {
|
|
1021
|
+
throw new ResuxCompileError("Events need an argument and expression.", locationFromVueNode(state.file, prop));
|
|
1022
|
+
}
|
|
1023
|
+
const isSimpleIdentifier = /^[A-Za-z_$][\w$]*$/.test(expression);
|
|
1024
|
+
const handler = (isSimpleIdentifier && !state.activeLocals.includes(expression))
|
|
1025
|
+
? expression
|
|
1026
|
+
: createInlineEventHandler(expression, state, prop);
|
|
1027
|
+
const event = {
|
|
1028
|
+
name: arg,
|
|
1029
|
+
handler,
|
|
1030
|
+
modifiers
|
|
1031
|
+
};
|
|
1032
|
+
events.push(event);
|
|
1033
|
+
state.handlers.push(event);
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
if (prop.name === "if") {
|
|
1037
|
+
if (options.ifExpressionOverride) {
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
const expression = expressionContent(prop.exp);
|
|
1041
|
+
if (!expression) {
|
|
1042
|
+
throw new ResuxCompileError("v-if needs an expression.", locationFromVueNode(state.file, prop));
|
|
1043
|
+
}
|
|
1044
|
+
element.if = {
|
|
1045
|
+
expression: registerTemplateExpression(expression, state.templateRefBindings, state.file, prop, state),
|
|
1046
|
+
blockId: nextBindingId(state)
|
|
1047
|
+
};
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
if (prop.name === "else-if" || prop.name === "else") {
|
|
1051
|
+
if (options.ifExpressionOverride) {
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
throw new ResuxCompileError(`v-${prop.name} must follow a sibling with v-if or v-else-if.`, locationFromVueNode(state.file, prop));
|
|
1055
|
+
}
|
|
1056
|
+
if (prop.name === "for") {
|
|
1057
|
+
const expression = expressionContent(prop.exp);
|
|
1058
|
+
if (!expression) {
|
|
1059
|
+
throw new ResuxCompileError("v-for needs an expression.", locationFromVueNode(state.file, prop));
|
|
1060
|
+
}
|
|
1061
|
+
element.for = parseForExpression(expression, state.file, prop, state);
|
|
1062
|
+
element.for.source = registerTemplateExpression(element.for.source, state.templateRefBindings, state.file, prop, state);
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
if (prop.name === "show") {
|
|
1066
|
+
const expression = expressionContent(prop.exp);
|
|
1067
|
+
if (!expression) {
|
|
1068
|
+
throw new ResuxCompileError("v-show needs an expression.", locationFromVueNode(state.file, prop));
|
|
1069
|
+
}
|
|
1070
|
+
attrs.push({
|
|
1071
|
+
kind: "dynamic",
|
|
1072
|
+
name: "hidden",
|
|
1073
|
+
value: registerRawTemplateExpression(`!(${transformTemplateExpressionCode(expression, state.templateRefBindings, state.file, prop).transformed})`, expression, transformTemplateExpressionCode(expression, state.templateRefBindings, state.file, prop).identifiers, state),
|
|
1074
|
+
bindingId: nextBindingId(state)
|
|
1075
|
+
});
|
|
1076
|
+
continue;
|
|
1077
|
+
}
|
|
1078
|
+
if (prop.name === "text") {
|
|
1079
|
+
const expression = expressionContent(prop.exp);
|
|
1080
|
+
if (!expression) {
|
|
1081
|
+
throw new ResuxCompileError("v-text needs an expression.", locationFromVueNode(state.file, prop));
|
|
1082
|
+
}
|
|
1083
|
+
element.children = [{
|
|
1084
|
+
type: "interpolation",
|
|
1085
|
+
expression: registerTemplateExpression(expression, state.templateRefBindings, state.file, prop, state),
|
|
1086
|
+
bindingId: nextBindingId(state)
|
|
1087
|
+
}];
|
|
1088
|
+
continue;
|
|
1089
|
+
}
|
|
1090
|
+
if (prop.name === "html") {
|
|
1091
|
+
const expression = expressionContent(prop.exp);
|
|
1092
|
+
if (!expression) {
|
|
1093
|
+
throw new ResuxCompileError("v-html needs an expression.", locationFromVueNode(state.file, prop));
|
|
1094
|
+
}
|
|
1095
|
+
element.html = {
|
|
1096
|
+
expression: registerTemplateExpression(expression, state.templateRefBindings, state.file, prop, state),
|
|
1097
|
+
bindingId: nextBindingId(state)
|
|
1098
|
+
};
|
|
1099
|
+
element.children = [];
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
if (prop.name === "model") {
|
|
1103
|
+
const expression = expressionContent(prop.exp);
|
|
1104
|
+
if (!expression) {
|
|
1105
|
+
throw new ResuxCompileError("v-model needs an expression.", locationFromVueNode(state.file, prop));
|
|
1106
|
+
}
|
|
1107
|
+
if (!isAssignableExpression(expression)) {
|
|
1108
|
+
throw new ResuxCompileError("v-model needs an assignable expression like \"message.value\".", locationFromVueNode(state.file, prop));
|
|
1109
|
+
}
|
|
1110
|
+
const model = createModelBinding(node.tag, node.props, expression, state);
|
|
1111
|
+
attrs.push({
|
|
1112
|
+
kind: "dynamic",
|
|
1113
|
+
name: model.attribute,
|
|
1114
|
+
value: registerTemplateExpression(model.value, state.templateRefBindings, state.file, prop, state),
|
|
1115
|
+
bindingId: nextBindingId(state)
|
|
1116
|
+
});
|
|
1117
|
+
const event = {
|
|
1118
|
+
name: model.event,
|
|
1119
|
+
handler: model.handler,
|
|
1120
|
+
modifiers: []
|
|
1121
|
+
};
|
|
1122
|
+
events.push(event);
|
|
1123
|
+
state.handlers.push(event);
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
const argSuffix = prop.arg ? `:${expressionContent(prop.arg)}` : "";
|
|
1127
|
+
const name = `v-${prop.name}${argSuffix}`;
|
|
1128
|
+
const expression = expressionContent(prop.exp);
|
|
1129
|
+
if (expression) {
|
|
1130
|
+
attrs.push({
|
|
1131
|
+
kind: "dynamic",
|
|
1132
|
+
name,
|
|
1133
|
+
value: registerTemplateExpression(expression, state.templateRefBindings, state.file, prop, state),
|
|
1134
|
+
bindingId: nextBindingId(state)
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
else {
|
|
1138
|
+
attrs.push({
|
|
1139
|
+
kind: "static",
|
|
1140
|
+
name,
|
|
1141
|
+
value: ""
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
continue;
|
|
1145
|
+
}
|
|
1146
|
+
if (options.ifExpressionOverride) {
|
|
1147
|
+
element.if = {
|
|
1148
|
+
expression: registerRawTemplateExpression(options.ifExpressionOverride, options.ifExpressionOverride, [], state),
|
|
1149
|
+
blockId: nextBindingId(state),
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
if (addedLocals > 0) {
|
|
1153
|
+
state.activeLocals.splice(state.activeLocals.length - addedLocals, addedLocals);
|
|
1154
|
+
}
|
|
1155
|
+
return element;
|
|
1156
|
+
}
|
|
1157
|
+
function createInlineEventHandler(expression, state, node) {
|
|
1158
|
+
const name = nextInlineHandlerName(state);
|
|
1159
|
+
const transformed = transformTemplateExpressionCode(expression, state.templateRefBindings, state.file, node ?? {}).transformed;
|
|
1160
|
+
state.inlineHandlers.push({
|
|
1161
|
+
name,
|
|
1162
|
+
source: `function ${name}($event) {\n${transformed}\n}`,
|
|
1163
|
+
locals: [...state.activeLocals]
|
|
1164
|
+
});
|
|
1165
|
+
return name;
|
|
1166
|
+
}
|
|
1167
|
+
function createModelBinding(tag, props, expression, state) {
|
|
1168
|
+
const normalizedTag = tag.toLowerCase();
|
|
1169
|
+
const inputType = normalizedTag === "input" ? staticAttributeValue(props, "type")?.toLowerCase() : undefined;
|
|
1170
|
+
const isCheckbox = inputType === "checkbox";
|
|
1171
|
+
const handler = nextInlineHandlerName(state);
|
|
1172
|
+
const target = "$event.target";
|
|
1173
|
+
const assignmentExpression = state.templateRefBindings.has(expression.trim()) ? `${expression.trim()}.value` : expression;
|
|
1174
|
+
const assignment = isCheckbox
|
|
1175
|
+
? `${assignmentExpression} = Boolean(${target} && ${target}.checked)`
|
|
1176
|
+
: `${assignmentExpression} = ${target} ? ${target}.value : ""`;
|
|
1177
|
+
state.inlineHandlers.push({
|
|
1178
|
+
name: handler,
|
|
1179
|
+
source: `function ${handler}($event) {\n${assignment}\n}`,
|
|
1180
|
+
locals: [...state.activeLocals]
|
|
1181
|
+
});
|
|
1182
|
+
return {
|
|
1183
|
+
attribute: isCheckbox ? "checked" : "value",
|
|
1184
|
+
value: expression,
|
|
1185
|
+
event: isCheckbox || normalizedTag === "select" ? "change" : "input",
|
|
1186
|
+
handler
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
function staticAttributeValue(props, name) {
|
|
1190
|
+
const attr = props.find((prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === name);
|
|
1191
|
+
return attr?.value?.content;
|
|
1192
|
+
}
|
|
1193
|
+
function registerTemplateExpression(expression, templateRefBindings, file, node, state) {
|
|
1194
|
+
const result = transformTemplateExpressionCode(expression, templateRefBindings, file, node);
|
|
1195
|
+
return registerRawTemplateExpression(result.transformed, expression, result.identifiers, state);
|
|
1196
|
+
}
|
|
1197
|
+
function registerRawTemplateExpression(transformed, original, identifiers, state) {
|
|
1198
|
+
const id = `__rx_expr_${state.expressions.length}`;
|
|
1199
|
+
state.expressions.push({
|
|
1200
|
+
id,
|
|
1201
|
+
original,
|
|
1202
|
+
transformed,
|
|
1203
|
+
locals: identifiers // repurposing locals to store the free identifiers needed for the closure
|
|
1204
|
+
});
|
|
1205
|
+
return id;
|
|
1206
|
+
}
|
|
1207
|
+
function transformTemplateExpressionCode(expression, templateRefBindings, file, node) {
|
|
1208
|
+
if (expression.trim() === "") {
|
|
1209
|
+
return { transformed: expression, identifiers: [] };
|
|
1210
|
+
}
|
|
1211
|
+
const wrapped = `(${expression})`;
|
|
1212
|
+
const sourceFile = ts.createSourceFile(`${file}?template-expression`, wrapped, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
1213
|
+
if ((sourceFile.parseDiagnostics ?? []).length > 0) {
|
|
1214
|
+
throw new ResuxCompileError("Template expression is not valid JavaScript.", locationFromVueNode(file, node));
|
|
1215
|
+
}
|
|
1216
|
+
const insertions = [];
|
|
1217
|
+
const identifiers = new Set();
|
|
1218
|
+
const visit = (current) => {
|
|
1219
|
+
if (ts.isIdentifier(current)) {
|
|
1220
|
+
if (shouldAutoUnwrapTemplateIdentifier(current)) {
|
|
1221
|
+
if (templateRefBindings.has(current.text)) {
|
|
1222
|
+
const position = current.end - 1;
|
|
1223
|
+
if (position >= 0 && position <= expression.length) {
|
|
1224
|
+
insertions.push(position);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
let isPropertyName = false;
|
|
1229
|
+
const parent = current.parent;
|
|
1230
|
+
if (parent) {
|
|
1231
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name === current) {
|
|
1232
|
+
isPropertyName = true;
|
|
1233
|
+
}
|
|
1234
|
+
if (ts.isPropertyAssignment(parent) && parent.name === current) {
|
|
1235
|
+
isPropertyName = true;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
if (!isPropertyName && !["undefined", "NaN", "Infinity", "arguments", "this"].includes(current.text)) {
|
|
1239
|
+
identifiers.add(current.text);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
ts.forEachChild(current, visit);
|
|
1243
|
+
};
|
|
1244
|
+
visit(sourceFile);
|
|
1245
|
+
let transformed = expression;
|
|
1246
|
+
if (insertions.length > 0) {
|
|
1247
|
+
const uniqueInsertions = [...new Set(insertions)].sort((a, b) => b - a);
|
|
1248
|
+
for (const position of uniqueInsertions) {
|
|
1249
|
+
transformed = `${transformed.slice(0, position)}.value${transformed.slice(position)}`;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
return { transformed, identifiers: [...identifiers] };
|
|
1253
|
+
}
|
|
1254
|
+
function shouldAutoUnwrapTemplateIdentifier(node) {
|
|
1255
|
+
const parent = node.parent;
|
|
1256
|
+
if (!parent) {
|
|
1257
|
+
return true;
|
|
1258
|
+
}
|
|
1259
|
+
if (ts.isPropertyAccessExpression(parent)) {
|
|
1260
|
+
if (parent.expression === node && parent.name.text === "value") {
|
|
1261
|
+
return false;
|
|
1262
|
+
}
|
|
1263
|
+
return parent.name !== node;
|
|
1264
|
+
}
|
|
1265
|
+
if (ts.isPropertyAssignment(parent) && parent.name === node) {
|
|
1266
|
+
return false;
|
|
1267
|
+
}
|
|
1268
|
+
if (ts.isShorthandPropertyAssignment(parent) || ts.isBindingElement(parent)) {
|
|
1269
|
+
return false;
|
|
1270
|
+
}
|
|
1271
|
+
return true;
|
|
1272
|
+
}
|
|
1273
|
+
function isAssignableExpression(expression) {
|
|
1274
|
+
return /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^\]]+\])*$/.test(expression.trim());
|
|
1275
|
+
}
|
|
1276
|
+
function normalizeEventModifiers(modifiers, file, node) {
|
|
1277
|
+
const modifierNames = modifiers.map((modifier) => String(modifier.content));
|
|
1278
|
+
const supported = new Set([
|
|
1279
|
+
"prevent",
|
|
1280
|
+
"stop",
|
|
1281
|
+
"self",
|
|
1282
|
+
"once",
|
|
1283
|
+
"capture",
|
|
1284
|
+
"passive",
|
|
1285
|
+
"ctrl",
|
|
1286
|
+
"shift",
|
|
1287
|
+
"alt",
|
|
1288
|
+
"meta",
|
|
1289
|
+
"exact",
|
|
1290
|
+
"left",
|
|
1291
|
+
"middle",
|
|
1292
|
+
"right",
|
|
1293
|
+
"enter",
|
|
1294
|
+
"tab",
|
|
1295
|
+
"delete",
|
|
1296
|
+
"esc",
|
|
1297
|
+
"escape",
|
|
1298
|
+
"space",
|
|
1299
|
+
"up",
|
|
1300
|
+
"down",
|
|
1301
|
+
"left",
|
|
1302
|
+
"right"
|
|
1303
|
+
]);
|
|
1304
|
+
const unsupported = modifierNames.find((modifier) => !supported.has(modifier));
|
|
1305
|
+
if (unsupported) {
|
|
1306
|
+
throw new ResuxCompileError(`Event modifier ".${unsupported}" is not supported in the resumability runtime yet.`, locationFromVueNode(file, node));
|
|
1307
|
+
}
|
|
1308
|
+
return modifierNames;
|
|
1309
|
+
}
|
|
1310
|
+
function parseForExpression(expression, file, node, state) {
|
|
1311
|
+
const match = /^\s*(?:\(([^)]+)\)|([A-Za-z_$][\w$]*))\s+(?:in|of)\s+(.+)\s*$/.exec(expression);
|
|
1312
|
+
if (!match) {
|
|
1313
|
+
throw new ResuxCompileError("v-for must look like \"item in items\" or \"(item, index) in items\".", locationFromVueNode(file, node));
|
|
1314
|
+
}
|
|
1315
|
+
const aliases = (match[1] ?? match[2]).split(",").map((part) => part.trim()).filter(Boolean);
|
|
1316
|
+
if (!aliases[0] || aliases.length > 2) {
|
|
1317
|
+
throw new ResuxCompileError("v-for supports only value and optional index aliases.", locationFromVueNode(file, node));
|
|
1318
|
+
}
|
|
1319
|
+
return {
|
|
1320
|
+
value: aliases[0],
|
|
1321
|
+
index: aliases[1],
|
|
1322
|
+
source: match[3],
|
|
1323
|
+
blockId: nextBindingId(state)
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
function parseBindingNames(expression) {
|
|
1327
|
+
const source = `const ${expression} = null;`;
|
|
1328
|
+
const sf = ts.createSourceFile("temp.ts", source, ts.ScriptTarget.Latest, true);
|
|
1329
|
+
const names = [];
|
|
1330
|
+
if (sf.statements.length > 0) {
|
|
1331
|
+
const stmt = sf.statements[0];
|
|
1332
|
+
if (ts.isVariableStatement(stmt)) {
|
|
1333
|
+
const decl = stmt.declarationList.declarations[0];
|
|
1334
|
+
if (decl) {
|
|
1335
|
+
names.push(...collectBindingNames(decl.name));
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
return names;
|
|
1340
|
+
}
|
|
1341
|
+
function rewriteImportStatementText(statement, sourceFile, file) {
|
|
1342
|
+
if (ts.isImportDeclaration(statement)) {
|
|
1343
|
+
const specifier = statement.moduleSpecifier;
|
|
1344
|
+
if (ts.isStringLiteral(specifier)) {
|
|
1345
|
+
const importPath = specifier.text;
|
|
1346
|
+
if (importPath.startsWith(".")) {
|
|
1347
|
+
const absoluteImported = path.resolve(path.dirname(file), importPath);
|
|
1348
|
+
const resolvedPath = resolveFileExtension(absoluteImported);
|
|
1349
|
+
const normalized = fileUrl(resolvedPath);
|
|
1350
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1351
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1352
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1353
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
else if (ts.isImportEqualsDeclaration(statement)) {
|
|
1358
|
+
const moduleRef = statement.moduleReference;
|
|
1359
|
+
if (ts.isExternalModuleReference(moduleRef) && ts.isStringLiteral(moduleRef.expression)) {
|
|
1360
|
+
const specifier = moduleRef.expression;
|
|
1361
|
+
const importPath = specifier.text;
|
|
1362
|
+
if (importPath.startsWith(".")) {
|
|
1363
|
+
const absoluteImported = path.resolve(path.dirname(file), importPath);
|
|
1364
|
+
const resolvedPath = resolveFileExtension(absoluteImported);
|
|
1365
|
+
const normalized = fileUrl(resolvedPath);
|
|
1366
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1367
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1368
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1369
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
return statement.getFullText(sourceFile);
|
|
1374
|
+
}
|
|
1375
|
+
function findProjectRoot(startFile) {
|
|
1376
|
+
let dir = path.dirname(startFile);
|
|
1377
|
+
while (true) {
|
|
1378
|
+
if (existsSync(path.join(dir, "resux.config.ts")) ||
|
|
1379
|
+
existsSync(path.join(dir, "package.json")) ||
|
|
1380
|
+
existsSync(path.join(dir, "nuxt.config.ts"))) {
|
|
1381
|
+
return dir;
|
|
1382
|
+
}
|
|
1383
|
+
const parent = path.dirname(dir);
|
|
1384
|
+
if (parent === dir) {
|
|
1385
|
+
break;
|
|
1386
|
+
}
|
|
1387
|
+
dir = parent;
|
|
1388
|
+
}
|
|
1389
|
+
return path.dirname(startFile);
|
|
1390
|
+
}
|
|
1391
|
+
const IMAGE_VIDEO_FONT_EXTENSIONS = new Set([
|
|
1392
|
+
".webp", ".png", ".jpg", ".jpeg", ".svg", ".gif", ".ico", ".webm", ".mp4",
|
|
1393
|
+
".wav", ".mp3", ".ogg", ".woff", ".woff2", ".ttf", ".eot"
|
|
1394
|
+
]);
|
|
1395
|
+
const STYLESHEET_EXTENSIONS = new Set([
|
|
1396
|
+
".css", ".scss", ".sass", ".less", ".styl", ".stylus"
|
|
1397
|
+
]);
|
|
1398
|
+
function ensureCompiledUserModule(resolvedFile, projectRoot, outDir, compiledSet = new Set()) {
|
|
1399
|
+
const relativePath = path.relative(projectRoot, resolvedFile);
|
|
1400
|
+
const targetJsFile = path.join(outDir, "server", "imported", relativePath.replace(/\.[ct]sx?$/, ".mjs"));
|
|
1401
|
+
if (compiledSet.has(resolvedFile)) {
|
|
1402
|
+
return targetJsFile;
|
|
1403
|
+
}
|
|
1404
|
+
compiledSet.add(resolvedFile);
|
|
1405
|
+
let sourceText = "";
|
|
1406
|
+
try {
|
|
1407
|
+
sourceText = ts.sys.readFile(resolvedFile) ?? "";
|
|
1408
|
+
}
|
|
1409
|
+
catch {
|
|
1410
|
+
return resolvedFile;
|
|
1411
|
+
}
|
|
1412
|
+
const sourceFile = ts.createSourceFile(resolvedFile, sourceText, ts.ScriptTarget.ES2022, true);
|
|
1413
|
+
const replacements = [];
|
|
1414
|
+
for (const statement of sourceFile.statements) {
|
|
1415
|
+
if (ts.isImportDeclaration(statement) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) {
|
|
1416
|
+
const specifier = statement.moduleSpecifier;
|
|
1417
|
+
const importPath = specifier.text;
|
|
1418
|
+
if (importPath.startsWith(".") || importPath.startsWith("@/") || importPath.startsWith("~/")) {
|
|
1419
|
+
let resolvedImported = "";
|
|
1420
|
+
if (importPath.startsWith(".")) {
|
|
1421
|
+
resolvedImported = path.resolve(path.dirname(resolvedFile), importPath);
|
|
1422
|
+
}
|
|
1423
|
+
else {
|
|
1424
|
+
resolvedImported = path.resolve(projectRoot, importPath.slice(2));
|
|
1425
|
+
}
|
|
1426
|
+
resolvedImported = resolveFileExtension(resolvedImported);
|
|
1427
|
+
const ext = path.extname(resolvedImported).toLowerCase();
|
|
1428
|
+
if (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx") {
|
|
1429
|
+
const compiledTarget = ensureCompiledUserModule(resolvedImported, projectRoot, outDir, compiledSet);
|
|
1430
|
+
const relativeToCompiled = path.relative(path.dirname(targetJsFile), compiledTarget);
|
|
1431
|
+
const relativeImportPath = relativeToCompiled.startsWith(".")
|
|
1432
|
+
? relativeToCompiled.replace(/\\/g, "/")
|
|
1433
|
+
: "./" + relativeToCompiled.replace(/\\/g, "/");
|
|
1434
|
+
replacements.push({
|
|
1435
|
+
start: specifier.getStart(sourceFile),
|
|
1436
|
+
end: specifier.getEnd(),
|
|
1437
|
+
replacement: JSON.stringify(relativeImportPath)
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
replacements.sort((a, b) => b.start - a.start);
|
|
1444
|
+
let rewrittenSource = sourceText;
|
|
1445
|
+
for (const r of replacements) {
|
|
1446
|
+
rewrittenSource = rewrittenSource.slice(0, r.start) + r.replacement + rewrittenSource.slice(r.end);
|
|
1447
|
+
}
|
|
1448
|
+
const transpiled = ts.transpileModule(rewrittenSource, {
|
|
1449
|
+
compilerOptions: {
|
|
1450
|
+
target: ts.ScriptTarget.ES2022,
|
|
1451
|
+
module: ts.ModuleKind.ES2022,
|
|
1452
|
+
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove
|
|
1453
|
+
}
|
|
1454
|
+
}).outputText;
|
|
1455
|
+
const targetDir = path.dirname(targetJsFile);
|
|
1456
|
+
if (!existsSync(targetDir)) {
|
|
1457
|
+
mkdirSync(targetDir, { recursive: true });
|
|
1458
|
+
}
|
|
1459
|
+
writeFileSync(targetJsFile, transpiled, "utf8");
|
|
1460
|
+
return targetJsFile;
|
|
1461
|
+
}
|
|
1462
|
+
function processImportDeclaration(statement, sourceFile, file, client) {
|
|
1463
|
+
if (ts.isImportDeclaration(statement)) {
|
|
1464
|
+
const specifier = statement.moduleSpecifier;
|
|
1465
|
+
if (!ts.isStringLiteral(specifier)) {
|
|
1466
|
+
return statement.getFullText(sourceFile);
|
|
1467
|
+
}
|
|
1468
|
+
const importPath = specifier.text;
|
|
1469
|
+
const isRelative = importPath.startsWith(".");
|
|
1470
|
+
const isAlias = importPath.startsWith("@/") || importPath.startsWith("~/");
|
|
1471
|
+
const ext = path.extname(importPath).toLowerCase();
|
|
1472
|
+
if (IMAGE_VIDEO_FONT_EXTENSIONS.has(ext) || STYLESHEET_EXTENSIONS.has(ext)) {
|
|
1473
|
+
if (client) {
|
|
1474
|
+
if (isRelative) {
|
|
1475
|
+
const absoluteImported = path.resolve(path.dirname(file), importPath);
|
|
1476
|
+
const normalized = fileUrl(absoluteImported);
|
|
1477
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1478
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1479
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1480
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1481
|
+
}
|
|
1482
|
+
if (isAlias) {
|
|
1483
|
+
const projectRoot = findProjectRoot(file);
|
|
1484
|
+
const absoluteImported = path.resolve(projectRoot, importPath.slice(2));
|
|
1485
|
+
const normalized = fileUrl(absoluteImported);
|
|
1486
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1487
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1488
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1489
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1490
|
+
}
|
|
1491
|
+
return statement.getFullText(sourceFile);
|
|
1492
|
+
}
|
|
1493
|
+
else {
|
|
1494
|
+
if (STYLESHEET_EXTENSIONS.has(ext)) {
|
|
1495
|
+
return "";
|
|
1496
|
+
}
|
|
1497
|
+
const projectRoot = findProjectRoot(file);
|
|
1498
|
+
let absolutePath = "";
|
|
1499
|
+
if (isAlias) {
|
|
1500
|
+
absolutePath = path.resolve(projectRoot, importPath.slice(2));
|
|
1501
|
+
}
|
|
1502
|
+
else if (isRelative) {
|
|
1503
|
+
absolutePath = path.resolve(path.dirname(file), importPath);
|
|
1504
|
+
}
|
|
1505
|
+
else {
|
|
1506
|
+
absolutePath = importPath;
|
|
1507
|
+
}
|
|
1508
|
+
let webPath = importPath;
|
|
1509
|
+
if (absolutePath.startsWith(projectRoot)) {
|
|
1510
|
+
const relativeToRoot = path.relative(projectRoot, absolutePath);
|
|
1511
|
+
webPath = "/" + relativeToRoot.replace(/\\/g, "/");
|
|
1512
|
+
}
|
|
1513
|
+
const clause = statement.importClause;
|
|
1514
|
+
if (!clause) {
|
|
1515
|
+
return "";
|
|
1516
|
+
}
|
|
1517
|
+
const bindings = [];
|
|
1518
|
+
if (clause.name) {
|
|
1519
|
+
bindings.push(clause.name.text);
|
|
1520
|
+
}
|
|
1521
|
+
if (clause.namedBindings) {
|
|
1522
|
+
if (ts.isNamespaceImport(clause.namedBindings)) {
|
|
1523
|
+
bindings.push(clause.namedBindings.name.text);
|
|
1524
|
+
}
|
|
1525
|
+
else {
|
|
1526
|
+
for (const element of clause.namedBindings.elements) {
|
|
1527
|
+
bindings.push(element.name.text);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
if (bindings.length === 0) {
|
|
1532
|
+
return "";
|
|
1533
|
+
}
|
|
1534
|
+
return bindings.map(name => `const ${name} = ${JSON.stringify(webPath)};`).join("\n");
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
if (isRelative) {
|
|
1538
|
+
const absoluteImported = path.resolve(path.dirname(file), importPath);
|
|
1539
|
+
const resolvedPath = resolveFileExtension(absoluteImported);
|
|
1540
|
+
const resolvedExt = path.extname(resolvedPath).toLowerCase();
|
|
1541
|
+
let normalized = "";
|
|
1542
|
+
if (!client && (resolvedExt === ".ts" || resolvedExt === ".tsx" || resolvedExt === ".js" || resolvedExt === ".jsx")) {
|
|
1543
|
+
const projectRoot = findProjectRoot(file);
|
|
1544
|
+
const outDir = path.join(projectRoot, ".resux");
|
|
1545
|
+
const compiledTarget = ensureCompiledUserModule(resolvedPath, projectRoot, outDir);
|
|
1546
|
+
normalized = fileUrl(compiledTarget);
|
|
1547
|
+
}
|
|
1548
|
+
else {
|
|
1549
|
+
normalized = fileUrl(resolvedPath);
|
|
1550
|
+
}
|
|
1551
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1552
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1553
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1554
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1555
|
+
}
|
|
1556
|
+
if (!client && isAlias) {
|
|
1557
|
+
const projectRoot = findProjectRoot(file);
|
|
1558
|
+
const absoluteImported = path.resolve(projectRoot, importPath.slice(2));
|
|
1559
|
+
const resolvedPath = resolveFileExtension(absoluteImported);
|
|
1560
|
+
const resolvedExt = path.extname(resolvedPath).toLowerCase();
|
|
1561
|
+
let normalized = "";
|
|
1562
|
+
if (resolvedExt === ".ts" || resolvedExt === ".tsx" || resolvedExt === ".js" || resolvedExt === ".jsx") {
|
|
1563
|
+
const outDir = path.join(projectRoot, ".resux");
|
|
1564
|
+
const compiledTarget = ensureCompiledUserModule(resolvedPath, projectRoot, outDir);
|
|
1565
|
+
normalized = fileUrl(compiledTarget);
|
|
1566
|
+
}
|
|
1567
|
+
else {
|
|
1568
|
+
normalized = fileUrl(resolvedPath);
|
|
1569
|
+
}
|
|
1570
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1571
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1572
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1573
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
else if (ts.isImportEqualsDeclaration(statement)) {
|
|
1577
|
+
const moduleRef = statement.moduleReference;
|
|
1578
|
+
if (ts.isExternalModuleReference(moduleRef) && ts.isStringLiteral(moduleRef.expression)) {
|
|
1579
|
+
const specifier = moduleRef.expression;
|
|
1580
|
+
const importPath = specifier.text;
|
|
1581
|
+
const isRelative = importPath.startsWith(".");
|
|
1582
|
+
const isAlias = importPath.startsWith("@/") || importPath.startsWith("~/");
|
|
1583
|
+
const ext = path.extname(importPath).toLowerCase();
|
|
1584
|
+
if (IMAGE_VIDEO_FONT_EXTENSIONS.has(ext) || STYLESHEET_EXTENSIONS.has(ext)) {
|
|
1585
|
+
if (client) {
|
|
1586
|
+
if (isRelative) {
|
|
1587
|
+
const absoluteImported = path.resolve(path.dirname(file), importPath);
|
|
1588
|
+
const normalized = fileUrl(absoluteImported);
|
|
1589
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1590
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1591
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1592
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1593
|
+
}
|
|
1594
|
+
if (isAlias) {
|
|
1595
|
+
const projectRoot = findProjectRoot(file);
|
|
1596
|
+
const absoluteImported = path.resolve(projectRoot, importPath.slice(2));
|
|
1597
|
+
const normalized = fileUrl(absoluteImported);
|
|
1598
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1599
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1600
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1601
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1602
|
+
}
|
|
1603
|
+
return statement.getFullText(sourceFile);
|
|
1604
|
+
}
|
|
1605
|
+
else {
|
|
1606
|
+
if (STYLESHEET_EXTENSIONS.has(ext)) {
|
|
1607
|
+
return "";
|
|
1608
|
+
}
|
|
1609
|
+
const projectRoot = findProjectRoot(file);
|
|
1610
|
+
let absolutePath = "";
|
|
1611
|
+
if (isAlias) {
|
|
1612
|
+
absolutePath = path.resolve(projectRoot, importPath.slice(2));
|
|
1613
|
+
}
|
|
1614
|
+
else if (isRelative) {
|
|
1615
|
+
absolutePath = path.resolve(path.dirname(file), importPath);
|
|
1616
|
+
}
|
|
1617
|
+
else {
|
|
1618
|
+
absolutePath = importPath;
|
|
1619
|
+
}
|
|
1620
|
+
let webPath = importPath;
|
|
1621
|
+
if (absolutePath.startsWith(projectRoot)) {
|
|
1622
|
+
const relativeToRoot = path.relative(projectRoot, absolutePath);
|
|
1623
|
+
webPath = "/" + relativeToRoot.replace(/\\/g, "/");
|
|
1624
|
+
}
|
|
1625
|
+
if (!statement.name) {
|
|
1626
|
+
return "";
|
|
1627
|
+
}
|
|
1628
|
+
return `const ${statement.name.text} = ${JSON.stringify(webPath)};`;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
if (isRelative) {
|
|
1632
|
+
const absoluteImported = path.resolve(path.dirname(file), importPath);
|
|
1633
|
+
const resolvedPath = resolveFileExtension(absoluteImported);
|
|
1634
|
+
const resolvedExt = path.extname(resolvedPath).toLowerCase();
|
|
1635
|
+
let normalized = "";
|
|
1636
|
+
if (!client && (resolvedExt === ".ts" || resolvedExt === ".tsx" || resolvedExt === ".js" || resolvedExt === ".jsx")) {
|
|
1637
|
+
const projectRoot = findProjectRoot(file);
|
|
1638
|
+
const outDir = path.join(projectRoot, ".resux");
|
|
1639
|
+
const compiledTarget = ensureCompiledUserModule(resolvedPath, projectRoot, outDir);
|
|
1640
|
+
normalized = fileUrl(compiledTarget);
|
|
1641
|
+
}
|
|
1642
|
+
else {
|
|
1643
|
+
normalized = fileUrl(resolvedPath);
|
|
1644
|
+
}
|
|
1645
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1646
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1647
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1648
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1649
|
+
}
|
|
1650
|
+
if (!client && isAlias) {
|
|
1651
|
+
const projectRoot = findProjectRoot(file);
|
|
1652
|
+
const absoluteImported = path.resolve(projectRoot, importPath.slice(2));
|
|
1653
|
+
const resolvedPath = resolveFileExtension(absoluteImported);
|
|
1654
|
+
const resolvedExt = path.extname(resolvedPath).toLowerCase();
|
|
1655
|
+
let normalized = "";
|
|
1656
|
+
if (resolvedExt === ".ts" || resolvedExt === ".tsx" || resolvedExt === ".js" || resolvedExt === ".jsx") {
|
|
1657
|
+
const outDir = path.join(projectRoot, ".resux");
|
|
1658
|
+
const compiledTarget = ensureCompiledUserModule(resolvedPath, projectRoot, outDir);
|
|
1659
|
+
normalized = fileUrl(compiledTarget);
|
|
1660
|
+
}
|
|
1661
|
+
else {
|
|
1662
|
+
normalized = fileUrl(resolvedPath);
|
|
1663
|
+
}
|
|
1664
|
+
const fullText = statement.getFullText(sourceFile);
|
|
1665
|
+
const start = specifier.getStart(sourceFile) - statement.getFullStart();
|
|
1666
|
+
const end = specifier.getEnd() - statement.getFullStart();
|
|
1667
|
+
return fullText.slice(0, start) + JSON.stringify(normalized) + fullText.slice(end);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
return statement.getFullText(sourceFile);
|
|
1672
|
+
}
|
|
1673
|
+
function analyzeScript(script, file, inlineHandlers = []) {
|
|
1674
|
+
const sourceFile = ts.createSourceFile(file, script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
1675
|
+
const imports = [];
|
|
1676
|
+
const importDeclarations = [];
|
|
1677
|
+
const body = [];
|
|
1678
|
+
const bindings = new Set();
|
|
1679
|
+
const handlerNames = new Set();
|
|
1680
|
+
const resumableBindings = new Set();
|
|
1681
|
+
const importedBindings = new Set();
|
|
1682
|
+
const inlineHandlerLocals = new Map();
|
|
1683
|
+
const templateRefBindings = inferTemplateRefBindings(script, file);
|
|
1684
|
+
const handlers = new Map();
|
|
1685
|
+
let pageMeta;
|
|
1686
|
+
for (const h of inlineHandlers) {
|
|
1687
|
+
if (h.locals) {
|
|
1688
|
+
inlineHandlerLocals.set(h.name, h.locals);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
for (const statement of sourceFile.statements) {
|
|
1692
|
+
const text = statement.getFullText(sourceFile);
|
|
1693
|
+
if (ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) {
|
|
1694
|
+
imports.push(rewriteImportStatementText(statement, sourceFile, file));
|
|
1695
|
+
importDeclarations.push(statement);
|
|
1696
|
+
if (ts.isImportDeclaration(statement)) {
|
|
1697
|
+
const clause = statement.importClause;
|
|
1698
|
+
if (clause) {
|
|
1699
|
+
if (clause.name) {
|
|
1700
|
+
bindings.add(clause.name.text);
|
|
1701
|
+
importedBindings.add(clause.name.text);
|
|
1702
|
+
}
|
|
1703
|
+
if (clause.namedBindings) {
|
|
1704
|
+
if (ts.isNamespaceImport(clause.namedBindings)) {
|
|
1705
|
+
bindings.add(clause.namedBindings.name.text);
|
|
1706
|
+
importedBindings.add(clause.namedBindings.name.text);
|
|
1707
|
+
}
|
|
1708
|
+
else {
|
|
1709
|
+
for (const element of clause.namedBindings.elements) {
|
|
1710
|
+
bindings.add(element.name.text);
|
|
1711
|
+
importedBindings.add(element.name.text);
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
else if (ts.isImportEqualsDeclaration(statement) && statement.name) {
|
|
1718
|
+
bindings.add(statement.name.text);
|
|
1719
|
+
importedBindings.add(statement.name.text);
|
|
1720
|
+
}
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
if (isDefinePageMetaStatement(statement)) {
|
|
1724
|
+
pageMeta = readPageMeta(statement, sourceFile, file);
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
body.push(text);
|
|
1728
|
+
if (ts.isFunctionDeclaration(statement) && statement.name) {
|
|
1729
|
+
bindings.add(statement.name.text);
|
|
1730
|
+
handlerNames.add(statement.name.text);
|
|
1731
|
+
handlers.set(statement.name.text, statement);
|
|
1732
|
+
continue;
|
|
1733
|
+
}
|
|
1734
|
+
if (ts.isVariableStatement(statement)) {
|
|
1735
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
1736
|
+
for (const name of collectBindingNames(declaration.name)) {
|
|
1737
|
+
bindings.add(name);
|
|
1738
|
+
}
|
|
1739
|
+
if (ts.isIdentifier(declaration.name)) {
|
|
1740
|
+
if (isHandlerLikeInitializer(declaration.initializer)) {
|
|
1741
|
+
handlerNames.add(declaration.name.text);
|
|
1742
|
+
handlers.set(declaration.name.text, declaration);
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
if (isResumableInitializer(declaration.initializer)) {
|
|
1746
|
+
for (const name of collectBindingNames(declaration.name)) {
|
|
1747
|
+
resumableBindings.add(name);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
if (inlineHandlers.length > 0) {
|
|
1754
|
+
const inlineSource = inlineHandlers.map((handler) => handler.source).join("\n");
|
|
1755
|
+
const inlineSourceFile = ts.createSourceFile(`${file}?inline-handlers`, inlineSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
1756
|
+
body.push(inlineSource);
|
|
1757
|
+
for (const statement of inlineSourceFile.statements) {
|
|
1758
|
+
if (ts.isFunctionDeclaration(statement) && statement.name) {
|
|
1759
|
+
bindings.add(statement.name.text);
|
|
1760
|
+
handlerNames.add(statement.name.text);
|
|
1761
|
+
handlers.set(statement.name.text, statement);
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
return {
|
|
1766
|
+
imports: imports.join("\n"),
|
|
1767
|
+
importDeclarations,
|
|
1768
|
+
setupBody: body.join("\n"),
|
|
1769
|
+
bindings: [...bindings],
|
|
1770
|
+
handlerNames,
|
|
1771
|
+
resumableBindings,
|
|
1772
|
+
importedBindings,
|
|
1773
|
+
inlineHandlerLocals,
|
|
1774
|
+
templateRefBindings,
|
|
1775
|
+
handlers,
|
|
1776
|
+
sourceFile,
|
|
1777
|
+
pageMeta
|
|
1778
|
+
};
|
|
1779
|
+
}
|
|
1780
|
+
function inferTemplateRefBindings(script, file) {
|
|
1781
|
+
const sourceFile = ts.createSourceFile(file, script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
1782
|
+
const bindings = new Set();
|
|
1783
|
+
for (const statement of sourceFile.statements) {
|
|
1784
|
+
if (!ts.isVariableStatement(statement)) {
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
1788
|
+
const initializer = unwrapAwaitExpression(declaration.initializer);
|
|
1789
|
+
if (!initializer || !ts.isCallExpression(initializer)) {
|
|
1790
|
+
continue;
|
|
1791
|
+
}
|
|
1792
|
+
const callee = initializer.expression;
|
|
1793
|
+
const calleeName = ts.isIdentifier(callee)
|
|
1794
|
+
? callee.text
|
|
1795
|
+
: ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.name)
|
|
1796
|
+
? callee.name.text
|
|
1797
|
+
: "";
|
|
1798
|
+
if (ts.isIdentifier(declaration.name) && isTemplateRefFactory(calleeName)) {
|
|
1799
|
+
bindings.add(declaration.name.text);
|
|
1800
|
+
continue;
|
|
1801
|
+
}
|
|
1802
|
+
if (ts.isObjectBindingPattern(declaration.name) && isObjectTemplateRefFactory(calleeName)) {
|
|
1803
|
+
for (const element of declaration.name.elements) {
|
|
1804
|
+
if (!ts.isBindingElement(element) || !ts.isIdentifier(element.name)) {
|
|
1805
|
+
continue;
|
|
1806
|
+
}
|
|
1807
|
+
const propertyName = element.propertyName && ts.isIdentifier(element.propertyName)
|
|
1808
|
+
? element.propertyName.text
|
|
1809
|
+
: element.name.text;
|
|
1810
|
+
if (calleeName === "toRefs" || ["data", "pending", "error", "value"].includes(propertyName)) {
|
|
1811
|
+
bindings.add(element.name.text);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
return bindings;
|
|
1818
|
+
}
|
|
1819
|
+
function unwrapAwaitExpression(node) {
|
|
1820
|
+
return node && ts.isAwaitExpression(node) ? node.expression : node;
|
|
1821
|
+
}
|
|
1822
|
+
function isTemplateRefFactory(name) {
|
|
1823
|
+
return ["ref", "computed", "toRef", "useState", "useAsyncData", "useFetch", "useResuxImage", "useError"].includes(name);
|
|
1824
|
+
}
|
|
1825
|
+
function isAsyncDataFactory(name) {
|
|
1826
|
+
return ["useAsyncData", "useFetch"].includes(name);
|
|
1827
|
+
}
|
|
1828
|
+
function isObjectTemplateRefFactory(name) {
|
|
1829
|
+
return isAsyncDataFactory(name) || name === "toRefs";
|
|
1830
|
+
}
|
|
1831
|
+
function isDefinePageMetaStatement(statement) {
|
|
1832
|
+
return ts.isExpressionStatement(statement)
|
|
1833
|
+
&& ts.isCallExpression(statement.expression)
|
|
1834
|
+
&& ts.isIdentifier(statement.expression.expression)
|
|
1835
|
+
&& statement.expression.expression.text === "definePageMeta";
|
|
1836
|
+
}
|
|
1837
|
+
function readPageMeta(statement, sourceFile, file) {
|
|
1838
|
+
if (!isDefinePageMetaStatement(statement)) {
|
|
1839
|
+
return {};
|
|
1840
|
+
}
|
|
1841
|
+
const call = statement.expression;
|
|
1842
|
+
const firstArg = call.arguments[0];
|
|
1843
|
+
if (!firstArg || !ts.isObjectLiteralExpression(firstArg)) {
|
|
1844
|
+
throw new ResuxCompileError("definePageMeta only supports an object literal in Resux.", locationFromTsNode(file, sourceFile, statement));
|
|
1845
|
+
}
|
|
1846
|
+
return readObjectLiteral(firstArg, sourceFile, file);
|
|
1847
|
+
}
|
|
1848
|
+
function readObjectLiteral(node, sourceFile, file) {
|
|
1849
|
+
const output = {};
|
|
1850
|
+
for (const property of node.properties) {
|
|
1851
|
+
if (!ts.isPropertyAssignment(property)) {
|
|
1852
|
+
throw new ResuxCompileError("Only plain object properties are supported here.", locationFromTsNode(file, sourceFile, property));
|
|
1853
|
+
}
|
|
1854
|
+
const name = readPropertyName(property.name, sourceFile, file);
|
|
1855
|
+
output[name] = readLiteralValue(property.initializer, sourceFile, file);
|
|
1856
|
+
}
|
|
1857
|
+
return output;
|
|
1858
|
+
}
|
|
1859
|
+
function readLiteralValue(node, sourceFile, file) {
|
|
1860
|
+
if (ts.isStringLiteralLike(node)) {
|
|
1861
|
+
return node.text;
|
|
1862
|
+
}
|
|
1863
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword) {
|
|
1864
|
+
return true;
|
|
1865
|
+
}
|
|
1866
|
+
if (node.kind === ts.SyntaxKind.FalseKeyword) {
|
|
1867
|
+
return false;
|
|
1868
|
+
}
|
|
1869
|
+
if (ts.isNumericLiteral(node)) {
|
|
1870
|
+
return Number(node.text);
|
|
1871
|
+
}
|
|
1872
|
+
if (ts.isArrayLiteralExpression(node)) {
|
|
1873
|
+
return node.elements.map((element) => readLiteralValue(element, sourceFile, file));
|
|
1874
|
+
}
|
|
1875
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
1876
|
+
return readObjectLiteral(node, sourceFile, file);
|
|
1877
|
+
}
|
|
1878
|
+
throw new ResuxCompileError("Only JSON-like literals are supported here.", locationFromTsNode(file, sourceFile, node));
|
|
1879
|
+
}
|
|
1880
|
+
function readPropertyName(name, sourceFile, file) {
|
|
1881
|
+
if (ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
|
|
1882
|
+
return name.text;
|
|
1883
|
+
}
|
|
1884
|
+
throw new ResuxCompileError("Only simple property names are supported here.", locationFromTsNode(file, sourceFile, name));
|
|
1885
|
+
}
|
|
1886
|
+
function validateTemplateHandlers(events, analysis, file, fullSource, templateLocals = []) {
|
|
1887
|
+
const allowedHandlers = new Set([...analysis.handlerNames, ...templateLocals]);
|
|
1888
|
+
for (const event of events) {
|
|
1889
|
+
if (!allowedHandlers.has(event.handler)) {
|
|
1890
|
+
throw new ResuxCompileError(`Handler "${event.handler}" must be a top-level function or arrow function.`, locationFromOffset(file, fullSource, 0));
|
|
1891
|
+
}
|
|
1892
|
+
const handlerNode = analysis.handlers.get(event.handler);
|
|
1893
|
+
if (!handlerNode) {
|
|
1894
|
+
continue;
|
|
1895
|
+
}
|
|
1896
|
+
const locals = analysis.inlineHandlerLocals.get(event.handler) ?? [];
|
|
1897
|
+
const unsupportedCapture = findUnsupportedCapture(handlerNode, event.handler, analysis, locals);
|
|
1898
|
+
if (unsupportedCapture) {
|
|
1899
|
+
throw new ResuxCompileError(`Handler "${event.handler}" captures "${unsupportedCapture}", which is not resumable in Resux.`, locationFromTsNode(file, analysis.sourceFile, handlerNode));
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
function findUnsupportedCapture(node, handlerName, analysis, templateLocals = []) {
|
|
1904
|
+
const locals = new Set([handlerName, "event", ...templateLocals]);
|
|
1905
|
+
const allowedTopLevel = new Set([
|
|
1906
|
+
...analysis.resumableBindings,
|
|
1907
|
+
...analysis.handlerNames,
|
|
1908
|
+
...analysis.importedBindings
|
|
1909
|
+
]);
|
|
1910
|
+
function registerPattern(name) {
|
|
1911
|
+
for (const binding of collectBindingNames(name)) {
|
|
1912
|
+
locals.add(binding);
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
if (ts.isFunctionDeclaration(node)) {
|
|
1916
|
+
for (const parameter of node.parameters) {
|
|
1917
|
+
registerPattern(parameter.name);
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
if (ts.isVariableDeclaration(node) && node.initializer && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))) {
|
|
1921
|
+
for (const parameter of node.initializer.parameters) {
|
|
1922
|
+
registerPattern(parameter.name);
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
let unsupported = null;
|
|
1926
|
+
function visit(current) {
|
|
1927
|
+
if (unsupported) {
|
|
1928
|
+
return;
|
|
1929
|
+
}
|
|
1930
|
+
if (ts.isVariableDeclaration(current)) {
|
|
1931
|
+
registerPattern(current.name);
|
|
1932
|
+
}
|
|
1933
|
+
if (ts.isIdentifier(current) && isValueIdentifier(current)) {
|
|
1934
|
+
const name = current.text;
|
|
1935
|
+
if (!locals.has(name) && !RESUMABLE_HANDLER_ALLOWED_GLOBALS.has(name) && !allowedTopLevel.has(name)) {
|
|
1936
|
+
unsupported = name;
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
ts.forEachChild(current, visit);
|
|
1941
|
+
}
|
|
1942
|
+
ts.forEachChild(node, visit);
|
|
1943
|
+
return unsupported;
|
|
1944
|
+
}
|
|
1945
|
+
function isValueIdentifier(node) {
|
|
1946
|
+
const parent = node.parent;
|
|
1947
|
+
if (!parent) {
|
|
1948
|
+
return true;
|
|
1949
|
+
}
|
|
1950
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name === node) {
|
|
1951
|
+
return false;
|
|
1952
|
+
}
|
|
1953
|
+
if (ts.isPropertyAssignment(parent) && parent.name === node) {
|
|
1954
|
+
return false;
|
|
1955
|
+
}
|
|
1956
|
+
if ((ts.isVariableDeclaration(parent) || ts.isFunctionDeclaration(parent) || ts.isParameter(parent)) && parent.name === node) {
|
|
1957
|
+
return false;
|
|
1958
|
+
}
|
|
1959
|
+
if (ts.isBindingElement(parent) && parent.name === node) {
|
|
1960
|
+
return false;
|
|
1961
|
+
}
|
|
1962
|
+
return true;
|
|
1963
|
+
}
|
|
1964
|
+
function isHandlerLikeInitializer(node) {
|
|
1965
|
+
return Boolean(node && (ts.isArrowFunction(node) || ts.isFunctionExpression(node)));
|
|
1966
|
+
}
|
|
1967
|
+
function isResumableInitializer(node) {
|
|
1968
|
+
if (!node) {
|
|
1969
|
+
return false;
|
|
1970
|
+
}
|
|
1971
|
+
if (ts.isNumericLiteral(node) || ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
|
|
1972
|
+
return true;
|
|
1973
|
+
}
|
|
1974
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword || node.kind === ts.SyntaxKind.NullKeyword) {
|
|
1975
|
+
return true;
|
|
1976
|
+
}
|
|
1977
|
+
if (ts.isPrefixUnaryExpression(node) && ts.isNumericLiteral(node.operand)) {
|
|
1978
|
+
return true;
|
|
1979
|
+
}
|
|
1980
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
1981
|
+
if (node.expression.text.startsWith("use")) {
|
|
1982
|
+
return true;
|
|
1983
|
+
}
|
|
1984
|
+
return [
|
|
1985
|
+
"ref",
|
|
1986
|
+
"reactive",
|
|
1987
|
+
"computed",
|
|
1988
|
+
"readonly",
|
|
1989
|
+
"toRef",
|
|
1990
|
+
"toRefs",
|
|
1991
|
+
"watch",
|
|
1992
|
+
"watchEffect",
|
|
1993
|
+
"useState",
|
|
1994
|
+
"useAsyncData",
|
|
1995
|
+
"useRoute",
|
|
1996
|
+
"useRouter",
|
|
1997
|
+
"useRuntimeConfig",
|
|
1998
|
+
"useResuxApp",
|
|
1999
|
+
"useResuxImage",
|
|
2000
|
+
"usePackageReady",
|
|
2001
|
+
"defineProps",
|
|
2002
|
+
"defineEmits"
|
|
2003
|
+
].includes(node.expression.text);
|
|
2004
|
+
}
|
|
2005
|
+
if (ts.isAwaitExpression(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression)) {
|
|
2006
|
+
if (node.expression.expression.text.startsWith("use")) {
|
|
2007
|
+
return true;
|
|
2008
|
+
}
|
|
2009
|
+
return ["useAsyncData", "useFetch"].includes(node.expression.expression.text);
|
|
2010
|
+
}
|
|
2011
|
+
return false;
|
|
2012
|
+
}
|
|
2013
|
+
function collectBindingNames(name) {
|
|
2014
|
+
if (ts.isIdentifier(name)) {
|
|
2015
|
+
return [name.text];
|
|
2016
|
+
}
|
|
2017
|
+
const names = [];
|
|
2018
|
+
for (const element of name.elements) {
|
|
2019
|
+
if (ts.isBindingElement(element)) {
|
|
2020
|
+
names.push(...collectBindingNames(element.name));
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
return names;
|
|
2024
|
+
}
|
|
2025
|
+
function createComponentModuleSource(options) {
|
|
2026
|
+
const importPath = options.client ? "/__resux/runtime-client.mjs" : "resuxjs/runtime";
|
|
2027
|
+
const factory = options.client ? "createClientComponent" : "defineComponent";
|
|
2028
|
+
const expressionClosures = (options.expressions ?? []).map((expr) => {
|
|
2029
|
+
const destructure = expr.locals.length > 0
|
|
2030
|
+
? expr.locals.map(id => `let ${id} = (locals && "${id}" in locals) ? locals.${id} : (scope && "${id}" in scope) ? scope.${id} : (typeof globalThis !== "undefined" && "${id}" in globalThis) ? globalThis.${id} : undefined;
|
|
2031
|
+
if (typeof ${id} === "string" && ${id}.startsWith("__rx_callback:")) {
|
|
2032
|
+
const parts = ${id}.split(":");
|
|
2033
|
+
const cbScopeId = parts[2];
|
|
2034
|
+
const cbHandler = parts[3];
|
|
2035
|
+
${id} = async (...args) => {
|
|
2036
|
+
const payload = globalThis.__RESUX__;
|
|
2037
|
+
if (payload && payload.scopes[cbScopeId]) {
|
|
2038
|
+
const comp = await importComponent(payload.scopes[cbScopeId].moduleId, payload.modules, devImportRevision);
|
|
2039
|
+
let sRec = scopeCache.get(cbScopeId);
|
|
2040
|
+
if (!sRec) {
|
|
2041
|
+
sRec = await comp.createScope(payload.scopes[cbScopeId], payload.route);
|
|
2042
|
+
scopeCache.set(cbScopeId, sRec);
|
|
2043
|
+
}
|
|
2044
|
+
const patches = await comp.run(sRec, cbHandler, args[0]);
|
|
2045
|
+
const serialized = comp.serialize(sRec);
|
|
2046
|
+
payload.scopes[cbScopeId].props = serialized.props;
|
|
2047
|
+
payload.scopes[cbScopeId].state = serialized.state;
|
|
2048
|
+
payload.scopes[cbScopeId].asyncData = serialized.asyncData;
|
|
2049
|
+
applyPatches(cbScopeId, patches);
|
|
2050
|
+
}
|
|
2051
|
+
};
|
|
2052
|
+
}`).join("\n ")
|
|
2053
|
+
: "";
|
|
2054
|
+
return ` ${JSON.stringify(expr.id)}: function(scope, locals) {
|
|
2055
|
+
${destructure}
|
|
2056
|
+
return (${expr.transformed});
|
|
2057
|
+
},`;
|
|
2058
|
+
}).join("\n");
|
|
2059
|
+
const importsText = (options.analysis.importDeclarations ?? []).map((decl) => {
|
|
2060
|
+
return processImportDeclaration(decl, options.analysis.sourceFile, options.file, options.client);
|
|
2061
|
+
}).filter(Boolean).join("\n");
|
|
2062
|
+
const source = [
|
|
2063
|
+
`import { ${factory} } from ${JSON.stringify(importPath)};`,
|
|
2064
|
+
importsText,
|
|
2065
|
+
`const __template = ${JSON.stringify(options.template, null, 2)};`,
|
|
2066
|
+
`async function __rx_setup(__ctx) {`,
|
|
2067
|
+
`const { ref, reactive, computed, watch, watchEffect, readonly, toRef, toRefs, unref, isRef, isReactive, isReadonly, nextTick, useState, useAsyncData, useRoute, useRouter, useHead, useSeoMeta, useRuntimeConfig, useResuxApp, useResuxImage, apiURL, useFetch, $fetch, useError, clearError, showError, createError, useLazyPackage, useClientPackage, usePackageReady, defineLazyPackage, defineClientOnlyPackage, definePackageAdapter, defineClientEnhancement, useClientEnhancement, onMounted, definePageMeta, defineProps, defineEmits, useLocalePath, useSwitchLocalePath, useI18n, useDevice, $device, importComponent, scopeCache, devImportRevision, applyPatches } = __ctx;`,
|
|
2068
|
+
options.analysis.setupBody,
|
|
2069
|
+
`const __rx_expressions = {`,
|
|
2070
|
+
expressionClosures,
|
|
2071
|
+
`};`,
|
|
2072
|
+
`return { ${options.analysis.bindings.join(", ")}, __rx_expressions };`,
|
|
2073
|
+
`}`,
|
|
2074
|
+
`export default ${factory}({`,
|
|
2075
|
+
`id: ${JSON.stringify(options.id)},`,
|
|
2076
|
+
`name: ${JSON.stringify(options.name)},`,
|
|
2077
|
+
`file: ${JSON.stringify(normalizePath(options.file))},`,
|
|
2078
|
+
`script: __rx_setup,`,
|
|
2079
|
+
`template: __template,`,
|
|
2080
|
+
`handlers: ${JSON.stringify([...options.analysis.handlerNames])},`,
|
|
2081
|
+
`styles: ${JSON.stringify(options.styles)},`,
|
|
2082
|
+
`styleScopeId: ${JSON.stringify(options.styleScopeId)},`,
|
|
2083
|
+
`meta: ${JSON.stringify(options.analysis.pageMeta ?? {})}`,
|
|
2084
|
+
`});`
|
|
2085
|
+
].join("\n");
|
|
2086
|
+
return ts.transpileModule(source, {
|
|
2087
|
+
compilerOptions: {
|
|
2088
|
+
target: ts.ScriptTarget.ES2022,
|
|
2089
|
+
module: ts.ModuleKind.ES2022,
|
|
2090
|
+
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove
|
|
2091
|
+
}
|
|
2092
|
+
}).outputText;
|
|
2093
|
+
}
|
|
2094
|
+
function createVueIslandClientSource(island, entryDir) {
|
|
2095
|
+
const componentImport = relativeImportPath(entryDir, island.file);
|
|
2096
|
+
return [
|
|
2097
|
+
`import { createApp } from "vue";`,
|
|
2098
|
+
`import Component from ${JSON.stringify(componentImport)};`,
|
|
2099
|
+
`export function mount(el, props = {}) {`,
|
|
2100
|
+
` const app = createApp(Component, props);`,
|
|
2101
|
+
` app.mount(el);`,
|
|
2102
|
+
` return app;`,
|
|
2103
|
+
`}`,
|
|
2104
|
+
`export default { mount };`
|
|
2105
|
+
].join("\n");
|
|
2106
|
+
}
|
|
2107
|
+
function relativeImportPath(fromDir, file) {
|
|
2108
|
+
const relative = normalizePath(path.relative(fromDir, file));
|
|
2109
|
+
return relative.startsWith(".") ? relative : `./${relative}`;
|
|
2110
|
+
}
|
|
2111
|
+
function createServerManifestSource(routes, components, layouts, plugins, middleware, serverMiddleware, serverHandlers, vueIslands, app, error, runtimeConfig = {}, buildOptions = {}) {
|
|
2112
|
+
const importSuffix = buildOptions.vite === "dev" ? `?t=${Date.now()}` : "";
|
|
2113
|
+
const serverPlugins = plugins.filter((entry) => entry.mode !== "client");
|
|
2114
|
+
const clientPlugins = plugins.filter((entry) => entry.mode !== "server");
|
|
2115
|
+
const serverRouteMiddleware = middleware.filter((entry) => entry.mode !== "client");
|
|
2116
|
+
const clientRouteMiddleware = middleware.filter((entry) => entry.mode !== "server");
|
|
2117
|
+
const imports = components.map((component) => `import ${component.id} from "./${component.id}.mjs${importSuffix}";`).join("\n");
|
|
2118
|
+
const pluginImports = serverPlugins.map((plugin) => `import ${plugin.id} from "./resux-plugins/${plugin.id}.mjs${importSuffix}";`).join("\n");
|
|
2119
|
+
const middlewareImports = serverRouteMiddleware.map((entry) => `import ${entry.id} from "./resux-middleware/${entry.id}.mjs${importSuffix}";`).join("\n");
|
|
2120
|
+
const serverMiddlewareImports = serverMiddleware.map((entry) => `import ${entry.id} from "./request-middleware/${entry.id}.mjs${importSuffix}";`).join("\n");
|
|
2121
|
+
const handlerImports = serverHandlers.map((handler) => `import ${handler.id} from "./handlers/${handler.id}.mjs${importSuffix}";`).join("\n");
|
|
2122
|
+
const componentEntries = components.map((component) => `${JSON.stringify(component.name)}: ${component.id}`).join(",\n");
|
|
2123
|
+
const layoutEntries = layouts.map((layout) => `${JSON.stringify(layoutNameFromFile(layout.file))}: ${layout.id}`).join(",\n");
|
|
2124
|
+
const moduleEntries = components
|
|
2125
|
+
.map((component) => `${JSON.stringify(component.id)}: ${JSON.stringify(`/__resux/handlers/${component.id}.mjs`)}`)
|
|
2126
|
+
.join(",\n");
|
|
2127
|
+
const vueIslandEntries = vueIslands
|
|
2128
|
+
.map((island) => `${JSON.stringify(island.name)}: ${JSON.stringify(`/__resux/vue-islands/${island.name}.mjs`)}`)
|
|
2129
|
+
.join(",\n");
|
|
2130
|
+
const pluginEntries = serverPlugins
|
|
2131
|
+
.map((plugin) => plugin.id)
|
|
2132
|
+
.join(",\n");
|
|
2133
|
+
const clientPluginEntries = clientPlugins
|
|
2134
|
+
.map((plugin) => `{
|
|
2135
|
+
id: ${JSON.stringify(plugin.id)},
|
|
2136
|
+
file: ${JSON.stringify(normalizePath(plugin.file))},
|
|
2137
|
+
mode: ${JSON.stringify(plugin.mode)},
|
|
2138
|
+
src: ${JSON.stringify(`/__resux/plugins/${plugin.id}.mjs`)}
|
|
2139
|
+
}`)
|
|
2140
|
+
.join(",\n");
|
|
2141
|
+
const middlewareEntries = serverRouteMiddleware
|
|
2142
|
+
.map((entry) => `{
|
|
2143
|
+
id: ${JSON.stringify(entry.id)},
|
|
2144
|
+
name: ${JSON.stringify(entry.name)},
|
|
2145
|
+
file: ${JSON.stringify(normalizePath(entry.file))},
|
|
2146
|
+
global: ${JSON.stringify(entry.global)},
|
|
2147
|
+
mode: ${JSON.stringify(entry.mode)},
|
|
2148
|
+
handler: ${entry.id}
|
|
2149
|
+
}`)
|
|
2150
|
+
.join(",\n");
|
|
2151
|
+
const clientMiddlewareEntries = clientRouteMiddleware
|
|
2152
|
+
.map((entry) => `{
|
|
2153
|
+
id: ${JSON.stringify(entry.id)},
|
|
2154
|
+
name: ${JSON.stringify(entry.name)},
|
|
2155
|
+
file: ${JSON.stringify(normalizePath(entry.file))},
|
|
2156
|
+
global: ${JSON.stringify(entry.global)},
|
|
2157
|
+
mode: ${JSON.stringify(entry.mode)},
|
|
2158
|
+
src: ${JSON.stringify(`/__resux/middleware/${entry.id}.mjs`)}
|
|
2159
|
+
}`)
|
|
2160
|
+
.join(",\n");
|
|
2161
|
+
const serverMiddlewareEntries = serverMiddleware
|
|
2162
|
+
.map((entry) => `{
|
|
2163
|
+
id: ${JSON.stringify(entry.id)},
|
|
2164
|
+
file: ${JSON.stringify(normalizePath(entry.file))},
|
|
2165
|
+
handler: ${entry.id}
|
|
2166
|
+
}`)
|
|
2167
|
+
.join(",\n");
|
|
2168
|
+
const serverHandlerEntries = serverHandlers
|
|
2169
|
+
.map((handler) => `{
|
|
2170
|
+
id: ${JSON.stringify(handler.id)},
|
|
2171
|
+
path: ${JSON.stringify(handler.path)},
|
|
2172
|
+
file: ${JSON.stringify(normalizePath(handler.file))},
|
|
2173
|
+
params: ${JSON.stringify(handler.params)},
|
|
2174
|
+
handler: ${handler.id},
|
|
2175
|
+
match: createMatcher(${JSON.stringify(handler.path)})
|
|
2176
|
+
}`)
|
|
2177
|
+
.join(",\n");
|
|
2178
|
+
const routeEntries = routes
|
|
2179
|
+
.map((route) => {
|
|
2180
|
+
const component = components.find((candidate) => candidate.id === route.componentId);
|
|
2181
|
+
if (!component) {
|
|
2182
|
+
throw new Error(`Missing compiled component for ${route.file}.`);
|
|
2183
|
+
}
|
|
2184
|
+
return `{
|
|
2185
|
+
id: ${JSON.stringify(route.id)},
|
|
2186
|
+
path: ${JSON.stringify(route.path)},
|
|
2187
|
+
file: ${JSON.stringify(normalizePath(route.file))},
|
|
2188
|
+
params: ${JSON.stringify(route.params)},
|
|
2189
|
+
meta: ${JSON.stringify(route.meta ?? {})},
|
|
2190
|
+
component: ${route.componentId},
|
|
2191
|
+
match: createMatcher(${JSON.stringify(route.path)})
|
|
2192
|
+
}`;
|
|
2193
|
+
})
|
|
2194
|
+
.join(",\n");
|
|
2195
|
+
const appHead = createAppHead(runtimeConfig);
|
|
2196
|
+
const appRuntimeConfig = createRuntimeConfig(runtimeConfig);
|
|
2197
|
+
const routeRules = createRouteRules(runtimeConfig);
|
|
2198
|
+
return `${imports}
|
|
2199
|
+
${pluginImports}
|
|
2200
|
+
${middlewareImports}
|
|
2201
|
+
${serverMiddlewareImports}
|
|
2202
|
+
${handlerImports}
|
|
2203
|
+
export const app = ${app ? app.id : "undefined"};
|
|
2204
|
+
export const errorComponent = ${error ? error.id : "undefined"};
|
|
2205
|
+
export const components = {
|
|
2206
|
+
${componentEntries}
|
|
2207
|
+
};
|
|
2208
|
+
export const layouts = {
|
|
2209
|
+
${layoutEntries}
|
|
2210
|
+
};
|
|
2211
|
+
export const modules = {
|
|
2212
|
+
${moduleEntries}
|
|
2213
|
+
};
|
|
2214
|
+
export const vueIslands = {
|
|
2215
|
+
${vueIslandEntries}
|
|
2216
|
+
};
|
|
2217
|
+
export const resuxPlugins = [
|
|
2218
|
+
${pluginEntries}
|
|
2219
|
+
];
|
|
2220
|
+
export const clientPlugins = [
|
|
2221
|
+
${clientPluginEntries}
|
|
2222
|
+
];
|
|
2223
|
+
export const middleware = [
|
|
2224
|
+
${middlewareEntries}
|
|
2225
|
+
];
|
|
2226
|
+
export const clientMiddleware = [
|
|
2227
|
+
${clientMiddlewareEntries}
|
|
2228
|
+
];
|
|
2229
|
+
export const serverMiddleware = [
|
|
2230
|
+
${serverMiddlewareEntries}
|
|
2231
|
+
];
|
|
2232
|
+
export const serverHandlers = [
|
|
2233
|
+
${serverHandlerEntries}
|
|
2234
|
+
];
|
|
2235
|
+
export const runtimeConfig = ${JSON.stringify(appRuntimeConfig, null, 2)};
|
|
2236
|
+
export const appHead = ${JSON.stringify(appHead, null, 2)};
|
|
2237
|
+
export const routeRules = ${JSON.stringify(routeRules, null, 2)};
|
|
2238
|
+
export const routes = [
|
|
2239
|
+
${routeEntries}
|
|
2240
|
+
];
|
|
2241
|
+
export function matchRoute(pathname) {
|
|
2242
|
+
for (const route of routes) {
|
|
2243
|
+
const params = route.match(pathname);
|
|
2244
|
+
if (params) return { route, params };
|
|
2245
|
+
}
|
|
2246
|
+
return null;
|
|
2247
|
+
}
|
|
2248
|
+
export function matchServerHandler(pathname) {
|
|
2249
|
+
for (const route of serverHandlers) {
|
|
2250
|
+
const params = route.match(pathname);
|
|
2251
|
+
if (params) return { route, params };
|
|
2252
|
+
}
|
|
2253
|
+
return null;
|
|
2254
|
+
}
|
|
2255
|
+
function createMatcher(pattern) {
|
|
2256
|
+
const names = [];
|
|
2257
|
+
const source = pattern === "/" ? "^/$" : "^" + pattern.split("/").map((part) => {
|
|
2258
|
+
if (!part) return "";
|
|
2259
|
+
if (part.startsWith(":") && part.endsWith("*")) {
|
|
2260
|
+
names.push(part.slice(1, -1));
|
|
2261
|
+
return "(?:/(.*))?";
|
|
2262
|
+
}
|
|
2263
|
+
if (part.startsWith(":")) {
|
|
2264
|
+
names.push(part.slice(1));
|
|
2265
|
+
return "/([^/]+)";
|
|
2266
|
+
}
|
|
2267
|
+
return "/" + part.replace(/[.*+?^${"${"}}()|[\\]\\\\]/g, "\\\\$&");
|
|
2268
|
+
}).join("") + "$";
|
|
2269
|
+
const regex = new RegExp(source);
|
|
2270
|
+
return (pathname) => {
|
|
2271
|
+
const match = regex.exec(pathname);
|
|
2272
|
+
if (!match) return null;
|
|
2273
|
+
const params = {};
|
|
2274
|
+
names.forEach((name, index) => {
|
|
2275
|
+
params[name] = decodeURIComponent(match[index + 1] ?? "");
|
|
2276
|
+
});
|
|
2277
|
+
return params;
|
|
2278
|
+
};
|
|
2279
|
+
}
|
|
2280
|
+
`;
|
|
2281
|
+
}
|
|
2282
|
+
function createAppHead(runtimeConfig) {
|
|
2283
|
+
const config = runtimeConfig;
|
|
2284
|
+
const head = typeof config.app === "object" && config.app && "head" in config.app
|
|
2285
|
+
? config.app.head
|
|
2286
|
+
: {};
|
|
2287
|
+
const links = Array.isArray(config.css)
|
|
2288
|
+
? config.css.map((href) => ({ rel: "stylesheet", href: String(href) }))
|
|
2289
|
+
: [];
|
|
2290
|
+
return {
|
|
2291
|
+
...(typeof head === "object" && head ? head : {}),
|
|
2292
|
+
link: [
|
|
2293
|
+
...((head?.link) ?? []),
|
|
2294
|
+
...links
|
|
2295
|
+
]
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
function scanRuntimeConfigForSecrets(config, halalConfig) {
|
|
2299
|
+
const publicConfig = config.public;
|
|
2300
|
+
if (!publicConfig || typeof publicConfig !== "object") {
|
|
2301
|
+
return;
|
|
2302
|
+
}
|
|
2303
|
+
const isStrict = halalConfig?.strict === true;
|
|
2304
|
+
const unsafeKeys = ["SECRET", "TOKEN", "PASSWORD", "PRIVATE", "DATABASE", "KEY"];
|
|
2305
|
+
const secretValuePatterns = [
|
|
2306
|
+
/^[a-f0-9]{32,128}$/i,
|
|
2307
|
+
/ey[a-zA-Z0-9_-]{15,}\.ey[a-zA-Z0-9_-]{15,}\.[a-zA-Z0-9_-]{15,}/,
|
|
2308
|
+
/sk_live_[0-9a-zA-Z]{24}/,
|
|
2309
|
+
/AIzaSy[0-9a-zA-Z_-]{33}/,
|
|
2310
|
+
/amzn\.mws\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}/i,
|
|
2311
|
+
/https?:\/\/[^/]+:[^/]+@/
|
|
2312
|
+
];
|
|
2313
|
+
for (const [key, value] of Object.entries(publicConfig)) {
|
|
2314
|
+
const upperKey = key.toUpperCase();
|
|
2315
|
+
const matchesUnsafeKey = unsafeKeys.some(unsafe => upperKey.includes(unsafe));
|
|
2316
|
+
if (matchesUnsafeKey) {
|
|
2317
|
+
const msg = `[resux-safety] Unsafe key name "${key}" found in public runtimeConfig. Do not expose secrets to the client.`;
|
|
2318
|
+
if (isStrict) {
|
|
2319
|
+
throw new Error(msg);
|
|
2320
|
+
}
|
|
2321
|
+
else {
|
|
2322
|
+
console.warn(`\x1b[33m${msg}\x1b[0m`);
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
if (typeof value === "string") {
|
|
2326
|
+
const looksLikeSecret = secretValuePatterns.some(pattern => pattern.test(value));
|
|
2327
|
+
if (looksLikeSecret) {
|
|
2328
|
+
const msg = `[resux-safety] Value of public runtimeConfig key "${key}" looks like a private credential or API secret. Do not expose secrets to the client.`;
|
|
2329
|
+
if (isStrict) {
|
|
2330
|
+
throw new Error(msg);
|
|
2331
|
+
}
|
|
2332
|
+
else {
|
|
2333
|
+
console.warn(`\x1b[33m${msg}\x1b[0m`);
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
function createRuntimeConfig(config) {
|
|
2340
|
+
const runtimeConfig = config.runtimeConfig;
|
|
2341
|
+
const packagesConfig = isPlainObject(config.packages)
|
|
2342
|
+
? config.packages
|
|
2343
|
+
: null;
|
|
2344
|
+
const videoConfig = isPlainObject(config.video)
|
|
2345
|
+
? config.video
|
|
2346
|
+
: null;
|
|
2347
|
+
const publicConfig = (runtimeConfig?.public && typeof runtimeConfig.public === "object" && !Array.isArray(runtimeConfig.public))
|
|
2348
|
+
? runtimeConfig.public
|
|
2349
|
+
: {};
|
|
2350
|
+
const appRuntimeConfig = {
|
|
2351
|
+
...(runtimeConfig ?? {}),
|
|
2352
|
+
public: {
|
|
2353
|
+
...publicConfig,
|
|
2354
|
+
...(packagesConfig ? { packages: packagesConfig } : {}),
|
|
2355
|
+
...(videoConfig ? { video: videoConfig } : {}),
|
|
2356
|
+
}
|
|
2357
|
+
};
|
|
2358
|
+
const halalConfig = config.halalAI;
|
|
2359
|
+
scanRuntimeConfigForSecrets(appRuntimeConfig, halalConfig);
|
|
2360
|
+
return appRuntimeConfig;
|
|
2361
|
+
}
|
|
2362
|
+
function createRouteRules(config) {
|
|
2363
|
+
const routeRules = config.routeRules;
|
|
2364
|
+
if (!routeRules || typeof routeRules !== "object" || Array.isArray(routeRules)) {
|
|
2365
|
+
return {};
|
|
2366
|
+
}
|
|
2367
|
+
const normalized = {};
|
|
2368
|
+
for (const [routePath, rule] of Object.entries(routeRules)) {
|
|
2369
|
+
if (!routePath.startsWith("/") || !rule || typeof rule !== "object" || Array.isArray(rule)) {
|
|
2370
|
+
continue;
|
|
2371
|
+
}
|
|
2372
|
+
const routeRule = rule;
|
|
2373
|
+
normalized[routePath] = {
|
|
2374
|
+
...(routeRule.headers && typeof routeRule.headers === "object" ? { headers: normalizeStringRecord(routeRule.headers) } : {}),
|
|
2375
|
+
...(typeof routeRule.redirect === "string" || isRedirectObject(routeRule.redirect)
|
|
2376
|
+
? { redirect: routeRule.redirect }
|
|
2377
|
+
: {}),
|
|
2378
|
+
...(isStatusCode(routeRule.statusCode) ? { statusCode: routeRule.statusCode } : {}),
|
|
2379
|
+
...(normalizeCacheRule(routeRule.cache) !== undefined ? { cache: normalizeCacheRule(routeRule.cache) } : {}),
|
|
2380
|
+
...(normalizeCorsRule(routeRule.cors) !== undefined ? { cors: normalizeCorsRule(routeRule.cors) } : {})
|
|
2381
|
+
};
|
|
2382
|
+
}
|
|
2383
|
+
return normalized;
|
|
2384
|
+
}
|
|
2385
|
+
function isStatusCode(value) {
|
|
2386
|
+
return Number.isInteger(value) && value >= 100 && value <= 599;
|
|
2387
|
+
}
|
|
2388
|
+
function normalizeCacheRule(value) {
|
|
2389
|
+
if (value === undefined) {
|
|
2390
|
+
return undefined;
|
|
2391
|
+
}
|
|
2392
|
+
if (value === false || typeof value === "string") {
|
|
2393
|
+
return value;
|
|
2394
|
+
}
|
|
2395
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
2396
|
+
return undefined;
|
|
2397
|
+
}
|
|
2398
|
+
const cache = {};
|
|
2399
|
+
if (Number.isFinite(value.maxAge) && value.maxAge >= 0) {
|
|
2400
|
+
cache.maxAge = Math.floor(value.maxAge);
|
|
2401
|
+
}
|
|
2402
|
+
if (Number.isFinite(value.swr) && value.swr >= 0) {
|
|
2403
|
+
cache.swr = Math.floor(value.swr);
|
|
2404
|
+
}
|
|
2405
|
+
return Object.keys(cache).length > 0 ? cache : undefined;
|
|
2406
|
+
}
|
|
2407
|
+
function normalizeCorsRule(value) {
|
|
2408
|
+
if (value === undefined) {
|
|
2409
|
+
return undefined;
|
|
2410
|
+
}
|
|
2411
|
+
if (typeof value === "boolean") {
|
|
2412
|
+
return value;
|
|
2413
|
+
}
|
|
2414
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
2415
|
+
return undefined;
|
|
2416
|
+
}
|
|
2417
|
+
return {
|
|
2418
|
+
...(typeof value.origin === "string" ? { origin: value.origin } : {}),
|
|
2419
|
+
...(Array.isArray(value.methods) ? { methods: value.methods.map(String) } : {}),
|
|
2420
|
+
...(Array.isArray(value.headers) ? { headers: value.headers.map(String) } : {}),
|
|
2421
|
+
...(typeof value.credentials === "boolean" ? { credentials: value.credentials } : {})
|
|
2422
|
+
};
|
|
2423
|
+
}
|
|
2424
|
+
function normalizeStringRecord(record) {
|
|
2425
|
+
const output = {};
|
|
2426
|
+
for (const [key, value] of Object.entries(record)) {
|
|
2427
|
+
if (value !== undefined && value !== null) {
|
|
2428
|
+
output[key] = String(value);
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
return output;
|
|
2432
|
+
}
|
|
2433
|
+
function isRedirectObject(value) {
|
|
2434
|
+
return Boolean(value
|
|
2435
|
+
&& typeof value === "object"
|
|
2436
|
+
&& !Array.isArray(value)
|
|
2437
|
+
&& typeof value.to === "string");
|
|
2438
|
+
}
|
|
2439
|
+
function layoutNameFromFile(file) {
|
|
2440
|
+
return kebabCase(path.basename(file, ".vue"));
|
|
2441
|
+
}
|
|
2442
|
+
function supportFileMode(file) {
|
|
2443
|
+
if (file.includes(".client.")) {
|
|
2444
|
+
return "client";
|
|
2445
|
+
}
|
|
2446
|
+
if (file.includes(".server.")) {
|
|
2447
|
+
return "server";
|
|
2448
|
+
}
|
|
2449
|
+
return "all";
|
|
2450
|
+
}
|
|
2451
|
+
function supportFileBaseName(file) {
|
|
2452
|
+
const extensionStripped = path.basename(file).replace(/\.[cm]?[tj]s$/, "");
|
|
2453
|
+
return extensionStripped.replace(/(?:\.global|\.client|\.server)+$/, "");
|
|
2454
|
+
}
|
|
2455
|
+
function compilePluginFile(file, index) {
|
|
2456
|
+
const mode = supportFileMode(file);
|
|
2457
|
+
return {
|
|
2458
|
+
id: `p${index}`,
|
|
2459
|
+
file,
|
|
2460
|
+
mode,
|
|
2461
|
+
serverSource: transpileSupportModule(file, {
|
|
2462
|
+
prefix: `import { defineResuxPlugin } from "resuxjs/runtime";\nconst defineNuxtPlugin = defineResuxPlugin;\n`,
|
|
2463
|
+
autoImports: [{
|
|
2464
|
+
from: "resuxjs/runtime",
|
|
2465
|
+
names: SUPPORT_CLIENT_RUNTIME_HELPERS,
|
|
2466
|
+
}],
|
|
2467
|
+
}),
|
|
2468
|
+
clientSource: transpileSupportModule(file, {
|
|
2469
|
+
prefix: `import { defineResuxPlugin } from "/__resux/runtime-client.mjs";\nconst defineNuxtPlugin = defineResuxPlugin;\n`,
|
|
2470
|
+
autoImports: [{
|
|
2471
|
+
from: "/__resux/runtime-client.mjs",
|
|
2472
|
+
names: SUPPORT_CLIENT_RUNTIME_HELPERS,
|
|
2473
|
+
}],
|
|
2474
|
+
rewriteImports: {
|
|
2475
|
+
"resuxjs": "/__resux/runtime-client.mjs",
|
|
2476
|
+
"resuxjs/runtime": "/__resux/runtime-client.mjs",
|
|
2477
|
+
},
|
|
2478
|
+
})
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2481
|
+
function compileMiddlewareFile(file, index) {
|
|
2482
|
+
const baseName = supportFileBaseName(file);
|
|
2483
|
+
const mode = supportFileMode(file);
|
|
2484
|
+
const global = /\.global(?:\.(?:client|server))?\.[cm]?[tj]s$/.test(file);
|
|
2485
|
+
return {
|
|
2486
|
+
id: `w${index}`,
|
|
2487
|
+
name: kebabCase(baseName),
|
|
2488
|
+
file,
|
|
2489
|
+
mode,
|
|
2490
|
+
global,
|
|
2491
|
+
serverSource: transpileSupportModule(file, `import { defineResuxRouteMiddleware, navigateTo, abortNavigation } from "resuxjs/runtime";\n`),
|
|
2492
|
+
clientSource: transpileSupportModule(file, `import { defineResuxRouteMiddleware, defineClientRouteRedirect as navigateTo, defineClientRouteAbort as abortNavigation } from "/__resux/runtime-client.mjs";\n`)
|
|
2493
|
+
};
|
|
2494
|
+
}
|
|
2495
|
+
function compileServerMiddlewareFile(file, index) {
|
|
2496
|
+
return {
|
|
2497
|
+
id: `s${index}`,
|
|
2498
|
+
file,
|
|
2499
|
+
source: transpileSupportModule(file, `import { defineServerMiddleware, defineEventHandler, eventHandler, readBody, getQuery, setHeader } from "resuxjs/runtime";\n`)
|
|
2500
|
+
};
|
|
2501
|
+
}
|
|
2502
|
+
function compileServerHandlerFile(file, index, routePath) {
|
|
2503
|
+
const params = collectRouteParams(routePath);
|
|
2504
|
+
return {
|
|
2505
|
+
id: `h${index}`,
|
|
2506
|
+
path: routePath,
|
|
2507
|
+
file,
|
|
2508
|
+
params,
|
|
2509
|
+
source: transpileSupportModule(file, `import { defineEventHandler, eventHandler, readBody, getQuery, setHeader } from "resuxjs/runtime";\n`)
|
|
2510
|
+
};
|
|
2511
|
+
}
|
|
2512
|
+
function transpileSupportModule(file, input = "") {
|
|
2513
|
+
const source = ts.sys.readFile(file) ?? "";
|
|
2514
|
+
const options = typeof input === "string"
|
|
2515
|
+
? { prefix: input }
|
|
2516
|
+
: input;
|
|
2517
|
+
const rewrittenSource = rewriteSupportModuleImports(source, options.rewriteImports);
|
|
2518
|
+
const autoImportPrefix = createSupportModuleAutoImportPrefix(file, rewrittenSource, options.autoImports ?? []);
|
|
2519
|
+
return ts.transpileModule(`${options.prefix ?? ""}${autoImportPrefix}${rewrittenSource}`, {
|
|
2520
|
+
compilerOptions: {
|
|
2521
|
+
target: ts.ScriptTarget.ES2022,
|
|
2522
|
+
module: ts.ModuleKind.ES2022,
|
|
2523
|
+
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove
|
|
2524
|
+
}
|
|
2525
|
+
}).outputText;
|
|
2526
|
+
}
|
|
2527
|
+
function rewriteSupportModuleImports(source, rewrites) {
|
|
2528
|
+
if (!rewrites || Object.keys(rewrites).length === 0) {
|
|
2529
|
+
return source;
|
|
2530
|
+
}
|
|
2531
|
+
let output = source;
|
|
2532
|
+
for (const [from, to] of Object.entries(rewrites)) {
|
|
2533
|
+
if (!from || !to || from === to) {
|
|
2534
|
+
continue;
|
|
2535
|
+
}
|
|
2536
|
+
const escapedFrom = escapeRegExp(from);
|
|
2537
|
+
output = output.replace(new RegExp(`(\\bfrom\\s+["'])${escapedFrom}(["'])`, "g"), `$1${to}$2`);
|
|
2538
|
+
output = output.replace(new RegExp(`(\\bimport\\s*\\(\\s*["'])${escapedFrom}(["']\\s*\\))`, "g"), `$1${to}$2`);
|
|
2539
|
+
}
|
|
2540
|
+
return output;
|
|
2541
|
+
}
|
|
2542
|
+
function escapeRegExp(value) {
|
|
2543
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2544
|
+
}
|
|
2545
|
+
function createSupportModuleAutoImportPrefix(file, source, autoImports) {
|
|
2546
|
+
if (!autoImports.length) {
|
|
2547
|
+
return "";
|
|
2548
|
+
}
|
|
2549
|
+
const declared = collectSupportModuleTopLevelBindings(file, source);
|
|
2550
|
+
const lines = [];
|
|
2551
|
+
for (const entry of autoImports) {
|
|
2552
|
+
const seen = new Set();
|
|
2553
|
+
const names = [];
|
|
2554
|
+
for (const name of entry.names) {
|
|
2555
|
+
if (seen.has(name) || declared.has(name)) {
|
|
2556
|
+
continue;
|
|
2557
|
+
}
|
|
2558
|
+
seen.add(name);
|
|
2559
|
+
const pattern = new RegExp(`\\b${name}\\b`);
|
|
2560
|
+
if (!pattern.test(source)) {
|
|
2561
|
+
continue;
|
|
2562
|
+
}
|
|
2563
|
+
names.push(name);
|
|
2564
|
+
}
|
|
2565
|
+
if (names.length > 0) {
|
|
2566
|
+
lines.push(`import { ${names.join(", ")} } from ${JSON.stringify(entry.from)};`);
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
if (!lines.length) {
|
|
2570
|
+
return "";
|
|
2571
|
+
}
|
|
2572
|
+
return `${lines.join("\n")}\n`;
|
|
2573
|
+
}
|
|
2574
|
+
function collectSupportModuleTopLevelBindings(file, source) {
|
|
2575
|
+
const bindings = new Set();
|
|
2576
|
+
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);
|
|
2577
|
+
for (const statement of sourceFile.statements) {
|
|
2578
|
+
if (ts.isImportDeclaration(statement)) {
|
|
2579
|
+
const clause = statement.importClause;
|
|
2580
|
+
if (!clause) {
|
|
2581
|
+
continue;
|
|
2582
|
+
}
|
|
2583
|
+
if (clause.name) {
|
|
2584
|
+
bindings.add(clause.name.text);
|
|
2585
|
+
}
|
|
2586
|
+
if (clause.namedBindings) {
|
|
2587
|
+
if (ts.isNamespaceImport(clause.namedBindings)) {
|
|
2588
|
+
bindings.add(clause.namedBindings.name.text);
|
|
2589
|
+
}
|
|
2590
|
+
else {
|
|
2591
|
+
for (const element of clause.namedBindings.elements) {
|
|
2592
|
+
bindings.add(element.name.text);
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
continue;
|
|
2597
|
+
}
|
|
2598
|
+
if (ts.isVariableStatement(statement)) {
|
|
2599
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
2600
|
+
for (const name of collectBindingNames(declaration.name)) {
|
|
2601
|
+
bindings.add(name);
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
continue;
|
|
2605
|
+
}
|
|
2606
|
+
if (ts.isFunctionDeclaration(statement) && statement.name) {
|
|
2607
|
+
bindings.add(statement.name.text);
|
|
2608
|
+
continue;
|
|
2609
|
+
}
|
|
2610
|
+
if (ts.isClassDeclaration(statement) && statement.name) {
|
|
2611
|
+
bindings.add(statement.name.text);
|
|
2612
|
+
continue;
|
|
2613
|
+
}
|
|
2614
|
+
if (ts.isEnumDeclaration(statement)) {
|
|
2615
|
+
bindings.add(statement.name.text);
|
|
2616
|
+
continue;
|
|
2617
|
+
}
|
|
2618
|
+
if (ts.isTypeAliasDeclaration(statement)) {
|
|
2619
|
+
bindings.add(statement.name.text);
|
|
2620
|
+
continue;
|
|
2621
|
+
}
|
|
2622
|
+
if (ts.isInterfaceDeclaration(statement)) {
|
|
2623
|
+
bindings.add(statement.name.text);
|
|
2624
|
+
continue;
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
return bindings;
|
|
2628
|
+
}
|
|
2629
|
+
async function readRuntimeConfig(root, outDir, hooks) {
|
|
2630
|
+
const moduleContainer = new ResuxModuleContainer();
|
|
2631
|
+
const candidates = [
|
|
2632
|
+
"resux.config.ts",
|
|
2633
|
+
"resux.config.mjs",
|
|
2634
|
+
"resux.config.js"
|
|
2635
|
+
];
|
|
2636
|
+
for (const candidate of candidates) {
|
|
2637
|
+
const file = await optionalFile(path.join(root, candidate));
|
|
2638
|
+
if (!file) {
|
|
2639
|
+
continue;
|
|
2640
|
+
}
|
|
2641
|
+
const source = normalizeConfigHelpers(await readFile(file, "utf8"));
|
|
2642
|
+
const outputFile = path.join(outDir, "server", "config.mjs");
|
|
2643
|
+
const compiled = ts.transpileModule(source, {
|
|
2644
|
+
compilerOptions: {
|
|
2645
|
+
target: ts.ScriptTarget.ES2022,
|
|
2646
|
+
module: ts.ModuleKind.ES2022
|
|
2647
|
+
}
|
|
2648
|
+
}).outputText;
|
|
2649
|
+
await writeFile(outputFile, compiled, "utf8");
|
|
2650
|
+
const imported = await import(`${pathToFileURL(outputFile).href}?t=${Date.now()}`);
|
|
2651
|
+
const config = (imported.default ?? {});
|
|
2652
|
+
Object.assign(config, createResux({ rootDir: root, buildDir: outDir, config }).options);
|
|
2653
|
+
const context = moduleContainer.createContext(config, root, outDir, hooks);
|
|
2654
|
+
await applyConfiguredModules(config, root, outDir, context);
|
|
2655
|
+
delete config.modules;
|
|
2656
|
+
await writeFile(outputFile, `export default ${JSON.stringify(config, null, 2)};`, "utf8");
|
|
2657
|
+
return { config, moduleContainer };
|
|
2658
|
+
}
|
|
2659
|
+
return { config: createResux({ rootDir: root, buildDir: outDir, config: {} }).options, moduleContainer };
|
|
2660
|
+
}
|
|
2661
|
+
function normalizeConfigHelpers(source) {
|
|
2662
|
+
return source
|
|
2663
|
+
.replace(/\bdefineResuxConfig\s*\(/g, "(")
|
|
2664
|
+
.replace(/\bdefineResuxModule\s*\(/g, "(");
|
|
2665
|
+
}
|
|
2666
|
+
async function applyConfiguredModules(config, root, outDir, context) {
|
|
2667
|
+
const modules = Array.isArray(config.modules) ? config.modules : [];
|
|
2668
|
+
for (const moduleEntry of modules) {
|
|
2669
|
+
const { module, options } = await resolveModuleEntry(moduleEntry, root, outDir);
|
|
2670
|
+
const setup = getModuleSetup(module);
|
|
2671
|
+
await Promise.resolve(withResuxKitContext(context, () => setup(createModuleOptions(module, options), context)));
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
function deepMerge(base, next) {
|
|
2675
|
+
const output = { ...base };
|
|
2676
|
+
for (const [key, value] of Object.entries(next)) {
|
|
2677
|
+
const current = output[key];
|
|
2678
|
+
output[key] = isPlainObject(current) && isPlainObject(value)
|
|
2679
|
+
? deepMerge(current, value)
|
|
2680
|
+
: value;
|
|
2681
|
+
}
|
|
2682
|
+
return output;
|
|
2683
|
+
}
|
|
2684
|
+
function isPlainObject(value) {
|
|
2685
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
2686
|
+
}
|
|
2687
|
+
async function resolveModuleEntry(entry, root, outDir) {
|
|
2688
|
+
if (Array.isArray(entry)) {
|
|
2689
|
+
return {
|
|
2690
|
+
module: await loadModule(entry[0], root, outDir),
|
|
2691
|
+
options: entry[1] ?? {}
|
|
2692
|
+
};
|
|
2693
|
+
}
|
|
2694
|
+
return {
|
|
2695
|
+
module: await loadModule(entry, root, outDir),
|
|
2696
|
+
options: {}
|
|
2697
|
+
};
|
|
2698
|
+
}
|
|
2699
|
+
async function loadModule(module, root, outDir) {
|
|
2700
|
+
if (typeof module === "function" || isPlainObject(module)) {
|
|
2701
|
+
return module;
|
|
2702
|
+
}
|
|
2703
|
+
if (typeof module !== "string") {
|
|
2704
|
+
throw new Error("Resux modules must be functions, module objects, module specifiers, or [module, options] tuples.");
|
|
2705
|
+
}
|
|
2706
|
+
const builtin = resolveBuiltinModule(module);
|
|
2707
|
+
if (builtin) {
|
|
2708
|
+
return builtin;
|
|
2709
|
+
}
|
|
2710
|
+
const resolved = resolveModuleSpecifier(module, root);
|
|
2711
|
+
const imported = await import(`${await moduleImportUrl(resolved, outDir)}?t=${Date.now()}`);
|
|
2712
|
+
return imported.default ?? imported;
|
|
2713
|
+
}
|
|
2714
|
+
function getModuleSetup(module) {
|
|
2715
|
+
if (typeof module === "function") {
|
|
2716
|
+
return module;
|
|
2717
|
+
}
|
|
2718
|
+
if (isPlainObject(module) && typeof module.setup === "function") {
|
|
2719
|
+
return module.setup;
|
|
2720
|
+
}
|
|
2721
|
+
throw new Error("Resux modules must export a setup function or defineResuxModule({ setup }).");
|
|
2722
|
+
}
|
|
2723
|
+
function createModuleOptions(module, options) {
|
|
2724
|
+
if (isPlainObject(module) && isPlainObject(module.defaults)) {
|
|
2725
|
+
return {
|
|
2726
|
+
...module.defaults,
|
|
2727
|
+
...(isPlainObject(options) ? options : {})
|
|
2728
|
+
};
|
|
2729
|
+
}
|
|
2730
|
+
return options;
|
|
2731
|
+
}
|
|
2732
|
+
function resolveBuiltinModule(specifier) {
|
|
2733
|
+
const normalized = specifier.startsWith("resux:") ? specifier.slice("resux:".length) : specifier;
|
|
2734
|
+
return builtinModules[normalized] ?? null;
|
|
2735
|
+
}
|
|
2736
|
+
const i18nBuiltinModule = {
|
|
2737
|
+
async setup(options, resux) {
|
|
2738
|
+
const imported = await import("../i18n/index.js");
|
|
2739
|
+
const module = imported.default ?? imported;
|
|
2740
|
+
const setup = getModuleSetup(module);
|
|
2741
|
+
await setup(options, resux);
|
|
2742
|
+
}
|
|
2743
|
+
};
|
|
2744
|
+
const builtinModules = {
|
|
2745
|
+
i18n: i18nBuiltinModule,
|
|
2746
|
+
"resuxjs/i18n": i18nBuiltinModule,
|
|
2747
|
+
"@resuxjs/i18n": i18nBuiltinModule,
|
|
2748
|
+
security: {
|
|
2749
|
+
defaults: {
|
|
2750
|
+
route: "/**",
|
|
2751
|
+
contentSecurityPolicy: false
|
|
2752
|
+
},
|
|
2753
|
+
setup(options, resux) {
|
|
2754
|
+
const input = isPlainObject(options) ? options : {};
|
|
2755
|
+
const routePath = firstString(input.route) ?? "/**";
|
|
2756
|
+
const headers = {
|
|
2757
|
+
"x-content-type-options": "nosniff",
|
|
2758
|
+
"referrer-policy": "strict-origin-when-cross-origin",
|
|
2759
|
+
"x-frame-options": "SAMEORIGIN",
|
|
2760
|
+
"cross-origin-opener-policy": "same-origin",
|
|
2761
|
+
"permissions-policy": "camera=(), microphone=(), geolocation=()",
|
|
2762
|
+
...(isPlainObject(input.headers) ? normalizeStringRecord(input.headers) : {})
|
|
2763
|
+
};
|
|
2764
|
+
const csp = firstString(input.contentSecurityPolicy);
|
|
2765
|
+
if (csp) {
|
|
2766
|
+
headers["content-security-policy"] = csp;
|
|
2767
|
+
}
|
|
2768
|
+
resux.addRouteRule(routePath, { headers });
|
|
2769
|
+
resux.extendRuntimeConfig({ public: { securityHeaders: true } });
|
|
2770
|
+
}
|
|
2771
|
+
},
|
|
2772
|
+
performance: {
|
|
2773
|
+
defaults: {
|
|
2774
|
+
assetMaxAge: 31536000,
|
|
2775
|
+
routePayloadNoStore: true
|
|
2776
|
+
},
|
|
2777
|
+
setup(options, resux) {
|
|
2778
|
+
const input = isPlainObject(options) ? options : {};
|
|
2779
|
+
const maxAge = Number.isFinite(input.assetMaxAge) ? Math.max(0, Math.floor(input.assetMaxAge)) : 31536000;
|
|
2780
|
+
const assetCache = { maxAge };
|
|
2781
|
+
resux.addRouteRule("/__resux/runtime-client.mjs", { cache: assetCache });
|
|
2782
|
+
resux.addRouteRule("/__resux/handlers/**", { cache: assetCache });
|
|
2783
|
+
resux.addRouteRule("/__resux/vue-islands/**", { cache: assetCache });
|
|
2784
|
+
resux.addRouteRule("/__resux/image", { cache: assetCache });
|
|
2785
|
+
resux.addRouteRule("/__resux/video", { cache: assetCache });
|
|
2786
|
+
if (input.routePayloadNoStore !== false) {
|
|
2787
|
+
resux.addRouteRule("/__resux/route", { cache: false });
|
|
2788
|
+
}
|
|
2789
|
+
resux.extendRuntimeConfig({ public: { performanceModule: { assetMaxAge: maxAge } } });
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
};
|
|
2793
|
+
function firstString(value) {
|
|
2794
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
2795
|
+
}
|
|
2796
|
+
function resolveModuleSpecifier(specifier, root) {
|
|
2797
|
+
if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("file:")) {
|
|
2798
|
+
const resolved = specifier.startsWith("file:")
|
|
2799
|
+
? new URL(specifier)
|
|
2800
|
+
: path.resolve(root, specifier);
|
|
2801
|
+
const file = resolved instanceof URL ? fileURLToPath(resolved) : resolved;
|
|
2802
|
+
return resolveLocalModuleFile(file);
|
|
2803
|
+
}
|
|
2804
|
+
return require.resolve(specifier, { paths: [root] });
|
|
2805
|
+
}
|
|
2806
|
+
function resolveLocalModuleFile(file) {
|
|
2807
|
+
const candidates = [
|
|
2808
|
+
file,
|
|
2809
|
+
`${file}.ts`,
|
|
2810
|
+
`${file}.mts`,
|
|
2811
|
+
`${file}.js`,
|
|
2812
|
+
`${file}.mjs`,
|
|
2813
|
+
path.join(file, "index.ts"),
|
|
2814
|
+
path.join(file, "index.mts"),
|
|
2815
|
+
path.join(file, "index.js"),
|
|
2816
|
+
path.join(file, "index.mjs")
|
|
2817
|
+
];
|
|
2818
|
+
const found = candidates.find((candidate) => ts.sys.fileExists(candidate));
|
|
2819
|
+
if (!found) {
|
|
2820
|
+
throw new Error(`Cannot resolve Resux module "${file}".`);
|
|
2821
|
+
}
|
|
2822
|
+
return found;
|
|
2823
|
+
}
|
|
2824
|
+
async function moduleImportUrl(file, outDir) {
|
|
2825
|
+
if (/\.[cm]?ts$/.test(file)) {
|
|
2826
|
+
const outputFile = path.join(outDir, "server", "config-modules", `${safeModuleFileName(file)}.mjs`);
|
|
2827
|
+
await writeFile(outputFile, transpileConfigSupportModule(file), "utf8");
|
|
2828
|
+
return pathToFileURL(outputFile).href;
|
|
2829
|
+
}
|
|
2830
|
+
return pathToFileURL(file).href;
|
|
2831
|
+
}
|
|
2832
|
+
function transpileConfigSupportModule(file) {
|
|
2833
|
+
const source = normalizeConfigHelpers(ts.sys.readFile(file) ?? "");
|
|
2834
|
+
return ts.transpileModule(source, {
|
|
2835
|
+
compilerOptions: {
|
|
2836
|
+
target: ts.ScriptTarget.ES2022,
|
|
2837
|
+
module: ts.ModuleKind.ES2022,
|
|
2838
|
+
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove
|
|
2839
|
+
}
|
|
2840
|
+
}).outputText;
|
|
2841
|
+
}
|
|
2842
|
+
function safeModuleFileName(file) {
|
|
2843
|
+
return normalizePath(path.resolve(file)).replace(/[^A-Za-z0-9_-]+/g, "_");
|
|
2844
|
+
}
|
|
2845
|
+
function nextBindingId(state) {
|
|
2846
|
+
return `b${state.bindingIndex++}`;
|
|
2847
|
+
}
|
|
2848
|
+
function nextInlineHandlerName(state) {
|
|
2849
|
+
return `__rx_inline_${state.inlineHandlerIndex++}`;
|
|
2850
|
+
}
|
|
2851
|
+
function routeScore(routePath) {
|
|
2852
|
+
return routePath
|
|
2853
|
+
.split("/")
|
|
2854
|
+
.filter(Boolean)
|
|
2855
|
+
.reduce((score, part) => score + (part.startsWith(":") ? 1 : 3), 0);
|
|
2856
|
+
}
|
|
2857
|
+
async function discoverVueFiles(dir) {
|
|
2858
|
+
try {
|
|
2859
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
2860
|
+
const files = [];
|
|
2861
|
+
for (const entry of entries) {
|
|
2862
|
+
const fullPath = path.join(dir, entry.name);
|
|
2863
|
+
if (entry.isDirectory()) {
|
|
2864
|
+
files.push(...await discoverVueFiles(fullPath));
|
|
2865
|
+
}
|
|
2866
|
+
else if (entry.isFile() && entry.name.endsWith(".vue")) {
|
|
2867
|
+
files.push(fullPath);
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
return files.sort();
|
|
2871
|
+
}
|
|
2872
|
+
catch {
|
|
2873
|
+
return [];
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
async function discoverAppVueFiles(root, dirName) {
|
|
2877
|
+
return unique([
|
|
2878
|
+
...await discoverVueFiles(path.join(root, dirName)),
|
|
2879
|
+
...await discoverVueFiles(path.join(root, "app", dirName))
|
|
2880
|
+
]);
|
|
2881
|
+
}
|
|
2882
|
+
async function discoverVueFilesFromDirs(dirs) {
|
|
2883
|
+
const files = [];
|
|
2884
|
+
for (const dir of dirs) {
|
|
2885
|
+
files.push(...await discoverVueFiles(dir));
|
|
2886
|
+
}
|
|
2887
|
+
return unique(files);
|
|
2888
|
+
}
|
|
2889
|
+
async function discoverSupportTsFiles(root, dirName) {
|
|
2890
|
+
const dirs = [path.join(root, dirName), path.join(root, "app", dirName)];
|
|
2891
|
+
const files = [];
|
|
2892
|
+
for (const dir of dirs) {
|
|
2893
|
+
files.push(...await discoverSupportTsFilesInDir(dir));
|
|
2894
|
+
}
|
|
2895
|
+
return unique(files).sort((left, right) => normalizePath(left).localeCompare(normalizePath(right)));
|
|
2896
|
+
}
|
|
2897
|
+
function isClientEnhancementSupportFile(file) {
|
|
2898
|
+
return /\.client\.[cm]?[tj]s$/.test(file) && !/\.d\.[cm]?[tj]s$/.test(file);
|
|
2899
|
+
}
|
|
2900
|
+
async function discoverClientEnhancementFiles(root) {
|
|
2901
|
+
const files = [];
|
|
2902
|
+
for (const relativeDir of CLIENT_ENHANCEMENT_DIR_CANDIDATES) {
|
|
2903
|
+
const absoluteDir = path.join(root, relativeDir);
|
|
2904
|
+
files.push(...await discoverSupportTsFilesInDir(absoluteDir));
|
|
2905
|
+
}
|
|
2906
|
+
return unique(files)
|
|
2907
|
+
.map((file) => path.resolve(file))
|
|
2908
|
+
.filter((file) => isClientEnhancementSupportFile(file))
|
|
2909
|
+
.sort((left, right) => normalizePath(left).localeCompare(normalizePath(right)));
|
|
2910
|
+
}
|
|
2911
|
+
async function discoverAutoImportsFromDirs(root, dirs) {
|
|
2912
|
+
const entries = [];
|
|
2913
|
+
for (const dir of dirs) {
|
|
2914
|
+
const files = await discoverSupportTsFilesInDir(dir);
|
|
2915
|
+
for (const file of files) {
|
|
2916
|
+
const source = await readFile(file, "utf8");
|
|
2917
|
+
const names = collectNamedExportsFromSource(file, source);
|
|
2918
|
+
const relative = normalizePath(path.relative(root, file).replace(/\.[cm]?[tj]s$/, ""));
|
|
2919
|
+
const from = relative.startsWith(".") ? relative : `./${relative}`;
|
|
2920
|
+
for (const name of names) {
|
|
2921
|
+
entries.push({ from, name });
|
|
2922
|
+
}
|
|
2923
|
+
}
|
|
2924
|
+
}
|
|
2925
|
+
return dedupeImports(entries);
|
|
2926
|
+
}
|
|
2927
|
+
function collectNamedExportsFromSource(file, source) {
|
|
2928
|
+
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);
|
|
2929
|
+
const names = new Set();
|
|
2930
|
+
for (const statement of sourceFile.statements) {
|
|
2931
|
+
if (!isStatementExported(statement)) {
|
|
2932
|
+
continue;
|
|
2933
|
+
}
|
|
2934
|
+
if (ts.isFunctionDeclaration(statement) && statement.name) {
|
|
2935
|
+
names.add(statement.name.text);
|
|
2936
|
+
continue;
|
|
2937
|
+
}
|
|
2938
|
+
if (ts.isClassDeclaration(statement) && statement.name) {
|
|
2939
|
+
names.add(statement.name.text);
|
|
2940
|
+
continue;
|
|
2941
|
+
}
|
|
2942
|
+
if (ts.isVariableStatement(statement)) {
|
|
2943
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
2944
|
+
if (ts.isIdentifier(declaration.name)) {
|
|
2945
|
+
names.add(declaration.name.text);
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
continue;
|
|
2949
|
+
}
|
|
2950
|
+
if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
|
|
2951
|
+
for (const specifier of statement.exportClause.elements) {
|
|
2952
|
+
names.add(specifier.name.text);
|
|
2953
|
+
}
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
return [...names].sort();
|
|
2957
|
+
}
|
|
2958
|
+
function isStatementExported(statement) {
|
|
2959
|
+
const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
|
|
2960
|
+
return Boolean(modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword));
|
|
2961
|
+
}
|
|
2962
|
+
function uniqueServerHandlers(records) {
|
|
2963
|
+
const map = new Map();
|
|
2964
|
+
for (const record of records) {
|
|
2965
|
+
const key = `${normalizeRoutePath(record.path)}::${normalizePath(path.resolve(record.file))}`;
|
|
2966
|
+
map.set(key, { file: path.resolve(record.file), path: normalizeRoutePath(record.path) });
|
|
2967
|
+
}
|
|
2968
|
+
return [...map.values()].sort((left, right) => left.path.localeCompare(right.path) || normalizePath(left.file).localeCompare(normalizePath(right.file)));
|
|
2969
|
+
}
|
|
2970
|
+
async function writeModuleTemplates(outDir, contributions) {
|
|
2971
|
+
const written = [];
|
|
2972
|
+
for (const template of [...contributions.templates, ...contributions.typeTemplates]) {
|
|
2973
|
+
if (template.write === false) {
|
|
2974
|
+
continue;
|
|
2975
|
+
}
|
|
2976
|
+
const target = path.join(outDir, "templates", template.filename);
|
|
2977
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
2978
|
+
await writeFile(target, await template.getContents(), "utf8");
|
|
2979
|
+
written.push(target);
|
|
2980
|
+
}
|
|
2981
|
+
return written.sort((left, right) => normalizePath(left).localeCompare(normalizePath(right)));
|
|
2982
|
+
}
|
|
2983
|
+
function buildRuntimeArtifacts(input) {
|
|
2984
|
+
const manifest = {
|
|
2985
|
+
routes: input.routes,
|
|
2986
|
+
components: input.components.map(({ id, name, file, handlers, styles, styleScopeId, meta }) => ({ id, name, file, handlers, styles, styleScopeId, meta })),
|
|
2987
|
+
layouts: input.layouts.map(({ id, name, file, styles, styleScopeId }) => ({ id, name, file, styles, styleScopeId })),
|
|
2988
|
+
plugins: input.plugins.map(({ id, file, mode }) => ({ id, file, mode })),
|
|
2989
|
+
clientEnhancements: input.clientEnhancements.map(({ name, id, file, src }) => ({ name, id, file, src })),
|
|
2990
|
+
middleware: input.middleware.map(({ id, name, file, global, mode }) => ({ id, name, file, global, mode })),
|
|
2991
|
+
serverMiddleware: input.serverMiddleware.map(({ id, file }) => ({ id, file })),
|
|
2992
|
+
serverHandlers: input.serverHandlers.map(({ id, path: routePath, file, params }) => ({ id, path: routePath, file, params })),
|
|
2993
|
+
vueIslands: input.vueIslands,
|
|
2994
|
+
app: input.app?.id,
|
|
2995
|
+
error: input.error?.id,
|
|
2996
|
+
runtimeConfig: input.runtimeConfig,
|
|
2997
|
+
routeRules: input.routeRules,
|
|
2998
|
+
packages: input.packages,
|
|
2999
|
+
features: input.buildOptions
|
|
3000
|
+
};
|
|
3001
|
+
const buildManifest = {
|
|
3002
|
+
routes: input.routes.map((route) => route.path),
|
|
3003
|
+
serverHandlers: input.serverHandlers.map((handler) => ({ path: handler.path, file: handler.file })),
|
|
3004
|
+
plugins: input.plugins.map((plugin) => ({ file: plugin.file, mode: plugin.mode })),
|
|
3005
|
+
clientEnhancements: input.clientEnhancements.map((entry) => ({ name: entry.name, id: entry.id, file: entry.file, src: entry.src })),
|
|
3006
|
+
middleware: input.middleware.map((entry) => ({ name: entry.name, file: entry.file, mode: entry.mode, global: entry.global })),
|
|
3007
|
+
components: input.components.map((component) => ({ name: component.name, file: component.file })),
|
|
3008
|
+
assets: [],
|
|
3009
|
+
imageTransforms: [],
|
|
3010
|
+
routeRules: Object.entries(input.routeRules).map(([routePath, rule]) => ({ path: routePath, rule })),
|
|
3011
|
+
runtimeConfig: input.runtimeConfig,
|
|
3012
|
+
packages: input.packages
|
|
3013
|
+
};
|
|
3014
|
+
const componentMap = new Map();
|
|
3015
|
+
for (const component of input.components) {
|
|
3016
|
+
componentMap.set(component.name, component);
|
|
3017
|
+
const basename = pascalCase(path.basename(component.file, ".vue"));
|
|
3018
|
+
if (!componentMap.has(basename)) {
|
|
3019
|
+
componentMap.set(basename, component);
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
const componentNames = unique([...componentMap.keys()].filter(Boolean)).sort();
|
|
3023
|
+
const imports = dedupeImports([...BUILTIN_AUTO_IMPORTS, ...input.contributions.imports]);
|
|
3024
|
+
const importsSignatures = imports
|
|
3025
|
+
.map((entry) => `${entry.name}${entry.as ? ` as ${entry.as}` : ""} from ${entry.from}`)
|
|
3026
|
+
.join("\n");
|
|
3027
|
+
const routesSource = `export default ${JSON.stringify(input.routes.map((route) => ({ id: route.id, path: route.path, file: route.file, params: route.params, componentId: route.componentId, meta: route.meta })), null, 2)};\n`;
|
|
3028
|
+
const pluginsSource = `export default ${JSON.stringify(input.plugins.map((plugin) => ({ id: plugin.id, file: plugin.file, mode: plugin.mode })), null, 2)};\n`;
|
|
3029
|
+
const middlewareSource = `export default ${JSON.stringify(input.middleware.map((entry) => ({ id: entry.id, name: entry.name, file: entry.file, global: entry.global, mode: entry.mode })), null, 2)};\n`;
|
|
3030
|
+
const componentsSource = `export default ${JSON.stringify([...componentMap.entries()].map(([name, comp]) => ({ id: comp.id, name, file: comp.file })), null, 2)};\n`;
|
|
3031
|
+
const importsSource = `export default ${JSON.stringify(imports, null, 2)};\n`;
|
|
3032
|
+
const appSource = [
|
|
3033
|
+
`import routes from "./routes.mjs";`,
|
|
3034
|
+
`import plugins from "./plugins.mjs";`,
|
|
3035
|
+
`import middleware from "./middleware.mjs";`,
|
|
3036
|
+
`import components from "./components.mjs";`,
|
|
3037
|
+
`import imports from "./imports.mjs";`,
|
|
3038
|
+
`export default {`,
|
|
3039
|
+
` app: ${JSON.stringify(input.app?.id ?? null)},`,
|
|
3040
|
+
` error: ${JSON.stringify(input.error?.id ?? null)},`,
|
|
3041
|
+
` routes,`,
|
|
3042
|
+
` plugins,`,
|
|
3043
|
+
` middleware,`,
|
|
3044
|
+
` components,`,
|
|
3045
|
+
` imports`,
|
|
3046
|
+
`};`,
|
|
3047
|
+
``
|
|
3048
|
+
].join("\n");
|
|
3049
|
+
const resuxDts = [
|
|
3050
|
+
`export interface ResuxGeneratedAppManifest {`,
|
|
3051
|
+
` app: string | null;`,
|
|
3052
|
+
` error: string | null;`,
|
|
3053
|
+
` routes: Array<{ id: string; path: string; file: string; params: string[]; componentId: string }>;`,
|
|
3054
|
+
` plugins: Array<{ id: string; file: string; mode: "all" | "server" | "client" }>;`,
|
|
3055
|
+
` clientEnhancements: Array<{ name: string; id: string; file: string; src: string }>;`,
|
|
3056
|
+
` middleware: Array<{ id: string; name: string; file: string; mode: "all" | "server" | "client"; global: boolean }>;`,
|
|
3057
|
+
` components: Array<{ id: string; name: string; file: string }>;`,
|
|
3058
|
+
` imports: Array<{ from: string; name: string; as?: string }>;`,
|
|
3059
|
+
`}`,
|
|
3060
|
+
`declare const manifest: ResuxGeneratedAppManifest;`,
|
|
3061
|
+
`export default manifest;`,
|
|
3062
|
+
``
|
|
3063
|
+
].join("\n");
|
|
3064
|
+
const importsDts = [
|
|
3065
|
+
`// Generated by Resux`,
|
|
3066
|
+
`declare module "resuxjs" {`,
|
|
3067
|
+
` export interface ResuxAutoImportsRegistry {`,
|
|
3068
|
+
...(importsSignatures ? imports.map((entry) => ` "${entry.as ?? entry.name}": typeof import("${entry.from}")["${entry.name}"];`) : [" // no user imports detected"]),
|
|
3069
|
+
` }`,
|
|
3070
|
+
`}`,
|
|
3071
|
+
`export {};`,
|
|
3072
|
+
``
|
|
3073
|
+
].join("\n");
|
|
3074
|
+
const componentsDts = [
|
|
3075
|
+
`declare module "resuxjs/components" {`,
|
|
3076
|
+
` export interface ResuxComponentsRegistry {`,
|
|
3077
|
+
...(componentNames.length ? componentNames.map((name) => ` "${name}": unknown;`) : [" // no components detected"]),
|
|
3078
|
+
` }`,
|
|
3079
|
+
`}`,
|
|
3080
|
+
`export {};`,
|
|
3081
|
+
``
|
|
3082
|
+
].join("\n");
|
|
3083
|
+
const serverRoutesDts = [
|
|
3084
|
+
`declare module "resuxjs/server-routes" {`,
|
|
3085
|
+
` export interface ResuxServerRouteMap {`,
|
|
3086
|
+
...(input.serverHandlers.length
|
|
3087
|
+
? input.serverHandlers.map((handler) => ` "${handler.path}": unknown;`)
|
|
3088
|
+
: [" // no server routes detected"]),
|
|
3089
|
+
` }`,
|
|
3090
|
+
`}`,
|
|
3091
|
+
`export {};`,
|
|
3092
|
+
``
|
|
3093
|
+
].join("\n");
|
|
3094
|
+
return {
|
|
3095
|
+
manifest: manifest,
|
|
3096
|
+
buildManifest: buildManifest,
|
|
3097
|
+
routesSource,
|
|
3098
|
+
pluginsSource,
|
|
3099
|
+
middlewareSource,
|
|
3100
|
+
componentsSource,
|
|
3101
|
+
importsSource,
|
|
3102
|
+
appSource,
|
|
3103
|
+
resuxDts,
|
|
3104
|
+
importsDts,
|
|
3105
|
+
componentsDts,
|
|
3106
|
+
serverRoutesDts,
|
|
3107
|
+
diagnostics: {
|
|
3108
|
+
routeManifest: input.routes.map((route) => ({ id: route.id, path: route.path, file: route.file, params: route.params })),
|
|
3109
|
+
pluginManifest: input.plugins.map((plugin) => ({ id: plugin.id, file: plugin.file, mode: plugin.mode })),
|
|
3110
|
+
clientEnhancementManifest: input.clientEnhancements.map((entry) => ({ name: entry.name, id: entry.id, file: entry.file, src: entry.src })),
|
|
3111
|
+
middlewareManifest: input.middleware.map((entry) => ({ id: entry.id, name: entry.name, file: entry.file, global: entry.global, mode: entry.mode })),
|
|
3112
|
+
componentManifest: input.components.map((component) => ({ id: component.id, name: component.name, file: component.file }))
|
|
3113
|
+
}
|
|
3114
|
+
};
|
|
3115
|
+
}
|
|
3116
|
+
async function writeGeneratedArtifacts(outDir, artifacts, dev) {
|
|
3117
|
+
await writeFile(path.join(outDir, "manifest.json"), JSON.stringify(artifacts.manifest, null, 2), "utf8");
|
|
3118
|
+
await writeFile(path.join(outDir, "manifest", "build-manifest.json"), JSON.stringify(artifacts.buildManifest, null, 2), "utf8");
|
|
3119
|
+
await writeFile(path.join(outDir, "routes.mjs"), artifacts.routesSource, "utf8");
|
|
3120
|
+
await writeFile(path.join(outDir, "plugins.mjs"), artifacts.pluginsSource, "utf8");
|
|
3121
|
+
await writeFile(path.join(outDir, "middleware.mjs"), artifacts.middlewareSource, "utf8");
|
|
3122
|
+
await writeFile(path.join(outDir, "components.mjs"), artifacts.componentsSource, "utf8");
|
|
3123
|
+
await writeFile(path.join(outDir, "imports.mjs"), artifacts.importsSource, "utf8");
|
|
3124
|
+
await writeFile(path.join(outDir, "app.mjs"), artifacts.appSource, "utf8");
|
|
3125
|
+
await writeFile(path.join(outDir, "resux.d.ts"), artifacts.resuxDts, "utf8");
|
|
3126
|
+
await writeFile(path.join(outDir, "imports.d.ts"), artifacts.importsDts, "utf8");
|
|
3127
|
+
await writeFile(path.join(outDir, "components.d.ts"), artifacts.componentsDts, "utf8");
|
|
3128
|
+
await writeFile(path.join(outDir, "server-routes.d.ts"), artifacts.serverRoutesDts, "utf8");
|
|
3129
|
+
await writeFile(path.join(outDir, "types", "resux.d.ts"), artifacts.resuxDts, "utf8");
|
|
3130
|
+
await writeFile(path.join(outDir, "types", "imports.d.ts"), artifacts.importsDts, "utf8");
|
|
3131
|
+
await writeFile(path.join(outDir, "types", "components.d.ts"), artifacts.componentsDts, "utf8");
|
|
3132
|
+
await writeFile(path.join(outDir, "types", "server-routes.d.ts"), artifacts.serverRoutesDts, "utf8");
|
|
3133
|
+
if (!dev) {
|
|
3134
|
+
return;
|
|
3135
|
+
}
|
|
3136
|
+
await mkdir(path.join(outDir, "dev"), { recursive: true });
|
|
3137
|
+
await writeFile(path.join(outDir, "dev", "route-manifest.json"), JSON.stringify(artifacts.diagnostics.routeManifest, null, 2), "utf8");
|
|
3138
|
+
await writeFile(path.join(outDir, "dev", "plugin-manifest.json"), JSON.stringify(artifacts.diagnostics.pluginManifest, null, 2), "utf8");
|
|
3139
|
+
await writeFile(path.join(outDir, "dev", "client-enhancement-manifest.json"), JSON.stringify(artifacts.diagnostics.clientEnhancementManifest, null, 2), "utf8");
|
|
3140
|
+
await writeFile(path.join(outDir, "dev", "middleware-manifest.json"), JSON.stringify(artifacts.diagnostics.middlewareManifest, null, 2), "utf8");
|
|
3141
|
+
await writeFile(path.join(outDir, "dev", "component-manifest.json"), JSON.stringify(artifacts.diagnostics.componentManifest, null, 2), "utf8");
|
|
3142
|
+
await writeFile(path.join(outDir, "dev", "imports.d.ts"), artifacts.importsDts, "utf8");
|
|
3143
|
+
await writeFile(path.join(outDir, "dev", "resux.d.ts"), artifacts.resuxDts, "utf8");
|
|
3144
|
+
}
|
|
3145
|
+
function uniquePackageSourceFiles(entries) {
|
|
3146
|
+
const map = new Map();
|
|
3147
|
+
for (const entry of entries) {
|
|
3148
|
+
const resolved = path.resolve(entry.file);
|
|
3149
|
+
const key = normalizePath(resolved);
|
|
3150
|
+
const existing = map.get(key);
|
|
3151
|
+
if (!existing) {
|
|
3152
|
+
map.set(key, { file: resolved, mode: entry.mode });
|
|
3153
|
+
continue;
|
|
3154
|
+
}
|
|
3155
|
+
if (existing.mode === entry.mode) {
|
|
3156
|
+
continue;
|
|
3157
|
+
}
|
|
3158
|
+
map.set(key, { file: resolved, mode: "all" });
|
|
3159
|
+
}
|
|
3160
|
+
return [...map.values()].sort((left, right) => normalizePath(left.file).localeCompare(normalizePath(right.file)));
|
|
3161
|
+
}
|
|
3162
|
+
function isPackageSpecifier(specifier) {
|
|
3163
|
+
if (!specifier) {
|
|
3164
|
+
return false;
|
|
3165
|
+
}
|
|
3166
|
+
if (specifier.startsWith(".")
|
|
3167
|
+
|| specifier.startsWith("/")
|
|
3168
|
+
|| specifier.startsWith("http://")
|
|
3169
|
+
|| specifier.startsWith("https://")
|
|
3170
|
+
|| specifier.startsWith("data:")
|
|
3171
|
+
|| specifier.startsWith("file:")
|
|
3172
|
+
|| specifier.startsWith("virtual:")
|
|
3173
|
+
|| specifier.startsWith("node:")) {
|
|
3174
|
+
return false;
|
|
3175
|
+
}
|
|
3176
|
+
return true;
|
|
3177
|
+
}
|
|
3178
|
+
function normalizePackageName(specifier) {
|
|
3179
|
+
const clean = specifier.split("?")[0]?.split("#")[0] ?? specifier;
|
|
3180
|
+
const segments = clean.split("/");
|
|
3181
|
+
if (clean.startsWith("@")) {
|
|
3182
|
+
return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : clean;
|
|
3183
|
+
}
|
|
3184
|
+
return segments[0] ?? clean;
|
|
3185
|
+
}
|
|
3186
|
+
function collectPackageImportsFromSource(source) {
|
|
3187
|
+
const imports = [];
|
|
3188
|
+
const staticRegex = /import\s+(?:type\s+)?(?:[^"'()]*?\s+from\s+)?["']([^"']+)["']/g;
|
|
3189
|
+
const dynamicRegex = /import\(\s*["']([^"']+)["']\s*\)/g;
|
|
3190
|
+
const requireRegex = /require\(\s*["']([^"']+)["']\s*\)/g;
|
|
3191
|
+
const packageApiRegex = /(?:useClientPackage|useLazyPackage|defineClientOnlyPackage|defineLazyPackage)(?:\s*<[\s\S]*?>)?\(\s*([A-Za-z_$][A-Za-z0-9_$]*|["'][^"']+["'])\s*(?:,\s*\{([\s\S]*?)\})?\s*\)/g;
|
|
3192
|
+
const packageConstRegex = /(?:^|[;\r\n])\s*const\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*["']([^"']+)["']/g;
|
|
3193
|
+
const cssArrayRegex = /css\s*:\s*\[([\s\S]*?)\]/g;
|
|
3194
|
+
const cssStringRegex = /css\s*:\s*["']([^"']+)["']/g;
|
|
3195
|
+
const stringLiteralRegex = /["']([^"']+)["']/g;
|
|
3196
|
+
const packageConstMap = new Map();
|
|
3197
|
+
for (const match of source.matchAll(packageConstRegex)) {
|
|
3198
|
+
const name = (match[1] ?? "").trim();
|
|
3199
|
+
const value = (match[2] ?? "").trim();
|
|
3200
|
+
if (!name || !value) {
|
|
3201
|
+
continue;
|
|
3202
|
+
}
|
|
3203
|
+
packageConstMap.set(name, value);
|
|
3204
|
+
}
|
|
3205
|
+
for (const match of source.matchAll(staticRegex)) {
|
|
3206
|
+
const specifier = match[1] ?? "";
|
|
3207
|
+
imports.push({
|
|
3208
|
+
specifier,
|
|
3209
|
+
dynamic: false,
|
|
3210
|
+
css: /\.css(?:[?#]|$)/i.test(specifier),
|
|
3211
|
+
});
|
|
3212
|
+
}
|
|
3213
|
+
for (const match of source.matchAll(dynamicRegex)) {
|
|
3214
|
+
const specifier = match[1] ?? "";
|
|
3215
|
+
imports.push({
|
|
3216
|
+
specifier,
|
|
3217
|
+
dynamic: true,
|
|
3218
|
+
css: /\.css(?:[?#]|$)/i.test(specifier),
|
|
3219
|
+
});
|
|
3220
|
+
}
|
|
3221
|
+
for (const match of source.matchAll(requireRegex)) {
|
|
3222
|
+
const specifier = match[1] ?? "";
|
|
3223
|
+
imports.push({
|
|
3224
|
+
specifier,
|
|
3225
|
+
dynamic: false,
|
|
3226
|
+
css: /\.css(?:[?#]|$)/i.test(specifier),
|
|
3227
|
+
});
|
|
3228
|
+
}
|
|
3229
|
+
for (const match of source.matchAll(packageApiRegex)) {
|
|
3230
|
+
const token = (match[1] ?? "").trim();
|
|
3231
|
+
const specifier = token.startsWith("\"") || token.startsWith("'")
|
|
3232
|
+
? token.slice(1, -1).trim()
|
|
3233
|
+
: (packageConstMap.get(token) ?? "");
|
|
3234
|
+
const optionsSource = match[2] ?? "";
|
|
3235
|
+
if (specifier.length > 0) {
|
|
3236
|
+
imports.push({
|
|
3237
|
+
specifier,
|
|
3238
|
+
dynamic: true,
|
|
3239
|
+
css: false,
|
|
3240
|
+
});
|
|
3241
|
+
}
|
|
3242
|
+
for (const cssArray of optionsSource.matchAll(cssArrayRegex)) {
|
|
3243
|
+
const content = cssArray[1] ?? "";
|
|
3244
|
+
for (const cssEntry of content.matchAll(stringLiteralRegex)) {
|
|
3245
|
+
const cssSpecifier = (cssEntry[1] ?? "").trim();
|
|
3246
|
+
if (!cssSpecifier) {
|
|
3247
|
+
continue;
|
|
3248
|
+
}
|
|
3249
|
+
imports.push({
|
|
3250
|
+
specifier: cssSpecifier,
|
|
3251
|
+
dynamic: true,
|
|
3252
|
+
css: true,
|
|
3253
|
+
});
|
|
3254
|
+
}
|
|
3255
|
+
}
|
|
3256
|
+
for (const cssValue of optionsSource.matchAll(cssStringRegex)) {
|
|
3257
|
+
const cssSpecifier = (cssValue[1] ?? "").trim();
|
|
3258
|
+
if (!cssSpecifier) {
|
|
3259
|
+
continue;
|
|
3260
|
+
}
|
|
3261
|
+
imports.push({
|
|
3262
|
+
specifier: cssSpecifier,
|
|
3263
|
+
dynamic: true,
|
|
3264
|
+
css: true,
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
return imports;
|
|
3269
|
+
}
|
|
3270
|
+
function readConfiguredPackages(runtimeConfig) {
|
|
3271
|
+
const directPackages = runtimeConfig.packages;
|
|
3272
|
+
if (isPlainObject(directPackages)) {
|
|
3273
|
+
return directPackages;
|
|
3274
|
+
}
|
|
3275
|
+
const nestedRuntimeConfig = isPlainObject(runtimeConfig.runtimeConfig)
|
|
3276
|
+
? runtimeConfig.runtimeConfig
|
|
3277
|
+
: null;
|
|
3278
|
+
const nestedPublic = nestedRuntimeConfig && isPlainObject(nestedRuntimeConfig.public)
|
|
3279
|
+
? nestedRuntimeConfig.public
|
|
3280
|
+
: null;
|
|
3281
|
+
const nestedPackages = nestedPublic?.packages;
|
|
3282
|
+
if (isPlainObject(nestedPackages)) {
|
|
3283
|
+
return nestedPackages;
|
|
3284
|
+
}
|
|
3285
|
+
return {};
|
|
3286
|
+
}
|
|
3287
|
+
function normalizeConfiguredPackageList(value) {
|
|
3288
|
+
if (!Array.isArray(value)) {
|
|
3289
|
+
return [];
|
|
3290
|
+
}
|
|
3291
|
+
return [...new Set(value
|
|
3292
|
+
.map((entry) => String(entry ?? "").trim())
|
|
3293
|
+
.filter((entry) => entry.length > 0))]
|
|
3294
|
+
.sort((left, right) => left.localeCompare(right));
|
|
3295
|
+
}
|
|
3296
|
+
function normalizeConfiguredPackageCssMap(config) {
|
|
3297
|
+
const output = {};
|
|
3298
|
+
if (!config.css || typeof config.css !== "object" || Array.isArray(config.css)) {
|
|
3299
|
+
return output;
|
|
3300
|
+
}
|
|
3301
|
+
for (const [packageName, entries] of Object.entries(config.css)) {
|
|
3302
|
+
const normalizedPackageName = String(packageName || "").trim();
|
|
3303
|
+
if (!normalizedPackageName || !Array.isArray(entries)) {
|
|
3304
|
+
continue;
|
|
3305
|
+
}
|
|
3306
|
+
const normalizedEntries = [...new Set(entries
|
|
3307
|
+
.map((entry) => String(entry || "").trim())
|
|
3308
|
+
.filter((entry) => entry.length > 0))]
|
|
3309
|
+
.sort((left, right) => left.localeCompare(right));
|
|
3310
|
+
if (normalizedEntries.length > 0) {
|
|
3311
|
+
output[normalizedPackageName] = normalizedEntries;
|
|
3312
|
+
}
|
|
3313
|
+
}
|
|
3314
|
+
return output;
|
|
3315
|
+
}
|
|
3316
|
+
function canResolvePackageSpecifier(appRoot, specifier) {
|
|
3317
|
+
try {
|
|
3318
|
+
require.resolve(specifier, { paths: [appRoot] });
|
|
3319
|
+
return true;
|
|
3320
|
+
}
|
|
3321
|
+
catch {
|
|
3322
|
+
return false;
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
function createClientRuntimePackageRegistry(appRoot, configuredPackages, packageDiagnostics) {
|
|
3326
|
+
const importers = new Set();
|
|
3327
|
+
const declaredPackages = new Set();
|
|
3328
|
+
const cssByPackage = normalizeConfiguredPackageCssMap(configuredPackages);
|
|
3329
|
+
const configuredModeMap = configuredPackages.mode && typeof configuredPackages.mode === "object" && !Array.isArray(configuredPackages.mode)
|
|
3330
|
+
? configuredPackages.mode
|
|
3331
|
+
: {};
|
|
3332
|
+
const configuredLazy = normalizeConfiguredPackageList(configuredPackages.lazy);
|
|
3333
|
+
const configuredClientOnly = normalizeConfiguredPackageList(configuredPackages.clientOnly);
|
|
3334
|
+
for (const packageName of configuredLazy) {
|
|
3335
|
+
declaredPackages.add(packageName);
|
|
3336
|
+
importers.add(packageName);
|
|
3337
|
+
}
|
|
3338
|
+
for (const packageName of configuredClientOnly) {
|
|
3339
|
+
declaredPackages.add(packageName);
|
|
3340
|
+
importers.add(packageName);
|
|
3341
|
+
}
|
|
3342
|
+
for (const packageName of Object.keys(configuredModeMap)) {
|
|
3343
|
+
const normalizedPackageName = String(packageName || "").trim();
|
|
3344
|
+
if (!normalizedPackageName) {
|
|
3345
|
+
continue;
|
|
3346
|
+
}
|
|
3347
|
+
declaredPackages.add(normalizedPackageName);
|
|
3348
|
+
const mode = normalizeConfiguredPackageMode(configuredModeMap[normalizedPackageName], "ssr");
|
|
3349
|
+
if (mode !== "serverOnly") {
|
|
3350
|
+
importers.add(normalizedPackageName);
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
for (const [packageName, cssEntries] of Object.entries(cssByPackage)) {
|
|
3354
|
+
declaredPackages.add(packageName);
|
|
3355
|
+
importers.add(packageName);
|
|
3356
|
+
for (const entry of cssEntries) {
|
|
3357
|
+
importers.add(entry);
|
|
3358
|
+
}
|
|
3359
|
+
}
|
|
3360
|
+
if (Array.isArray(configuredPackages.css)) {
|
|
3361
|
+
for (const entry of configuredPackages.css) {
|
|
3362
|
+
const normalized = String(entry || "").trim();
|
|
3363
|
+
if (!normalized) {
|
|
3364
|
+
continue;
|
|
3365
|
+
}
|
|
3366
|
+
importers.add(normalized);
|
|
3367
|
+
}
|
|
3368
|
+
}
|
|
3369
|
+
for (const packageEntry of packageDiagnostics) {
|
|
3370
|
+
declaredPackages.add(packageEntry.name);
|
|
3371
|
+
const includeImporter = packageEntry.declaredMode !== "serverOnly"
|
|
3372
|
+
&& packageEntry.modes.some((mode) => mode !== "server");
|
|
3373
|
+
if (includeImporter) {
|
|
3374
|
+
importers.add(packageEntry.name);
|
|
3375
|
+
for (const specifier of packageEntry.specifiers) {
|
|
3376
|
+
const normalizedSpecifier = String(specifier || "").trim();
|
|
3377
|
+
if (!normalizedSpecifier || !isPackageSpecifier(normalizedSpecifier)) {
|
|
3378
|
+
continue;
|
|
3379
|
+
}
|
|
3380
|
+
importers.add(normalizedSpecifier);
|
|
3381
|
+
declaredPackages.add(normalizedSpecifier);
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
3384
|
+
for (const cssSpecifier of packageEntry.cssImports) {
|
|
3385
|
+
const normalizedCssSpecifier = String(cssSpecifier || "").trim();
|
|
3386
|
+
if (!normalizedCssSpecifier) {
|
|
3387
|
+
continue;
|
|
3388
|
+
}
|
|
3389
|
+
const cssOwner = normalizePackageName(normalizedCssSpecifier);
|
|
3390
|
+
if (!cssByPackage[cssOwner]) {
|
|
3391
|
+
cssByPackage[cssOwner] = [];
|
|
3392
|
+
}
|
|
3393
|
+
if (!cssByPackage[cssOwner].includes(normalizedCssSpecifier)) {
|
|
3394
|
+
cssByPackage[cssOwner].push(normalizedCssSpecifier);
|
|
3395
|
+
}
|
|
3396
|
+
importers.add(normalizedCssSpecifier);
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
const resolvedImporters = [...importers]
|
|
3400
|
+
.map((entry) => entry.trim())
|
|
3401
|
+
.filter((entry) => entry.length > 0)
|
|
3402
|
+
.filter((entry) => isPackageSpecifier(entry))
|
|
3403
|
+
.filter((entry) => canResolvePackageSpecifier(appRoot, entry))
|
|
3404
|
+
.sort((left, right) => left.localeCompare(right));
|
|
3405
|
+
const normalizedCssByPackage = {};
|
|
3406
|
+
for (const [packageName, entries] of Object.entries(cssByPackage)) {
|
|
3407
|
+
const normalizedEntries = [...new Set(entries
|
|
3408
|
+
.map((entry) => entry.trim())
|
|
3409
|
+
.filter((entry) => entry.length > 0))]
|
|
3410
|
+
.sort((left, right) => left.localeCompare(right));
|
|
3411
|
+
if (normalizedEntries.length > 0) {
|
|
3412
|
+
normalizedCssByPackage[packageName] = normalizedEntries;
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
return {
|
|
3416
|
+
importers: resolvedImporters,
|
|
3417
|
+
cssByPackage: normalizedCssByPackage,
|
|
3418
|
+
declared: [...declaredPackages].sort((left, right) => left.localeCompare(right)),
|
|
3419
|
+
};
|
|
3420
|
+
}
|
|
3421
|
+
function normalizeConfiguredPackageMode(value, fallback = "ssr") {
|
|
3422
|
+
if (typeof value !== "string") {
|
|
3423
|
+
return fallback;
|
|
3424
|
+
}
|
|
3425
|
+
const normalized = value.trim();
|
|
3426
|
+
if (normalized === "ssr"
|
|
3427
|
+
|| normalized === "clientOnly"
|
|
3428
|
+
|| normalized === "serverOnly"
|
|
3429
|
+
|| normalized === "progressive") {
|
|
3430
|
+
return normalized;
|
|
3431
|
+
}
|
|
3432
|
+
return fallback;
|
|
3433
|
+
}
|
|
3434
|
+
function resolveConfiguredPackageMode(packageName, config) {
|
|
3435
|
+
if (config.mode && typeof config.mode === "object" && !Array.isArray(config.mode)) {
|
|
3436
|
+
const direct = config.mode[packageName];
|
|
3437
|
+
if (direct) {
|
|
3438
|
+
return normalizeConfiguredPackageMode(direct, "ssr");
|
|
3439
|
+
}
|
|
3440
|
+
}
|
|
3441
|
+
const serverOnly = Array.isArray(config.serverOnly) ? config.serverOnly.map(String) : [];
|
|
3442
|
+
if (serverOnly.includes(packageName)) {
|
|
3443
|
+
return "serverOnly";
|
|
3444
|
+
}
|
|
3445
|
+
const clientOnly = Array.isArray(config.clientOnly) ? config.clientOnly.map(String) : [];
|
|
3446
|
+
if (clientOnly.includes(packageName)) {
|
|
3447
|
+
return "clientOnly";
|
|
3448
|
+
}
|
|
3449
|
+
return "ssr";
|
|
3450
|
+
}
|
|
3451
|
+
async function analyzePackageUsage(appRoot, sources, runtimeConfig) {
|
|
3452
|
+
const configuredPackages = readConfiguredPackages(runtimeConfig);
|
|
3453
|
+
const map = new Map();
|
|
3454
|
+
const ignoredPackages = new Set(["resuxjs", "vue", "h3", "nitropack", "typescript"]);
|
|
3455
|
+
for (const entry of sources) {
|
|
3456
|
+
let sourceText = "";
|
|
3457
|
+
try {
|
|
3458
|
+
sourceText = await readFile(entry.file, "utf8");
|
|
3459
|
+
}
|
|
3460
|
+
catch {
|
|
3461
|
+
continue;
|
|
3462
|
+
}
|
|
3463
|
+
const imports = collectPackageImportsFromSource(sourceText);
|
|
3464
|
+
for (const imported of imports) {
|
|
3465
|
+
if (!isPackageSpecifier(imported.specifier)) {
|
|
3466
|
+
continue;
|
|
3467
|
+
}
|
|
3468
|
+
const packageName = normalizePackageName(imported.specifier);
|
|
3469
|
+
if (!packageName || ignoredPackages.has(packageName)) {
|
|
3470
|
+
continue;
|
|
3471
|
+
}
|
|
3472
|
+
const usage = map.get(packageName) ?? {
|
|
3473
|
+
files: new Set(),
|
|
3474
|
+
modes: new Set(),
|
|
3475
|
+
dynamic: false,
|
|
3476
|
+
specifiers: new Set(),
|
|
3477
|
+
cssImports: new Set(),
|
|
3478
|
+
declaredMode: resolveConfiguredPackageMode(packageName, configuredPackages),
|
|
3479
|
+
warnings: new Set(),
|
|
3480
|
+
};
|
|
3481
|
+
usage.files.add(normalizePath(path.relative(appRoot, entry.file)));
|
|
3482
|
+
usage.modes.add(entry.mode);
|
|
3483
|
+
usage.dynamic = usage.dynamic || imported.dynamic;
|
|
3484
|
+
usage.specifiers.add(imported.specifier);
|
|
3485
|
+
if (imported.css) {
|
|
3486
|
+
usage.cssImports.add(imported.specifier);
|
|
3487
|
+
}
|
|
3488
|
+
if (entry.mode === "server" && (usage.declaredMode === "clientOnly" || usage.declaredMode === "progressive")) {
|
|
3489
|
+
usage.warnings.add(`Package "${packageName}" is marked ${usage.declaredMode} but appears in server files.`);
|
|
3490
|
+
}
|
|
3491
|
+
if (entry.mode !== "server" && usage.declaredMode === "serverOnly") {
|
|
3492
|
+
usage.warnings.add(`Package "${packageName}" is marked serverOnly but appears in client files.`);
|
|
3493
|
+
}
|
|
3494
|
+
if (usage.declaredMode === "progressive" && entry.mode === "all") {
|
|
3495
|
+
usage.warnings.add(`Package "${packageName}" is marked progressive. Prefer loading it inside a client enhancement instead of setup-time imports.`);
|
|
3496
|
+
}
|
|
3497
|
+
if (entry.mode === "server"
|
|
3498
|
+
&& usage.declaredMode === "ssr"
|
|
3499
|
+
&& /(swiper|gsap|chart\.js|echarts|plyr|animejs|video\.js)/i.test(packageName)) {
|
|
3500
|
+
usage.warnings.add(`Package "${packageName}" may be browser-only but is imported in server files. Consider packages.mode["${packageName}"] = "clientOnly" or "progressive".`);
|
|
3501
|
+
}
|
|
3502
|
+
map.set(packageName, usage);
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
const output = [];
|
|
3506
|
+
for (const [name, usage] of map.entries()) {
|
|
3507
|
+
let missing = false;
|
|
3508
|
+
try {
|
|
3509
|
+
require.resolve(name, { paths: [appRoot] });
|
|
3510
|
+
}
|
|
3511
|
+
catch {
|
|
3512
|
+
missing = true;
|
|
3513
|
+
usage.warnings.add(`Package "${name}" is imported but not installed.`);
|
|
3514
|
+
}
|
|
3515
|
+
output.push({
|
|
3516
|
+
name,
|
|
3517
|
+
specifiers: [...usage.specifiers].sort(),
|
|
3518
|
+
files: [...usage.files].sort(),
|
|
3519
|
+
modes: [...usage.modes].sort(),
|
|
3520
|
+
dynamic: usage.dynamic,
|
|
3521
|
+
cssImports: [...usage.cssImports].sort(),
|
|
3522
|
+
missing,
|
|
3523
|
+
declaredMode: usage.declaredMode,
|
|
3524
|
+
warnings: [...usage.warnings].sort(),
|
|
3525
|
+
});
|
|
3526
|
+
}
|
|
3527
|
+
return output.sort((left, right) => left.name.localeCompare(right.name));
|
|
3528
|
+
}
|
|
3529
|
+
function dedupeImports(entries) {
|
|
3530
|
+
const map = new Map();
|
|
3531
|
+
for (const entry of entries) {
|
|
3532
|
+
const key = `${entry.from}::${entry.name}::${entry.as ?? ""}`;
|
|
3533
|
+
map.set(key, entry);
|
|
3534
|
+
}
|
|
3535
|
+
return [...map.values()].sort((left, right) => {
|
|
3536
|
+
const leftKey = `${left.from}:${left.name}:${left.as ?? ""}`;
|
|
3537
|
+
const rightKey = `${right.from}:${right.name}:${right.as ?? ""}`;
|
|
3538
|
+
return leftKey.localeCompare(rightKey);
|
|
3539
|
+
});
|
|
3540
|
+
}
|
|
3541
|
+
async function discoverSupportTsFilesInDir(dir) {
|
|
3542
|
+
try {
|
|
3543
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
3544
|
+
const files = [];
|
|
3545
|
+
for (const entry of entries) {
|
|
3546
|
+
const fullPath = path.join(dir, entry.name);
|
|
3547
|
+
if (entry.isDirectory()) {
|
|
3548
|
+
files.push(...await discoverSupportTsFilesInDir(fullPath));
|
|
3549
|
+
continue;
|
|
3550
|
+
}
|
|
3551
|
+
if (!entry.isFile()) {
|
|
3552
|
+
continue;
|
|
3553
|
+
}
|
|
3554
|
+
if (!/\.[cm]?[tj]s$/.test(entry.name)) {
|
|
3555
|
+
continue;
|
|
3556
|
+
}
|
|
3557
|
+
if (/\.d\.[cm]?[tj]s$/.test(entry.name)) {
|
|
3558
|
+
continue;
|
|
3559
|
+
}
|
|
3560
|
+
files.push(fullPath);
|
|
3561
|
+
}
|
|
3562
|
+
return files;
|
|
3563
|
+
}
|
|
3564
|
+
catch {
|
|
3565
|
+
return [];
|
|
3566
|
+
}
|
|
3567
|
+
}
|
|
3568
|
+
async function discoverServerFiles(dir, routePrefix) {
|
|
3569
|
+
try {
|
|
3570
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
3571
|
+
const files = [];
|
|
3572
|
+
for (const entry of entries) {
|
|
3573
|
+
const fullPath = path.join(dir, entry.name);
|
|
3574
|
+
if (entry.isDirectory()) {
|
|
3575
|
+
files.push(...await discoverServerFiles(fullPath, `${routePrefix}/${entry.name}`));
|
|
3576
|
+
}
|
|
3577
|
+
else if (entry.isFile() && /\.[cm]?[tj]s$/.test(entry.name)) {
|
|
3578
|
+
const name = entry.name.replace(/\.[cm]?[tj]s$/, "");
|
|
3579
|
+
const segment = name === "index" ? "" : `/${name}`;
|
|
3580
|
+
files.push({
|
|
3581
|
+
file: fullPath,
|
|
3582
|
+
path: normalizeRoutePath(`${routePrefix}${segment}`)
|
|
3583
|
+
});
|
|
3584
|
+
}
|
|
3585
|
+
}
|
|
3586
|
+
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
3587
|
+
}
|
|
3588
|
+
catch {
|
|
3589
|
+
return [];
|
|
3590
|
+
}
|
|
3591
|
+
}
|
|
3592
|
+
async function discoverVueIslands(root) {
|
|
3593
|
+
const islandRoot = path.join(root, "islands", "vue");
|
|
3594
|
+
const files = await discoverVueFiles(islandRoot);
|
|
3595
|
+
return files.map((file) => {
|
|
3596
|
+
const relative = path.relative(islandRoot, file).replace(/\.vue$/, "");
|
|
3597
|
+
return {
|
|
3598
|
+
name: pascalCase(relative),
|
|
3599
|
+
file
|
|
3600
|
+
};
|
|
3601
|
+
});
|
|
3602
|
+
}
|
|
3603
|
+
async function findFirstExisting(files) {
|
|
3604
|
+
for (const file of files) {
|
|
3605
|
+
const found = await optionalFile(file);
|
|
3606
|
+
if (found) {
|
|
3607
|
+
return found;
|
|
3608
|
+
}
|
|
3609
|
+
}
|
|
3610
|
+
return null;
|
|
3611
|
+
}
|
|
3612
|
+
function unique(items) {
|
|
3613
|
+
return [...new Set(items)];
|
|
3614
|
+
}
|
|
3615
|
+
async function optionalFile(file) {
|
|
3616
|
+
try {
|
|
3617
|
+
await readFile(file, "utf8");
|
|
3618
|
+
return file;
|
|
3619
|
+
}
|
|
3620
|
+
catch {
|
|
3621
|
+
return null;
|
|
3622
|
+
}
|
|
3623
|
+
}
|
|
3624
|
+
async function existsFile(file) {
|
|
3625
|
+
try {
|
|
3626
|
+
await stat(file);
|
|
3627
|
+
return true;
|
|
3628
|
+
}
|
|
3629
|
+
catch {
|
|
3630
|
+
return false;
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3633
|
+
function inferComponentName(root, file, componentDirs = []) {
|
|
3634
|
+
const relative = normalizePath(path.relative(root, file));
|
|
3635
|
+
if (relative === "app.vue") {
|
|
3636
|
+
return "App";
|
|
3637
|
+
}
|
|
3638
|
+
const normalizedFile = normalizePath(path.resolve(file));
|
|
3639
|
+
for (const dir of componentDirs) {
|
|
3640
|
+
const normalizedDir = normalizePath(path.resolve(dir)) + "/";
|
|
3641
|
+
if (normalizedFile.startsWith(normalizedDir)) {
|
|
3642
|
+
const relToDir = normalizedFile.slice(normalizedDir.length).replace(/\.vue$/, "");
|
|
3643
|
+
const segments = relToDir.split("/").filter(Boolean);
|
|
3644
|
+
const parts = [];
|
|
3645
|
+
for (let i = 0; i < segments.length; i++) {
|
|
3646
|
+
const current = pascalCase(segments[i]);
|
|
3647
|
+
if (i < segments.length - 1) {
|
|
3648
|
+
const next = pascalCase(segments[i + 1]);
|
|
3649
|
+
if (next.toLowerCase().startsWith(current.toLowerCase())) {
|
|
3650
|
+
continue;
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3653
|
+
parts.push(current);
|
|
3654
|
+
}
|
|
3655
|
+
return parts.join("");
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
return pascalCase(path.basename(file, ".vue"));
|
|
3659
|
+
}
|
|
3660
|
+
function pascalCase(value) {
|
|
3661
|
+
return value
|
|
3662
|
+
.replace(/\[[^\]]+\]/g, (match) => match.slice(1, -1))
|
|
3663
|
+
.split(/[^A-Za-z0-9]+/)
|
|
3664
|
+
.filter(Boolean)
|
|
3665
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
3666
|
+
.join("");
|
|
3667
|
+
}
|
|
3668
|
+
function kebabCase(value) {
|
|
3669
|
+
return value
|
|
3670
|
+
.replace(/\[[^\]]+\]/g, (match) => match.slice(1, -1))
|
|
3671
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1-$2")
|
|
3672
|
+
.replace(/\.global$/, "")
|
|
3673
|
+
.split(/[^A-Za-z0-9]+/)
|
|
3674
|
+
.filter(Boolean)
|
|
3675
|
+
.join("-")
|
|
3676
|
+
.toLowerCase();
|
|
3677
|
+
}
|
|
3678
|
+
function normalizePath(value) {
|
|
3679
|
+
return value.replaceAll("\\", "/");
|
|
3680
|
+
}
|
|
3681
|
+
function normalizeRoutePath(value) {
|
|
3682
|
+
const normalized = value
|
|
3683
|
+
.replaceAll("\\", "/")
|
|
3684
|
+
.replace(/\.[cm]?[tj]s$/, "")
|
|
3685
|
+
.replace(/\[\.\.\.([A-Za-z0-9_]+)\]/g, ":$1*")
|
|
3686
|
+
.replace(/\[([A-Za-z0-9_]+)\]/g, ":$1")
|
|
3687
|
+
.replace(/\/index$/, "");
|
|
3688
|
+
return (`/${normalized}`.replace(/\/+/g, "/").replace(/\/$/, "")) || "/";
|
|
3689
|
+
}
|
|
3690
|
+
function collectRouteParams(routePath) {
|
|
3691
|
+
return routePath
|
|
3692
|
+
.split("/")
|
|
3693
|
+
.filter((part) => part.startsWith(":"))
|
|
3694
|
+
.map((part) => part.slice(1).replace(/\*$/, ""));
|
|
3695
|
+
}
|
|
3696
|
+
function locationFromVueNode(file, node) {
|
|
3697
|
+
return {
|
|
3698
|
+
file,
|
|
3699
|
+
line: node.loc?.start?.line ?? 1,
|
|
3700
|
+
column: node.loc?.start?.column ?? 1
|
|
3701
|
+
};
|
|
3702
|
+
}
|
|
3703
|
+
function locationFromTsNode(file, sourceFile, node) {
|
|
3704
|
+
const nodeSourceFile = node.getSourceFile() ?? sourceFile;
|
|
3705
|
+
const position = nodeSourceFile.getLineAndCharacterOfPosition(node.getStart(nodeSourceFile));
|
|
3706
|
+
return {
|
|
3707
|
+
file,
|
|
3708
|
+
line: position.line + 1,
|
|
3709
|
+
column: position.character + 1
|
|
3710
|
+
};
|
|
3711
|
+
}
|
|
3712
|
+
function locationFromOffset(file, source, offset) {
|
|
3713
|
+
const lines = source.slice(0, offset).split(/\r?\n/);
|
|
3714
|
+
return {
|
|
3715
|
+
file,
|
|
3716
|
+
line: lines.length,
|
|
3717
|
+
column: lines[lines.length - 1].length + 1
|
|
3718
|
+
};
|
|
3719
|
+
}
|
|
3720
|
+
export function resolveFileExtension(filePath) {
|
|
3721
|
+
const ext = path.extname(filePath);
|
|
3722
|
+
if (ext) {
|
|
3723
|
+
return filePath;
|
|
3724
|
+
}
|
|
3725
|
+
const extensions = [".ts", ".js", ".vue", ".tsx", ".jsx", ".mjs", ".cjs"];
|
|
3726
|
+
for (const ext of extensions) {
|
|
3727
|
+
const candidate = filePath + ext;
|
|
3728
|
+
if (existsSync(candidate)) {
|
|
3729
|
+
return candidate;
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
if (existsSync(filePath) && statSync(filePath).isDirectory()) {
|
|
3733
|
+
for (const ext of extensions) {
|
|
3734
|
+
const candidate = path.join(filePath, "index" + ext);
|
|
3735
|
+
if (existsSync(candidate)) {
|
|
3736
|
+
return candidate;
|
|
3737
|
+
}
|
|
3738
|
+
}
|
|
3739
|
+
}
|
|
3740
|
+
return filePath;
|
|
3741
|
+
}
|
|
3742
|
+
export function fileUrl(file) {
|
|
3743
|
+
return pathToFileURL(file).href;
|
|
3744
|
+
}
|
|
3745
|
+
//# sourceMappingURL=index.js.map
|