@lingfan-engine/create 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +201 -0
  2. package/bin/create.mjs +18 -0
  3. package/package.json +44 -3
  4. package/src/cli/cli.ts +302 -0
  5. package/src/cli/prompts.ts +115 -0
  6. package/src/generate/dotfiles.ts +27 -0
  7. package/src/generate/index.ts +20 -0
  8. package/src/generate/project.ts +279 -0
  9. package/src/generate/replace.ts +91 -0
  10. package/src/index.ts +46 -0
  11. package/src/overlay/index.ts +10 -0
  12. package/src/overlay/merge.ts +143 -0
  13. package/src/registry/index.ts +15 -0
  14. package/src/registry/template-meta.ts +107 -0
  15. package/src/registry/versions.ts +109 -0
  16. package/src/shared/guards.ts +85 -0
  17. package/src/shared/index.ts +7 -0
  18. package/src/shared/texts.ts +55 -0
  19. package/template/README.md +138 -0
  20. package/template/__PROJECT__/Resources/Audio/.gitkeep +0 -0
  21. package/template/__PROJECT__/Resources/Fonts/README.md +10 -0
  22. package/template/__PROJECT__/Resources/Images/.gitkeep +0 -0
  23. package/template/__PROJECT__/Resources/Lang/.gitkeep +0 -0
  24. package/template/__PROJECT__/Resources/Stories/title/title_main.story +24 -0
  25. package/template/__PROJECT__/Resources/Video/.gitkeep +0 -0
  26. package/template/__PROJECT__/Resources/project.json +7 -0
  27. package/template/__PROJECT__/gitignore +8 -0
  28. package/template/__PROJECT__/index.html +34 -0
  29. package/template/__PROJECT__/package.json +22 -0
  30. package/template/__PROJECT__/pnpm-workspace.yaml +8 -0
  31. package/template/__PROJECT__/src/host/boot.ts +181 -0
  32. package/template/__PROJECT__/src/host/dialogue-view.ts +235 -0
  33. package/template/__PROJECT__/src/host/effects.ts +68 -0
  34. package/template/__PROJECT__/src/host/engine-wiring.ts +206 -0
  35. package/template/__PROJECT__/src/host/frame-loop.ts +42 -0
  36. package/template/__PROJECT__/src/host/index.ts +27 -0
  37. package/template/__PROJECT__/src/host/input-map.ts +51 -0
  38. package/template/__PROJECT__/src/host/layer-z.ts +50 -0
  39. package/template/__PROJECT__/src/host/save-slots.ts +38 -0
  40. package/template/__PROJECT__/src/host/stage-dom.ts +74 -0
  41. package/template/__PROJECT__/src/host/theme-fonts.ts +60 -0
  42. package/template/__PROJECT__/src/host/toast.ts +29 -0
  43. package/template/__PROJECT__/src/main.ts +61 -0
  44. package/template/__PROJECT__/src/styles/stage.css +183 -0
  45. package/template/__PROJECT__/src/vite-env.d.ts +14 -0
  46. package/template/__PROJECT__/tsconfig.json +19 -0
  47. package/template/__PROJECT__/tsconfig.node.json +14 -0
  48. package/template/__PROJECT__/vite.config.ts +64 -0
  49. package/template/overlays/README.md +70 -0
  50. package/template/overlays/miniprogram/README.md +104 -0
  51. package/template/overlays/miniprogram/index.html +15 -0
  52. package/template/overlays/miniprogram/package.patch.json +40 -0
  53. package/template/overlays/miniprogram/scripts/serve-project.mjs +273 -0
  54. package/template/overlays/miniprogram/src/App.vue +23 -0
  55. package/template/overlays/miniprogram/src/components/ChoiceLayer.vue +208 -0
  56. package/template/overlays/miniprogram/src/components/DialogueLayer.vue +183 -0
  57. package/template/overlays/miniprogram/src/components/NodeTree.vue +44 -0
  58. package/template/overlays/miniprogram/src/components/NoticeLayer.vue +87 -0
  59. package/template/overlays/miniprogram/src/components/SaveLoadBar.vue +168 -0
  60. package/template/overlays/miniprogram/src/components/StageView.vue +50 -0
  61. package/template/overlays/miniprogram/src/env.d.ts +1 -0
  62. package/template/overlays/miniprogram/src/main.ts +12 -0
  63. package/template/overlays/miniprogram/src/manifest.json +21 -0
  64. package/template/overlays/miniprogram/src/mp/frame.ts +51 -0
  65. package/template/overlays/miniprogram/src/mp/guards.ts +28 -0
  66. package/template/overlays/miniprogram/src/mp/host.ts +252 -0
  67. package/template/overlays/miniprogram/src/mp/index.ts +9 -0
  68. package/template/overlays/miniprogram/src/mp/platform.ts +210 -0
  69. package/template/overlays/miniprogram/src/mp/ports.ts +84 -0
  70. package/template/overlays/miniprogram/src/mp/project-source.ts +77 -0
  71. package/template/overlays/miniprogram/src/mp/slots.ts +64 -0
  72. package/template/overlays/miniprogram/src/mp/surface.ts +239 -0
  73. package/template/overlays/miniprogram/src/mp/video-surface.ts +104 -0
  74. package/template/overlays/miniprogram/src/mp/view.ts +91 -0
  75. package/template/overlays/miniprogram/src/pages/index/index.vue +299 -0
  76. package/template/overlays/miniprogram/src/pages.json +18 -0
  77. package/template/overlays/miniprogram/tsconfig.json +20 -0
  78. package/template/overlays/miniprogram/vite.config.ts +87 -0
  79. package/template/overlays/react/index.html +16 -0
  80. package/template/overlays/react/package.patch.json +18 -0
  81. package/template/overlays/react/src/App.tsx +32 -0
  82. package/template/overlays/react/src/main.tsx +74 -0
  83. package/template/overlays/react/src/vite-env.d.ts +14 -0
  84. package/template/overlays/react/tsconfig.json +20 -0
  85. package/template/overlays/react/vite.config.ts +67 -0
  86. package/template/overlays/tauri/README.md +59 -0
  87. package/template/overlays/tauri/package.patch.json +14 -0
  88. package/template/overlays/tauri/src/main.ts +58 -0
  89. package/template/overlays/tauri/src-tauri/Cargo.toml +16 -0
  90. package/template/overlays/tauri/src-tauri/build.rs +6 -0
  91. package/template/overlays/tauri/src-tauri/capabilities/default.json +7 -0
  92. package/template/overlays/tauri/src-tauri/icons/128x128.png +0 -0
  93. package/template/overlays/tauri/src-tauri/icons/128x128@2x.png +0 -0
  94. package/template/overlays/tauri/src-tauri/icons/32x32.png +0 -0
  95. package/template/overlays/tauri/src-tauri/icons/Square107x107Logo.png +0 -0
  96. package/template/overlays/tauri/src-tauri/icons/Square142x142Logo.png +0 -0
  97. package/template/overlays/tauri/src-tauri/icons/Square150x150Logo.png +0 -0
  98. package/template/overlays/tauri/src-tauri/icons/Square284x284Logo.png +0 -0
  99. package/template/overlays/tauri/src-tauri/icons/Square30x30Logo.png +0 -0
  100. package/template/overlays/tauri/src-tauri/icons/Square310x310Logo.png +0 -0
  101. package/template/overlays/tauri/src-tauri/icons/Square44x44Logo.png +0 -0
  102. package/template/overlays/tauri/src-tauri/icons/Square71x71Logo.png +0 -0
  103. package/template/overlays/tauri/src-tauri/icons/Square89x89Logo.png +0 -0
  104. package/template/overlays/tauri/src-tauri/icons/StoreLogo.png +0 -0
  105. package/template/overlays/tauri/src-tauri/icons/icon.icns +0 -0
  106. package/template/overlays/tauri/src-tauri/icons/icon.ico +0 -0
  107. package/template/overlays/tauri/src-tauri/icons/icon.png +0 -0
  108. package/template/overlays/tauri/src-tauri/src/lib.rs +26 -0
  109. package/template/overlays/tauri/src-tauri/src/main.rs +7 -0
  110. package/template/overlays/tauri/src-tauri/src/preferences.rs +50 -0
  111. package/template/overlays/tauri/src-tauri/src/save.rs +178 -0
  112. package/template/overlays/tauri/src-tauri/tauri.conf.json +35 -0
  113. package/template/overlays/vue/index.html +16 -0
  114. package/template/overlays/vue/package.patch.json +16 -0
  115. package/template/overlays/vue/src/App.vue +30 -0
  116. package/template/overlays/vue/src/main.ts +68 -0
  117. package/template/overlays/vue/src/vite-env.d.ts +24 -0
  118. package/template/overlays/vue/tsconfig.json +19 -0
  119. package/template/overlays/vue/vite.config.ts +67 -0
  120. package/template/pack-template.ps1 +65 -0
  121. package/template/template-meta.json +40 -0
  122. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2026 MoFeng-02
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/bin/create.mjs ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `npm create @lingfan-engine` / `pnpm create @lingfan-engine` 的可执行入口(bin 垫片)。
4
+ *
5
+ * 为什么需要这层垫片:本包与仓库其它包一致,以 TypeScript 源码出口(`exports` 指向
6
+ * `./src/*.ts`)。Node 的类型擦除**拒绝加载 node_modules 里的 .ts**
7
+ * (ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING),所以装了本包的机器既不能 `node` 直跑
8
+ * `src/cli/cli.ts`,也不该被迫装一整套构建链。垫片用本包自带依赖 `tsx` 装载真实 CLI,
9
+ * 呈现与编排逻辑仍然只有一份。
10
+ *
11
+ * 用法:`npm create @lingfan-engine [工程名] [-- --framework vanilla --shell browser]`;
12
+ * 不带参数即进入交互问答。
13
+ */
14
+ import { tsImport } from "tsx/esm/api";
15
+
16
+ const { runCreateCli } = await tsImport("../src/cli/cli.ts", import.meta.url);
17
+ const code = await runCreateCli(process.argv.slice(2));
18
+ if (code !== 0) process.exit(code);
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@lingfan-engine/create",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.4",
4
+ "type": "module",
5
+ "description": "工程生成器:从模板骨架生成新工程,可选框架与壳",
6
+ "license": "Apache-2.0",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./cli": "./src/cli/cli.ts"
10
+ },
11
+ "bin": {
12
+ "lingfan-create": "./bin/create.mjs"
13
+ },
14
+ "files": [
15
+ "src",
16
+ "bin",
17
+ "template",
18
+ "!src/**/*.test.ts"
19
+ ],
20
+ "sideEffects": false,
21
+ "dependencies": {
22
+ "tsx": "^4.23.15"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/MoFeng-02/LingFan.Engine.git",
27
+ "directory": "packages/create"
28
+ },
29
+ "homepage": "https://github.com/MoFeng-02/LingFan.Engine#readme",
30
+ "bugs": {
31
+ "url": "https://github.com/MoFeng-02/LingFan.Engine/issues"
32
+ },
33
+ "keywords": [
34
+ "narrative",
35
+ "engine",
36
+ "scaffold",
37
+ "create",
38
+ "template"
39
+ ],
40
+ "engines": {
41
+ "node": ">=22.12.0"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {}
6
47
  }
