@makoojs/cli 0.4.1 → 0.5.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.
Files changed (61) hide show
  1. package/README.CN.md +48 -387
  2. package/README.md +48 -387
  3. package/dist/bin.js +594 -1141
  4. package/dist/cli/commands/build.d.ts +2 -0
  5. package/dist/cli/commands/dev/DevTerminal.d.ts +51 -0
  6. package/dist/cli/commands/dev/dev.d.ts +2 -0
  7. package/dist/cli/commands/preview.d.ts +2 -0
  8. package/dist/cli/injections/renderInjections.d.ts +2 -0
  9. package/dist/{shared → cli}/terminalColor.d.ts +2 -0
  10. package/dist/cli/version.d.ts +1 -0
  11. package/dist/config/defaults.d.ts +3 -24
  12. package/dist/config/errors.d.ts +3 -0
  13. package/dist/config/resolve.d.ts +6 -18
  14. package/dist/config/types.d.ts +8 -106
  15. package/dist/config/validation.d.ts +4 -7
  16. package/dist/index.cjs +89 -38
  17. package/dist/index.d.ts +3 -3
  18. package/dist/index.js +1008 -3255
  19. package/dist/session/DevSession.d.ts +14 -0
  20. package/dist/session/types.d.ts +47 -0
  21. package/dist/vite/makoo.d.ts +3 -0
  22. package/dist/vite/makooDev.d.ts +7 -0
  23. package/package.json +8 -13
  24. package/dist/command/_util.d.ts +0 -8
  25. package/dist/command/add.d.ts +0 -1
  26. package/dist/command/build.d.ts +0 -1
  27. package/dist/command/dev.d.ts +0 -1
  28. package/dist/command/inspect.d.ts +0 -35
  29. package/dist/config/config.d.ts +0 -3
  30. package/dist/error/MakooCliError.d.ts +0 -58
  31. package/dist/generator/generator.d.ts +0 -3
  32. package/dist/generator/render/import/importAdapter.d.ts +0 -3
  33. package/dist/generator/render/import/importComp.d.ts +0 -3
  34. package/dist/generator/render/import/importMakooRuntime.d.ts +0 -1
  35. package/dist/generator/render/import/importManifest.d.ts +0 -3
  36. package/dist/generator/render/import/importRuntimeSetup.d.ts +0 -1
  37. package/dist/generator/render/init/initMakooRuntime.d.ts +0 -4
  38. package/dist/generator/render/init/registerComp.d.ts +0 -3
  39. package/dist/generator/render/init/registerListener.d.ts +0 -4
  40. package/dist/generator/render/run/renderMakooStart.d.ts +0 -1
  41. package/dist/generator/render/util/match.d.ts +0 -1
  42. package/dist/generator/render/util/value.d.ts +0 -1
  43. package/dist/generator/types.d.ts +0 -27
  44. package/dist/manifest/index.cjs +0 -1
  45. package/dist/manifest/index.d.ts +0 -2
  46. package/dist/manifest/index.js +0 -7
  47. package/dist/scanner/collectDependenics.d.ts +0 -2
  48. package/dist/scanner/load/loadManifes.d.ts +0 -3
  49. package/dist/scanner/load/loadMeta.d.ts +0 -2
  50. package/dist/scanner/manifestBinding.d.ts +0 -14
  51. package/dist/scanner/scanner.d.ts +0 -3
  52. package/dist/scanner/types.d.ts +0 -50
  53. package/dist/scanner/util.d.ts +0 -2
  54. package/dist/scanner/validation.d.ts +0 -190
  55. package/dist/vitePlugin/hmrController.d.ts +0 -6
  56. package/dist/vitePlugin/makoo.d.ts +0 -3
  57. package/dist/vitePlugin/makooMonkey.d.ts +0 -3
  58. package/dist/vitePlugin/types.d.ts +0 -18
  59. package/dist/vitePlugin/virtualModule.d.ts +0 -2
  60. package/dist/vitePlugin/watchList.d.ts +0 -5
  61. /package/dist/{command → cli}/bin.d.ts +0 -0
package/dist/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/command/bin.ts
4
- import { MakooError as MakooError2 } from "@makoojs/core";
3
+ // src/cli/bin.ts
4
+ import { MakooError } from "@makoojs/core";
5
5
 
6
6
  // ../../node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
