@weapp-core/init 2.1.5 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/index.cjs +491 -304
  2. package/dist/index.d.cts +71 -41
  3. package/dist/index.d.ts +71 -41
  4. package/dist/index.js +488 -301
  5. package/package.json +1 -1
  6. package/templates/default/gitignore +34 -0
  7. package/templates/default/package.json +2 -2
  8. package/templates/{tdesign/src/components/Navbar/Navbar.json → default/src/components/HelloWorld/HelloWorld.json} +1 -2
  9. package/templates/default/src/components/HelloWorld/HelloWorld.ts +1 -0
  10. package/templates/default/src/components/HelloWorld/HelloWorld.wxml +4 -0
  11. package/templates/default/src/pages/index/index.json +7 -0
  12. package/templates/default/src/pages/index/index.wxml +1 -1
  13. package/templates/tailwindcss/gitignore +34 -0
  14. package/templates/tailwindcss/package.json +3 -3
  15. package/templates/tdesign/gitignore +34 -0
  16. package/templates/tdesign/package.json +3 -3
  17. package/templates/{default/src/components/Navbar/Navbar.json → tdesign/src/components/HelloWorld/HelloWorld.json} +0 -1
  18. package/templates/tdesign/src/components/HelloWorld/HelloWorld.ts +5 -0
  19. package/templates/tdesign/src/components/HelloWorld/HelloWorld.wxml +7 -0
  20. package/templates/tdesign/src/pages/index/index.json +1 -1
  21. package/templates/tdesign/src/pages/index/index.wxml +6 -10
  22. package/templates/vant/gitignore +34 -0
  23. package/templates/vant/package.json +3 -3
  24. package/templates/default/src/components/Navbar/Navbar.ts +0 -3
  25. package/templates/default/src/components/Navbar/Navbar.wxml +0 -1
  26. package/templates/tdesign/src/components/Navbar/Navbar.ts +0 -3
  27. package/templates/tdesign/src/components/Navbar/Navbar.wxml +0 -0
  28. /package/templates/default/src/components/{Navbar/Navbar.scss → HelloWorld/HelloWorld.scss} +0 -0
  29. /package/templates/tdesign/src/components/{Navbar/Navbar.scss → HelloWorld/HelloWorld.scss} +0 -0
package/dist/index.js CHANGED
@@ -1,9 +1,8 @@
1
1
  // src/index.ts
2
2
  import process2 from "process";
3
- import { fileURLToPath } from "url";
3
+
4
+ // src/configFiles.ts
4
5
  import logger from "@weapp-core/logger";
5
- import { defu, get, set } from "@weapp-core/shared";
6
- import fs from "fs-extra";
7
6
 
8
7
  // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