package/src/cli/cli.ts ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * 命令行入口。
3
+ *
4
+ * 分工:参数解析与流程编排在这里,「问什么」在 `prompts.ts`,「生成什么」在
5
+ * `generate` 域,「版本从哪来」在 `registry` 域。本文件只负责把这些串起来,
6
+ * 并把失败转成人能读的提示与退出码——库代码一律抛异常,只有这里决定措辞。
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { resolve as resolvePath } from "node:path";
10
+ import { defaultCreateTexts } from "../shared/index.ts";
11
+ import { isValidProjectName, suggestProjectName } from "../shared/index.ts";
12
+ import {
13
+ layerBases,
14
+ generateProject,
15
+ collectDependencyNames,
16
+ } from "../generate/index.ts";
17
+ import {
18
+ readTemplateMeta,
19
+ resolveTemplateRoot,
20
+ resolveVersions,
21
+ type TemplateMeta,
22
+ } from "../registry/index.ts";
23
+ import {
24
+ askOption,
25
+ askProjectName,
26
+ createTerminalIo,
27
+ type PromptTexts,
28
+ } from "./prompts.ts";
29
+
30
+ /** 解析后的命令行参数;缺席项为 undefined,交由问答或模板缺省值补 */
31
+ export interface CreateArgs {
32
+ readonly projectName?: string;
33
+ readonly framework?: string;
34
+ readonly shell?: string;
35
+ readonly dir?: string;
36
+ readonly install: boolean;
37
+ readonly yes: boolean;
38
+ readonly help: boolean;
39
+ }
40
+
41
+ /** 参数解析失败:信息即用户可见提示 */
42
+ class ArgError extends Error {}
43
+
44
+ /**
45
+ * 解析命令行。
46
+ *
47
+ * 支持 `--flag value` 与 `--flag=value` 两种写法:前者是手敲的习惯,
48
+ * 后者在脚本里拼接更省事,两者都认不需要额外成本。
49
+ */
50
+ export function parseArgs(argv: readonly string[]): CreateArgs {
51
+ let projectName: string | undefined;
52
+ let framework: string | undefined;
53
+ let shell: string | undefined;
54
+ let dir: string | undefined;
55
+ let install = true;
56
+ let yes = false;
57
+ let help = false;
58
+
59
+ for (let index = 0; index < argv.length; index += 1) {
60
+ const arg = argv[index];
61
+ const [flag, inline] = splitFlag(arg);
62
+ const takeValue = (): string => {
63
+ if (inline !== undefined) return inline;
64
+ const next = argv[index + 1];
65
+ if (next === undefined || next.startsWith("-")) {
66
+ throw new ArgError(`选项 ${flag} 缺少取值`);
67
+ }
68
+ index += 1;
69
+ return next;
70
+ };
71
+ switch (flag) {
72
+ case "-f":
73
+ case "--framework":
74
+ framework = takeValue();
75
+ break;
76
+ case "-s":
77
+ case "--shell":
78
+ shell = takeValue();
79
+ break;
80
+ case "-d":
81
+ case "--dir":
82
+ dir = takeValue();
83
+ break;
84
+ case "--no-install":
85
+ install = false;
86
+ break;
87
+ case "-y":
88
+ case "--yes":
89
+ yes = true;
90
+ break;
91
+ case "-h":
92
+ case "--help":
93
+ help = true;
94
+ break;
95
+ default:
96
+ if (flag.startsWith("-")) throw new ArgError(`未知选项:${flag}`);
97
+ if (projectName !== undefined) {
98
+ throw new ArgError(`多余的参数:${flag}`);
99
+ }
100
+ projectName = flag;
101
+ }
102
+ }
103
+ return { projectName, framework, shell, dir, install, yes, help };
104
+ }
105
+
106
+ /** 拆出 `--flag=value`;无等号时第二项为 undefined */
107
+ function splitFlag(arg: string): [string, string | undefined] {
108
+ if (!arg.startsWith("--")) return [arg, undefined];
109
+ const eq = arg.indexOf("=");
110
+ if (eq < 0) return [arg, undefined];
111
+ return [arg.slice(0, eq), arg.slice(eq + 1)];
112
+ }
113
+
114
+ /**
115
+ * 执行一次生成,返回进程退出码。
116
+ *
117
+ * 不调用 `process.exit`:退出码作为返回值交出去,测试与 bin 垫片各自决定怎么用,
118
+ * 也让「跑一遍」在测试里不会直接杀掉进程。
119
+ */
120
+ export async function runCreateCli(argv: readonly string[]): Promise<number> {
121
+ const texts = defaultCreateTexts;
122
+ let args: CreateArgs;
123
+ try {
124
+ args = parseArgs(argv);
125
+ } catch (error) {
126
+ if (error instanceof ArgError) {
127
+ process.stderr.write(`${error.message}\n`);
128
+ return 1;
129
+ }
130
+ throw error;
131
+ }
132
+ if (args.help) {
133
+ process.stdout.write(`${texts.banner}\n\n${texts.help}\n`);
134
+ return 0;
135
+ }
136
+
137
+ const templateRoot = resolveTemplateRoot();
138
+ if (templateRoot === undefined) {
139
+ process.stderr.write(`${texts.templateMissing}\n`);
140
+ return 1;
141
+ }
142
+ const meta = readTemplateMeta(templateRoot);
143
+
144
+ const io = args.yes ? undefined : createTerminalIo();
145
+ const promptTexts = texts;
146
+ try {
147
+ const projectName = await resolveName(args, promptTexts, io);
148
+ if (projectName === undefined) return 1;
149
+ const framework = await resolveOption(
150
+ "framework",
151
+ args.framework,
152
+ meta,
153
+ promptTexts,
154
+ io,
155
+ );
156
+ if (framework === undefined) return 1;
157
+ const shell = await resolveOption(
158
+ "shell",
159
+ args.shell,
160
+ meta,
161
+ promptTexts,
162
+ io,
163
+ );
164
+ if (shell === undefined) return 1;
165
+ return await generate({
166
+ args,
167
+ meta,
168
+ templateRoot,
169
+ projectName,
170
+ framework,
171
+ shell,
172
+ });
173
+ } finally {
174
+ io?.close();
175
+ }
176
+ }
177
+
178
+ /** 生成一步:查版本 → 写文件 → 可选安装 → 打印后续步骤 */
179
+ async function generate(input: {
180
+ readonly args: CreateArgs;
181
+ readonly meta: TemplateMeta;
182
+ readonly templateRoot: string;
183
+ readonly projectName: string;
184
+ readonly framework: string;
185
+ readonly shell: string;
186
+ }): Promise<number> {
187
+ const texts = defaultCreateTexts;
188
+ const targetBase = resolvePath(input.args.dir ?? process.cwd());
189
+ const layout = {
190
+ templateRoot: input.templateRoot,
191
+ targetBase,
192
+ projectName: input.projectName,
193
+ framework: input.framework,
194
+ shell: input.shell,
195
+ resolved: new Map<string, string>(),
196
+ };
197
+
198
+ process.stderr.write(`${texts.stageResolve}\n`);
199
+ const names = collectDependencyNames(layerBases(layout));
200
+ const resolved = await resolveVersions(names);
201
+ if (resolved.size === 0 && names.length > 0) {
202
+ process.stderr.write(`${texts.warnVersionOffline}\n`);
203
+ }
204
+
205
+ process.stderr.write(`${texts.stageCopy}\n`);
206
+ let result;
207
+ try {
208
+ result = generateProject({ ...layout, resolved });
209
+ } catch (error) {
210
+ process.stderr.write(`${describe(error)}\n`);
211
+ return 1;
212
+ }
213
+
214
+ let installed = false;
215
+ if (input.args.install) {
216
+ process.stderr.write(`${texts.stageInstall}\n`);
217
+ installed = await install(result.projectDir);
218
+ if (!installed) process.stderr.write(`${texts.warnInstallFailed}\n`);
219
+ }
220
+
221
+ process.stdout.write(
222
+ [
223
+ "",
224
+ `${texts.doneTitle}:${result.projectDir}`,
225
+ `共 ${result.fileCount} 个文件,框架 ${input.framework},壳 ${input.shell}`,
226
+ "",
227
+ installed ? "依赖已安装。" : "依赖未安装。",
228
+ texts.nextSteps.split("<name>").join(result.projectDir),
229
+ "",
230
+ ].join("\n"),
231
+ );
232
+ return 0;
233
+ }
234
+
235
+ /** 解析工程名:参数优先,参数非法即报错;交互模式打错会重问 */
236
+ async function resolveName(
237
+ args: CreateArgs,
238
+ texts: PromptTexts & { readonly nameInvalid: string },
239
+ io: Parameters<typeof askProjectName>[0] | undefined,
240
+ ): Promise<string | undefined> {
241
+ if (args.projectName !== undefined) {
242
+ if (isValidProjectName(args.projectName)) return args.projectName;
243
+ process.stderr.write(`${texts.nameInvalid}:${args.projectName}\n`);
244
+ return undefined;
245
+ }
246
+ if (io === undefined) {
247
+ return suggestProjectName("");
248
+ }
249
+ return await askProjectName(io, texts, undefined);
250
+ }
251
+
252
+ /**
253
+ * 解析框架/壳:必须真实存在对应的叠加层,否则报错。
254
+ *
255
+ * 只校验「模板声明过」而不校验「目录存在」会放过一种情况:元数据写了 `vue`
256
+ * 但仓库里没有 `overlays/vue`,生成出来的工程静默缺少该框架的文件。
257
+ */
258
+ async function resolveOption(
259
+ kind: "framework" | "shell",
260
+ value: string | undefined,
261
+ meta: TemplateMeta,
262
+ texts: PromptTexts & { readonly overlayMissing: string },
263
+ io: Parameters<typeof askOption>[0] | undefined,
264
+ ): Promise<string | undefined> {
265
+ const options = kind === "framework" ? meta.frameworks : meta.shells;
266
+ const invalidText =
267
+ kind === "framework" ? texts.frameworkUnknown : texts.shellUnknown;
268
+ const label =
269
+ kind === "framework" ? texts.promptFramework : texts.promptShell;
270
+ const picked =
271
+ value !== undefined || io === undefined
272
+ ? (value ?? options[0]?.id)
273
+ : await askOption(io, label, options, undefined, invalidText);
274
+ if (picked === undefined || !options.some((item) => item.id === picked)) {
275
+ process.stderr.write(`${invalidText}:${String(picked)}\n`);
276
+ return undefined;
277
+ }
278
+ return picked;
279
+ }
280
+
281
+ /**
282
+ * 在工程目录里装依赖。
283
+ *
284
+ * 只有 pnpm:本仓与模板的工程都以 pnpm 为准(锁文件、workspace 协议改写都依赖它),
285
+ * 换别的包管理器会生成第二份锁文件,日后发布还要再处理一遍。
286
+ */
287
+ async function install(dir: string): Promise<boolean> {
288
+ return await new Promise<boolean>((done) => {
289
+ const child = spawn("pnpm", ["install"], {
290
+ cwd: dir,
291
+ stdio: "inherit",
292
+ shell: process.platform === "win32",
293
+ });
294
+ child.on("error", () => done(false));
295
+ child.on("close", (code) => done(code === 0));
296
+ });
297
+ }
298
+
299
+ /** 把异常折成一行提示:只暴露信息,不暴露堆栈 */
300
+ function describe(error: unknown): string {
301
+ return error instanceof Error ? error.message : String(error);
302
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * 交互问答。
3
+ *
4
+ * 生成器要问三件事:工程名、框架、壳。三项都能用命令行参数预先给定——CI、脚本、
5
+ * 或「我已经知道要什么」的人不该被问答拦住,因此问答只在参数缺席时发生。
6
+ *
7
+ * 实现只用 `node:readline` 的 promise 版:它随 Node 自带,不引第三方交互库。
8
+ * 提问写 stderr 而不是 stdout,产物路径之类的结果才走 stdout,这样
9
+ * `npm create … > log.txt` 不会把问题一起吞掉。
10
+ */
11
+ import { createInterface } from "node:readline/promises";
12
+ import { isValidProjectName, suggestProjectName } from "../shared/index.ts";
13
+ import type { TemplateOption } from "../registry/index.ts";
14
+
15
+ /** 问答需要的一份文案;由调用方从共享文案表传入,便于测试替换 */
16
+ export interface PromptTexts {
17
+ readonly promptProjectName: string;
18
+ readonly promptFramework: string;
19
+ readonly promptShell: string;
20
+ readonly nameRequired: string;
21
+ readonly nameInvalid: string;
22
+ readonly frameworkUnknown: string;
23
+ readonly shellUnknown: string;
24
+ }
25
+
26
+ /** 问答依赖的输入输出面;默认接真实终端,测试可换成脚本化实现 */
27
+ export interface PromptIo {
28
+ question(text: string): Promise<string>;
29
+ close(): void;
30
+ }
31
+
32
+ /** 造一个接到标准输入输出的问答面 */
33
+ export function createTerminalIo(): PromptIo {
34
+ const rl = createInterface({
35
+ input: process.stdin,
36
+ output: process.stderr,
37
+ terminal: process.stdin.isTTY === true,
38
+ });
39
+ return {
40
+ question: (text) => rl.question(text),
41
+ close: () => rl.close(),
42
+ };
43
+ }
44
+
45
+ /**
46
+ * 问工程名:空输入取建议值,非法输入重问。
47
+ *
48
+ * 重问而不是直接失败,是因为这里是人机交互——打错一个字不该让整条命令重来,
49
+ * 而失败退出只该发生在「参数模式」(调用方传了非法名字)下。
50
+ */
51
+ export async function askProjectName(
52
+ io: PromptIo,
53
+ texts: PromptTexts,
54
+ initial: string | undefined,
55
+ ): Promise<string> {
56
+ if (initial !== undefined) return initial;
57
+ for (;;) {
58
+ const answer = (await io.question(`${texts.promptProjectName}:`)).trim();
59
+ const name = answer === "" ? suggestProjectName("") : answer;
60
+ if (isValidProjectName(name)) return name;
61
+ process.stderr.write(
62
+ `${answer === "" ? texts.nameRequired : texts.nameInvalid}\n`,
63
+ );
64
+ }
65
+ }
66
+
67
+ /**
68
+ * 从选项表里选一项:输入序号(从 1 起)或直接输入 id,空输入取首项。
69
+ *
70
+ * 两种取值都认,是因为脚本里写 `--framework vue` 更自然,而交互时按数字更省事;
71
+ * 让同一套问答支持两种输入,参数模式与交互模式就不必分两套校验。
72
+ */
73
+ export async function askOption(
74
+ io: PromptIo,
75
+ label: string,
76
+ options: readonly TemplateOption[],
77
+ fallbackId: string | undefined,
78
+ invalidText: string,
79
+ ): Promise<string> {
80
+ if (fallbackId !== undefined) return fallbackId;
81
+ const lines = options
82
+ .map((option, index) => ` ${index + 1}. ${option.label} —— ${option.hint}`)
83
+ .join("\n");
84
+ process.stderr.write(`${label}:\n${lines}\n`);
85
+ for (;;) {
86
+ const answer = (
87
+ await io.question(`选择(1-${options.length},回车取 1):`)
88
+ ).trim();
89
+ const picked = pickOption(options, answer);
90
+ if (picked !== undefined) return picked;
91
+ process.stderr.write(`${invalidText}\n`);
92
+ }
93
+ }
94
+
95
+ /**
96
+ * 把一次输入解析成选项 id;解析不出返回 undefined。
97
+ *
98
+ * 序号先判再判 id:`1` 与某个 id 恰好同名时,序号语义优先——用户看到的是编号表。
99
+ */
100
+ export function pickOption(
101
+ options: readonly TemplateOption[],
102
+ answer: string,
103
+ ): string | undefined {
104
+ if (answer === "") {
105
+ return options.length > 0 ? options[0].id : undefined;
106
+ }
107
+ const index = Number(answer);
108
+ if (Number.isInteger(index) && index >= 1 && index <= options.length) {
109
+ return options[index - 1].id;
110
+ }
111
+ for (const option of options) {
112
+ if (option.id === answer) return option.id;
113
+ }
114
+ return undefined;
115
+ }