movehat 0.2.1 → 0.2.2

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 (134) hide show
  1. package/dist/__tests__/deployContract.test.js +56 -47
  2. package/dist/__tests__/deployContract.test.js.map +1 -1
  3. package/dist/__tests__/exports.test.d.ts +2 -0
  4. package/dist/__tests__/exports.test.d.ts.map +1 -0
  5. package/dist/__tests__/exports.test.js +30 -0
  6. package/dist/__tests__/exports.test.js.map +1 -0
  7. package/dist/__tests__/fixtures/sigint-deploy-harness.d.ts +4 -3
  8. package/dist/__tests__/fixtures/sigint-deploy-harness.d.ts.map +1 -1
  9. package/dist/__tests__/fixtures/sigint-deploy-harness.js +8 -7
  10. package/dist/__tests__/fixtures/sigint-deploy-harness.js.map +1 -1
  11. package/dist/__tests__/fork/api.test.js +5 -0
  12. package/dist/__tests__/fork/api.test.js.map +1 -1
  13. package/dist/__tests__/fork/api.timeout.test.d.ts +2 -0
  14. package/dist/__tests__/fork/api.timeout.test.d.ts.map +1 -0
  15. package/dist/__tests__/fork/api.timeout.test.js +98 -0
  16. package/dist/__tests__/fork/api.timeout.test.js.map +1 -0
  17. package/dist/commands/__tests__/compile.toml-mutation.test.d.ts +2 -0
  18. package/dist/commands/__tests__/compile.toml-mutation.test.d.ts.map +1 -0
  19. package/dist/commands/__tests__/compile.toml-mutation.test.js +69 -0
  20. package/dist/commands/__tests__/compile.toml-mutation.test.js.map +1 -0
  21. package/dist/commands/__tests__/init.test.js +73 -11
  22. package/dist/commands/__tests__/init.test.js.map +1 -1
  23. package/dist/commands/init.d.ts +22 -0
  24. package/dist/commands/init.d.ts.map +1 -1
  25. package/dist/commands/init.js +55 -6
  26. package/dist/commands/init.js.map +1 -1
  27. package/dist/core/AccountManager.d.ts.map +1 -1
  28. package/dist/core/AccountManager.js +14 -2
  29. package/dist/core/AccountManager.js.map +1 -1
  30. package/dist/core/Publisher.d.ts.map +1 -1
  31. package/dist/core/Publisher.js +52 -68
  32. package/dist/core/Publisher.js.map +1 -1
  33. package/dist/core/__tests__/AccountManager.global-state.test.d.ts +2 -0
  34. package/dist/core/__tests__/AccountManager.global-state.test.d.ts.map +1 -0
  35. package/dist/core/__tests__/AccountManager.global-state.test.js +69 -0
  36. package/dist/core/__tests__/AccountManager.global-state.test.js.map +1 -0
  37. package/dist/core/__tests__/movementProfile.test.d.ts +2 -0
  38. package/dist/core/__tests__/movementProfile.test.d.ts.map +1 -0
  39. package/dist/core/__tests__/movementProfile.test.js +112 -0
  40. package/dist/core/__tests__/movementProfile.test.js.map +1 -0
  41. package/dist/core/config.js +6 -5
  42. package/dist/core/config.js.map +1 -1
  43. package/dist/core/movementProfile.d.ts +55 -22
  44. package/dist/core/movementProfile.d.ts.map +1 -1
  45. package/dist/core/movementProfile.js +77 -99
  46. package/dist/core/movementProfile.js.map +1 -1
  47. package/dist/fork/__tests__/server.cors.test.d.ts +2 -0
  48. package/dist/fork/__tests__/server.cors.test.d.ts.map +1 -0
  49. package/dist/fork/__tests__/server.cors.test.js +79 -0
  50. package/dist/fork/__tests__/server.cors.test.js.map +1 -0
  51. package/dist/fork/api.d.ts +9 -1
  52. package/dist/fork/api.d.ts.map +1 -1
  53. package/dist/fork/api.js +37 -7
  54. package/dist/fork/api.js.map +1 -1
  55. package/dist/fork/server.d.ts +20 -1
  56. package/dist/fork/server.d.ts.map +1 -1
  57. package/dist/fork/server.js +19 -9
  58. package/dist/fork/server.js.map +1 -1
  59. package/dist/harness/Harness.d.ts +6 -2
  60. package/dist/harness/Harness.d.ts.map +1 -1
  61. package/dist/harness/Harness.js +8 -2
  62. package/dist/harness/Harness.js.map +1 -1
  63. package/dist/harness/codeObject.d.ts.map +1 -1
  64. package/dist/harness/codeObject.js +30 -33
  65. package/dist/harness/codeObject.js.map +1 -1
  66. package/dist/harness/script.d.ts +3 -3
  67. package/dist/harness/script.d.ts.map +1 -1
  68. package/dist/harness/script.js +33 -29
  69. package/dist/harness/script.js.map +1 -1
  70. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.d.ts +2 -0
  71. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.d.ts.map +1 -0
  72. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.js +172 -0
  73. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.js.map +1 -0
  74. package/dist/helpers/setupLocalTesting.d.ts.map +1 -1
  75. package/dist/helpers/setupLocalTesting.js +28 -2
  76. package/dist/helpers/setupLocalTesting.js.map +1 -1
  77. package/dist/index.d.ts +1 -0
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/node/LocalNodeManager.d.ts +8 -0
  80. package/dist/node/LocalNodeManager.d.ts.map +1 -1
  81. package/dist/node/LocalNodeManager.js +10 -1
  82. package/dist/node/LocalNodeManager.js.map +1 -1
  83. package/dist/node/__tests__/LocalNodeManager.api-port.test.d.ts +2 -0
  84. package/dist/node/__tests__/LocalNodeManager.api-port.test.d.ts.map +1 -0
  85. package/dist/node/__tests__/LocalNodeManager.api-port.test.js +55 -0
  86. package/dist/node/__tests__/LocalNodeManager.api-port.test.js.map +1 -0
  87. package/dist/node/__tests__/LocalNodeManager.test.js +4 -3
  88. package/dist/node/__tests__/LocalNodeManager.test.js.map +1 -1
  89. package/dist/templates/move/Move.toml +1 -1
  90. package/dist/templates/move/sources/Counter.move +31 -4
  91. package/dist/templates/scripts/deploy-counter.ts +10 -0
  92. package/dist/types/config.d.ts +8 -1
  93. package/dist/types/config.d.ts.map +1 -1
  94. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.d.ts +2 -0
  95. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.d.ts.map +1 -0
  96. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.js +43 -0
  97. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.js.map +1 -0
  98. package/dist/utils/childProcessAdapter.d.ts +7 -0
  99. package/dist/utils/childProcessAdapter.d.ts.map +1 -1
  100. package/dist/utils/childProcessAdapter.js +20 -2
  101. package/dist/utils/childProcessAdapter.js.map +1 -1
  102. package/package.json +1 -1
  103. package/src/__tests__/deployContract.test.ts +59 -50
  104. package/src/__tests__/exports.test.ts +32 -0
  105. package/src/__tests__/fixtures/sigint-deploy-harness.ts +8 -7
  106. package/src/__tests__/fork/api.test.ts +5 -0
  107. package/src/__tests__/fork/api.timeout.test.ts +150 -0
  108. package/src/commands/__tests__/compile.toml-mutation.test.ts +77 -0
  109. package/src/commands/__tests__/init.test.ts +96 -11
  110. package/src/commands/init.ts +77 -6
  111. package/src/core/AccountManager.ts +18 -1
  112. package/src/core/Publisher.ts +58 -77
  113. package/src/core/__tests__/AccountManager.global-state.test.ts +83 -0
  114. package/src/core/__tests__/movementProfile.test.ts +131 -0
  115. package/src/core/config.ts +9 -5
  116. package/src/core/movementProfile.ts +75 -127
  117. package/src/fork/__tests__/server.cors.test.ts +101 -0
  118. package/src/fork/api.ts +69 -10
  119. package/src/fork/server.ts +38 -9
  120. package/src/harness/Harness.ts +11 -2
  121. package/src/harness/codeObject.ts +37 -43
  122. package/src/harness/script.ts +40 -39
  123. package/src/helpers/__tests__/setupLocalTesting.fork-network.test.ts +212 -0
  124. package/src/helpers/setupLocalTesting.ts +36 -2
  125. package/src/index.ts +9 -1
  126. package/src/node/LocalNodeManager.ts +24 -2
  127. package/src/node/__tests__/LocalNodeManager.api-port.test.ts +62 -0
  128. package/src/node/__tests__/LocalNodeManager.test.ts +4 -3
  129. package/src/templates/move/Move.toml +1 -1
  130. package/src/templates/move/sources/Counter.move +31 -4
  131. package/src/templates/scripts/deploy-counter.ts +10 -0
  132. package/src/types/config.ts +8 -1
  133. package/src/utils/__tests__/childProcessAdapter.maxBuffer.test.ts +51 -0
  134. package/src/utils/childProcessAdapter.ts +32 -2
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import * as publicSurface from "../index.js";
3
+
4
+ /**
5
+ * Locks the public export surface of `movehat`. Adding a new symbol
6
+ * is a deliberate API change; removing one is a breaking change.
7
+ * Update this list (and the CHANGELOG) when the surface evolves.
8
+ */
9
+ const EXPECTED_RUNTIME_EXPORTS = [
10
+ "Harness",
11
+ "HarnessDisposedError",
12
+ "ForkManager",
13
+ "MovementApiClient",
14
+ "ForkStorage",
15
+ "ForkServer",
16
+ "ModuleAlreadyDeployedError",
17
+ "PostPublishError",
18
+ "initRuntime",
19
+ ] as const;
20
+
21
+ describe("public export surface (movehat root)", () => {
22
+ it.each(EXPECTED_RUNTIME_EXPORTS)("exports %s as a runtime value", (name) => {
23
+ expect(publicSurface[name as keyof typeof publicSurface]).toBeDefined();
24
+ });
25
+
26
+ // Type-only exports cannot be probed at runtime; the assertion is
27
+ // that the module imports successfully (failing types-only export
28
+ // would surface as a TS error in `pnpm check:example`).
29
+ it("imports without errors", () => {
30
+ expect(typeof publicSurface).toBe("object");
31
+ });
32
+ });
@@ -9,9 +9,10 @@
9
9
  * send SIGINT mid-flight.