9
8
  var _lazyMatch = () => {
@@ -423,119 +422,35 @@ var mix = (del = delimiter) => {
423
422
  var posix = /* @__PURE__ */ mix(":");
424
423
  var win32 = /* @__PURE__ */ mix(";");
425
424
 
426
- // ../../packages/weapp-vite/package.json
427
- var version = "5.1.8";
428
-
429
425
  // src/context.ts
430
426
  function createContext() {
431
427
  return {
432
- projectConfig: {
433
- name: "",
434
- path: "",
435
- value: {}
436
- },
437
- packageJson: {
438
- name: "",
439
- path: "",
440
- value: {}
441
- },
442
- viteConfig: {
443
- name: "",
444
- path: "",
445
- value: ""
446
- },
447
- tsconfig: {
448
- name: "",
449
- path: "",
450
- value: {}
451
- },
452
- tsconfigNode: {
453
- name: "",
454
- path: "",
455
- value: {}
456
- },
457
- dts: {
458
- name: "",
459
- path: "",
460
- value: ""
461
- }
428
+ projectConfig: createDocument(),
429
+ packageJson: createDocument(),
430
+ viteConfig: createDocument(),
431
+ tsconfig: createDocument(),
432
+ tsconfigNode: createDocument(),
433
+ dts: createDocument()
462
434
  };
463
435
  }
464
-
465
- // src/enums.ts
466
- var TemplateName = /* @__PURE__ */ ((TemplateName2) => {
467
- TemplateName2["default"] = "default";
468
- TemplateName2["tailwindcss"] = "tailwindcss";
469
- TemplateName2["vant"] = "vant";
470
- TemplateName2["tdesign"] = "tdesign";
471
- return TemplateName2;
472
- })(TemplateName || {});
473
-
474
- // src/gitignore.ts
475
- function getDefaultGitignore() {
476
- return `# dependencies
477
- node_modules
478
- .pnp
479
- .pnp.js
480
-
481
- # testing
482
- coverage
483
-
484
- # next.js
485
- .next/
486
- out/
487
- build
488
-
489
- # misc
490
- .DS_Store
491
- *.pem
492
-
493
- # debug
494
- npm-debug.log*
495
- yarn-debug.log*
496
- yarn-error.log*
497
- .pnpm-debug.log*
498
-
499
- # local env files
500
- .env.local
501
- .env.development.local
502
- .env.test.local
503
- .env.production.local
504
-
505
- # turbo
506
- .turbo
507
-
508
- dist
509
- dist-plugin
510
- vite.config.ts.timestamp-*.mjs`;
436
+ function createDocument() {
437
+ return {
438
+ name: "",
439
+ path: "",
440
+ value: null
441
+ };
511
442
  }
512
443
 
513
- // src/npm.ts
514
- import https from "https";
515
- function getLatestVersionFromNpm(packageName) {
516
- return new Promise((resolve2, reject) => {
517
- const url = `https://registry.npmjs.org/${packageName}/latest`;
518
- https.get(url, (res) => {
519
- let data = "";
520
- res.on("data", (chunk) => data += chunk);
521
- res.on("end", () => {
522
- try {
523
- const json = JSON.parse(data);
524
- resolve2(json.version);
525
- } catch (err) {
526
- reject(err);
527
- }
528
- });
529
- }).on("error", reject);
530
- });
531
- }
532
- async function latestVersion(packageName, prefix = "^") {
533
- let version2 = "latest";
534
- try {
535
- version2 = `${prefix}${await getLatestVersionFromNpm(packageName)}`;
536
- } catch {
537
- }
538
- return version2;
444
+ // src/state.ts
445
+ var ctx = createContext();
446
+ function resetContext() {
447
+ const next = createContext();
448
+ Object.assign(ctx.projectConfig, next.projectConfig);
449
+ Object.assign(ctx.packageJson, next.packageJson);
450
+ Object.assign(ctx.viteConfig, next.viteConfig);
451
+ Object.assign(ctx.tsconfig, next.tsconfig);
452
+ Object.assign(ctx.tsconfigNode, next.tsconfigNode);
453
+ Object.assign(ctx.dts, next.dts);
539
454
  }
540
455
 
541
456
  // src/tsconfigJson.ts
@@ -608,6 +523,69 @@ function getDefaultTsDts() {
608
523
  `;
609
524
  }
610
525
 
526
+ // src/utils/fs.ts
527
+ import fs from "fs-extra";
528
+ async function readJsonIfExists(filepath) {
529
+ try {
530
+ if (!await fs.pathExists(filepath)) {
531
+ return null;
532
+ }
533
+ return await fs.readJSON(filepath);
534
+ } catch (error) {
535
+ throw new FsReadError(filepath, error);
536
+ }
537
+ }
538
+ async function readFileIfExists(filepath) {
539
+ try {
540
+ if (!await fs.pathExists(filepath)) {
541
+ return null;
542
+ }
543
+ return await fs.readFile(filepath, "utf8");
544
+ } catch (error) {
545
+ throw new FsReadError(filepath, error);
546
+ }
547
+ }
548
+ async function writeJsonFile(filepath, data, spaces = 2) {
549
+ try {
550
+ await fs.outputJSON(filepath, data, {
551
+ spaces
552
+ });
553
+ } catch (error) {
554
+ throw new FsWriteError(filepath, error);
555
+ }
556
+ }
557
+ async function writeFile(filepath, contents) {
558
+ try {
559
+ await fs.outputFile(filepath, contents, "utf8");
560
+ } catch (error) {
561
+ throw new FsWriteError(filepath, error);
562
+ }
563
+ }
564
+ var FsReadError = class extends Error {
565
+ constructor(filepath, cause) {
566
+ super(`Failed to read ${filepath}`);
567
+ this.filepath = filepath;
568
+ this.cause = cause;
569
+ this.name = "FsReadError";
570
+ }
571
+ };
572
+ var FsWriteError = class extends Error {
573
+ constructor(filepath, cause) {
574
+ super(`Failed to write ${filepath}`);
575
+ this.filepath = filepath;
576
+ this.cause = cause;
577
+ this.name = "FsWriteError";
578
+ }
579
+ };
580
+
581
+ // src/utils/path.ts
582
+ function resolveOutputPath(root, dest, fallback) {
583
+ if (!dest) {
584
+ return fallback;
585
+ }
586
+ return posix.isAbsolute(dest) ? dest : posix.resolve(root, dest);
587
+ }
588
+
611
589
  // src/viteConfig.ts
612
590
  function getDefaultViteConfig() {
613
591
  return `import { defineConfig } from 'weapp-vite/config'
@@ -620,104 +598,277 @@ export default defineConfig({
620
598
  `;
621
599
  }
622
600
 
623
- // src/index.ts
624
- var __dirname2 = posix.dirname(fileURLToPath(import.meta.url));
625
- var ctx = createContext();
626
- async function createOrUpdateProjectConfig(options) {
627
- const { root, dest, cb, write, filename } = defu(
628
- options,
629
- {
630
- write: true,
631
- filename: "project.config.json"
632
- }
633
- );
634
- const projectConfigFilename = ctx.projectConfig.name = filename;
635
- const projectConfigPath = ctx.projectConfig.path = posix.resolve(root, projectConfigFilename);
636
- if (await fs.exists(projectConfigPath)) {
637
- try {
638
- const projectConfig = await fs.readJSON(projectConfigPath);
639
- set(projectConfig, "miniprogramRoot", "dist/");
640
- set(projectConfig, "srcMiniprogramRoot", "dist/");
641
- set(projectConfig, "setting.packNpmManually", true);
642
- const compileType = get(projectConfig, "compileType");
643
- if (compileType === "plugin") {
644
- set(projectConfig, "pluginRoot", "dist-plugin");
601
+ // src/configFiles.ts
602
+ async function initViteConfigFile(options) {
603
+ const { root, dest, write = true } = options;
604
+ const packageType = ctx.packageJson.value?.type ?? "module";
605
+ const targetFilename = ctx.viteConfig.name = packageType === "module" ? "vite.config.ts" : "vite.config.mts";
606
+ const viteConfigFilePath = ctx.viteConfig.path = posix.resolve(root, targetFilename);
607
+ const outputPath = resolveOutputPath(root, dest, viteConfigFilePath);
608
+ const code = getDefaultViteConfig();
609
+ ctx.viteConfig.value = code;
610
+ if (write) {
611
+ await writeFile(outputPath, code);
612
+ logger.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
613
+ }
614
+ return code;
615
+ }
616
+ async function initTsDtsFile(options) {
617
+ const { root, dest, write = true } = options;
618
+ const targetFilename = ctx.dts.name = "vite-env.d.ts";
619
+ const viteDtsFilePath = ctx.dts.path = posix.resolve(root, targetFilename);
620
+ const outputPath = resolveOutputPath(root, dest, viteDtsFilePath);
621
+ const code = getDefaultTsDts();
622
+ ctx.dts.value = code;
623
+ if (write) {
624
+ await writeFile(outputPath, code);
625
+ logger.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
626
+ }
627
+ return code;
628
+ }
629
+ async function initTsJsonFiles(options) {
630
+ const { root, dest, write = true } = options;
631
+ const tsJsonFilename = ctx.tsconfig.name = "tsconfig.json";
632
+ const tsJsonFilePath = ctx.tsconfig.path = posix.resolve(root, tsJsonFilename);
633
+ const tsNodeJsonFilename = ctx.tsconfigNode.name = "tsconfig.node.json";
634
+ const tsNodeJsonFilePath = ctx.tsconfigNode.path = posix.resolve(root, tsNodeJsonFilename);
635
+ const tsconfig = getDefaultTsconfigJson();
636
+ const includeFiles = ctx.viteConfig.name ? [ctx.viteConfig.name] : [];
637
+ const tsconfigNode = getDefaultTsconfigNodeJson(includeFiles);
638
+ ctx.tsconfig.value = tsconfig;
639
+ ctx.tsconfigNode.value = tsconfigNode;
640
+ if (write) {
641
+ const tsconfigOutputPath = resolveOutputPath(root, dest, tsJsonFilePath);
642
+ const tsconfigNodeOutputPath = tsNodeJsonFilePath;
643
+ await writeJsonFile(tsconfigOutputPath, tsconfig);
644
+ await writeJsonFile(tsconfigNodeOutputPath, tsconfigNode);
645
+ logger.log(`\u2728 \u5199\u5165 ${posix.relative(root, tsconfigOutputPath)} \u4E0E ${posix.relative(root, tsconfigNodeOutputPath)} \u6210\u529F!`);
646
+ }
647
+ return {
648
+ tsconfig,
649
+ tsconfigNode
650
+ };
651
+ }
652
+
653
+ // src/createProject.ts
654
+ import { fileURLToPath } from "url";
655
+ import logger3 from "@weapp-core/logger";
656
+ import fs2 from "fs-extra";
657
+
658
+ // ../../packages/weapp-vite/package.json
659
+ var version = "5.2.0";
660
+
661
+ // src/enums.ts
662
+ var TemplateName = /* @__PURE__ */ ((TemplateName2) => {
663
+ TemplateName2["default"] = "default";
664
+ TemplateName2["tailwindcss"] = "tailwindcss";
665
+ TemplateName2["vant"] = "vant";
666
+ TemplateName2["tdesign"] = "tdesign";
667
+ return TemplateName2;
668
+ })(TemplateName || {});
669
+
670
+ // src/npm.ts
671
+ import https from "https";
672
+ function getLatestVersionFromNpm(packageName) {
673
+ return new Promise((resolve2, reject) => {
674
+ const url = `https://registry.npmjs.org/${packageName}/latest`;
675
+ https.get(url, (res) => {
676
+ if (!res || res.statusCode && res.statusCode >= 400) {
677
+ res?.resume();
678
+ reject(new Error(`Request to ${url} failed with status ${res?.statusCode ?? "unknown"}`));
679
+ return;
645
680
  }
646
- cb?.(
647
- (...args) => {
648
- set(projectConfig, ...args);
649
- }
650
- );
651
- if (Array.isArray(get(projectConfig, "setting.packNpmRelationList"))) {
652
- const x = projectConfig.setting.packNpmRelationList.find(
653
- (x2) => x2.packageJsonPath === "./package.json" && x2.miniprogramNpmDistDir === "./dist"
654
- );
655
- if (!x) {
656
- projectConfig.setting.packNpmRelationList.push({
657
- packageJsonPath: "./package.json",
658
- miniprogramNpmDistDir: "./dist"
659
- });
660
- }
661
- } else {
662
- set(projectConfig, "setting.packNpmRelationList", [
663
- {
664
- packageJsonPath: "./package.json",
665
- miniprogramNpmDistDir: "./dist"
681
+ let data = "";
682
+ res.setEncoding("utf8");
683
+ res.on("data", (chunk) => data += chunk);
684
+ res.on("end", () => {
685
+ try {
686
+ const json = JSON.parse(data);
687
+ if (!json.version || typeof json.version !== "string") {
688
+ reject(new Error(`Unexpected response when fetching ${packageName}: missing version`));
689
+ return;
666
690
  }
667
- ]);
668
- }
669
- if (write) {
670
- await fs.outputJSON(dest ?? projectConfigPath, projectConfig, {
671
- spaces: 2
672
- });
673
- logger.log(`\u2728 \u8BBE\u7F6E ${projectConfigFilename} \u914D\u7F6E\u6587\u4EF6\u6210\u529F!`);
691
+ resolve2(json.version);
692
+ } catch (err) {
693
+ reject(err);
694
+ }
695
+ });
696
+ res.on("error", reject);
697
+ }).on("error", reject);
698
+ });
699
+ }
700
+ async function latestVersion(packageName, prefix = "^") {
701
+ try {
702
+ const resolved = await getLatestVersionFromNpm(packageName);
703
+ return resolved ? `${prefix}${resolved}` : null;
704
+ } catch {
705
+ return null;
706
+ }
707
+ }
708
+
709
+ // src/updateGitignore.ts
710
+ import logger2 from "@weapp-core/logger";
711
+
712
+ // src/gitignore.ts
713
+ var DEFAULT_GITIGNORE = `# dependencies
714
+ node_modules
715
+ .pnp
716
+ .pnp.js
717
+
718
+ # testing
719
+ coverage
720
+
721
+ # next.js
722
+ .next/
723
+ out/
724
+ build
725
+
726
+ # misc
727
+ .DS_Store
728
+ *.pem
729
+
730
+ # debug
731
+ npm-debug.log*
732
+ yarn-debug.log*
733
+ yarn-error.log*
734
+ .pnpm-debug.log*
735
+
736
+ # local env files
737
+ .env.local
738
+ .env.development.local
739
+ .env.test.local
740
+ .env.production.local
741
+
742
+ # turbo
743
+ .turbo
744
+
745
+ dist
746
+ dist-plugin
747
+ vite.config.ts.timestamp-*.mjs`;
748
+ function mergeGitignore(existing) {
749
+ const normalizedExisting = normalizeLineEndings(existing ?? "");
750
+ const existingLines = normalizedExisting.length ? normalizedExisting.split("\n") : [];
751
+ const merged = [...existingLines];
752
+ while (merged.length > 0 && merged[merged.length - 1] === "") {
753
+ merged.pop();
754
+ }
755
+ const seen = new Set(merged);
756
+ let appendedNonBlank = false;
757
+ for (const line of DEFAULT_GITIGNORE.split("\n")) {
758
+ const isBlank = line.length === 0;
759
+ if (isBlank) {
760
+ if (merged.length === 0 || merged[merged.length - 1] === "") {
761
+ continue;
674
762
  }
675
- ctx.projectConfig.value = projectConfig;
676
- return projectConfig;
677
- } catch {
678
- logger.warn(`\u2728 \u8BBE\u7F6E ${projectConfigFilename} \u914D\u7F6E\u6587\u4EF6\u5931\u8D25!`);
763
+ merged.push("");
764
+ continue;
679
765
  }
680
- } else {
681
- logger.info(`\u2728 \u6CA1\u6709\u627E\u5230 ${projectConfigFilename} \u6587\u4EF6! \u6B63\u5728\u4E3A\u4F60\u521B\u5EFA\u4E2D...`);
682
- await fs.outputJson(projectConfigPath, {
683
- compileType: "miniprogram",
684
- libVersion: "trial",
685
- packOptions: {
686
- ignore: [],
687
- include: []
688
- },
689
- setting: {
690
- coverView: true,
691
- es6: true,
692
- postcss: true,
693
- minified: true,
694
- enhance: true,
695
- showShadowRootInWxmlPanel: true,
696
- packNpmRelationList: [
697
- {
698
- packageJsonPath: "./package.json",
699
- miniprogramNpmDistDir: "./dist"
700
- }
701
- ],
702
- babelSetting: {
703
- ignore: [],
704
- disablePlugins: [],
705
- outputPath: ""
706
- },
707
- packNpmManually: true
708
- },
709
- condition: {},
710
- editorSetting: {
711
- tabIndent: "auto",
712
- tabSize: 2
713
- },
714
- appid: "",
715
- miniprogramRoot: "dist/",
716
- srcMiniprogramRoot: "dist/"
717
- }, { spaces: 2 });
718
- logger.success(`\u2728 \u521B\u5EFA\u5B8C\u6210! \u522B\u5FD8\u4E86\u5728\u91CC\u9762\u8BBE\u7F6E\u4F60\u7684 \`appid\` `);
766
+ if (seen.has(line)) {
767
+ continue;
768
+ }
769
+ if (!appendedNonBlank && merged.length > 0 && merged[merged.length - 1] !== "") {
770
+ merged.push("");
771
+ }
772
+ merged.push(line);
773
+ seen.add(line);
774
+ appendedNonBlank = true;
775
+ }
776
+ return ensureTrailingNewline(trimTrailingBlankLines(merged).join("\n"));
777
+ }
778
+ function normalizeLineEndings(value) {
779
+ return value.replace(/\r\n/g, "\n");
780
+ }
781
+ function trimTrailingBlankLines(lines) {
782
+ let end = lines.length;
783
+ while (end > 0 && lines[end - 1] === "") {
784
+ end -= 1;
785
+ }
786
+ return lines.slice(0, end);
787
+ }
788
+ function ensureTrailingNewline(value) {
789
+ return value.endsWith("\n") ? value : `${value}
790
+ `;
791
+ }
792
+
793
+ // src/updateGitignore.ts
794
+ async function updateGitIgnore(options) {
795
+ const { root, dest, write = true } = options;
796
+ const gitignorePath = posix.resolve(root, ".gitignore");
797
+ const outputPath = resolveOutputPath(root, dest, gitignorePath);
798
+ const existing = await readFileIfExists(outputPath);
799
+ const merged = mergeGitignore(existing);
800
+ if (write && merged !== (existing ?? "")) {
801
+ await writeFile(outputPath, merged);
802
+ logger2.log(`\u2728 \u66F4\u65B0 ${posix.relative(root, outputPath)} \u6210\u529F!`);
719
803
  }
804
+ return merged;
720
805
  }
806
+
807
+ // src/createProject.ts
808
+ var moduleDir = posix.dirname(fileURLToPath(import.meta.url));
809
+ async function createProject(targetDir = "", templateName = "default" /* default */) {
810
+ const targetTemplateDir = posix.resolve(moduleDir, "../templates", templateName);
811
+ if (!await fs2.pathExists(targetTemplateDir)) {
812
+ logger3.warn(`\u6CA1\u6709\u627E\u5230 ${templateName} \u6A21\u677F!`);
813
+ return;
814
+ }
815
+ await fs2.copy(targetTemplateDir, targetDir);
816
+ const templatePackagePath = posix.resolve(targetTemplateDir, "package.json");
817
+ const packageJsonPath = posix.resolve(targetDir, "package.json");
818
+ await ensureDotGitignore(targetDir);
819
+ const pkgJson = await fs2.pathExists(templatePackagePath) ? await fs2.readJSON(templatePackagePath) : createEmptyPackageJson();
820
+ if (!pkgJson.devDependencies) {
821
+ pkgJson.devDependencies = {};
822
+ }
823
+ if (pkgJson.devDependencies["weapp-vite"]) {
824
+ pkgJson.devDependencies["weapp-vite"] = version;
825
+ }
826
+ await upsertTailwindcssVersion(pkgJson);
827
+ await writeJsonFile(packageJsonPath, pkgJson);
828
+ await updateGitIgnore({ root: targetDir, write: true });
829
+ logger3.log("\u2728 \u521B\u5EFA\u6A21\u677F\u6210\u529F!");
830
+ }
831
+ async function upsertTailwindcssVersion(pkgJson) {
832
+ if (!pkgJson.devDependencies) {
833
+ return;
834
+ }
835
+ const resolved = await latestVersion("weapp-tailwindcss");
836
+ if (resolved) {
837
+ pkgJson.devDependencies["weapp-tailwindcss"] = resolved;
838
+ } else if (!pkgJson.devDependencies["weapp-tailwindcss"]) {
839
+ pkgJson.devDependencies["weapp-tailwindcss"] = "^4.3.3";
840
+ }
841
+ }
842
+ function createEmptyPackageJson() {
843
+ return {
844
+ name: "weapp-vite-app",
845
+ homepage: "https://vite.icebreaker.top/",
846
+ type: "module",
847
+ scripts: {},
848
+ devDependencies: {}
849
+ };
850
+ }
851
+ async function ensureDotGitignore(root) {
852
+ const gitignorePath = posix.resolve(root, "gitignore");
853
+ const dotGitignorePath = posix.resolve(root, ".gitignore");
854
+ if (!await fs2.pathExists(gitignorePath)) {
855
+ return;
856
+ }
857
+ if (await fs2.pathExists(dotGitignorePath)) {
858
+ await fs2.remove(gitignorePath);
859
+ return;
860
+ }
861
+ await fs2.move(gitignorePath, dotGitignorePath);
862
+ }
863
+
864
+ // src/packageJson.ts
865
+ import logger4 from "@weapp-core/logger";
866
+ import { defu, get, set } from "@weapp-core/shared";
867
+ var FALLBACK_DEP_VERSIONS = {
868
+ "miniprogram-api-typings": "^4.1.0",
869
+ "typescript": "^5.9.2",
870
+ "weapp-tailwindcss": "^4.3.3"
871
+ };
721
872
  async function createOrUpdatePackageJson(options) {
722
873
  const { root, dest, command, cb, write, filename } = defu(options, {
723
874
  write: true,
@@ -726,110 +877,168 @@ async function createOrUpdatePackageJson(options) {
726
877
  });
727
878
  const packageJsonFilename = ctx.packageJson.name = filename;
728
879
  const packageJsonPath = ctx.packageJson.path = posix.resolve(root, packageJsonFilename);
729
- let packageJson;
730
- if (await fs.exists(packageJsonPath)) {
731
- packageJson = await fs.readJSON(packageJsonPath);
732
- } else {
733
- packageJson = {
734
- name: "weapp-vite-app",
735
- homepage: "https://vite.icebreaker.top/",
736
- type: "module"
737
- };
738
- }
880
+ const outputPath = resolveOutputPath(root, dest, packageJsonPath);
739
881
  try {
882
+ let packageJson = await readJsonIfExists(packageJsonPath);
883
+ if (!packageJson) {
884
+ packageJson = createDefaultPackageJson();
885
+ logger4.info(`\u2728 \u6CA1\u6709\u627E\u5230 ${packageJsonFilename} \u6587\u4EF6\uFF0C\u6B63\u5728\u521B\u5EFA\u9ED8\u8BA4 package.json ...`);
886
+ }
740
887
  set(packageJson, "scripts.dev", `${command} dev`);
741
888
  set(packageJson, "scripts.dev:open", `${command} dev -o`);
742
889
  set(packageJson, "scripts.build", `${command} build`);
743
890
  if (command === "weapp-vite") {
744
891
  set(packageJson, "scripts.open", `${command} open`);
745
892
  set(packageJson, "scripts.g", `${command} generate`);
746
- set(packageJson, "devDependencies.miniprogram-api-typings", await latestVersion("miniprogram-api-typings"));
747
- set(packageJson, "devDependencies.weapp-vite", await latestVersion("weapp-vite"));
748
- set(packageJson, "devDependencies.typescript", await latestVersion("typescript"));
893
+ set(packageJson, "devDependencies.weapp-vite", `^${version}`);
894
+ await Promise.all([
895
+ upsertDependencyVersion(packageJson, "devDependencies.miniprogram-api-typings", "miniprogram-api-typings", { skipNetwork: !write }),
896
+ upsertDependencyVersion(packageJson, "devDependencies.typescript", "typescript", { skipNetwork: !write })
897
+ ]);
749
898
  }
750
899
  cb?.(
751
900
  (...args) => {
752
901
  set(packageJson, ...args);
753
902
  }
754
903
  );
904
+ ctx.packageJson.value = packageJson;
755
905
  if (write) {
756
- await fs.outputJSON(dest ?? packageJsonPath, packageJson, {
757
- spaces: 2
758
- });
759
- logger.log(`\u2728 \u8BBE\u7F6E ${packageJsonFilename} \u914D\u7F6E\u6587\u4EF6\u6210\u529F!`);
906
+ await writeJsonFile(outputPath, packageJson);
907
+ logger4.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
760
908
  }
761
- ctx.packageJson.value = packageJson;
762
909
  return packageJson;
763
- } catch {
910
+ } catch (error) {
911
+ logger4.error(`\u26A0\uFE0F \u8BBE\u7F6E ${packageJsonFilename} \u914D\u7F6E\u6587\u4EF6\u5931\u8D25`, error);
912
+ throw error;
764
913
  }
765
914
  }
766
- async function initViteConfigFile(options) {
767
- const { root, write = true } = options;
768
- const type = get(ctx.packageJson.value, "type");
769
- const targetFilename = ctx.viteConfig.name = type === "module" ? "vite.config.ts" : "vite.config.mts";
770
- const viteConfigFilePath = ctx.viteConfig.path = posix.resolve(root, targetFilename);
771
- const viteConfigFileCode = ctx.viteConfig.value = getDefaultViteConfig();
772
- if (write) {
773
- await fs.outputFile(viteConfigFilePath, viteConfigFileCode, "utf8");
774
- logger.log(`\u2728 \u8BBE\u7F6E ${targetFilename} \u914D\u7F6E\u6587\u4EF6\u6210\u529F!`);
915
+ async function upsertDependencyVersion(packageJson, keyPath, packageName, options = {}) {
916
+ const currentValue = get(packageJson, keyPath);
917
+ const resolved = options.skipNetwork ? null : await latestVersion(packageName);
918
+ if (resolved) {
919
+ set(packageJson, keyPath, resolved);
920
+ return;
775
921
  }
776
- return viteConfigFileCode;
777
- }
778
- async function initTsDtsFile(options) {
779
- const { root, write = true } = options;
780
- const targetFilename = "vite-env.d.ts";
781
- const viteDtsFilePath = posix.resolve(root, targetFilename);
782
- const code = getDefaultTsDts();
783
- if (write) {
784
- await fs.outputFile(viteDtsFilePath, code, "utf8");
785
- logger.log(`\u2728 \u8BBE\u7F6E ${targetFilename} \u914D\u7F6E\u6587\u4EF6\u6210\u529F!`);
922
+ if (currentValue === void 0) {
923
+ const fallback = FALLBACK_DEP_VERSIONS[packageName] ?? "latest";
924
+ set(packageJson, keyPath, fallback);
786
925
  }
787
- return code;
788
926
  }
789
- async function initTsJsonFiles(options) {
790
- const { root, write = true } = options;
791
- const tsJsonFilename = ctx.tsconfig.name = "tsconfig.json";
792
- const tsJsonFilePath = ctx.tsconfig.path = posix.resolve(root, tsJsonFilename);
793
- const tsNodeJsonFilename = ctx.tsconfigNode.name = "tsconfig.node.json";
794
- const tsNodeJsonFilePath = ctx.tsconfigNode.path = posix.resolve(root, tsNodeJsonFilename);
795
- if (write) {
796
- const tsJsonValue = getDefaultTsconfigJson();
797
- if (write) {
798
- await fs.outputJSON(
799
- tsJsonFilePath,
800
- tsJsonValue,
801
- {
802
- encoding: "utf8",
803
- spaces: 2
804
- }
805
- );
806
- logger.log(`\u2728 \u8BBE\u7F6E ${tsJsonFilename} \u914D\u7F6E\u6587\u4EF6\u6210\u529F!`);
927
+ function createDefaultPackageJson() {
928
+ return {
929
+ name: "weapp-vite-app",
930
+ homepage: "https://vite.icebreaker.top/",
931
+ type: "module",
932
+ scripts: {},
933
+ devDependencies: {}
934
+ };
935
+ }
936
+
937
+ // src/projectConfig.ts
938
+ import logger5 from "@weapp-core/logger";
939
+ import { defu as defu2, get as get2, set as set2 } from "@weapp-core/shared";
940
+ async function createOrUpdateProjectConfig(options) {
941
+ const { root, dest, cb, write, filename } = defu2(
942
+ options,
943
+ {
944
+ write: true,
945
+ filename: "project.config.json"
807
946
  }
808
- ctx.tsconfig.value = tsJsonValue;
809
- const tsJsonNodeValue = getDefaultTsconfigNodeJson([
810
- ctx.viteConfig.name
811
- ]);
947
+ );
948
+ const projectConfigFilename = ctx.projectConfig.name = filename;
949
+ const projectConfigPath = ctx.projectConfig.path = posix.resolve(root, projectConfigFilename);
950
+ const outputPath = resolveOutputPath(root, dest, projectConfigPath);
951
+ try {
952
+ let projectConfig = await readJsonIfExists(projectConfigPath);
953
+ if (projectConfig) {
954
+ applyProjectConfigDefaults(projectConfig);
955
+ } else {
956
+ projectConfig = createDefaultProjectConfig();
957
+ logger5.info(`\u2728 \u6CA1\u6709\u627E\u5230 ${projectConfigFilename} \u6587\u4EF6\uFF0C\u6B63\u5728\u4F7F\u7528\u9ED8\u8BA4\u6A21\u677F\u521B\u5EFA...`);
958
+ }
959
+ cb?.(
960
+ (...args) => {
961
+ set2(projectConfig, ...args);
962
+ }
963
+ );
964
+ ensurePackNpmRelationList(projectConfig);
965
+ ctx.projectConfig.value = projectConfig;
812
966
  if (write) {
813
- await fs.outputJSON(tsNodeJsonFilePath, tsJsonNodeValue, {
814
- encoding: "utf8",
815
- spaces: 2
816
- });
817
- logger.log(`\u2728 \u8BBE\u7F6E ${tsNodeJsonFilename} \u914D\u7F6E\u6587\u4EF6\u6210\u529F!`);
967
+ await writeJsonFile(outputPath, projectConfig);
968
+ logger5.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
818
969
  }
819
- ctx.tsconfigNode.value = tsJsonNodeValue;
970
+ return projectConfig;
971
+ } catch (error) {
972
+ logger5.error(`\u26A0\uFE0F \u8BBE\u7F6E ${projectConfigFilename} \u914D\u7F6E\u6587\u4EF6\u5931\u8D25`, error);
973
+ throw error;
820
974
  }
821
975
  }
822
- async function updateGitIgnore(options) {
823
- const { root, write = true } = options;
824
- const filepath = posix.resolve(root, ".gitignore");
825
- const data = getDefaultGitignore();
826
- if (write) {
827
- await fs.outputFile(filepath, data, {
828
- encoding: "utf8"
829
- });
976
+ function applyProjectConfigDefaults(projectConfig) {
977
+ set2(projectConfig, "miniprogramRoot", "dist/");
978
+ set2(projectConfig, "srcMiniprogramRoot", "dist/");
979
+ set2(projectConfig, "setting.packNpmManually", true);
980
+ const compileType = get2(projectConfig, "compileType");
981
+ if (compileType === "plugin") {
982
+ set2(projectConfig, "pluginRoot", "dist-plugin");
983
+ }
984
+ }
985
+ function ensurePackNpmRelationList(projectConfig) {
986
+ const relations = get2(projectConfig, "setting.packNpmRelationList");
987
+ const defaultRelation = {
988
+ packageJsonPath: "./package.json",
989
+ miniprogramNpmDistDir: "./dist"
990
+ };
991
+ if (Array.isArray(relations)) {
992
+ const exists = relations.some(
993
+ (relation) => relation.packageJsonPath === defaultRelation.packageJsonPath && relation.miniprogramNpmDistDir === defaultRelation.miniprogramNpmDistDir
994
+ );
995
+ if (!exists) {
996
+ relations.push(defaultRelation);
997
+ }
998
+ } else {
999
+ set2(projectConfig, "setting.packNpmRelationList", [defaultRelation]);
830
1000
  }
831
- return data;
832
1001
  }
1002
+ function createDefaultProjectConfig() {
1003
+ return {
1004
+ compileType: "miniprogram",
1005
+ libVersion: "trial",
1006
+ packOptions: {
1007
+ ignore: [],
1008
+ include: []
1009
+ },
1010
+ setting: {
1011
+ coverView: true,
1012
+ es6: true,
1013
+ postcss: true,
1014
+ minified: true,
1015
+ enhance: true,
1016
+ showShadowRootInWxmlPanel: true,
1017
+ packNpmRelationList: [
1018
+ {
1019
+ packageJsonPath: "./package.json",
1020
+ miniprogramNpmDistDir: "./dist"
1021
+ }
1022
+ ],
1023
+ babelSetting: {
1024
+ ignore: [],
1025
+ disablePlugins: [],
1026
+ outputPath: ""
1027
+ },
1028
+ packNpmManually: true
1029
+ },
1030
+ condition: {},
1031
+ editorSetting: {
1032
+ tabIndent: "auto",
1033
+ tabSize: 2
1034
+ },
1035
+ appid: "",
1036
+ miniprogramRoot: "dist/",
1037
+ srcMiniprogramRoot: "dist/"
1038
+ };
1039
+ }
1040
+
1041
+ // src/index.ts
833
1042
  async function initConfig(options) {
834
1043
  const { root = process2.cwd(), command } = options;
835
1044
  await createOrUpdateProjectConfig({ root });
@@ -842,29 +1051,6 @@ async function initConfig(options) {
842
1051
  }
843
1052
  return ctx;
844
1053
  }
845
- async function createProject(targetDir = "", templateName = "default" /* default */) {
846
- const targetTemplateDir = posix.resolve(import.meta.dirname, "../templates", templateName);
847
- if (await fs.exists(targetTemplateDir)) {
848
- await fs.copy(targetTemplateDir, targetDir);
849
- const pkgJsonPath = posix.resolve(targetTemplateDir, "package.json");
850
- const pkgJson = await fs.readJson(pkgJsonPath);
851
- if (pkgJson.devDependencies) {
852
- if (pkgJson.devDependencies["weapp-vite"]) {
853
- pkgJson.devDependencies["weapp-vite"] = version;
854
- }
855
- if (pkgJson.devDependencies["weapp-tailwindcss"]) {
856
- pkgJson.devDependencies["weapp-tailwindcss"] = await latestVersion("weapp-tailwindcss");
857
- }
858
- }
859
- await fs.writeJson(posix.resolve(targetDir, "package.json"), pkgJson, { spaces: 2 });
860
- if (!await fs.exists(posix.resolve(targetDir, ".gitignore"))) {
861
- await updateGitIgnore({ root: targetDir, write: true });
862
- }
863
- logger.log(`\u2728 \u521B\u5EFA\u6A21\u677F\u6210\u529F!`);
864
- } else {
865
- logger.warn(`\u6CA1\u6709\u627E\u5230 ${templateName} \u6A21\u677F!`);
866
- }
867
- }
868
1054
  export {
869
1055
  TemplateName,
870
1056
  createOrUpdatePackageJson,
@@ -873,5 +1059,6 @@ export {
873
1059
  initConfig,
874
1060
  initTsDtsFile,
875
1061
  initTsJsonFiles,
876
- initViteConfigFile
1062
+ initViteConfigFile,
1063
+ resetContext
877
1064
  };