7
7
  function toArr(any) {
@@ -619,201 +619,21 @@ var CAC = class extends EventTarget {
619
619
  };
620
620
  var cac = (name = "") => new CAC(name);
621
621
 
622
- // src/command/add.ts
623
- import { existsSync as existsSync2 } from "fs";
624
- import { mkdir, writeFile as writeFile2 } from "fs/promises";
625
- import { join as join2 } from "path";
626
-
627
- // src/config/defaults.ts
628
- import process2 from "process";
629
- var SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"];
630
- var ESM_IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]|\bexport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g;
631
- var CJS_IMPORT_RE = /\brequire\s*\(['"]([^'"]+)['"]\)/g;
632
- var REACT_EXTENSIONS = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
633
- var VUE_EXTENSIONS = /* @__PURE__ */ new Set([".vue"]);
634
- var DEFAULT_SOURCE_DIR = "injections";
635
- var DEFAULT_MANIFEST_FILE_NAME = "manifest";
636
- var DEFAULT_SOURCE_CONFIG = {
637
- dir: DEFAULT_SOURCE_DIR,
638
- // '*' matches any single path segment (bare directory name).
639
- // '**/*' would require a '/' and never match top-level folder names via picomatch.
640
- include: ["*"],
641
- exclude: [],
642
- manifest: DEFAULT_MANIFEST_FILE_NAME
643
- };
644
- var DEFAULT_INJECTION_DEFAULTS = {
645
- alive: false,
646
- scope: "local",
647
- timeout: 5e3,
648
- hooks: {}
649
- };
650
- var DEFAULT_MONKEY_SERVER_CONFIG = {
651
- open: process2.platform === "win32" || process2.platform === "darwin",
652
- prefix: "server:"
653
- };
654
-
655
- // src/error/MakooCliError.ts
656
- import { relative } from "path";
657
- import process3 from "process";
658
- import { ErrorCode, MakooError } from "@makoojs/core";
659
- var ModuleAlreadyExistsError = class extends MakooError {
660
- constructor(message, code = ErrorCode.CLI_MODULE_ALREADY_EXISTS, cause) {
661
- super(message, void 0, code, cause);
662
- this.name = "ModuleAlreadyExistsError";
663
- }
664
- };
665
- var LoadViteMakooConfigError = class extends MakooError {
666
- constructor(message, code, cause) {
667
- super(message, void 0, code, cause);
668
- this.name = "LoadViteMakooConfigError";
669
- }
670
- };
671
- var RuntimeSetupNotFoundError = class extends MakooError {
672
- constructor(file, code = ErrorCode.CLI_RUNTIME_SETUP_NOT_FOUND, cause) {
673
- super(
674
- `Runtime setup file not found at ${file}`,
675
- [{ path: "runtime.setup", message: file }],
676
- code,
677
- cause
678
- );
679
- this.name = "RuntimeSetupNotFoundError";
680
- }
681
- };
682
- var ManifestValidationError = class extends MakooError {
683
- constructor(file, zodIssues, code = ErrorCode.CLI_MANIFEST_VALIDATION_FAIL, cause) {
684
- const issues = zodIssues.map(toMakooIssue);
685
- const rel = relative(process3.cwd(), file);
686
- super(`Invalid manifest at ${rel}`, issues, code, cause);
687
- this.name = "ManifestValidationError";
688
- }
689
- };
690
- var UnknownFrameworkError = class extends MakooError {
691
- constructor(componentPath, code = ErrorCode.CLI_UNKNOWN_FRAMEWORK, cause) {
692
- super(
693
- `Cannot infer framework from "${componentPath}". Set "framework" explicitly ("Vue" or "React") in the module manifest.`,
694
- [{ path: "framework", message: `cannot infer from "${componentPath}"` }],
695
- code,
696
- cause
697
- );
698
- this.name = "UnknownFrameworkError";
699
- }
700
- };
701
- var ComponentNotFoundError = class extends MakooError {
702
- constructor(injectionName, code = ErrorCode.CLI_COMPONENT_NOT_FOUND, cause) {
703
- super(
704
- `Missing component path for injection "${injectionName}"`,
705
- [{ path: "component", message: "could not resolve component path" }],
706
- code,
707
- cause
708
- );
709
- this.name = "ComponentNotFoundError";
710
- }
711
- };
712
- var UnsupportedFrameworkGenerationError = class extends MakooError {
713
- constructor(ext, code = ErrorCode.CLI_UNSUPPORTED_FRAMEWORK, cause) {
714
- super(`Unsupported framework for template generation: ${ext}`, void 0, code, cause);
715
- this.name = "UnsupportedFrameworkError";
716
- }
717
- };
718
- var SourceDirNotFoundError = class extends MakooError {
719
- constructor(dir, code = ErrorCode.CLI_SOURCE_DIR_NOT_FOUND, cause) {
720
- super(`Source directory not found at ${dir}`, void 0, code, cause);
721
- this.name = "SourceDirNotFoundError";
722
- }
723
- };
724
- var ManifestNotFoundError = class extends MakooError {
725
- constructor(dir, code = ErrorCode.CLI_MANIFEST_NOT_FOUND, cause) {
726
- super(`No manifest found in source directory at ${dir}`, void 0, code, cause);
727
- this.name = "ManifestNotFoundError";
728
- }
729
- };
730
- var ManifestBindingNotFoundError = class extends MakooError {
731
- constructor(kind, id, code = ErrorCode.CLI_MANIFEST_BINDING_NOT_FOUND, cause) {
732
- const path5 = kind === "injectionDefaults" ? `${kind}.${id}` : `${kind}s.${id}`;
733
- const label = kind === "injectionDefaults" ? "injection defaults" : kind;
734
- super(
735
- `Missing manifest binding for ${label} "${id}"`,
736
- [{ path: path5, message: "could not resolve manifest source" }],
737
- code,
738
- cause
739
- );
740
- this.name = "ManifestBindingNotFoundError";
741
- }
742
- };
743
- var UnsupportedSelectorTargetError = class extends MakooError {
744
- constructor(file, path5, target, code = ErrorCode.CLI_SELECTOR_TARGET_UNSUPPORTED, cause) {
745
- const rel = relative(process3.cwd(), file);
746
- super(
747
- `Unsupported selector target "${target}" in manifest at ${rel}`,
748
- [{ path: path5, message: "must be a CSS selector; document and window are not supported" }],
749
- code,
750
- cause
751
- );
752
- this.name = "UnsupportedSelectorTargetError";
753
- }
754
- };
755
- var ManifestLoadError = class extends MakooError {
756
- constructor(path5, code = ErrorCode.CLI_MANIFEST_LOAD_FAIL, cause) {
757
- super(
758
- `Failed to load manifest at ${path5}`,
759
- [{ path: "(load)", message: cause instanceof Error ? cause.message : String(cause) }],
760
- code,
761
- cause
762
- );
763
- this.name = "ManifestLoadError";
764
- }
765
- };
766
- var ModuleManifestLoadError = class extends MakooError {
767
- constructor(path5, code = ErrorCode.CLI_MODULE_MANIFEST_LOAD_FAIL, cause) {
768
- super(
769
- `Failed to load module manifest at ${path5}`,
770
- [{ path: "(load)", message: cause instanceof Error ? cause.message : String(cause) }],
771
- code,
772
- cause
773
- );
774
- this.name = "ModuleManifestLoadError";
775
- }
776
- };
777
- var NoEnabledTasksError = class extends MakooError {
778
- constructor(code = ErrorCode.CLI_NO_ENABLED_TASKS, cause) {
779
- super(
780
- "No enabled tasks \u2014 all injections and listeners are disabled or filtered out",
781
- void 0,
782
- code,
783
- cause
784
- );
785
- this.name = "NoEnabledTasksError";
786
- }
787
- };
788
- function formatZodPath(path5) {
789
- if (path5.length === 0) return "(root)";
790
- return path5.filter((p) => typeof p !== "symbol").map((p) => typeof p === "number" ? `[${p}]` : p).join(".");
791
- }
792
- function formatZodMessage(issue) {
793
- if (issue.code === "invalid_type" && issue.message.endsWith("received undefined")) {
794
- return "is required";
795
- }
796
- return issue.message;
797
- }
798
- function toMakooIssue(issue) {
799
- return {
800
- path: formatZodPath(issue.path),
801
- message: formatZodMessage(issue)
802
- };
622
+ // src/cli/commands/build.ts
623
+ import { build } from "vite";
624
+ async function buildCommand(config) {
625
+ await build(config);
803
626
  }
804
627
 
805
- // src/command/_util.ts
806
- import { existsSync } from "fs";
807
- import { readdir, readFile, writeFile } from "fs/promises";
628
+ // src/cli/commands/dev/dev.ts
629
+ import { createServer } from "vite";
630
+
631
+ // src/cli/version.ts
632
+ import { readFile } from "fs/promises";
808
633
  import { dirname, join } from "path";
809
634
  import { fileURLToPath } from "url";
810
- import { ErrorCode as ErrorCode2 } from "@makoojs/core";
811
- import { createJiti } from "jiti";
812
- import { loadConfigFromFile } from "vite";
813
- async function loadCliVersion(cliVersionCache2) {
814
- if (cliVersionCache2) {
815
- return cliVersionCache2;
816
- }
635
+ async function loadCliVersion(cliVersionCache) {
636
+ if (cliVersionCache) return cliVersionCache;
817
637
  let currentDir = dirname(fileURLToPath(import.meta.url));
818
638
  while (true) {
819
639
  const packagePath = join(currentDir, "package.json");
@@ -821,1024 +641,657 @@ async function loadCliVersion(cliVersionCache2) {
821
641
  const content = await readFile(packagePath, "utf-8");
822
642
  const packageJson = JSON.parse(content);
823
643
  if (packageJson.name === "@makoojs/cli" && packageJson.version) {
824
- cliVersionCache2 = packageJson.version;
825
- return cliVersionCache2;
644
+ return packageJson.version;
826
645
  }
827
646
  } catch {
828
647
  }
829
648
  const parentDir = dirname(currentDir);
830
- if (parentDir === currentDir) {
831
- break;
832
- }
649
+ if (parentDir === currentDir) break;
833
650
  currentDir = parentDir;
834
651
  }
835
652
  return "0.0.0";
836
653
  }
837
- async function loadMakooConfig() {
838
- const root = process.cwd();
839
- const result = await loadConfigFromFile(
840
- { command: "build", mode: "production" },
841
- void 0,
842
- root
843
- );
844
- if (!result) {
845
- throw new LoadViteMakooConfigError(
846
- `No vite config file found in "${root}". Make sure a vite.config.ts (or .js/.mts) exists.`,
847
- ErrorCode2.CLI_VITE_CONFIG_NOT_FOUND
848
- );
849
- }
850
- const plugins = (result.config.plugins ?? []).flat().filter((p) => p != null && p !== false);
851
- const makooPlugin = plugins.find(
852
- (p) => p.name === "vite-plugin-makoo"
853
- );
854
- if (!makooPlugin) {
855
- throw new LoadViteMakooConfigError(
856
- `makoo plugin not found in vite config at "${result.path}". Make sure makoo() is included in your plugins array.`,
857
- ErrorCode2.CLI_PLUGIN_NOT_FOUND
858
- );
859
- }
860
- return makooPlugin.__makoo;
861
- }
862
- function getExtName(framework) {
863
- const lowerFramework = framework.toLowerCase();
864
- if (lowerFramework === "vue") {
865
- return ".vue";
866
- }
867
- if (lowerFramework === "react") {
868
- if (existsSync(join(process.cwd(), "tsconfig.json"))) {
869
- return ".tsx";
870
- }
871
- return ".jsx";
872
- }
873
- return null;
874
- }
875
- async function updateManifest(moduleName, updateData) {
876
- const sourcePath = join(process.cwd(), DEFAULT_SOURCE_DIR);
877
- const sourceFiles = await readdir(sourcePath);
878
- let manifestName = null;
879
- for (const file of sourceFiles) {
880
- if ("manifest" === file.split(".")[0]) {
881
- manifestName = file;
882
- break;
883
- }
884
- }
885
- const merged = { injections: { [moduleName]: updateData } };
886
- if (!manifestName) {
887
- const newManifestPath = join(sourcePath, "manifest.ts");
888
- await writeFile(
889
- newManifestPath,
890
- `import { defineInjections } from "@makoojs/cli/manifest";
891
- export default defineInjections(${JSON.stringify(merged, null, 2)})
892
- `,
893
- "utf-8"
894
- );
895
- return;
896
- }
897
- const manifestPath = join(sourcePath, manifestName);
898
- const manifestContent = await readFile(manifestPath, "utf-8");
899
- const jiti = createJiti(sourcePath, { moduleCache: false });
900
- const existing = await jiti.import(manifestPath, { default: true });
901
- const injections = existing.injections;
902
- let updatedInjections;
903
- if (Array.isArray(injections)) {
904
- updatedInjections = [...injections, { name: moduleName, ...updateData }];
905
- } else if (injections && typeof injections === "object") {
906
- updatedInjections = {
907
- ...injections,
908
- [moduleName]: updateData
909
- };
910
- } else {
911
- updatedInjections = { [moduleName]: updateData };
912
- }
913
- Object.assign(merged, { ...existing, injections: updatedInjections });
914
- const updated = manifestContent.replace(
915
- /defineInjections\s*\(\s*([\s\S]*?)\s*\)\s*;?\s*$/,
916
- `defineInjections(${JSON.stringify(merged, null, 2)})`
917
- );
918
- await writeFile(manifestPath, updated, "utf-8");
919
- }
920
- function moduleTemplate(framework) {
921
- switch (framework) {
922
- case "Vue":
923
- return vueTemplate();
924
- case "React":
925
- return reactTemplate();
926
- default:
927
- throw new UnsupportedFrameworkGenerationError(framework);
928
- }
929
- }
930
- function vueTemplate() {
931
- return `<template>
932
- <div>hello-Vue !!</div>
933
- </template>
934
- `;
935
- }
936
- function reactTemplate() {
937
- return `export default function App() {
938
- return <div>hello-React !!</div>;
939
- }
940
- `;
941
- }
942
654
 
943
- // src/command/add.ts
944
- async function addCommand(moduleName, framework) {
945
- const cwd = process.cwd();
946
- const sourceDir = join2(cwd, DEFAULT_SOURCE_DIR);
947
- const moduleDir = join2(sourceDir, moduleName);
948
- const extName = getExtName(framework);
949
- if (!extName) throw new UnsupportedFrameworkGenerationError(framework);
950
- const appPath = join2(moduleDir, `App${extName}`);
951
- if (existsSync2(moduleDir)) {
952
- throw new ModuleAlreadyExistsError(`Module "${moduleName}" already exists`);
953
- }
954
- await mkdir(moduleDir, { recursive: true });
955
- await writeFile2(appPath, moduleTemplate(framework));
956
- await updateManifest(moduleName, {
957
- injectAt: "body",
958
- component: `./${moduleName}/app${extName}`
959
- });
960
- }
655
+ // src/cli/commands/dev/DevTerminal.ts
656
+ import { emitKeypressEvents } from "readline";
657
+ import { createLogUpdate } from "log-update";
961
658
 
962
- // src/command/build.ts
963
- import { build } from "vite";
964
- async function buildCommand() {
965
- await build();
966
- }
659
+ // src/vite/makooDev.ts
660
+ var bindDevSession = /* @__PURE__ */ Symbol("makooDev.bindSession");
967
661
 
968
- // src/command/dev.ts
969
- import { createServer } from "vite";
662
+ // src/cli/injections/renderInjections.ts
663
+ import { stripVTControlCharacters } from "util";
970
664
 
971
- // src/shared/terminalColor.ts
665
+ // src/cli/terminalColor.ts
972
666
  var ansi = {
973
667
  reset: "\x1B[0m",
974
668
  bold: "\x1B[1m",
975
669
  cyan: "\x1B[36m",
976
670
  deepPink: "\x1B[38;5;162m",
977
671
  green: "\x1B[32m",
672
+ red: "\x1B[31m",
673
+ yellow: "\x1B[33m",
978
674
  dim: "\x1B[2m"
979
675
  };
980
676
  var colorize = (value, ...codes) => `${codes.join("")}${value}${ansi.reset}`;
981
677
 
982
- // src/command/dev.ts
983
- var cliVersionCache = null;
984
- async function printDevBanner(server) {
985
- const cliVersion = await loadCliVersion(cliVersionCache);
986
- const title = `Makoo v${cliVersion}`;
987
- const urls = server.resolvedUrls;
988
- const localUrl = urls?.local[0];
989
- const networkUrl = urls?.network[0];
990
- console.log(`
991
- ${colorize(title, ansi.bold, ansi.cyan)}
992
- `);
993
- console.log(
994
- ` ${colorize("\u279C", ansi.green)} ${colorize("Local:", ansi.bold)} ${colorize(localUrl ?? "unavailable", ansi.cyan)}`
995
- );
996
- console.log(
997
- ` ${colorize("\u279C", ansi.green)} ${colorize("Network:", ansi.bold)} ${networkUrl ?? colorize("use --host to expose", ansi.dim)}`
998
- );
999
- }
1000
- async function devCommand() {
1001
- const server = await createServer();
1002
- await server.listen();
1003
- await printDevBanner(server);
1004
- server.bindCLIShortcuts({ print: true });
1005
- }
1006
-
1007
- // src/scanner/scanner.ts
1008
- import { existsSync as existsSync5, readdirSync as readdirSync2 } from "fs";
1009
- import path4 from "path";
1010
- import picomatch from "picomatch";
1011
-
1012
- // src/config/resolve.ts
1013
- import {
1014
- basename,
1015
- dirname as dirname2,
1016
- extname,
1017
- isAbsolute,
1018
- normalize,
1019
- resolve as resolvePath
1020
- } from "path";
1021
- import process4 from "process";
1022
-
1023
- // src/config/validation.ts
1024
- import { z } from "zod";
1025
- var AppConfigSchema = z.object({
1026
- name: z.string().min(1, "app.name is required"),
1027
- version: z.string().min(1, "app.version is required"),
1028
- description: z.string().optional()
1029
- });
1030
- var MonkeyConfigSchema = z.object({
1031
- server: z.object({}).passthrough().optional()
1032
- }).passthrough().superRefine((value, context) => {
1033
- if ("clientAlias" in value) {
1034
- context.addIssue({
1035
- code: z.ZodIssueCode.custom,
1036
- path: ["clientAlias"],
1037
- message: "monkey.clientAlias is not supported by makoo"
1038
- });
1039
- }
1040
- if (value.server && typeof value.server === "object" && "mountGmApi" in value.server) {
1041
- context.addIssue({
1042
- code: z.ZodIssueCode.custom,
1043
- path: ["server", "mountGmApi"],
1044
- message: "monkey.server.mountGmApi is not supported by makoo"
1045
- });
1046
- }
1047
- });
1048
- var CliConfigSchema = z.object({
1049
- app: AppConfigSchema,
1050
- monkey: MonkeyConfigSchema.optional(),
1051
- source: z.object({}).passthrough().optional(),
1052
- runtime: z.object({}).passthrough().optional()
1053
- }).loose().superRefine((value, context) => {
1054
- if ("injector" in value) {
1055
- context.addIssue({
1056
- code: z.ZodIssueCode.custom,
1057
- path: ["injector"],
1058
- message: "injector is not supported in vite config; use manifest injectionDefaults instead"
1059
- });
1060
- }
1061
- });
1062
-
1063
- // src/config/resolve.ts
1064
- var toStringArray = (value, fallback) => {
1065
- if (Array.isArray(value)) {
1066
- return value;
1067
- }
1068
- if (typeof value === "undefined") {
1069
- return fallback;
1070
- }
1071
- return [value];
1072
- };
1073
- var resolveFileSystemPath = (root, value) => {
1074
- if (isAbsolute(value)) {
1075
- return normalize(value);
1076
- }
1077
- return normalize(resolvePath(root, value));
1078
- };
1079
- var resolveProjectRoot = (root) => {
1080
- return normalize(root ? resolvePath(root) : process4.cwd());
678
+ // src/cli/injections/renderInjections.ts
679
+ var MAX_ERROR_LENGTH = 120;
680
+ var MAX_NAME_LENGTH = 40;
681
+ var COLUMN_GAP = 2;
682
+ var ATTACHED_INDENT = " ";
683
+ var STATUS_ORDER = ["mounted", "bound", "waiting", "failed", "idle"];
684
+ var STATUS_COLORS = {
685
+ mounted: ansi.green,
686
+ bound: ansi.green,
687
+ waiting: ansi.yellow,
688
+ failed: ansi.red,
689
+ idle: ansi.dim
1081
690
  };
1082
- var inferFrameworkFromPath = (componentPath) => {
1083
- const extension = extname(componentPath).toLowerCase();
1084
- if (REACT_EXTENSIONS.has(extension)) {
1085
- return "React";
1086
- }
1087
- if (VUE_EXTENSIONS.has(extension)) {
1088
- return "Vue";
1089
- }
1090
- throw new UnknownFrameworkError(componentPath);
1091
- };
1092
- var resolveFramework = (framework, componentPath) => {
1093
- if (framework && framework !== "auto") {
1094
- return framework;
1095
- }
1096
- return inferFrameworkFromPath(componentPath);
1097
- };
1098
- var resolveMatchConfig = (match) => {
1099
- if (!match) {
1100
- return void 0;
1101
- }
1102
- if (Array.isArray(match)) {
1103
- return {
1104
- include: match
1105
- };
1106
- }
1107
- return {
1108
- include: match.include,
1109
- exclude: match.exclude
1110
- };
1111
- };
1112
- var deriveInjectionModuleId = (config, moduleDir, componentPath, fallbackName, index) => {
1113
- if (config.name) {
1114
- return config.name;
1115
- }
1116
- if (fallbackName) {
1117
- return fallbackName;
1118
- }
1119
- const moduleName = basename(moduleDir);
1120
- if (moduleName) {
1121
- return moduleName;
1122
- }
1123
- const componentName = basename(componentPath, extname(componentPath));
1124
- if (componentName) {
1125
- return componentName;
1126
- }
1127
- return `injection-${typeof index === "number" ? index + 1 : 1}`;
1128
- };
1129
- var deriveListenerId = (config, fallbackName, index) => {
1130
- if (config.name) {
1131
- return config.name;
1132
- }
1133
- if (fallbackName) {
1134
- return fallbackName;
1135
- }
1136
- return `listener-${typeof index === "number" ? index + 1 : 1}`;
1137
- };
1138
- var normalizeInjectionManifest = (injections) => {
1139
- const items = injections?.injections;
1140
- if (!items) {
1141
- return [];
1142
- }
1143
- if (Array.isArray(items)) {
1144
- return items;
1145
- }
1146
- return Object.entries(items).map(([name, config]) => ({
1147
- name,
1148
- ...config
1149
- }));
1150
- };
1151
- var normalizeListenerManifest = (manifest) => {
1152
- const items = manifest?.listeners;
1153
- if (!items) {
1154
- return [];
1155
- }
1156
- if (Array.isArray(items)) {
1157
- return items;
1158
- }
1159
- return Object.entries(items).map(([name, config]) => ({
1160
- name,
1161
- ...config
1162
- }));
1163
- };
1164
- var resolveSourceConfig = (config, root) => {
1165
- return {
1166
- dir: resolveFileSystemPath(root, DEFAULT_SOURCE_CONFIG.dir),
1167
- include: toStringArray(config?.include, DEFAULT_SOURCE_CONFIG.include),
1168
- exclude: toStringArray(config?.exclude, DEFAULT_SOURCE_CONFIG.exclude),
1169
- manifest: DEFAULT_MANIFEST_FILE_NAME
1170
- };
1171
- };
1172
- var resolveInjectionDefaults = (config) => {
1173
- return {
1174
- alive: config?.alive ?? DEFAULT_INJECTION_DEFAULTS.alive,
1175
- scope: config?.scope ?? DEFAULT_INJECTION_DEFAULTS.scope,
1176
- timeout: config?.timeout ?? DEFAULT_INJECTION_DEFAULTS.timeout,
1177
- hooks: config?.hooks
1178
- };
1179
- };
1180
- var resolveInjection = (config, options) => {
1181
- const root = resolveProjectRoot(options.root);
1182
- const source = options.source ?? resolveSourceConfig(void 0, root);
1183
- const injectionDefaults = options.injectionDefaults ?? resolveInjectionDefaults(void 0);
1184
- const componentBaseDir = options.moduleDir ? resolveFileSystemPath(root, options.moduleDir) : source.dir;
1185
- if (!options.componentPath) {
1186
- throw new ComponentNotFoundError(config.name ?? config.injectAt);
1187
- }
1188
- const componentPath = resolveFileSystemPath(root, options.componentPath);
1189
- const moduleDir = options.moduleDir ? componentBaseDir : componentPath ? dirname2(componentPath) : source.dir;
1190
- const {
1191
- component,
1192
- framework: _framework,
1193
- enabled: _enabled,
1194
- alive: _alive,
1195
- scope: _scope,
1196
- timeout: _timeout,
1197
- ...rest
1198
- } = config;
1199
- void component;
1200
- void _framework;
1201
- void _enabled;
1202
- void _alive;
1203
- void _scope;
1204
- void _timeout;
1205
- const moduleId = options.moduleId ?? deriveInjectionModuleId(
1206
- config,
1207
- moduleDir,
1208
- componentPath,
1209
- options.fallbackName,
1210
- options.index
1211
- );
1212
- const framework = resolveFramework(config.framework, componentPath);
1213
- const moduleManifestFile = options.moduleManifestFile ? resolveFileSystemPath(root, options.moduleManifestFile) : void 0;
1214
- return {
1215
- ...rest,
1216
- moduleId,
1217
- componentPath,
1218
- framework,
1219
- moduleDir,
1220
- moduleManifestFile,
1221
- enabled: config.enabled ?? true,
1222
- alive: config.alive ?? injectionDefaults.alive,
1223
- scope: config.scope ?? injectionDefaults.scope,
1224
- timeout: config.timeout ?? injectionDefaults.timeout,
1225
- match: resolveMatchConfig(config.match)
1226
- };
1227
- };
1228
- var resolveInjections = (injections, options) => {
1229
- const root = resolveProjectRoot(options.root);
1230
- const normalizedInjections = normalizeInjectionManifest(injections);
1231
- return normalizedInjections.map(
1232
- (injection, index) => resolveInjection(injection, {
1233
- root,
1234
- source: options.source,
1235
- injectionDefaults: options.injectionDefaults,
1236
- componentPath: resolvePath(options.source.dir, injection.component),
1237
- // `index` was a name of element
1238
- index
1239
- })
1240
- );
1241
- };
1242
- var resolveListener = (config, options) => {
1243
- const { name: _name, enabled: _enabled, match: _match, ...rest } = config;
1244
- void _name;
1245
- void _enabled;
1246
- void _match;
1247
- return {
1248
- ...rest,
1249
- listenerId: options.listenerId ?? deriveListenerId(config, options.fallbackName, options.index),
1250
- enabled: config.enabled ?? true,
1251
- match: resolveMatchConfig(config.match)
1252
- };
1253
- };
1254
- var resolveListeners = (manifest, options) => {
1255
- const normalizedListeners = normalizeListenerManifest(manifest);
1256
- return normalizedListeners.map(
1257
- (listener, index) => resolveListener(listener, {
1258
- root: options.root,
1259
- index
1260
- })
1261
- );
1262
- };
1263
-
1264
- // src/scanner/collectDependenics.ts
1265
- import { existsSync as existsSync3, readFileSync, statSync } from "fs";
1266
- import path from "path";
1267
- function isInsideRoot(file, root) {
1268
- const rel = path.relative(root, file);
1269
- return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
691
+ function visibleLength(value) {
692
+ return stripVTControlCharacters(value).length;
1270
693
  }
1271
- function isNodeModulesFile(file) {
1272
- return file.split(path.sep).includes("node_modules");
694
+ function padEndVisible(value, width) {
695
+ const pad = width - visibleLength(value);
696
+ return pad > 0 ? `${value}${" ".repeat(pad)}` : value;
1273
697
  }
1274
- function isRelativeSpecifier(specifier) {
1275
- return specifier.startsWith("./") || specifier.startsWith("../");
698
+ function truncateDisplayName(name) {
699
+ if (name.length <= MAX_NAME_LENGTH) return name;
700
+ return `${name.slice(0, MAX_NAME_LENGTH - 1)}\u2026`;
1276
701
  }
1277
- function extractLocalSpecifiers(code) {
1278
- const specifiers = [];
1279
- for (const match of code.matchAll(ESM_IMPORT_RE)) {
1280
- const specifier = match[1] ?? match[2];
1281
- if (!specifier) continue;
1282
- if (!isRelativeSpecifier(specifier)) continue;
1283
- specifiers.push(specifier);
1284
- }
1285
- for (const match of code.matchAll(CJS_IMPORT_RE)) {
1286
- const specifier = match[1];
1287
- if (!specifier) continue;
1288
- if (!isRelativeSpecifier(specifier)) continue;
1289
- specifiers.push(specifier);
1290
- }
1291
- return specifiers;
702
+ function attachedDisplayName(name) {
703
+ return `\u2514 ${truncateDisplayName(name)}`;
1292
704
  }
1293
- function tryFile(filePath) {
1294
- if (!existsSync3(filePath)) return null;
1295
- if (!statSync(filePath).isFile()) return null;
1296
- return path.resolve(filePath);
705
+ function renderStatus(status) {
706
+ return colorize(`\u25CF ${status}`, STATUS_COLORS[status]);
1297
707
  }
1298
- function resolveLocalImport(fromDir, specifier) {
1299
- const base = path.resolve(fromDir, specifier);
1300
- const direct = tryFile(base);
1301
- if (direct) return direct;
1302
- for (const ext of SOURCE_EXTENSIONS) {
1303
- const withExt = tryFile(base + ext);
1304
- if (withExt) return withExt;
1305
- }
1306
- for (const ext of SOURCE_EXTENSIONS) {
1307
- const asIndex = tryFile(path.join(base, `index${ext}`));
1308
- if (asIndex) return asIndex;
1309
- }
1310
- return null;
708
+ function renderError(error) {
709
+ let text = `${error.code}: ${error.message}`;
710
+ if (error.cause !== void 0) text += ` (cause: ${error.cause})`;
711
+ text = text.replaceAll("\n", " \xB7 ");
712
+ if (text.length > MAX_ERROR_LENGTH) text = `${text.slice(0, MAX_ERROR_LENGTH - 1)}\u2026`;
713
+ return text;
1311
714
  }
1312
- function collectDependencies(entryFile, options) {
1313
- const root = path.resolve(options.root);
1314
- const visited = /* @__PURE__ */ new Set();
1315
- const result = /* @__PURE__ */ new Set();
1316
- const walk = (file) => {
1317
- const resolveFile = path.resolve(file);
1318
- if (visited.has(resolveFile)) return;
1319
- visited.add(resolveFile);
1320
- if (!isInsideRoot(resolveFile, root)) return;
1321
- if (isNodeModulesFile(resolveFile)) return;
1322
- if (!existsSync3(resolveFile)) return;
1323
- if (!statSync(resolveFile).isFile()) return;
1324
- if (options.includeEntry || resolveFile !== path.resolve(entryFile))
1325
- result.add(resolveFile);
1326
- const code = readFileSync(resolveFile, "utf8");
1327
- const dir = path.dirname(resolveFile);
1328
- for (const specifier of extractLocalSpecifiers(code)) {
1329
- const dep = resolveLocalImport(dir, specifier);
1330
- if (!dep) continue;
1331
- walk(dep);
1332
- }
1333
- };
1334
- walk(entryFile);
1335
- return Array.from(result);
715
+ function kindLabel(injection) {
716
+ return injection.kind === "component" ? "component" : "standalone listener";
1336
717
  }
1337
-
1338
- // src/scanner/load/loadManifes.ts
1339
- import { existsSync as existsSync4, readdirSync, statSync as statSync2 } from "fs";
1340
- import path2 from "path";
1341
- import { createJiti as createJiti2 } from "jiti";
1342
-
1343
- // src/scanner/validation.ts
1344
- import { OBSERVE_EVENT_NAMES } from "@makoojs/core";
1345
- import { z as z2 } from "zod";
1346
- var ObserveEventNameSchema = z2.enum(OBSERVE_EVENT_NAMES);
1347
- var ObserveHookSchema = z2.custom((value) => typeof value === "function");
1348
- var HookSchema = z2.union([ObserveHookSchema, z2.array(ObserveHookSchema)]);
1349
- var LifecycleHookMapSchema = z2.record(z2.string(), HookSchema).refine((obj) => Object.keys(obj).every((k) => ObserveEventNameSchema.safeParse(k).success), {
1350
- message: "Invalid hook event name"
1351
- });
1352
- var InjectionDefaultsSchema = z2.object({
1353
- alive: z2.boolean().optional(),
1354
- scope: z2.enum(["local", "global"]).optional(),
1355
- timeout: z2.number().optional(),
1356
- hooks: LifecycleHookMapSchema.optional()
1357
- });
1358
- var InjectionMatchSchema = z2.union([
1359
- z2.array(z2.string()),
1360
- z2.object({
1361
- include: z2.array(z2.string()).optional(),
1362
- exclude: z2.array(z2.string()).optional()
1363
- })
1364
- ]);
1365
- var EventListenerSchema = z2.custom((value) => typeof value === "function");
1366
- var ActivitySignalSchema = z2.custom(
1367
- (value) => typeof value === "function"
1368
- );
1369
- var InjectionModuleListenerSchema = z2.object({
1370
- listenAt: z2.string(),
1371
- type: z2.string(),
1372
- callback: EventListenerSchema,
1373
- capture: z2.boolean().optional(),
1374
- activitySignal: ActivitySignalSchema.optional()
1375
- });
1376
- var InjectionModuleSchema = z2.object({
1377
- name: z2.string().optional(),
1378
- injectAt: z2.string(),
1379
- component: z2.string(),
1380
- framework: z2.enum(["auto", "Vue", "React"]).optional(),
1381
- enabled: z2.boolean().optional(),
1382
- match: InjectionMatchSchema.optional(),
1383
- alive: z2.boolean().optional(),
1384
- scope: z2.enum(["local", "global"]).optional(),
1385
- timeout: z2.number().optional(),
1386
- hooks: LifecycleHookMapSchema.optional(),
1387
- on: InjectionModuleListenerSchema.optional()
1388
- });
1389
- var InjectionListenerSchema = InjectionModuleListenerSchema.extend({
1390
- name: z2.string().optional(),
1391
- enabled: z2.boolean().optional(),
1392
- match: InjectionMatchSchema.optional()
1393
- });
1394
- var InjectionManifestSchema = z2.object({
1395
- injectionDefaults: InjectionDefaultsSchema.optional(),
1396
- injections: z2.union([
1397
- z2.array(InjectionModuleSchema),
1398
- z2.record(z2.string(), InjectionModuleSchema.omit({ name: true }))
1399
- ]).optional(),
1400
- listeners: z2.union([
1401
- z2.array(InjectionListenerSchema),
1402
- z2.record(z2.string(), InjectionListenerSchema.omit({ name: true }))
1403
- ]).optional()
1404
- }).strict().refine((manifest) => manifest.injections || manifest.listeners, {
1405
- message: "Manifest must define injections or listeners"
1406
- });
1407
- function validateManifest(data, file) {
1408
- const result = InjectionManifestSchema.safeParse(data);
1409
- if (!result.success) {
1410
- throw new ManifestValidationError(file, result.error.issues);
718
+ function columnWidths(injections) {
719
+ let status = visibleLength("STATUS");
720
+ let name = visibleLength("NAME");
721
+ let attachedName = 0;
722
+ for (const injection of injections) {
723
+ status = Math.max(status, visibleLength(renderStatus(injection.status)));
724
+ name = Math.max(name, visibleLength(truncateDisplayName(injection.name)));
725
+ if (injection.kind !== "component") continue;
726
+ for (const listener of injection.attachedListeners) {
727
+ status = Math.max(status, visibleLength(renderStatus(listener.status)));
728
+ attachedName = Math.max(
729
+ attachedName,
730
+ visibleLength(attachedDisplayName(listener.name))
731
+ );
732
+ }
1411
733
  }
1412
- assertManifestSelectorTargets(result.data, file);
1413
- return result.data;
734
+ return { status, name, attachedName };
1414
735
  }
1415
- function validateModuleMeta(data, file) {
1416
- const result = InjectionModuleSchema.safeParse(data);
1417
- if (!result.success) {
1418
- throw new ManifestValidationError(file, result.error.issues);
1419
- }
1420
- assertSelectorTarget(result.data.injectAt, file, "injectAt");
1421
- assertSelectorTarget(result.data.on?.listenAt, file, "on.listenAt");
1422
- return result.data;
736
+ function renderTopLevelRow(injection, widths) {
737
+ const status = padEndVisible(renderStatus(injection.status), widths.status);
738
+ const name = padEndVisible(
739
+ colorize(truncateDisplayName(injection.name), ansi.bold, ansi.cyan),
740
+ widths.name
741
+ );
742
+ const kind = colorize(kindLabel(injection), ansi.deepPink);
743
+ const gap = " ".repeat(COLUMN_GAP);
744
+ return `${status}${gap}${name}${gap}${kind}`;
1423
745
  }
1424
- function assertManifestSelectorTargets(manifest, file) {
1425
- if (Array.isArray(manifest.injections)) {
1426
- manifest.injections.forEach((injection, index) => {
1427
- assertSelectorTarget(injection.injectAt, file, `injections[${index}].injectAt`);
1428
- assertSelectorTarget(injection.on?.listenAt, file, `injections[${index}].on.listenAt`);
1429
- });
1430
- } else if (manifest.injections) {
1431
- Object.entries(manifest.injections).forEach(([id, injection]) => {
1432
- assertSelectorTarget(injection.injectAt, file, `injections.${id}.injectAt`);
1433
- assertSelectorTarget(injection.on?.listenAt, file, `injections.${id}.on.listenAt`);
1434
- });
746
+ function renderAttachedRow(listener, widths) {
747
+ const status = padEndVisible(renderStatus(listener.status), widths.status);
748
+ const name = padEndVisible(attachedDisplayName(listener.name), widths.attachedName);
749
+ const kind = colorize("attached listener", ansi.dim);
750
+ const gap = " ".repeat(COLUMN_GAP);
751
+ return `${ATTACHED_INDENT}${status}${gap}${name}${gap}${kind}`;
752
+ }
753
+ function renderInjectionBlock(injection, widths) {
754
+ const lines = [renderTopLevelRow(injection, widths)];
755
+ if (injection.status === "failed" && injection.lastError) {
756
+ lines.push(colorize(`${ATTACHED_INDENT}${renderError(injection.lastError)}`, ansi.red));
1435
757
  }
1436
- if (Array.isArray(manifest.listeners)) {
1437
- manifest.listeners.forEach((listener, index) => {
1438
- assertSelectorTarget(listener.listenAt, file, `listeners[${index}].listenAt`);
1439
- });
1440
- } else if (manifest.listeners) {
1441
- Object.entries(manifest.listeners).forEach(([id, listener]) => {
1442
- assertSelectorTarget(listener.listenAt, file, `listeners.${id}.listenAt`);
1443
- });
758
+ if (injection.kind !== "component") return lines;
759
+ for (const listener of injection.attachedListeners) {
760
+ lines.push(renderAttachedRow(listener, widths));
1444
761
  }
762
+ return lines;
1445
763
  }
1446
- function assertSelectorTarget(target, file, path5) {
1447
- if (target === "document" || target === "window") {
1448
- throw new UnsupportedSelectorTargetError(file, path5, target);
1449
- }
764
+ function renderHeader(widths) {
765
+ const gap = " ".repeat(COLUMN_GAP);
766
+ return [
767
+ padEndVisible(colorize("STATUS", ansi.bold), widths.status),
768
+ padEndVisible(colorize("NAME", ansi.bold), widths.name),
769
+ colorize("KIND", ansi.bold)
770
+ ].join(gap);
1450
771
  }
1451
-
1452
- // src/scanner/load/loadManifes.ts
1453
- async function loadManifest(source) {
1454
- if (!existsSync4(source.dir)) {
1455
- throw new SourceDirNotFoundError(source.dir);
1456
- }
1457
- const manifestName = source.manifest;
1458
- const jiti = createJiti2(source.dir, { moduleCache: false });
1459
- for (const entry of readdirSync(source.dir)) {
1460
- const fullPath = path2.join(source.dir, entry);
1461
- if (statSync2(fullPath).isFile() && path2.basename(entry, path2.extname(entry)) === manifestName) {
1462
- let raw;
1463
- try {
1464
- raw = await jiti.import(fullPath, { default: true });
1465
- } catch (err) {
1466
- throw new ManifestLoadError(
1467
- fullPath,
1468
- void 0,
1469
- err instanceof Error ? err : void 0
1470
- );
1471
- }
1472
- return {
1473
- manifest: validateManifest(raw, fullPath),
1474
- manifestFile: fullPath,
1475
- dependencies: collectDependencies(fullPath, {
1476
- root: path2.resolve(source.dir, "..")
1477
- })
1478
- };
1479
- }
1480
- }
1481
- return null;
772
+ function renderDiagnostic(diagnostic) {
773
+ const error = colorize(renderError(diagnostic.error), ansi.red);
774
+ if (diagnostic.name === void 0) return ` ${error}`;
775
+ return ` ${colorize(diagnostic.name, ansi.bold, ansi.cyan)} ${error}`;
1482
776
  }
1483
-
1484
- // src/scanner/load/loadMeta.ts
1485
- import fs from "fs";
1486
- import path3 from "path";
1487
- import { createJiti as createJiti3 } from "jiti";
1488
- async function loadMeta(root) {
1489
- const files = fs.readdirSync(root).filter((name) => {
1490
- const fullPath = path3.join(root, name);
1491
- return fs.statSync(fullPath).isFile();
777
+ function renderSummary(injections) {
778
+ const total = injections.length === 1 ? "1 injection" : `${injections.length} injections`;
779
+ const counts = STATUS_ORDER.flatMap((status) => {
780
+ const count = injections.filter((injection) => injection.status === status).length;
781
+ return count === 0 ? [] : [colorize(`${count} ${status}`, STATUS_COLORS[status])];
1492
782
  });
1493
- if (files.length === 0) {
1494
- return null;
1495
- }
1496
- const jiti = createJiti3(root, { moduleCache: false });
1497
- for (const f of files) {
1498
- const fileName = path3.basename(f, path3.extname(f));
1499
- if (fileName === DEFAULT_MANIFEST_FILE_NAME) {
1500
- const fullPath = path3.join(root, f);
1501
- let raw;
1502
- try {
1503
- raw = await jiti.import(fullPath, { default: true });
1504
- } catch (err) {
1505
- throw new ModuleManifestLoadError(
1506
- fullPath,
1507
- void 0,
1508
- err instanceof Error ? err : void 0
1509
- );
783
+ return [total, ...counts].join(" \xB7 ");
784
+ }
785
+ function renderInjectionsTable(snapshots) {
786
+ const lines = [colorize("Makoo Injections", ansi.bold, ansi.deepPink), ""];
787
+ if (snapshots.length === 0) {
788
+ lines.push(
789
+ colorize("\u25CF Runtime Session disconnected.", ansi.yellow),
790
+ "",
791
+ colorize("Waiting for reconnection.", ansi.dim)
792
+ );
793
+ return lines.join("\n");
794
+ }
795
+ const visible = snapshots.filter(
796
+ (runtime) => runtime.injections.length > 0 || runtime.diagnostics.length > 0
797
+ );
798
+ if (visible.length === 0) {
799
+ lines.push("No injections registered.");
800
+ return lines.join("\n");
801
+ }
802
+ const showLabel = snapshots.length > 1;
803
+ const showClient = new Set(snapshots.map((runtime) => runtime.clientId)).size > 1;
804
+ for (const [index, runtime] of visible.entries()) {
805
+ if (showLabel) {
806
+ let label = `Makoo${runtime.runtimeId}`;
807
+ if (showClient) label = `Client ${runtime.clientId} \xB7 ${label}`;
808
+ lines.push(colorize(label, ansi.bold), "");
809
+ }
810
+ if (runtime.injections.length > 0) {
811
+ const widths = columnWidths(runtime.injections);
812
+ lines.push(renderHeader(widths));
813
+ for (const injection of runtime.injections) {
814
+ lines.push(...renderInjectionBlock(injection, widths));
1510
815
  }
1511
- return {
1512
- moduleManifestFile: fullPath,
1513
- moduleConfig: validateModuleMeta(raw, fullPath),
1514
- dependencies: collectDependencies(fullPath, {
1515
- root: path3.resolve(root, "..", "..")
1516
- })
1517
- };
1518
816
  }
817
+ if (runtime.diagnostics.length > 0) {
818
+ if (runtime.injections.length > 0) lines.push("");
819
+ lines.push(
820
+ colorize("Diagnostics", ansi.bold),
821
+ ...runtime.diagnostics.map(renderDiagnostic)
822
+ );
823
+ }
824
+ if (index < visible.length - 1) lines.push("");
1519
825
  }
1520
- return null;
826
+ const injections = visible.flatMap((runtime) => runtime.injections);
827
+ if (injections.length > 0) lines.push("", renderSummary(injections));
828
+ return lines.join("\n");
1521
829
  }
1522
830
 
1523
- // src/scanner/manifestBinding.ts
1524
- function buildManifestBindings(options) {
1525
- const manifestInjectionSources = /* @__PURE__ */ new Map();
1526
- const moduleInjectionSources = /* @__PURE__ */ new Map();
1527
- const listenerBindings = /* @__PURE__ */ new Map();
1528
- const injectionKeys = getCollectionKeys(options.manifest.injections);
1529
- const listenerKeys = getCollectionKeys(options.manifest.listeners);
1530
- const injectionConfigs = normalizeInjectionManifest(options.manifest);
1531
- const listenerConfigs = normalizeListenerManifest(options.manifest);
1532
- options.manifestInjections.forEach((injection, index) => {
1533
- manifestInjectionSources.set(injection.moduleId, {
1534
- config: injectionConfigs[index],
1535
- binding: {
1536
- manifestFile: options.manifestFile,
1537
- valuePath: ["injections", injectionKeys[index]]
1538
- }
1539
- });
1540
- });
1541
- options.moduleInjections.forEach((injection) => {
1542
- if (!injection.moduleManifestFile) return;
1543
- const config = options.moduleInjectionConfigs.get(injection.moduleId);
1544
- if (!config) {
1545
- throw new ManifestBindingNotFoundError("injection", injection.moduleId);
831
+ // src/cli/commands/dev/DevTerminal.ts
832
+ var ENTER_ALT_SCREEN = "\x1B[?1049h";
833
+ var LEAVE_ALT_SCREEN = "\x1B[?1049l";
834
+ var MAX_BUFFERED_LOGS = 1e3;
835
+ var DevTerminal = class {
836
+ constructor(server, cliVersion) {
837
+ this.server = server;
838
+ this.cliVersion = cliVersion;
839
+ this.session = server.config.plugins.find(
840
+ (plugin) => plugin.name === "makoo:dev"
841
+ )?.api?.session;
842
+ this.logger = server.config.logger;
843
+ this.originalInfo = this.logger.info;
844
+ this.originalWarn = this.logger.warn;
845
+ this.originalWarnOnce = this.logger.warnOnce;
846
+ this.originalError = this.logger.error;
847
+ this.originalClearScreen = this.logger.clearScreen;
848
+ this.logger.info = (message, options) => this.writeLog({ type: "info", message, options });
849
+ this.logger.warn = (message, options) => this.writeLog({ type: "warn", message, options });
850
+ this.logger.warnOnce = (message, options) => this.writeLog({ type: "warnOnce", message, options });
851
+ this.logger.error = (message, options) => this.writeLog({ type: "error", message, options });
852
+ this.logger.clearScreen = (type) => {
853
+ if (this.currentView === "logs") this.originalClearScreen.call(this.logger, type);
854
+ };
855
+ }
856
+ server;
857
+ cliVersion;
858
+ interactive = Boolean(
859
+ process.stdin.isTTY && process.stdout.isTTY && !process.env.CI
860
+ );
861
+ session;
862
+ unsubscribe;
863
+ currentView = "logs";
864
+ previousView = "home";
865
+ selectedRuntime = 0;
866
+ runtimeCount = -1;
867
+ ready = false;
868
+ restarting = false;
869
+ actionRunning = false;
870
+ closed = false;
871
+ stopInput;
872
+ bufferedLogs = [];
873
+ omittedLogs = 0;
874
+ unreadErrors = 0;
875
+ screenOutput = createLogUpdate(process.stdout, { showCursor: true });
876
+ logger;
877
+ originalInfo;
878
+ originalWarn;
879
+ originalWarnOnce;
880
+ originalError;
881
+ originalClearScreen;
882
+ async start() {
883
+ process.once("exit", this.close);
884
+ if (this.session) {
885
+ this.server.config.inlineConfig.customLogger = this.logger;
886
+ this.server.config.inlineConfig[bindDevSession] = this.attachSession;
887
+ this.attachSession(this.session);
888
+ process.once("SIGINT", this.shutdown);
1546
889
  }
1547
- moduleInjectionSources.set(injection.moduleId, {
1548
- config,
1549
- binding: {
1550
- manifestFile: injection.moduleManifestFile,
1551
- valuePath: []
890
+ try {
891
+ await this.server.listen();
892
+ this.ready = true;
893
+ if (!this.session) {
894
+ this.logger.info(this.renderBanner());
895
+ this.server.bindCLIShortcuts({ print: true });
896
+ return;
1552
897
  }
1553
- });
1554
- });
1555
- options.manifestListeners.forEach((listener, index) => {
1556
- const baseBinding = {
1557
- manifestFile: options.manifestFile,
1558
- valuePath: ["listeners", listenerKeys[index]]
1559
- };
1560
- const listenerConfig = listenerConfigs[index];
1561
- listenerBindings.set(listener.listenerId, {
1562
- callback: appendValuePath(baseBinding, ["callback"]),
1563
- activitySignal: listenerConfig.activitySignal ? appendValuePath(baseBinding, ["activitySignal"]) : void 0
1564
- });
1565
- });
1566
- return {
1567
- injectionDefaults: options.manifest.injectionDefaults?.hooks ? {
1568
- hooks: {
1569
- manifestFile: options.manifestFile,
1570
- valuePath: ["injectionDefaults", "hooks"]
898
+ if (this.interactive) {
899
+ this.show("home");
900
+ this.bindShortcuts();
901
+ } else {
902
+ const runtimes = this.session.getRuntimeSnapshots();
903
+ this.runtimeCount = runtimes.length;
904
+ this.logger.info(this.renderHome(runtimes));
1571
905
  }
1572
- } : void 0,
1573
- injections: Object.fromEntries(
1574
- options.enabledInjections.map((injection) => {
1575
- const manifestSource = manifestInjectionSources.get(injection.moduleId);
1576
- const moduleSource = moduleInjectionSources.get(injection.moduleId);
1577
- if (!manifestSource && !moduleSource) {
1578
- throw new ManifestBindingNotFoundError("injection", injection.moduleId);
1579
- }
1580
- return [injection.moduleId, buildInjectionBindings(manifestSource, moduleSource)];
1581
- })
1582
- ),
1583
- listeners: selectBindings(
1584
- options.enabledListeners.map((listener) => listener.listenerId),
1585
- listenerBindings,
1586
- "listener"
1587
- )
1588
- };
1589
- }
1590
- function buildInjectionBindings(manifestSource, moduleSource) {
1591
- const hooksSource = selectFieldSource("hooks", manifestSource, moduleSource);
1592
- const onSource = selectFieldSource("on", manifestSource, moduleSource);
1593
- return {
1594
- hooks: hooksSource?.config.hooks ? appendValuePath(hooksSource.binding, ["hooks"]) : void 0,
1595
- on: onSource?.config.on ? {
1596
- callback: appendValuePath(onSource.binding, ["on", "callback"]),
1597
- activitySignal: onSource.config.on.activitySignal ? appendValuePath(onSource.binding, ["on", "activitySignal"]) : void 0
1598
- } : void 0
1599
- };
1600
- }
1601
- function selectFieldSource(field, manifestSource, moduleSource) {
1602
- if (moduleSource && Object.hasOwn(moduleSource.config, field)) {
1603
- return moduleSource;
906
+ } catch (error) {
907
+ this.close();
908
+ await this.server.close();
909
+ throw error;
910
+ }
1604
911
  }
1605
- return manifestSource;
1606
- }
1607
- function appendValuePath(binding, valuePath) {
1608
- return {
1609
- manifestFile: binding.manifestFile,
1610
- valuePath: [...binding.valuePath, ...valuePath]
912
+ attachSession = (session) => {
913
+ this.unsubscribe?.();
914
+ this.session = session;
915
+ this.selectedRuntime = 0;
916
+ this.unsubscribe = session.subscribe(this.refresh);
917
+ this.refresh();
1611
918
  };
1612
- }
1613
- function getCollectionKeys(collection) {
1614
- if (!collection) return [];
1615
- return Array.isArray(collection) ? collection.map((_, index) => index) : Object.keys(collection);
1616
- }
1617
- function selectBindings(ids, bindings, kind) {
1618
- return Object.fromEntries(
1619
- ids.map((id) => {
1620
- const binding = bindings.get(id);
1621
- if (!binding) {
1622
- throw new ManifestBindingNotFoundError(kind, id);
919
+ // Session events, navigation and new logs all redraw through this entry point.
920
+ refresh = () => {
921
+ if (!this.ready || this.closed || !this.session) return;
922
+ const runtimes = this.session.getRuntimeSnapshots();
923
+ this.selectedRuntime = runtimes.length === 0 ? 0 : this.selectedRuntime % runtimes.length;
924
+ if (!this.interactive) {
925
+ if (this.runtimeCount !== runtimes.length) {
926
+ this.runtimeCount = runtimes.length;
927
+ this.logger.info(` Runtime ${this.renderRuntimeStatus(runtimes.length)}`);
1623
928
  }
1624
- return [id, binding];
1625
- })
1626
- );
1627
- }
1628
-
1629
- // src/scanner/util.ts
1630
- function mergeMeta(source, target) {
1631
- const targetMap = new Map(target.map((m) => [m.moduleId, m]));
1632
- const result = source.map((s) => targetMap.get(s.moduleId) ?? s);
1633
- for (const t of target) {
1634
- if (!source.some((s) => s.moduleId === t.moduleId)) {
1635
- result.push(t);
929
+ return;
1636
930
  }
1637
- }
1638
- return result;
1639
- }
1640
-
1641
- // src/scanner/scanner.ts
1642
- async function scanner(config) {
1643
- const loadedManifest = await loadManifest(config.source);
1644
- if (!loadedManifest) {
1645
- throw new ManifestNotFoundError(config.source.dir);
1646
- }
1647
- const manifestDependencies = new Set(loadedManifest.dependencies);
1648
- const moduleManifestDependencies = /* @__PURE__ */ new Set();
1649
- const runtimeSetupFiles = /* @__PURE__ */ new Set();
1650
- const runtimeDependencies = /* @__PURE__ */ new Set();
1651
- for (const setupFile of config.runtime.setup) {
1652
- if (!existsSync5(setupFile)) {
1653
- throw new RuntimeSetupNotFoundError(setupFile);
931
+ switch (this.currentView) {
932
+ case "home":
933
+ this.draw(
934
+ this.renderHome(runtimes),
935
+ "Press a key to select an action. Press Ctrl+C to stop."
936
+ );
937
+ break;
938
+ case "injections":
939
+ this.draw(
940
+ this.renderInjections(runtimes),
941
+ "Press t or Esc to return home. Press Ctrl+C to stop."
942
+ );
943
+ break;
944
+ case "help":
945
+ this.draw(this.renderHelp(), "Press h or Esc to return. Press Ctrl+C to stop.");
946
+ break;
947
+ case "logs":
948
+ break;
1654
949
  }
1655
- runtimeSetupFiles.add(setupFile);
1656
- for (const dependency of collectDependencies(setupFile, { root: config.root })) {
1657
- runtimeDependencies.add(dependency);
950
+ };
951
+ show(view) {
952
+ if (this.closed || !this.interactive) return;
953
+ const previous = this.currentView;
954
+ this.currentView = view;
955
+ if (previous === "logs" && view !== "logs") process.stdout.write(ENTER_ALT_SCREEN);
956
+ if (previous !== "logs" && view === "logs") {
957
+ this.screenOutput.clear();
958
+ process.stdout.write(LEAVE_ALT_SCREEN);
959
+ this.flushLogs();
960
+ this.originalInfo.call(
961
+ this.logger,
962
+ colorize("Press l or Esc to return home. Press Ctrl+C to stop.", ansi.dim)
963
+ );
1658
964
  }
965
+ this.refresh();
1659
966
  }
1660
- const injectionDefaults = resolveInjectionDefaults(loadedManifest.manifest.injectionDefaults);
1661
- const resolveManifest = resolveInjections(loadedManifest.manifest, {
1662
- root: config.root,
1663
- source: config.source,
1664
- injectionDefaults
1665
- });
1666
- const normalizedManifestInjections = normalizeInjectionManifest(loadedManifest.manifest);
1667
- const manifestInjectionConfigs = new Map(
1668
- resolveManifest.map((injection, index) => [
1669
- injection.moduleId,
1670
- normalizedManifestInjections[index]
1671
- ])
1672
- );
1673
- const folder = readdirSync2(config.source.dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
1674
- const isIncluded = picomatch(config.source.include);
1675
- const isExcluded = picomatch(config.source.exclude);
1676
- const filteredFolders = folder.filter((name) => isIncluded(name) && !isExcluded(name));
1677
- const injectionsMeta = [];
1678
- const moduleInjectionConfigs = /* @__PURE__ */ new Map();
1679
- for (const module of filteredFolders) {
1680
- const modulePath = path4.join(config.source.dir, module);
1681
- const meta = await loadMeta(modulePath);
1682
- if (!meta) {
1683
- continue;
1684
- }
1685
- for (const dependency of meta.dependencies) {
1686
- moduleManifestDependencies.add(dependency);
967
+ renderBanner() {
968
+ const urls = this.server.resolvedUrls;
969
+ return [
970
+ `
971
+ ${colorize("\u25C6", ansi.deepPink)} ${colorize(`Makoo v${this.cliVersion}`, ansi.bold, ansi.cyan)} ${colorize("dev", ansi.dim)}
972
+ `,
973
+ ` ${colorize("Local", ansi.dim)} ${colorize(urls?.local[0] ?? "unavailable", ansi.cyan)}`,
974
+ ` ${colorize("Network", ansi.dim)} ${urls?.network[0] ?? colorize("use --host to expose", ansi.dim)}`
975
+ ].join("\n");
976
+ }
977
+ renderRuntimeStatus(count) {
978
+ if (this.restarting) return "Restarting\u2026";
979
+ if (count === 0) return "Waiting for a browser runtime";
980
+ return `${count} browser runtime${count === 1 ? "" : "s"} connected`;
981
+ }
982
+ renderHome(runtimes) {
983
+ const waiting = this.restarting || runtimes.length === 0;
984
+ const total = this.bufferedLogs.length + this.omittedLogs;
985
+ const logs = `${total} new${this.unreadErrors ? ` \xB7 ${this.unreadErrors} error${this.unreadErrors === 1 ? "" : "s"}` : ""}`;
986
+ return [
987
+ this.renderBanner(),
988
+ ` ${colorize("Runtime", ansi.dim)} ${colorize(waiting ? "\u25CB" : "\u25CF", waiting ? ansi.yellow : ansi.green)} ${this.renderRuntimeStatus(runtimes.length)}`,
989
+ ` ${colorize("Logs", ansi.dim)} ${colorize(logs, this.unreadErrors ? ansi.red : ansi.dim)}`,
990
+ `
991
+ ${colorize("Actions", ansi.bold)}`,
992
+ ...this.hasInstallationPage() ? [` ${colorize("i", ansi.bold, ansi.cyan)} Open installation page`] : [],
993
+ ` ${colorize("t", ansi.bold, ansi.cyan)} View runtime injections`,
994
+ ` ${colorize("l", ansi.bold, ansi.cyan)} View logs`,
995
+ ` ${colorize("r", ansi.bold, ansi.cyan)} Restart server`,
996
+ ` ${colorize("h", ansi.bold, ansi.cyan)} Show help`
997
+ ].join("\n");
998
+ }
999
+ renderInjections(runtimes) {
1000
+ if (runtimes.length === 0) return "Makoo Injections\n\nWaiting for a browser runtime";
1001
+ const runtime = runtimes[this.selectedRuntime];
1002
+ return [
1003
+ `Runtime ${this.selectedRuntime + 1}/${runtimes.length} \xB7 Client ${runtime.clientId} \xB7 Makoo${runtime.runtimeId}`,
1004
+ renderInjectionsTable([runtime]),
1005
+ ...runtimes.length > 1 ? ["Press n to view the next runtime."] : []
1006
+ ].join("\n\n");
1007
+ }
1008
+ renderHelp() {
1009
+ return [
1010
+ colorize("Shortcuts", ansi.bold),
1011
+ "",
1012
+ ...this.hasInstallationPage() ? [
1013
+ ` ${colorize("i", ansi.bold, ansi.cyan)} open development script installation page`
1014
+ ] : [],
1015
+ ...[
1016
+ ["t", "toggle runtime injections"],
1017
+ ["n", "view next runtime injections"],
1018
+ ["l", "view logs / return home"],
1019
+ ["r", "restart the server"],
1020
+ ["u", "show server URLs"],
1021
+ ["o", "open in browser"],
1022
+ ["c", "clear console"],
1023
+ ["q", "quit"],
1024
+ ["h", "show help"]
1025
+ ].map(
1026
+ ([key, description]) => ` ${colorize(key, ansi.bold, ansi.cyan)} ${description}`
1027
+ )
1028
+ ].join("\n");
1029
+ }
1030
+ draw(content, hint) {
1031
+ const lines = [content, ""];
1032
+ const total = this.bufferedLogs.length + this.omittedLogs;
1033
+ if (total > 0 && this.currentView !== "home") {
1034
+ const status = `${total} new dev log${total === 1 ? "" : "s"}`;
1035
+ const errors = this.unreadErrors > 0 ? ` \xB7 ${this.unreadErrors} error${this.unreadErrors === 1 ? "" : "s"}` : "";
1036
+ lines.push(colorize(status + errors, this.unreadErrors ? ansi.red : ansi.dim));
1687
1037
  }
1688
- const resolveOptions = {
1689
- root: config.root,
1690
- source: config.source,
1691
- injectionDefaults,
1692
- moduleDir: modulePath,
1693
- componentPath: path4.join(modulePath, meta.moduleConfig.component),
1694
- fallbackName: module,
1695
- moduleManifestFile: meta.moduleManifestFile
1038
+ lines.push(colorize(hint, ansi.dim));
1039
+ this.screenOutput(lines.join("\n"));
1040
+ }
1041
+ hasInstallationPage() {
1042
+ return this.server.config.plugins.some((plugin) => plugin.name === "monkey:virtualHtml");
1043
+ }
1044
+ bindShortcuts() {
1045
+ const wasRaw = process.stdin.isRaw;
1046
+ const wasFlowing = process.stdin.readableFlowing;
1047
+ emitKeypressEvents(process.stdin);
1048
+ process.stdin.setRawMode(true);
1049
+ process.stdin.on("keypress", this.onKey);
1050
+ process.stdin.resume();
1051
+ this.stopInput = () => {
1052
+ process.stdin.off("keypress", this.onKey);
1053
+ process.stdin.setRawMode(wasRaw);
1054
+ if (!wasFlowing) process.stdin.pause();
1696
1055
  };
1697
- const moduleId = meta.moduleConfig.name || module;
1698
- const manifestConfig = manifestInjectionConfigs.get(moduleId);
1699
- const resolveMeta = resolveInjection(
1700
- manifestConfig ? { ...manifestConfig, ...meta.moduleConfig } : meta.moduleConfig,
1701
- resolveOptions
1702
- );
1703
- injectionsMeta.push(resolveMeta);
1704
- moduleInjectionConfigs.set(resolveMeta.moduleId, meta.moduleConfig);
1705
1056
  }
1706
- const injections = mergeMeta(resolveManifest, injectionsMeta).filter(
1707
- (injection) => injection.enabled
1708
- );
1709
- const resolvedListeners = resolveListeners(loadedManifest.manifest, {
1710
- root: config.root
1711
- });
1712
- const listeners = resolvedListeners.filter((listener) => listener.enabled);
1713
- if (injections.length === 0 && listeners.length === 0) {
1714
- throw new NoEnabledTasksError();
1715
- }
1716
- const manifestBindings = buildManifestBindings({
1717
- manifest: loadedManifest.manifest,
1718
- manifestFile: loadedManifest.manifestFile,
1719
- manifestInjections: resolveManifest,
1720
- moduleInjections: injectionsMeta,
1721
- moduleInjectionConfigs,
1722
- manifestListeners: resolvedListeners,
1723
- enabledInjections: injections,
1724
- enabledListeners: listeners
1725
- });
1726
- injections.sort((a, b) => a.moduleId.localeCompare(b.moduleId));
1727
- listeners.sort((a, b) => a.listenerId.localeCompare(b.listenerId));
1728
- const frameworks = [...new Set(injections.map((m) => m.framework))];
1729
- return {
1730
- config,
1731
- injectionDefaults,
1732
- manifestFile: loadedManifest.manifestFile,
1733
- manifestBindings,
1734
- manifestDependencies: [...manifestDependencies].sort(),
1735
- moduleManifestDependencies: [...moduleManifestDependencies].sort(),
1736
- runtimeSetupFiles: [...runtimeSetupFiles].sort(),
1737
- runtimeDependencies: [...runtimeDependencies].sort(),
1738
- injections,
1739
- listeners,
1740
- frameworks
1057
+ onKey = async (_text, key) => {
1058
+ if (key.ctrl && key.name === "c") {
1059
+ await this.shutdown();
1060
+ return;
1061
+ }
1062
+ if (this.actionRunning || key.ctrl) return;
1063
+ if (key.name === "escape") {
1064
+ this.show(this.currentView === "help" ? this.previousView : "home");
1065
+ return;
1066
+ }
1067
+ if (key.meta || key.sequence?.length !== 1) return;
1068
+ if (key.name === "h") {
1069
+ if (this.currentView === "help") this.show(this.previousView);
1070
+ else {
1071
+ this.previousView = this.currentView;
1072
+ this.show("help");
1073
+ }
1074
+ return;
1075
+ }
1076
+ if (!["i", "t", "n", "l", "r", "u", "o", "c", "q"].includes(key.name ?? "")) return;
1077
+ if (key.name === "i" && !this.hasInstallationPage()) return;
1078
+ if (this.currentView === "help") this.show(this.previousView);
1079
+ this.actionRunning = true;
1080
+ try {
1081
+ switch (key.name) {
1082
+ case "t":
1083
+ this.show(this.currentView === "injections" ? "home" : "injections");
1084
+ break;
1085
+ case "n":
1086
+ this.selectedRuntime += 1;
1087
+ this.show("injections");
1088
+ break;
1089
+ case "l":
1090
+ this.show(this.currentView === "logs" ? "home" : "logs");
1091
+ break;
1092
+ case "r":
1093
+ await this.restart();
1094
+ break;
1095
+ case "u":
1096
+ this.show("home");
1097
+ break;
1098
+ case "o":
1099
+ this.server.openBrowser();
1100
+ break;
1101
+ case "i":
1102
+ this.openInstallationPage();
1103
+ break;
1104
+ case "c":
1105
+ this.show("logs");
1106
+ this.logger.clearScreen("error");
1107
+ break;
1108
+ case "q":
1109
+ await this.shutdown();
1110
+ break;
1111
+ }
1112
+ } catch (error) {
1113
+ this.logger.error(`[makoo] ${error instanceof Error ? error.message : String(error)}`);
1114
+ } finally {
1115
+ this.actionRunning = false;
1116
+ }
1117
+ };
1118
+ openInstallationPage() {
1119
+ const open = this.server.config.server.open;
1120
+ try {
1121
+ this.server.config.server.open = this.server.config.base;
1122
+ this.server.openBrowser();
1123
+ } finally {
1124
+ this.server.config.server.open = open;
1125
+ }
1126
+ }
1127
+ async restart() {
1128
+ this.restarting = true;
1129
+ this.show("home");
1130
+ try {
1131
+ await this.server.restart();
1132
+ } finally {
1133
+ this.restarting = false;
1134
+ this.refresh();
1135
+ }
1136
+ }
1137
+ shutdown = async () => {
1138
+ this.close();
1139
+ try {
1140
+ await this.server.close();
1141
+ } finally {
1142
+ process.exit(0);
1143
+ }
1144
+ };
1145
+ close = () => {
1146
+ if (this.closed) return;
1147
+ this.closed = true;
1148
+ this.unsubscribe?.();
1149
+ this.stopInput?.();
1150
+ process.off("exit", this.close);
1151
+ process.off("SIGINT", this.shutdown);
1152
+ if (this.currentView !== "logs") {
1153
+ this.screenOutput.clear();
1154
+ process.stdout.write(LEAVE_ALT_SCREEN);
1155
+ this.currentView = "logs";
1156
+ this.flushLogs();
1157
+ }
1158
+ this.logger.info = this.originalInfo;
1159
+ this.logger.warn = this.originalWarn;
1160
+ this.logger.warnOnce = this.originalWarnOnce;
1161
+ this.logger.error = this.originalError;
1162
+ this.logger.clearScreen = this.originalClearScreen;
1741
1163
  };
1164
+ writeLog(log) {
1165
+ if (this.currentView === "logs") {
1166
+ this.printLog(log);
1167
+ return;
1168
+ }
1169
+ if (log.type === "error") this.unreadErrors += 1;
1170
+ if (log.options) log.options = { ...log.options, clear: false };
1171
+ this.bufferedLogs.push(log);
1172
+ if (this.bufferedLogs.length > MAX_BUFFERED_LOGS) {
1173
+ this.bufferedLogs.shift();
1174
+ this.omittedLogs += 1;
1175
+ }
1176
+ this.refresh();
1177
+ }
1178
+ printLog(log) {
1179
+ switch (log.type) {
1180
+ case "info":
1181
+ this.originalInfo.call(this.logger, log.message, log.options);
1182
+ break;
1183
+ case "warn":
1184
+ this.originalWarn.call(this.logger, log.message, log.options);
1185
+ break;
1186
+ case "warnOnce":
1187
+ this.originalWarnOnce.call(this.logger, log.message, log.options);
1188
+ break;
1189
+ case "error":
1190
+ this.originalError.call(this.logger, log.message, log.options);
1191
+ break;
1192
+ }
1193
+ }
1194
+ flushLogs() {
1195
+ if (this.omittedLogs > 0)
1196
+ this.originalWarn.call(
1197
+ this.logger,
1198
+ `[makoo] ${this.omittedLogs} earlier dev logs omitted.`
1199
+ );
1200
+ for (const log of this.bufferedLogs) this.printLog(log);
1201
+ this.bufferedLogs = [];
1202
+ this.omittedLogs = 0;
1203
+ this.unreadErrors = 0;
1204
+ }
1205
+ };
1206
+
1207
+ // src/cli/commands/dev/dev.ts
1208
+ async function devCommand(config) {
1209
+ const server = await createServer(config);
1210
+ const cliVersion = await loadCliVersion(null);
1211
+ const terminal = new DevTerminal(server, cliVersion);
1212
+ await terminal.start();
1742
1213
  }
1743
1214
 
1744
- // src/command/inspect.ts
1745
- function formatInspectInjection(injection, injectionDefaults) {
1746
- const { alive, scope, timeout, ...rest } = injection;
1747
- const resolvedInjectionDefaults = { alive, scope, timeout };
1748
- const injectionDefaultsOverrides = {
1749
- ...alive !== injectionDefaults.alive ? { alive } : {},
1750
- ...scope !== injectionDefaults.scope ? { scope } : {},
1751
- ...timeout !== injectionDefaults.timeout ? { timeout } : {}
1752
- };
1753
- if (Object.keys(injectionDefaultsOverrides).length === 0) {
1754
- return {
1755
- ...rest,
1756
- injectionDefaults: resolvedInjectionDefaults
1757
- };
1215
+ // src/cli/commands/preview.ts
1216
+ import { preview } from "vite";
1217
+ async function previewCommand(config) {
1218
+ const server = await preview(config);
1219
+ server.printUrls();
1220
+ server.bindCLIShortcuts({ print: true });
1221
+ }
1222
+
1223
+ // src/cli/bin.ts
1224
+ var cli = cac("makoo");
1225
+ function normalizeDuplicateOptions(options) {
1226
+ for (const [key, value] of Object.entries(options)) {
1227
+ if (Array.isArray(value)) options[key] = value[value.length - 1];
1758
1228
  }
1229
+ }
1230
+ function resolveCommonOptions(root, options) {
1759
1231
  return {
1760
- ...rest,
1761
- injectionDefaults: resolvedInjectionDefaults,
1762
- injectionDefaultsOverrides
1232
+ root,
1233
+ configFile: options.config,
1234
+ base: options.base === 0 ? "" : options.base === void 0 ? void 0 : String(options.base),
1235
+ mode: options.mode,
1236
+ logLevel: options.logLevel,
1237
+ clearScreen: options.clearScreen,
1238
+ configLoader: options.configLoader
1763
1239
  };
1764
1240
  }
1765
- function formatInspectResult(result) {
1766
- const { config, injectionDefaults, injections, listeners } = result;
1767
- const moduleManifestFiles = [
1768
- ...new Set(
1769
- injections.map((injection) => injection.moduleManifestFile).filter((file) => typeof file === "string")
1770
- )
1771
- ].sort();
1772
- return {
1773
- project: {
1774
- root: config.root,
1775
- app: config.app
1241
+ cli.option("-c, --config <file>", "Use specified Vite config file").option("-m, --mode <mode>", "Set environment mode").option("--base <path>", "Public base path").option("-l, --logLevel <level>", "Log level: info | warn | error | silent").option("--clearScreen", "Allow/disable clearing the terminal").option("--configLoader <loader>", "Config loader: bundle | runner | native");
1242
+ cli.command("build [root]", "Build the userscript").option("--target <target>", "Transpile target").option("--outDir <dir>", "Output directory").option("--assetsDir <dir>", "Directory for generated assets").option("--assetsInlineLimit <number>", "Asset inline threshold in bytes").option("--sourcemap [output]", "Source maps: true | false | inline | hidden").option("--minify [minifier]", "Enable/disable minification, or select a minifier").option("--manifest [name]", "Emit a build manifest").option("--emptyOutDir", "Allow/disable emptying the output directory").option("-w, --watch", "Rebuild when source files change").action(async (root, options) => {
1243
+ normalizeDuplicateOptions(options);
1244
+ let sourcemap = options.sourcemap;
1245
+ if (sourcemap === "true") sourcemap = true;
1246
+ if (sourcemap === "false") sourcemap = false;
1247
+ await buildCommand({
1248
+ ...resolveCommonOptions(root, options),
1249
+ build: {
1250
+ target: options.target,
1251
+ outDir: options.outDir,
1252
+ assetsDir: options.assetsDir,
1253
+ assetsInlineLimit: options.assetsInlineLimit,
1254
+ sourcemap,
1255
+ minify: options.minify,
1256
+ manifest: options.manifest,
1257
+ emptyOutDir: options.emptyOutDir,
1258
+ watch: options.watch ? {} : void 0
1259
+ }
1260
+ });
1261
+ });
1262
+ cli.command("dev [root]", "Start the dev server").option("--host [host]", "Listen on a hostname or all addresses").option("--port <port>", "Development server port").option("--open [path]", "Open the browser on startup").option("--cors", "Enable/disable CORS").option("--strictPort", "Exit if the requested port is in use").option("--force", "Ignore the dependency optimizer cache").action(async (root, options) => {
1263
+ normalizeDuplicateOptions(options);
1264
+ await devCommand({
1265
+ ...resolveCommonOptions(root, options),
1266
+ server: {
1267
+ host: typeof options.host === "number" ? String(options.host) : options.host,
1268
+ port: options.port,
1269
+ open: options.open,
1270
+ cors: options.cors,
1271
+ strictPort: options.strictPort
1776
1272
  },
1777
- source: {
1778
- config: config.source,
1779
- manifestFile: result.manifestFile,
1780
- moduleManifestFiles,
1781
- dependencies: {
1782
- manifest: result.manifestDependencies,
1783
- moduleManifests: result.moduleManifestDependencies
1273
+ forceOptimizeDeps: options.force
1274
+ });
1275
+ });
1276
+ cli.command("preview [root]", "Preview the built userscript").option("--host [host]", "Listen on a hostname or all addresses").option("--port <port>", "Preview server port").option("--open [path]", "Open the browser on startup").option("--strictPort", "Exit if the requested port is in use").option("--outDir <dir>", "Directory to preview").action(
1277
+ async (root, options) => {
1278
+ normalizeDuplicateOptions(options);
1279
+ await previewCommand({
1280
+ ...resolveCommonOptions(root, options),
1281
+ build: { outDir: options.outDir },
1282
+ preview: {
1283
+ host: typeof options.host === "number" ? String(options.host) : options.host,
1284
+ port: options.port,
1285
+ open: options.open,
1286
+ strictPort: options.strictPort
1784
1287
  }
1785
- },
1786
- runtime: {
1787
- setupFiles: result.runtimeSetupFiles,
1788
- dependencies: result.runtimeDependencies
1789
- },
1790
- monkey: config.monkey,
1791
- injectionDefaults,
1792
- injections: injections.map(
1793
- (injection) => formatInspectInjection(injection, injectionDefaults)
1794
- ),
1795
- listeners,
1796
- frameworks: result.frameworks
1797
- };
1798
- }
1799
- async function inspectCommand() {
1800
- const resolveViteMakooConfig = await loadMakooConfig();
1801
- const resolveManifest = await scanner(resolveViteMakooConfig);
1802
- const inspectResult = formatInspectResult(resolveManifest);
1803
- const sections = [
1804
- ["Project", inspectResult.project],
1805
- ["Source", inspectResult.source],
1806
- ["Runtime", inspectResult.runtime],
1807
- ["Monkey", inspectResult.monkey],
1808
- ["Injection Defaults", inspectResult.injectionDefaults],
1809
- ["Injections", inspectResult.injections],
1810
- ["Listeners", inspectResult.listeners],
1811
- ["Frameworks", inspectResult.frameworks]
1812
- ];
1813
- console.log(colorize("Makoo Inspect", ansi.bold, ansi.green));
1814
- for (const [label, value] of sections) {
1815
- console.log(`
1816
- ${colorize(label, ansi.cyan)}`);
1817
- console.dir(value, {
1818
- depth: null,
1819
- colors: true
1820
1288
  });
1821
1289
  }
1822
- }
1823
-
1824
- // src/command/bin.ts
1825
- var cli = cac("makoo");
1826
- cli.command("build", "Build the userscript").action(async () => {
1827
- await buildCommand();
1828
- });
1829
- cli.command("dev", "Start the dev server").action(async () => {
1830
- await devCommand();
1831
- });
1832
- cli.command("add <name>", "Add a new injection module").option("--framework <framework>", "Framework to use", { default: "React" }).action(async (name, options) => {
1833
- await addCommand(name, options.framework);
1834
- });
1835
- cli.command("inspect", "Inspect resolved makoo config").action(async () => {
1836
- await inspectCommand();
1837
- });
1290
+ );
1838
1291
  cli.help();
1839
- cli.version("1.3.1");
1292
+ cli.version(await loadCliVersion(null));
1840
1293
  process.on("unhandledRejection", (err) => {
1841
- if (err instanceof MakooError2) {
1294
+ if (err instanceof MakooError) {
1842
1295
  console.error(err);
1843
1296
  } else {
1844
1297
  console.error("[makoo]", err);