10
10
  * 2. Drive `Publisher.deploy()` against the fake adapter using a
11
11
  * synthetic MovehatConfig + Account read from env vars.
12
- * 3. Write the chosen `movehat-deploy-<uuid>` profile name to stdout
13
- * as JSON (`{"profile": "..."}`) before the slow publish so the
14
- * parent test knows which key to look for after SIGINT.
12
+ * 3. Write the temp key file path to stdout as JSON
13
+ * (`{"keyFile": "/tmp/movehat-key-<uuid>"}`) before the slow
14
+ * publish so the parent test knows which file to look for after
15
+ * SIGINT.
15
16
  * 4. If the deploy completes naturally (test failure case), exit 0.
16
17
  * 5. When SIGINT arrives, Publisher's signal handler runs synchronous
17
18
  * cleanup and `setImmediate(() => process.exit(130))`.
@@ -61,10 +62,10 @@ async function main() {
61
62
  return { exitCode: 0, stdout: "built", stderr: "" };
62
63
  }
63
64
  if (input.args[1] === "publish") {
64
- // Surface the unique profile name to the parent BEFORE blocking.
65
- const profileIdx = input.args.indexOf("--profile");
66
- const profile = profileIdx >= 0 ? input.args[profileIdx + 1] : "";
67
- process.stdout.write(JSON.stringify({ profile }) + "\n");
65
+ // Surface the temp key file path to the parent BEFORE blocking.
66
+ const keyFileIdx = input.args.indexOf("--private-key-file");
67
+ const keyFile = keyFileIdx >= 0 ? input.args[keyFileIdx + 1] : "";
68
+ process.stdout.write(JSON.stringify({ keyFile }) + "\n");
68
69
  // Hold long enough for the parent to deliver SIGINT.
69
70
  await new Promise((r) => setTimeout(r, 3000));
70
71
  return {
@@ -77,6 +77,11 @@ function setupGetCapture(): {
77
77
 
78
78
  const fakeReq = new EventEmitter() as unknown as ClientRequest;
79
79
  (fakeReq as unknown as { end: () => void }).end = () => {};
80
+ // F3: api.ts now installs a setTimeout on the request and may call
81
+ // destroy() on overflow / timeout. Stub both so this happy-path
82
+ // capture mock still satisfies the new contract.
83
+ (fakeReq as unknown as { setTimeout: (ms: number, cb?: () => void) => void }).setTimeout = () => {};
84
+ (fakeReq as unknown as { destroy: () => void }).destroy = () => {};
80
85
 
81
86
  if (callback) {
82
87
  const body = JSON.stringify({
@@ -0,0 +1,150 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import type { ClientRequest, IncomingMessage } from "node:http";
3
+ import { EventEmitter } from "node:events";
4
+
5
+ /**
6
+ * F3 — MovementApiClient must bound responses by time AND bytes.
7
+ *
8
+ * Without these guards a malicious / hung upstream can:
9
+ * - leak the request promise forever (never emits 'end'), or
10
+ * - exhaust heap by pushing unbounded `data` chunks.
11
+ *
12
+ * Strategy mirrors src/__tests__/fork/api.test.ts: vi.mock node:http
13
+ * and node:https, intercept `client.get(url, options, cb)`, and feed
14
+ * a controllable `IncomingMessage` to the callback. The fake
15
+ * `ClientRequest` exposes `setTimeout`, `destroy`, and emits 'error' /
16
+ * 'timeout' so we can drive the failure modes from the test.
17
+ */
18
+
19
+ interface FakeReq extends EventEmitter {
20
+ end(): void;
21
+ destroy(err?: Error): void;
22
+ setTimeout(ms: number, cb?: () => void): void;
23
+ destroyed: boolean;
24
+ }
25
+
26
+ const httpsGet = vi.fn();
27
+ const httpGet = vi.fn();
28
+
29
+ vi.mock("https", () => ({ default: { get: httpsGet }, get: httpsGet }));
30
+ vi.mock("http", () => ({ default: { get: httpGet }, get: httpGet }));
31
+
32
+ function makeFakeReq(): FakeReq {
33
+ const req = new EventEmitter() as FakeReq;
34
+ req.destroyed = false;
35
+ let timeoutHandle: NodeJS.Timeout | undefined;
36
+ req.end = () => {};
37
+ req.destroy = (err?: Error) => {
38
+ req.destroyed = true;
39
+ if (timeoutHandle) clearTimeout(timeoutHandle);
40
+ setImmediate(() => req.emit("error", err ?? new Error("destroyed")));
41
+ };
42
+ req.setTimeout = (ms: number, cb?: () => void) => {
43
+ timeoutHandle = setTimeout(() => {
44
+ req.emit("timeout");
45
+ if (cb) cb();
46
+ }, ms);
47
+ // Don't keep the event loop alive — Node sets this itself but the
48
+ // mock has no native socket to inherit from.
49
+ timeoutHandle.unref?.();
50
+ };
51
+ return req;
52
+ }
53
+
54
+ function makeUnresolvableResponse(): IncomingMessage {
55
+ const res = new EventEmitter() as unknown as IncomingMessage;
56
+ (res as unknown as { statusCode: number }).statusCode = 200;
57
+ return res;
58
+ }
59
+
60
+ function makeStreamingResponse(
61
+ bytesPerChunk: number,
62
+ chunks: number
63
+ ): IncomingMessage {
64
+ const res = new EventEmitter() as unknown as IncomingMessage;
65
+ (res as unknown as { statusCode: number }).statusCode = 200;
66
+ setImmediate(() => {
67
+ let i = 0;
68
+ const pump = () => {
69
+ if (i >= chunks) {
70
+ (res as unknown as EventEmitter).emit("end");
71
+ return;
72
+ }
73
+ (res as unknown as EventEmitter).emit(
74
+ "data",
75
+ Buffer.alloc(bytesPerChunk, 0x61)
76
+ );
77
+ i++;
78
+ setImmediate(pump);
79
+ };
80
+ pump();
81
+ });
82
+ return res;
83
+ }
84
+
85
+ describe("F3 — MovementApiClient timeouts and byte cap", () => {
86
+ beforeEach(() => {
87
+ httpsGet.mockReset();
88
+ httpGet.mockReset();
89
+ });
90
+
91
+ afterEach(() => {
92
+ vi.restoreAllMocks();
93
+ });
94
+
95
+ it("rejects with a timeout error when the upstream never responds", async () => {
96
+ const fakeReq = makeFakeReq();
97
+ httpGet.mockImplementation(
98
+ (
99
+ _url: string,
100
+ options: unknown,
101
+ cb?: (res: IncomingMessage) => void
102
+ ) => {
103
+ const callback =
104
+ typeof options === "function"
105
+ ? (options as (r: IncomingMessage) => void)
106
+ : cb;
107
+ if (callback) callback(makeUnresolvableResponse());
108
+ return fakeReq as unknown as ClientRequest;
109
+ }
110
+ );
111
+
112
+ const { MovementApiClient } = await import("../../fork/api.js");
113
+ const client = new MovementApiClient("http://hung.example/v1", undefined, {
114
+ timeoutMs: 25,
115
+ maxBytes: 1024 * 1024,
116
+ });
117
+
118
+ await expect(client.getLedgerInfo()).rejects.toThrow(/timed out|timeout/i);
119
+ expect(fakeReq.destroyed).toBe(true);
120
+ });
121
+
122
+ it("rejects and destroys the request when the response exceeds maxBytes", async () => {
123
+ const fakeReq = makeFakeReq();
124
+ httpGet.mockImplementation(
125
+ (
126
+ _url: string,
127
+ options: unknown,
128
+ cb?: (res: IncomingMessage) => void
129
+ ) => {
130
+ const callback =
131
+ typeof options === "function"
132
+ ? (options as (r: IncomingMessage) => void)
133
+ : cb;
134
+ if (callback) callback(makeStreamingResponse(2048, 100));
135
+ return fakeReq as unknown as ClientRequest;
136
+ }
137
+ );
138
+
139
+ const { MovementApiClient } = await import("../../fork/api.js");
140
+ const client = new MovementApiClient("http://big.example/v1", undefined, {
141
+ timeoutMs: 5000,
142
+ maxBytes: 4096,
143
+ });
144
+
145
+ await expect(client.getLedgerInfo()).rejects.toThrow(
146
+ /maxBytes|too large|exceeded/i
147
+ );
148
+ expect(fakeReq.destroyed).toBe(true);
149
+ });
150
+ });
@@ -0,0 +1,77 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { vol, fs as memfsFs } from "memfs";
3
+
4
+ vi.mock("fs", () => {
5
+ return {
6
+ default: memfsFs,
7
+ ...memfsFs,
8
+ };
9
+ });
10
+
11
+ import { updateMoveToml } from "../compile.js";
12
+
13
+ /**
14
+ * F7 — `movehat compile` mutates `Move.toml` when it detects a named
15
+ * address that isn't declared yet. This test pins down the current
16
+ * behavior so a future change (introducing a `--write` flag, moving
17
+ * the mutation to a dedicated `movehat update-toml` command, etc.)
18
+ * MUST update this test alongside the source change.
19
+ *
20
+ * Audit finding F7 is marked "no concluyente — requires product
21
+ * decision": the mutation may be the right UX default for the
22
+ * Hardhat-style workflow, but the asymmetry (compile reading + writing)
23
+ * deserves to be a deliberate choice. See ROADMAP follow-up.
24
+ */
25
+ describe("F7 — updateMoveToml mutates Move.toml on disk (current behavior captured)", () => {
26
+ beforeEach(() => vol.reset());
27
+ afterEach(() => vol.reset());
28
+
29
+ it("writes new named addresses into [addresses] and [dev-addresses] when missing", () => {
30
+ const before = `[package]
31
+ name = "captured"
32
+ version = "1.0.0"
33
+
34
+ [addresses]
35
+ existing = "_"
36
+
37
+ [dev-addresses]
38
+ existing = "0xcafe"
39
+
40
+ [dependencies]
41
+ `;
42
+ vol.fromJSON({ "/move/Move.toml": before });
43
+
44
+ const detected = new Set(["existing", "audit_module"]);
45
+ const added = updateMoveToml("/move", detected);
46
+
47
+ expect(added).toEqual(["audit_module"]);
48
+
49
+ // Source-of-truth assertion: the on-disk file CHANGED. F7 is the
50
+ // observation that a "compile" verb has a side effect on the user's
51
+ // working tree. The behavior is captured here so an unintended
52
+ // regression (or a deliberate revisit) cannot land silently.
53
+ const after = vol.readFileSync("/move/Move.toml", "utf-8") as string;
54
+ expect(after).not.toBe(before);
55
+ expect(after).toContain("audit_module = \"_\"");
56
+ });
57
+
58
+ it("returns an empty list and leaves Move.toml byte-identical when all named addresses are already declared", () => {
59
+ const before = `[package]
60
+ name = "captured"
61
+
62
+ [addresses]
63
+ existing = "_"
64
+
65
+ [dev-addresses]
66
+ existing = "0xcafe"
67
+ `;
68
+ vol.fromJSON({ "/move/Move.toml": before });
69
+
70
+ const added = updateMoveToml("/move", new Set(["existing"]));
71
+ expect(added).toEqual([]);
72
+ // No mutation in the no-op path — the asymmetry only triggers when
73
+ // detected ⊄ declared. Useful boundary for the F7 product decision.
74
+ const after = vol.readFileSync("/move/Move.toml", "utf-8") as string;
75
+ expect(after).toBe(before);
76
+ });
77
+ });
@@ -13,7 +13,8 @@ vi.mock("../../helpers/banner.js", () => ({
13
13
  printMovehatBanner: () => undefined,
14
14
  }));
15
15
 
16
- const { default: initCommand } = await import("../init.js");
16
+ const initModule = await import("../init.js");
17
+ const { default: initCommand, resolveProjectNames, InvalidProjectNameError } = initModule;
17
18
 
18
19
  /**
19
20
  * Strategy: real tmpdir + real fs ops (matches §6.1's example-as-canonical
@@ -28,10 +29,38 @@ const { default: initCommand } = await import("../init.js");
28
29
  * to `src/templates/` cleanly. No bundling step required.
29
30
  */
30
31
 
32
+ describe("resolveProjectNames", () => {
33
+ const cases: Array<[
34
+ string,
35
+ { dirName: string; npmName: string; moveName: string; sanitized: boolean }
36
+ ]> = [
37
+ ["my_project", { dirName: "my_project", npmName: "my_project", moveName: "my_project", sanitized: false }],
38
+ ["my-project", { dirName: "my-project", npmName: "my-project", moveName: "my_project", sanitized: true }],
39
+ ["/tmp/my-project", { dirName: "/tmp/my-project", npmName: "my-project", moveName: "my_project", sanitized: true }],
40
+ ["123abc", { dirName: "123abc", npmName: "123abc", moveName: "pkg_123abc", sanitized: true }],
41
+ ["_underscore", { dirName: "_underscore", npmName: "_underscore", moveName: "_underscore", sanitized: false }],
42
+ ["UPPER", { dirName: "UPPER", npmName: "UPPER", moveName: "UPPER", sanitized: false }],
43
+ [" spaced ", { dirName: "spaced", npmName: "spaced", moveName: "spaced", sanitized: false }],
44
+ ["with spaces", { dirName: "with spaces", npmName: "with spaces", moveName: "with_spaces", sanitized: true }],
45
+ ];
46
+
47
+ it.each(cases)("derives names for %j", (input, expected) => {
48
+ expect(resolveProjectNames(input)).toEqual(expected);
49
+ });
50
+
51
+ it.each(["", " ", ".", "..", "/", "////"])(
52
+ "rejects %j as an invalid project name",
53
+ (input) => {
54
+ expect(() => resolveProjectNames(input)).toThrow(InvalidProjectNameError);
55
+ }
56
+ );
57
+ });
58
+
31
59
  describe("initCommand", () => {
32
60
  let tmpParent: string;
33
61
  let origCwd: string;
34
62
  let exitSpy: ReturnType<typeof vi.spyOn>;
63
+ let warnSpy: ReturnType<typeof vi.spyOn>;
35
64
 
36
65
  beforeEach(() => {
37
66
  promptsMock.mockReset();
@@ -48,6 +77,7 @@ describe("initCommand", () => {
48
77
  }) as never);
49
78
  vi.spyOn(console, "log").mockImplementation(() => undefined);
50
79
  vi.spyOn(console, "error").mockImplementation(() => undefined);
80
+ warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
51
81
  });
52
82
 
53
83
  afterEach(() => {
@@ -59,9 +89,9 @@ describe("initCommand", () => {
59
89
  });
60
90
 
61
91
  it("happy path: scaffolds a project from the canonical template", async () => {
62
- await initCommand("my-test-project");
92
+ await initCommand("my_test_project");
63
93
 
64
- const target = join(tmpParent, "my-test-project");
94
+ const target = join(tmpParent, "my_test_project");
65
95
  expect(existsSync(target)).toBe(true);
66
96
  // Canonical files at the project root.
67
97
  expect(existsSync(join(target, "package.json"))).toBe(true);
@@ -78,32 +108,37 @@ describe("initCommand", () => {
78
108
  // Excluded template-development directory.
79
109
  expect(existsSync(join(target, "types"))).toBe(false);
80
110
  expect(existsSync(join(target, ".vscode"))).toBe(false);
111
+ // Move.toml gets a valid Move identifier.
112
+ const moveToml = readFileSync(join(target, "move", "Move.toml"), "utf-8");
113
+ expect(moveToml).toContain('name = "my_test_project"');
114
+ expect(moveToml).not.toContain("{{movePackageName}}");
115
+ expect(moveToml).not.toContain("{{projectName}}");
81
116
  });
82
117
 
83
118
  it("substitutes {{projectName}} placeholders inside template files", async () => {
84
- await initCommand("substituted-project");
119
+ await initCommand("substituted_project");
85
120
 
86
121
  const pkg = readFileSync(
87
- join(tmpParent, "substituted-project", "package.json"),
122
+ join(tmpParent, "substituted_project", "package.json"),
88
123
  "utf-8"
89
124
  );
90
- expect(pkg).toContain("substituted-project");
125
+ expect(pkg).toContain("substituted_project");
91
126
  expect(pkg).not.toContain("{{projectName}}");
92
127
 
93
128
  const readme = readFileSync(
94
- join(tmpParent, "substituted-project", "README.md"),
129
+ join(tmpParent, "substituted_project", "README.md"),
95
130
  "utf-8"
96
131
  );
97
- expect(readme).toContain("substituted-project");
132
+ expect(readme).toContain("substituted_project");
98
133
  });
99
134
 
100
135
  it("prompts for project name when none is provided", async () => {
101
- promptsMock.mockResolvedValueOnce({ projectName: "from-prompt" });
136
+ promptsMock.mockResolvedValueOnce({ projectName: "from_prompt" });
102
137
 
103
138
  await initCommand();
104
139
 
105
140
  expect(promptsMock).toHaveBeenCalledTimes(1);
106
- expect(existsSync(join(tmpParent, "from-prompt"))).toBe(true);
141
+ expect(existsSync(join(tmpParent, "from_prompt"))).toBe(true);
107
142
  });
108
143
 
109
144
  it("exits 0 when the user Ctrl+Cs the prompt (no project created)", async () => {
@@ -116,10 +151,60 @@ describe("initCommand", () => {
116
151
  it("exits 1 when the template copy step hits an unwriteable target", async () => {
117
152
  // Plant a directory where the command will try to write package.json
118
153
  // as a file — fs.writeFile rejects with EISDIR.
119
- const targetName = "blocked-project";
154
+ const targetName = "blocked_project";
120
155
  mkdirSync(join(tmpParent, targetName, "package.json"), { recursive: true });
121
156
 
122
157
  await expect(initCommand(targetName)).rejects.toThrow("__test_exit_1__");
123
158
  expect(exitSpy).toHaveBeenCalledWith(1);
124
159
  });
160
+
161
+ it("sanitizes Move.toml for hyphenated names but keeps package.json original", async () => {
162
+ await initCommand("my-project");
163
+
164
+ const target = join(tmpParent, "my-project");
165
+ expect(existsSync(target)).toBe(true);
166
+ // package.json keeps the original (npm allows hyphens).
167
+ const pkg = readFileSync(join(target, "package.json"), "utf-8");
168
+ expect(pkg).toContain('"my-project"');
169
+ // Move.toml gets the sanitized identifier.
170
+ const moveToml = readFileSync(join(target, "move", "Move.toml"), "utf-8");
171
+ expect(moveToml).toContain('name = "my_project"');
172
+ expect(moveToml).not.toContain('"my-project"');
173
+ // Warning was emitted.
174
+ expect(warnSpy).toHaveBeenCalled();
175
+ const warningText = warnSpy.mock.calls.flat().join(" ");
176
+ expect(warningText).toContain("my-project");
177
+ expect(warningText).toContain("my_project");
178
+ });
179
+
180
+ it("with a path argument, creates the dir at the full path and sanitizes Move.toml", async () => {
181
+ const nestedPath = join(tmpParent, "nested", "sub-project");
182
+
183
+ await initCommand(nestedPath);
184
+
185
+ expect(existsSync(nestedPath)).toBe(true);
186
+ const moveToml = readFileSync(join(nestedPath, "move", "Move.toml"), "utf-8");
187
+ expect(moveToml).toContain('name = "sub_project"');
188
+ const pkg = readFileSync(join(nestedPath, "package.json"), "utf-8");
189
+ expect(pkg).toContain('"sub-project"');
190
+ });
191
+
192
+ it("prefixes Move.toml package name with pkg_ for names that start with a digit", async () => {
193
+ await initCommand("123abc");
194
+
195
+ const moveToml = readFileSync(
196
+ join(tmpParent, "123abc", "move", "Move.toml"),
197
+ "utf-8"
198
+ );
199
+ expect(moveToml).toContain('name = "pkg_123abc"');
200
+ expect(warnSpy).toHaveBeenCalled();
201
+ });
202
+
203
+ it.each([".", "..", "/", " "])(
204
+ "rejects %j as an invalid project name and exits 1",
205
+ async (input) => {
206
+ await expect(initCommand(input)).rejects.toThrow("__test_exit_1__");
207
+ expect(exitSpy).toHaveBeenCalledWith(1);
208
+ }
209
+ );
125
210
  });
@@ -8,6 +8,60 @@ import { logger, createSpinnerChain, formatCommand } from "../ui/index.js";
8
8
  const __filename = fileURLToPath(import.meta.url);
9
9
  const __dirname = path.dirname(__filename);
10
10
 
11
+ export class InvalidProjectNameError extends Error {
12
+ constructor(message: string) {
13
+ super(message);
14
+ this.name = "InvalidProjectNameError";
15
+ }
16
+ }
17
+
18
+ export interface ProjectNames {
19
+ /** User input as-is (after trim) — used for the filesystem target. */
20
+ dirName: string;
21
+ /** Basename of the resolved path — used for package.json + README.md. */
22
+ npmName: string;
23
+ /** Valid Move identifier — used for Move.toml. */
24
+ moveName: string;
25
+ /** True when moveName had to diverge from npmName to satisfy Move identifier rules. */
26
+ sanitized: boolean;
27
+ }
28
+
29
+ /**
30
+ * Derive filesystem, npm, and Move identifier names from a single user input.
31
+ *
32
+ * Move identifiers must match `[a-zA-Z_][a-zA-Z0-9_]*`. npm package names are
33
+ * looser (hyphens allowed). The filesystem accepts almost anything. Rather
34
+ * than reject inputs that would compile fine for npm but not for Move, we
35
+ * sanitize the Move identifier and leave the npm name + dir unchanged.
36
+ */
37
+ export function resolveProjectNames(input: string): ProjectNames {
38
+ const trimmed = input.trim();
39
+ if (
40
+ trimmed === "" ||
41
+ trimmed === "." ||
42
+ trimmed === ".." ||
43
+ /^\/+$/.test(trimmed)
44
+ ) {
45
+ throw new InvalidProjectNameError(
46
+ `Project name '${input}' must include at least one character besides path separators.`
47
+ );
48
+ }
49
+
50
+ const dirName = trimmed;
51
+ const npmName = path.basename(path.resolve(trimmed));
52
+ let moveName = npmName.replace(/[^a-zA-Z0-9_]/g, "_");
53
+ if (!/^[a-zA-Z_]/.test(moveName)) {
54
+ moveName = `pkg_${moveName}`;
55
+ }
56
+
57
+ return {
58
+ dirName,
59
+ npmName,
60
+ moveName,
61
+ sanitized: moveName !== npmName,
62
+ };
63
+ }
64
+
11
65
  /**
12
66
  * Initialize a new Movehat project with template files
13
67
  *
@@ -49,8 +103,25 @@ export default async function initCommand(projectName?: string) {
49
103
  projectName = response.projectName;
50
104
  }
51
105
 
52
- const targetDir = projectName!;
53
- const projectPath = path.resolve(process.cwd(), targetDir);
106
+ let names: ProjectNames;
107
+ try {
108
+ names = resolveProjectNames(projectName!);
109
+ } catch (error) {
110
+ if (error instanceof InvalidProjectNameError) {
111
+ logger.error(error.message);
112
+ process.exit(1);
113
+ }
114
+ throw error;
115
+ }
116
+
117
+ const { dirName, npmName, moveName, sanitized } = names;
118
+ const projectPath = path.resolve(process.cwd(), dirName);
119
+
120
+ if (sanitized) {
121
+ logger.warning(
122
+ `'${npmName}' is not a valid Move identifier; using '${moveName}' for move/Move.toml. (package.json keeps '${npmName}'.)`
123
+ );
124
+ }
54
125
 
55
126
  logger.newline();
56
127
  logger.info(`Initializing new Movehat project in ${projectPath}...`);
@@ -67,7 +138,7 @@ export default async function initCommand(projectName?: string) {
67
138
  await copyFile(
68
139
  path.join(templatesDir, "package.json"),
69
140
  path.join(projectPath, "package.json"),
70
- { projectName: projectName! }
141
+ { projectName: npmName }
71
142
  );
72
143
 
73
144
  await copyFile(
@@ -98,7 +169,7 @@ export default async function initCommand(projectName?: string) {
98
169
  await copyFile(
99
170
  path.join(templatesDir, "README.md"),
100
171
  path.join(projectPath, "README.md"),
101
- { projectName: projectName! }
172
+ { projectName: npmName }
102
173
  );
103
174
  });
104
175
 
@@ -107,7 +178,7 @@ export default async function initCommand(projectName?: string) {
107
178
  await copyDir(
108
179
  path.join(templatesDir, "move"),
109
180
  path.join(projectPath, "move"),
110
- { projectName: projectName! }
181
+ { projectName: npmName, movePackageName: moveName }
111
182
  );
112
183
  });
113
184
 
@@ -136,7 +207,7 @@ export default async function initCommand(projectName?: string) {
136
207
 
137
208
  // Next steps
138
209
  logger.section('Next steps');
139
- logger.item(formatCommand(`cd ${projectName}`), 2);
210
+ logger.item(formatCommand(`cd ${dirName}`), 2);
140
211
  logger.item(formatCommand('cp .env.example .env'), 2);
141
212
  logger.plain(' # Edit .env with your credentials');
142
213
  logger.item(formatCommand('npm install'), 2);
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  Account,
3
3
  Ed25519PrivateKey,
4
+ PrivateKey,
5
+ PrivateKeyVariants,
4
6
  } from "@aptos-labs/ts-sdk";
5
7
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
6
8
  import { join } from "path";
@@ -25,10 +27,18 @@ interface AccountPool {
25
27
  * Provides a pool of reusable test accounts with labels for better test readability.
26
28
  */
27
29
  export class AccountManager {
30
+ // Class-static maps: shared across every consumer in the same Node
31
+ // process (e.g. two Harness instances). Re-using a label across
32
+ // "sessions" overwrites the labelMap entry. Documented + fixed by
33
+ // contract in `AccountManager.global-state.test.ts` (audit F8).
28
34
  private static pool: Map<string, Account> = new Map(); // address → Account
29
35
  private static privateKeys: Map<string, string> = new Map(); // address → privateKey hex
30
36
  private static labelMap: Map<string, string> = new Map(); // label → address
31
37
  private static poolLoaded = false;
38
+ // `defaultPoolPath` is captured ONCE at module-import time. A later
39
+ // `process.chdir(...)` does NOT redirect the save destination — pass
40
+ // an explicit `poolPath` to `saveAccountPool`/`loadAccountPool` when
41
+ // per-test isolation matters. See audit finding F8.
32
42
  private static defaultPoolPath = join(process.cwd(), ".movehat", "accounts");
33
43
 
34
44
  /**
@@ -131,7 +141,14 @@ export class AccountManager {
131
141
  * const account = AccountManager.loadAccountFromPrivateKey("0xabc123...");
132
142
  */
133
143
  static loadAccountFromPrivateKey(privateKeyHex: string): Account {
134
- const privateKey = new Ed25519PrivateKey(privateKeyHex);
144
+ // Format into AIP-80 shape (`ed25519-priv-0x…`) before constructing
145
+ // the SDK type. Without this, raw-hex inputs trigger a noisy
146
+ // deprecation warning from `@aptos-labs/ts-sdk` on every call.
147
+ const formatted = PrivateKey.formatPrivateKey(
148
+ privateKeyHex,
149
+ PrivateKeyVariants.Ed25519,
150
+ );
151
+ const privateKey = new Ed25519PrivateKey(formatted);
135
152
  const account = Account.fromPrivateKey({ privateKey });
136
153
  const address = account.accountAddress.toString();
137
154