@turingcode/cli 0.2.13 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/README.md +2 -0
  2. package/dist/cli/create-cli.d.ts +10 -0
  3. package/dist/cli/create-cli.js +12 -1
  4. package/dist/cli/index.d.ts +9 -0
  5. package/dist/cli/index.js +5 -1
  6. package/dist/core/bound-error.d.ts +10 -0
  7. package/dist/core/date.d.ts +12 -0
  8. package/dist/core/exact/expression.d.ts +49 -0
  9. package/dist/core/exact/fraction.d.ts +85 -0
  10. package/dist/core/files.d.ts +44 -0
  11. package/dist/core/files.js +46 -1
  12. package/dist/core/json-shape.d.ts +45 -0
  13. package/dist/core/mcp.d.ts +92 -0
  14. package/dist/core/mcp.js +56 -15
  15. package/dist/core/query.d.ts +69 -0
  16. package/dist/core/report.d.ts +11 -0
  17. package/dist/core/tables/csv.d.ts +18 -0
  18. package/dist/core/tables/markdown.d.ts +22 -0
  19. package/dist/core/tables/types.d.ts +25 -0
  20. package/dist/features/contract/check.d.ts +30 -0
  21. package/dist/features/contract/command.d.ts +12 -0
  22. package/dist/features/contract/command.js +64 -64
  23. package/dist/features/contract/describe.d.ts +22 -0
  24. package/dist/features/contract/diagnostics.d.ts +108 -0
  25. package/dist/features/contract/load.d.ts +58 -0
  26. package/dist/features/contract/model.d.ts +67 -0
  27. package/dist/features/contract/rules.d.ts +137 -0
  28. package/dist/features/debug/clear_breakpoint.d.ts +2 -0
  29. package/dist/features/debug/clear_breakpoint.js +24 -0
  30. package/dist/features/debug/command.d.ts +5 -0
  31. package/dist/features/debug/command.js +66 -0
  32. package/dist/features/debug/continue.d.ts +2 -0
  33. package/dist/features/debug/continue.js +22 -0
  34. package/dist/features/debug/debug_start.d.ts +2 -0
  35. package/dist/features/debug/debug_start.js +22 -0
  36. package/dist/features/debug/debug_stop.d.ts +2 -0
  37. package/dist/features/debug/debug_stop.js +11 -0
  38. package/dist/features/debug/evaluate.d.ts +2 -0
  39. package/dist/features/debug/evaluate.js +48 -0
  40. package/dist/features/debug/get_stack.d.ts +2 -0
  41. package/dist/features/debug/get_stack.js +14 -0
  42. package/dist/features/debug/get_variables.d.ts +2 -0
  43. package/dist/features/debug/get_variables.js +26 -0
  44. package/dist/features/debug/halt.d.ts +2 -0
  45. package/dist/features/debug/halt.js +16 -0
  46. package/dist/features/debug/set_breakpoint.d.ts +2 -0
  47. package/dist/features/debug/set_breakpoint.js +30 -0
  48. package/dist/features/debug/step.d.ts +2 -0
  49. package/dist/features/debug/step.js +23 -0
  50. package/dist/features/install-mods/command.d.ts +6 -0
  51. package/dist/features/install-mods/command.js +18 -0
  52. package/dist/features/install-mods/install.d.ts +23 -0
  53. package/dist/features/install-mods/install.js +48 -0
  54. package/dist/features/install-skills/command.d.ts +7 -0
  55. package/dist/features/install-skills/command.js +22 -0
  56. package/dist/features/install-skills/install.d.ts +13 -0
  57. package/dist/features/install-skills/install.js +29 -0
  58. package/dist/features/probe/command.d.ts +5 -0
  59. package/dist/features/probe/command.js +44 -0
  60. package/dist/features/probe/kill_all_debuggers.d.ts +2 -0
  61. package/dist/features/probe/kill_all_debuggers.js +50 -0
  62. package/dist/features/probe/list_probes.d.ts +2 -0
  63. package/dist/features/probe/list_probes.js +8 -0
  64. package/dist/features/probe/program_project.d.ts +2 -0
  65. package/dist/features/probe/program_project.js +29 -0
  66. package/dist/features/probe/read_fault_status.d.ts +2 -0
  67. package/dist/features/probe/read_fault_status.js +19 -0
  68. package/dist/features/probe/read_memory.d.ts +2 -0
  69. package/dist/features/probe/read_memory.js +36 -0
  70. package/dist/features/probe/read_peripheral.d.ts +2 -0
  71. package/dist/features/probe/read_peripheral.js +58 -0
  72. package/dist/features/probe/reset_probe_usb.d.ts +2 -0
  73. package/dist/features/probe/reset_probe_usb.js +17 -0
  74. package/dist/features/probe/reset_target.d.ts +2 -0
  75. package/dist/features/probe/reset_target.js +16 -0
  76. package/dist/features/probe/target_info.d.ts +2 -0
  77. package/dist/features/probe/target_info.js +34 -0
  78. package/dist/features/project/analysis_static.d.ts +2 -0
  79. package/dist/features/project/analysis_static.js +19 -0
  80. package/dist/features/project/analysis_syntax_check.d.ts +2 -0
  81. package/dist/features/project/analysis_syntax_check.js +21 -0
  82. package/dist/features/project/command.d.ts +5 -0
  83. package/dist/features/project/command.js +64 -0
  84. package/dist/features/project/project_build.d.ts +2 -0
  85. package/dist/features/project/project_build.js +22 -0
  86. package/dist/features/project/project_download_template.d.ts +2 -0
  87. package/dist/features/project/project_download_template.js +34 -0
  88. package/dist/features/project/project_regenerate.d.ts +2 -0
  89. package/dist/features/project/project_regenerate.js +20 -0
  90. package/dist/features/project/project_sync_from_server.d.ts +2 -0
  91. package/dist/features/project/project_sync_from_server.js +13 -0
  92. package/dist/features/project/project_sync_to_server.d.ts +2 -0
  93. package/dist/features/project/project_sync_to_server.js +51 -0
  94. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +2 -0
  95. package/dist/features/project/stm32_cubetools_download_drivers.js +19 -0
  96. package/dist/features/status/command.d.ts +2 -0
  97. package/dist/features/status/command.js +6 -0
  98. package/dist/features/status/get_status.d.ts +2 -0
  99. package/dist/features/status/get_status.js +44 -0
  100. package/dist/features/table/check.d.ts +38 -0
  101. package/dist/features/table/command.d.ts +3 -0
  102. package/dist/features/table/read.d.ts +28 -0
  103. package/dist/features/tool/command.d.ts +35 -0
  104. package/dist/lib.d.ts +11 -0
  105. package/dist/lib.js +9 -0
  106. package/dist/stm32/actions/DebugAction.d.ts +63 -0
  107. package/dist/stm32/actions/DebugAction.js +105 -0
  108. package/dist/stm32/actions/DebugActionInfo.d.ts +7 -0
  109. package/dist/stm32/actions/DebugActionInfo.js +9 -0
  110. package/dist/stm32/actions/DebugActionListProbes.d.ts +9 -0
  111. package/dist/stm32/actions/DebugActionListProbes.js +10 -0
  112. package/dist/stm32/actions/DebugActionProgram.d.ts +28 -0
  113. package/dist/stm32/actions/DebugActionProgram.js +79 -0
  114. package/dist/stm32/actions/DebugActionRead.d.ts +38 -0
  115. package/dist/stm32/actions/DebugActionRead.js +59 -0
  116. package/dist/stm32/actions/DebugActionReset.d.ts +11 -0
  117. package/dist/stm32/actions/DebugActionReset.js +9 -0
  118. package/dist/stm32/actions/DebugActionServer.d.ts +7 -0
  119. package/dist/stm32/actions/DebugActionServer.js +9 -0
  120. package/dist/stm32/analysis.d.ts +19 -0
  121. package/dist/stm32/analysis.js +21 -0
  122. package/dist/stm32/build.d.ts +34 -0
  123. package/dist/stm32/build.js +79 -0
  124. package/dist/stm32/context.d.ts +23 -0
  125. package/dist/stm32/context.js +42 -0
  126. package/dist/stm32/daemon.d.ts +63 -0
  127. package/dist/stm32/daemon.js +202 -0
  128. package/dist/stm32/regen.d.ts +68 -0
  129. package/dist/stm32/regen.js +225 -0
  130. package/dist/stm32/session.d.ts +134 -0
  131. package/dist/stm32/session.js +374 -0
  132. package/dist/stm32/sync.d.ts +24 -0
  133. package/dist/stm32/sync.js +72 -0
  134. package/dist/stm32/tool.d.ts +43 -0
  135. package/dist/stm32/tool.js +20 -0
  136. package/dist/stm32/toolCommand.d.ts +50 -0
  137. package/dist/stm32/toolCommand.js +102 -0
  138. package/dist/stm32/utils/discover_tools.d.ts +24 -0
  139. package/dist/stm32/utils/discover_tools.js +121 -0
  140. package/dist/stm32/utils/downloadzip_utils.d.ts +57 -0
  141. package/dist/stm32/utils/downloadzip_utils.js +180 -0
  142. package/dist/stm32/utils/faultUtils.d.ts +14 -0
  143. package/dist/stm32/utils/faultUtils.js +69 -0
  144. package/dist/stm32/utils/findElf.d.ts +9 -0
  145. package/dist/stm32/utils/findElf.js +19 -0
  146. package/dist/stm32/utils/hash_utils.d.ts +19 -0
  147. package/dist/stm32/utils/hash_utils.js +28 -0
  148. package/dist/stm32/utils/listSyncFiles.d.ts +9 -0
  149. package/dist/stm32/utils/listSyncFiles.js +98 -0
  150. package/dist/stm32/utils/mcu_utils.d.ts +59 -0
  151. package/dist/stm32/utils/mcu_utils.js +99 -0
  152. package/dist/stm32/utils/project_utils.d.ts +54 -0
  153. package/dist/stm32/utils/project_utils.js +102 -0
  154. package/dist/stm32/utils/svdUtils.d.ts +31 -0
  155. package/dist/stm32/utils/svdUtils.js +30 -0
  156. package/dist/stm32/utils/truncate.d.ts +7 -0
  157. package/dist/stm32/utils/truncate.js +9 -0
  158. package/dist/stm32/utils/usb_utils.d.ts +5 -0
  159. package/dist/stm32/utils/usb_utils.js +23 -0
  160. package/dist/stm32/utils/user_code.d.ts +14 -0
  161. package/dist/stm32/utils/user_code.js +43 -0
  162. package/dist/stm32/utils/utils_mutex.d.ts +15 -0
  163. package/dist/stm32/utils/utils_mutex.js +93 -0
  164. package/dist/stm32/validate.d.ts +16 -0
  165. package/dist/stm32/validate.js +46 -0
  166. package/mods/claude/.claude-plugin/marketplace.json +8 -0
  167. package/mods/claude/turingcode-skills/.claude-plugin/plugin.json +5 -0
  168. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +50 -0
  169. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/board-and-debug.md +22 -0
  170. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/build-and-check.md +19 -0
  171. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/new-project.md +9 -0
  172. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +43 -0
  173. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +42 -0
  174. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +35 -0
  175. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +34 -0
  176. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +35 -0
  177. package/package.json +11 -3
@@ -0,0 +1,102 @@
1
+ import { TOKEN_HELP } from "../core/mcp.js";
2
+ import { daemonPaths, forwardToDaemon, pingDaemon, startDaemon } from "./daemon.js";
3
+ import { findProject } from "./utils/project_utils.js";
4
+ import { setProbeLockFile } from "./utils/utils_mutex.js";
5
+ import { safetyCheck, validateArgs } from "./validate.js";
6
+ /** Exit code of argument errors, as in create-cli.ts. */
7
+ const BAD_ARGUMENTS = 2;
8
+ /**
9
+ * Converts a tool argument name to its flag: `force_full_sync` -> `force-full-sync`.
10
+ *
11
+ * @param {string} name - Argument name from the tool's schema.
12
+ * @returns {string} The flag name, without dashes.
13
+ */
14
+ export const flagName = (name) => name.replace(/_/g, "-");
15
+ /**
16
+ * Picks the tool arguments from parsed flags, leaving out flags that were not given.
17
+ *
18
+ * @param {ToolDef} tool - The tool.
19
+ * @param {Record<string, unknown>} argv - Parsed yargs arguments.
20
+ * @returns {Record<string, unknown>} Tool arguments by schema name.
21
+ */
22
+ export function toolArgs(tool, argv) {
23
+ return Object.fromEntries(Object.keys(tool.inputSchema.properties)
24
+ .map(name => [name, argv[flagName(name)]])
25
+ .filter(([, value]) => value !== undefined));
26
+ }
27
+ /**
28
+ * Runs a tool where its mode says and returns its text.
29
+ *
30
+ * @param {ToolDef} tool - The tool.
31
+ * @param {Record<string, unknown>} args - Validated tool arguments.
32
+ * @param {RunMode} mode - Where it runs.
33
+ * @returns {Promise<string>} The tool's text output.
34
+ * @throws {Error} With the tool's or the daemon's error message.
35
+ */
36
+ export async function runToolCommand(tool, args, mode) {
37
+ const cwd = process.cwd();
38
+ const { root } = await findProject(cwd);
39
+ const paths = daemonPaths(root);
40
+ if (mode !== "local") {
41
+ let res = await forwardToDaemon(paths, tool.name, args, cwd);
42
+ if (!res && mode === "start") {
43
+ await startDaemon(root);
44
+ res = await forwardToDaemon(paths, tool.name, args, cwd);
45
+ }
46
+ if (!res && mode !== "probe") {
47
+ throw new Error("No debug session: run `turingcode debug start` first");
48
+ }
49
+ if (res) {
50
+ if (!res.ok)
51
+ throw new Error(res.error);
52
+ return res.text;
53
+ }
54
+ setProbeLockFile(paths.lock);
55
+ }
56
+ const session = mode === "local" ? (await pingDaemon(paths))?.session ?? false : false;
57
+ const refused = safetyCheck(tool, session);
58
+ if (refused)
59
+ throw new Error(refused);
60
+ return tool.run(args, { cwd, socketPath: paths.socket, debugActive: () => session });
61
+ }
62
+ /**
63
+ * Builds the yargs subcommand of one tool: a flag per argument, the tool's description as help, and its examples.
64
+ *
65
+ * @param {ToolCommandSpec} spec - Subcommand name, tool, run mode and examples.
66
+ * @returns {CommandModule} The subcommand.
67
+ */
68
+ export function toolCommand(spec) {
69
+ const { properties, required = [] } = spec.tool.inputSchema;
70
+ const options = Object.fromEntries(Object.entries(properties).map(([name, p]) => [flagName(name), {
71
+ type: p.type === "integer" || p.type === "number" ? "number" : p.type,
72
+ // the CLI hides yargs' type and choices tags, so the allowed values go in the text
73
+ describe: [p.description, p.enum && `one of ${p.enum.filter(Boolean).join(", ")}`, required.includes(name) ? "required" : undefined]
74
+ .filter(Boolean).join("; ") || undefined,
75
+ ...(p.enum && { choices: p.enum }),
76
+ ...(spec.aliases?.[flagName(name)] && { alias: spec.aliases[flagName(name)] }),
77
+ }]));
78
+ const description = spec.tool.description.replace(/\s+/g, " ").trim();
79
+ return {
80
+ command: spec.command,
81
+ describe: description.split(/(?<!\be\.g)(?<=\.)\s(?=[A-Z])/)[0],
82
+ builder: cli => {
83
+ let c = cli.options(options);
84
+ for (const [line, what] of spec.examples)
85
+ c = c.example(line, what);
86
+ return c.epilogue([
87
+ description,
88
+ "Prints the result as text.",
89
+ "Exit: 0 ok, 1 failed (error on stderr), 2 bad arguments.",
90
+ ...(spec.server ? [TOKEN_HELP] : []),
91
+ ].join("\n"));
92
+ },
93
+ handler: async (argv) => {
94
+ const args = toolArgs(spec.tool, argv);
95
+ const invalid = validateArgs(spec.tool, args);
96
+ if (invalid) {
97
+ throw Object.assign(new Error(invalid.replace(/^(Missing argument|Unknown argument): (\w+)/, (_m, what, name) => `${what}: --${flagName(name)}`)), { exitCode: BAD_ARGUMENTS });
98
+ }
99
+ process.stdout.write((await runToolCommand(spec.tool, args, spec.mode)).trimEnd() + "\n");
100
+ },
101
+ };
102
+ }
@@ -0,0 +1,24 @@
1
+ export type SystemToolId = 'probe-rs' | 'STM32_Programmer_CLI' | 'STM32CubeIDE' | 'STM32CubeMX';
2
+ export interface DiscoveredSystemTool {
3
+ id: SystemToolId;
4
+ path: string;
5
+ }
6
+ /**
7
+ * Finds one tool: its environment variable, then PATH, then its default install locations.
8
+ * @param id tool to find
9
+ * @returns the executable path, or undefined when the tool is not installed
10
+ */
11
+ export declare function findTool(id: SystemToolId): Promise<string | undefined>;
12
+ /**
13
+ * Finds every known tool installed on this machine. The result is cached; pass refresh to look again
14
+ * (e.g. after the user installed a tool).
15
+ * @param refresh true to ignore the cached result
16
+ * @returns the installed tools with their executable paths
17
+ */
18
+ export declare function discover_system_tools(refresh?: boolean): Promise<DiscoveredSystemTool[]>;
19
+ /**
20
+ * Tells where to get a tool, for "not found" errors.
21
+ * @param id tool
22
+ * @returns the install hint
23
+ */
24
+ export declare function toolHint(id: SystemToolId): string;
@@ -0,0 +1,121 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readdir } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { delimiter, dirname, join } from 'node:path';
5
+ const WIN = process.platform === 'win32';
6
+ const MAC = process.platform === 'darwin';
7
+ const EXE = WIN ? '.exe' : '';
8
+ const PROGRAM_FILES = process.env.ProgramFiles ?? 'C:\\Program Files';
9
+ const SYSTEM_DRIVE = process.env.SystemDrive ?? 'C:';
10
+ const TOOLS = {
11
+ 'probe-rs': {
12
+ env: 'PROBE_RS',
13
+ exe: `probe-rs${EXE}`,
14
+ hint: 'install it from https://probe.rs or set PROBE_RS',
15
+ places: async () => [
16
+ join(process.env.CARGO_HOME ?? join(homedir(), '.cargo'), 'bin', `probe-rs${EXE}`),
17
+ ],
18
+ },
19
+ STM32_Programmer_CLI: {
20
+ env: 'STM32_PROGRAMMER_CLI',
21
+ exe: `STM32_Programmer_CLI${EXE}`,
22
+ hint: 'install STM32CubeProgrammer or STM32CubeIDE, or set STM32_PROGRAMMER_CLI',
23
+ places: async () => [
24
+ WIN
25
+ ? join(PROGRAM_FILES, 'STMicroelectronics', 'STM32Cube', 'STM32CubeProgrammer', 'bin', 'STM32_Programmer_CLI.exe')
26
+ : MAC
27
+ ? '/Applications/STMicroelectronics/STM32CubeProgrammer.app/Contents/MacOs/bin/STM32_Programmer_CLI'
28
+ : join(homedir(), 'STMicroelectronics', 'STM32Cube', 'STM32CubeProgrammer', 'bin', 'STM32_Programmer_CLI'),
29
+ ...(await cubeIdeProgrammers()),
30
+ ],
31
+ },
32
+ STM32CubeIDE: {
33
+ env: 'STM32CUBEIDE',
34
+ exe: WIN ? 'stm32cubeide.exe' : 'stm32cubeide',
35
+ hint: 'install it from https://www.st.com/stm32cubeide or set STM32CUBEIDE',
36
+ places: async () => WIN
37
+ ? (await versioned_folders(`${SYSTEM_DRIVE}\\ST`, 'STM32CubeIDE')).map((d) => join(d, 'STM32CubeIDE', 'stm32cubeide.exe'))
38
+ : MAC
39
+ ? ['/Applications/STM32CubeIDE.app/Contents/MacOS/STM32CubeIDE']
40
+ : (await versioned_folders('/opt/st', 'stm32cubeide')).map((d) => join(d, 'stm32cubeide')),
41
+ },
42
+ STM32CubeMX: {
43
+ env: 'STM32CUBEMX',
44
+ exe: `STM32CubeMX${EXE}`,
45
+ hint: 'install it from https://www.st.com/stm32cubemx or set STM32CUBEMX',
46
+ places: async () => [
47
+ WIN
48
+ ? join(PROGRAM_FILES, 'STMicroelectronics', 'STM32Cube', 'STM32CubeMX', 'STM32CubeMX.exe')
49
+ : MAC
50
+ ? '/Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/STM32CubeMX'
51
+ : join(homedir(), 'STM32CubeMX', 'STM32CubeMX'),
52
+ ],
53
+ },
54
+ };
55
+ /**
56
+ * Lists the subfolders of a folder whose names start with a prefix (e.g. STM32CubeIDE_1.16.0), newest version first.
57
+ * @param parent folder to look in
58
+ * @param prefix folder name prefix, case-insensitive
59
+ * @returns the matching folder paths
60
+ */
61
+ async function versioned_folders(parent, prefix) {
62
+ const names = await readdir(parent).catch(() => []);
63
+ return names
64
+ .filter((n) => n.toLowerCase().startsWith(prefix.toLowerCase()))
65
+ .sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
66
+ .map((n) => join(parent, n));
67
+ }
68
+ /**
69
+ * Lists the STM32_Programmer_CLI copies bundled in the plugins of the installed STM32CubeIDE.
70
+ * @returns the executable paths, newest plugin first
71
+ */
72
+ async function cubeIdeProgrammers() {
73
+ const ide = await findTool('STM32CubeIDE');
74
+ if (!ide)
75
+ return [];
76
+ const plugins = MAC
77
+ ? join(dirname(ide), '..', 'Eclipse', 'plugins')
78
+ : join(dirname(ide), 'plugins');
79
+ const dirs = await versioned_folders(plugins, 'com.st.stm32cube.ide.mcu.externaltools.cubeprogrammer');
80
+ return dirs.map((d) => join(d, 'tools', 'bin', `STM32_Programmer_CLI${EXE}`));
81
+ }
82
+ /**
83
+ * Finds one tool: its environment variable, then PATH, then its default install locations.
84
+ * @param id tool to find
85
+ * @returns the executable path, or undefined when the tool is not installed
86
+ */
87
+ export async function findTool(id) {
88
+ const t = TOOLS[id];
89
+ const candidates = [
90
+ process.env[t.env],
91
+ ...(process.env.PATH ?? '')
92
+ .split(delimiter)
93
+ .filter(Boolean)
94
+ .map((d) => join(d, t.exe)),
95
+ ...(await t.places()),
96
+ ];
97
+ return candidates.find((c) => c && existsSync(c));
98
+ }
99
+ let cached_tools; // last discovery, shared by every action
100
+ /**
101
+ * Finds every known tool installed on this machine. The result is cached; pass refresh to look again
102
+ * (e.g. after the user installed a tool).
103
+ * @param refresh true to ignore the cached result
104
+ * @returns the installed tools with their executable paths
105
+ */
106
+ export async function discover_system_tools(refresh = false) {
107
+ if (cached_tools && !refresh)
108
+ return cached_tools;
109
+ const ids = Object.keys(TOOLS);
110
+ const paths = await Promise.all(ids.map(findTool));
111
+ cached_tools = ids.flatMap((id, i) => (paths[i] ? [{ id, path: paths[i] }] : []));
112
+ return cached_tools;
113
+ }
114
+ /**
115
+ * Tells where to get a tool, for "not found" errors.
116
+ * @param id tool
117
+ * @returns the install hint
118
+ */
119
+ export function toolHint(id) {
120
+ return TOOLS[id].hint;
121
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Downloads a zip from a URL and extracts it into parentDir (zip holds a top-level <name>/ folder).
3
+ * @param zipUrl URL of the zip
4
+ * @param parentDir folder to extract into
5
+ * @param overwrite replace existing files; false only adds the missing ones
6
+ */
7
+ export declare function downloadAndUnzip(zipUrl: string, parentDir: string, overwrite?: boolean): Promise<void>;
8
+ /**
9
+ * Extracts zip bytes into parentDir with unzip, falling back to tar.
10
+ * @param data the zip bytes
11
+ * @param parentDir folder to extract into
12
+ * @param overwrite replace existing files; false only adds the missing ones
13
+ */
14
+ export declare function extractZip(data: Buffer, parentDir: string, overwrite?: boolean): Promise<void>;
15
+ /**
16
+ * Lists the file names stored in a zip, read from its central directory (folder entries skipped).
17
+ * shortcut: no zip64 and no archive comment search beyond 64 KB; fine for the server's project zips.
18
+ * @param data the zip bytes
19
+ * @returns posix paths of the files in the zip
20
+ * @throws {Error} if data is not a zip
21
+ */
22
+ export declare function zipEntryNames(data: Buffer): string[];
23
+ /**
24
+ * Returns the first http(s) link in a sync tool reply (sync_project, sync_project_from_server).
25
+ * @param text server reply
26
+ * @returns the signed link
27
+ * @throws {Error} with the reply when it has no link, e.g. an [ERROR] line
28
+ */
29
+ export declare function syncLink(text: string): string;
30
+ /**
31
+ * Fetches a URL and throws with the response text on an HTTP error.
32
+ * @param url the URL
33
+ * @param init fetch options (method, body)
34
+ * @returns the response
35
+ * @throws {Error} with the HTTP status and the server's message
36
+ */
37
+ export declare function fetchOrThrow(url: string, init: RequestInit): Promise<Response>;
38
+ /**
39
+ * Downloads a URL to dest, creating its folder.
40
+ * @param url URL to download
41
+ * @param dest file path to write
42
+ */
43
+ export declare function downloadFile(url: string, dest: string): Promise<void>;
44
+ /**
45
+ * Returns the first .zip URL in a server reply, stripping markdown wrappers.
46
+ * @param text server reply
47
+ * @returns the zip URL
48
+ */
49
+ export declare function zipLink(text: string): string;
50
+ /**
51
+ * Builds a deflated zip archive in memory from files (posix relative names), compressing on zlib's thread pool.
52
+ * ponytail: no zip64, so archives and files must stay under 4 GB; fine for project sources.
53
+ */
54
+ export declare function zipFiles(files: {
55
+ name: string;
56
+ data: Buffer;
57
+ }[]): Promise<Buffer>;
@@ -0,0 +1,180 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { mkdir, unlink, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { deflateRaw } from "node:zlib";
8
+ const run = promisify(execFile);
9
+ const deflateRawAsync = promisify(deflateRaw);
10
+ /**
11
+ * Downloads a zip from a URL and extracts it into parentDir (zip holds a top-level <name>/ folder).
12
+ * @param zipUrl URL of the zip
13
+ * @param parentDir folder to extract into
14
+ * @param overwrite replace existing files; false only adds the missing ones
15
+ */
16
+ export async function downloadAndUnzip(zipUrl, parentDir, overwrite = true) {
17
+ const res = await fetchOrThrow(zipUrl, {});
18
+ await extractZip(Buffer.from(await res.arrayBuffer()), parentDir, overwrite);
19
+ }
20
+ /**
21
+ * Extracts zip bytes into parentDir with unzip, falling back to tar.
22
+ * @param data the zip bytes
23
+ * @param parentDir folder to extract into
24
+ * @param overwrite replace existing files; false only adds the missing ones
25
+ */
26
+ export async function extractZip(data, parentDir, overwrite = true) {
27
+ const zip = join(tmpdir(), `turingcode-${randomBytes(8).toString("hex")}.zip`);
28
+ try {
29
+ await writeFile(zip, data);
30
+ await mkdir(parentDir, { recursive: true }); // tar -C, unlike unzip -d, needs the folder to exist
31
+ try {
32
+ await run("unzip", [overwrite ? "-o" : "-n", zip, "-d", parentDir], { windowsHide: true });
33
+ }
34
+ catch (e) {
35
+ if (e?.code === 1)
36
+ return; // unzip exit 1 = warnings, extraction succeeded
37
+ if (e?.code !== "ENOENT")
38
+ throw new Error(`unzip failed: ${String(e?.stderr || e?.message).trim()}`);
39
+ // no unzip installed: tar (bsdtar on Windows and macOS) also reads zips
40
+ try {
41
+ await run("tar", ["-xf", zip, "-C", parentDir, ...(overwrite ? [] : ["-k"])], { windowsHide: true });
42
+ }
43
+ catch (t) {
44
+ throw new Error(`Could not extract zip (install unzip): ${String(t?.stderr || t?.message).trim()}`);
45
+ }
46
+ }
47
+ }
48
+ finally {
49
+ await unlink(zip).catch(() => { });
50
+ }
51
+ }
52
+ /**
53
+ * Lists the file names stored in a zip, read from its central directory (folder entries skipped).
54
+ * shortcut: no zip64 and no archive comment search beyond 64 KB; fine for the server's project zips.
55
+ * @param data the zip bytes
56
+ * @returns posix paths of the files in the zip
57
+ * @throws {Error} if data is not a zip
58
+ */
59
+ export function zipEntryNames(data) {
60
+ const end = data.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]), Math.max(0, data.length - 22));
61
+ if (end < 0 || end < data.length - 22 - 0xffff)
62
+ throw new Error("Not a zip file");
63
+ const names = [];
64
+ let p = data.readUInt32LE(end + 16);
65
+ for (let i = data.readUInt16LE(end + 10); i > 0; i--) {
66
+ if (data.readUInt32LE(p) !== 0x02014b50)
67
+ throw new Error("Corrupt zip central directory");
68
+ const nameLen = data.readUInt16LE(p + 28);
69
+ const name = data.toString("utf8", p + 46, p + 46 + nameLen);
70
+ if (!name.endsWith("/"))
71
+ names.push(name);
72
+ p += 46 + nameLen + data.readUInt16LE(p + 30) + data.readUInt16LE(p + 32);
73
+ }
74
+ return names;
75
+ }
76
+ /**
77
+ * Returns the first http(s) link in a sync tool reply (sync_project, sync_project_from_server).
78
+ * @param text server reply
79
+ * @returns the signed link
80
+ * @throws {Error} with the reply when it has no link, e.g. an [ERROR] line
81
+ */
82
+ export function syncLink(text) {
83
+ const m = text.match(/https?:\/\/[^\s'"`<>()]+/);
84
+ if (!m)
85
+ throw new Error(text.slice(0, 500));
86
+ return m[0];
87
+ }
88
+ /**
89
+ * Fetches a URL and throws with the response text on an HTTP error.
90
+ * @param url the URL
91
+ * @param init fetch options (method, body)
92
+ * @returns the response
93
+ * @throws {Error} with the HTTP status and the server's message
94
+ */
95
+ export async function fetchOrThrow(url, init) {
96
+ const res = await fetch(url, { signal: AbortSignal.timeout(125_000), ...init });
97
+ if (!res.ok)
98
+ throw new Error(`HTTP ${res.status}: ${(await res.text()).trim()}`);
99
+ return res;
100
+ }
101
+ /**
102
+ * Downloads a URL to dest, creating its folder.
103
+ * @param url URL to download
104
+ * @param dest file path to write
105
+ */
106
+ export async function downloadFile(url, dest) {
107
+ const res = await fetchOrThrow(url, {});
108
+ await mkdir(dirname(dest), { recursive: true });
109
+ await writeFile(dest, Buffer.from(await res.arrayBuffer()));
110
+ }
111
+ /**
112
+ * Returns the first .zip URL in a server reply, stripping markdown wrappers.
113
+ * @param text server reply
114
+ * @returns the zip URL
115
+ */
116
+ export function zipLink(text) {
117
+ const m = text.match(/https?:\/\/\S+?\.zip/);
118
+ if (!m)
119
+ throw new Error(`No download link in server reply: ${text.slice(0, 200)}`);
120
+ return m[0].replace(/^[(<`]+/, "");
121
+ }
122
+ const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
123
+ for (let k = 0; k < 8; k++)
124
+ n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1;
125
+ return n >>> 0;
126
+ });
127
+ /** CRC-32 of a buffer, as zip stores it. */
128
+ function crc32(buf) {
129
+ let c = 0xffffffff;
130
+ for (const b of buf)
131
+ c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8);
132
+ return (c ^ 0xffffffff) >>> 0;
133
+ }
134
+ /**
135
+ * Builds a deflated zip archive in memory from files (posix relative names), compressing on zlib's thread pool.
136
+ * ponytail: no zip64, so archives and files must stay under 4 GB; fine for project sources.
137
+ */
138
+ export async function zipFiles(files) {
139
+ const packedAll = await Promise.all(files.map((f) => deflateRawAsync(f.data)));
140
+ const parts = [];
141
+ const central = [];
142
+ let offset = 0;
143
+ for (const [i, { name, data }] of files.entries()) {
144
+ const fileName = Buffer.from(name, "utf8");
145
+ const packed = packedAll[i];
146
+ const crc = crc32(data);
147
+ // version 20, flag 0x0800 = UTF-8 names, method 8 = deflate, DOS time/date 0 (1980-01-01)
148
+ const local = Buffer.alloc(30);
149
+ local.writeUInt32LE(0x04034b50, 0);
150
+ local.writeUInt16LE(20, 4);
151
+ local.writeUInt16LE(0x0800, 6);
152
+ local.writeUInt16LE(8, 8);
153
+ local.writeUInt32LE(crc, 14);
154
+ local.writeUInt32LE(packed.length, 18);
155
+ local.writeUInt32LE(data.length, 22);
156
+ local.writeUInt16LE(fileName.length, 26);
157
+ const entry = Buffer.alloc(46);
158
+ entry.writeUInt32LE(0x02014b50, 0);
159
+ entry.writeUInt16LE(20, 4);
160
+ entry.writeUInt16LE(20, 6);
161
+ entry.writeUInt16LE(0x0800, 8);
162
+ entry.writeUInt16LE(8, 10);
163
+ entry.writeUInt32LE(crc, 16);
164
+ entry.writeUInt32LE(packed.length, 20);
165
+ entry.writeUInt32LE(data.length, 24);
166
+ entry.writeUInt16LE(fileName.length, 28);
167
+ entry.writeUInt32LE(offset, 42);
168
+ parts.push(local, fileName, packed);
169
+ central.push(entry, fileName);
170
+ offset += local.length + fileName.length + packed.length;
171
+ }
172
+ const cd = Buffer.concat(central);
173
+ const end = Buffer.alloc(22);
174
+ end.writeUInt32LE(0x06054b50, 0);
175
+ end.writeUInt16LE(files.length, 8);
176
+ end.writeUInt16LE(files.length, 10);
177
+ end.writeUInt32LE(cd.length, 12);
178
+ end.writeUInt32LE(offset, 16);
179
+ return Buffer.concat([...parts, cd, end]);
180
+ }
@@ -0,0 +1,14 @@
1
+ export declare const FAULT_REGS_ADDRESS = 3758157096;
2
+ /**
3
+ * Formats a number as 0x-prefixed, zero-padded hex.
4
+ * @param value number to format
5
+ * @param digits hex digits to pad to
6
+ * @returns e.g. 0x0000ABCD
7
+ */
8
+ export declare function hex(value: number, digits?: number): string;
9
+ /**
10
+ * Decodes the Cortex-M fault status registers.
11
+ * @param regs CFSR, HFSR, DFSR, MMFAR, BFAR, AFSR as read from FAULT_REGS_ADDRESS
12
+ * @returns a readable report
13
+ */
14
+ export declare function decodeFaultStatus(regs: number[]): string;
@@ -0,0 +1,69 @@
1
+ // Cortex-M fault status registers (SCB), read in one 6-word block from CFSR.
2
+ export const FAULT_REGS_ADDRESS = 0xe000ed28; // CFSR, HFSR, DFSR, MMFAR, BFAR, AFSR
3
+ const CFSR_BITS = [
4
+ [0, "IACCVIOL", "MemManage: instruction fetch from a no-execute or MPU-protected region"],
5
+ [1, "DACCVIOL", "MemManage: data access to an MPU-protected region"],
6
+ [3, "MUNSTKERR", "MemManage: fault while unstacking on exception return"],
7
+ [4, "MSTKERR", "MemManage: fault while stacking on exception entry"],
8
+ [5, "MLSPERR", "MemManage: fault during lazy FPU state preservation"],
9
+ [7, "MMARVALID", "MMFAR holds the faulting address"],
10
+ [8, "IBUSERR", "BusFault: instruction fetch bus error"],
11
+ [9, "PRECISERR", "BusFault: precise data bus error"],
12
+ [10, "IMPRECISERR", "BusFault: imprecise data bus error (BFAR not valid)"],
13
+ [11, "UNSTKERR", "BusFault: fault while unstacking on exception return"],
14
+ [12, "STKERR", "BusFault: fault while stacking on exception entry (stack overflow?)"],
15
+ [13, "LSPERR", "BusFault: fault during lazy FPU state preservation"],
16
+ [15, "BFARVALID", "BFAR holds the faulting address"],
17
+ [16, "UNDEFINSTR", "UsageFault: undefined instruction"],
18
+ [17, "INVSTATE", "UsageFault: invalid EPSR state (Thumb bit clear, e.g. bad function pointer)"],
19
+ [18, "INVPC", "UsageFault: invalid EXC_RETURN on exception return"],
20
+ [19, "NOCP", "UsageFault: coprocessor access while disabled (FPU not enabled?)"],
21
+ [20, "STKOF", "UsageFault: stack limit overflow (Armv8-M)"],
22
+ [24, "UNALIGNED", "UsageFault: unaligned access with UNALIGN_TRP set"],
23
+ [25, "DIVBYZERO", "UsageFault: divide by zero with DIV_0_TRP set"],
24
+ ];
25
+ const HFSR_BITS = [
26
+ [1, "VECTTBL", "bus fault on vector table read"],
27
+ [30, "FORCED", "escalated from a configurable fault (see CFSR)"],
28
+ [31, "DEBUGEVT", "debug event"],
29
+ ];
30
+ const DFSR_BITS = [
31
+ [0, "HALTED", "halt request or step"],
32
+ [1, "BKPT", "breakpoint"],
33
+ [2, "DWTTRAP", "watchpoint"],
34
+ [3, "VCATCH", "vector catch"],
35
+ [4, "EXTERNAL", "external debug request"],
36
+ ];
37
+ /**
38
+ * Formats a number as 0x-prefixed, zero-padded hex.
39
+ * @param value number to format
40
+ * @param digits hex digits to pad to
41
+ * @returns e.g. 0x0000ABCD
42
+ */
43
+ export function hex(value, digits = 8) {
44
+ return `0x${value.toString(16).toUpperCase().padStart(digits, "0")}`;
45
+ }
46
+ /**
47
+ * Lists the set bits of a register with their meaning.
48
+ * @param value register value
49
+ * @param bits bit table: [bit, name, meaning]
50
+ * @returns one indented line per set bit
51
+ */
52
+ function setBits(value, bits) {
53
+ return bits.filter(([bit]) => (value >>> bit) & 1).map(([, name, meaning]) => ` ${name}: ${meaning}`);
54
+ }
55
+ /**
56
+ * Decodes the Cortex-M fault status registers.
57
+ * @param regs CFSR, HFSR, DFSR, MMFAR, BFAR, AFSR as read from FAULT_REGS_ADDRESS
58
+ * @returns a readable report
59
+ */
60
+ export function decodeFaultStatus(regs) {
61
+ const [cfsr, hfsr, dfsr, mmfar, bfar, afsr] = regs;
62
+ const lines = [`CFSR = ${hex(cfsr)}`, ...setBits(cfsr, CFSR_BITS), `HFSR = ${hex(hfsr)}`, ...setBits(hfsr, HFSR_BITS), `DFSR = ${hex(dfsr)}`, ...setBits(dfsr, DFSR_BITS)];
63
+ lines.push(`MMFAR = ${hex(mmfar)}${(cfsr >>> 7) & 1 ? " (valid: faulting address)" : " (not valid)"}`);
64
+ lines.push(`BFAR = ${hex(bfar)}${(cfsr >>> 15) & 1 ? " (valid: faulting address)" : " (not valid)"}`);
65
+ lines.push(`AFSR = ${hex(afsr)}`);
66
+ if (!cfsr && !hfsr)
67
+ lines.push("", "No fault recorded (CFSR and HFSR are 0).");
68
+ return lines.join("\n");
69
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Finds the most recently built .elf under the project's build/ folder (project_build downloads it to build/<preset>/).
3
+ * @param root project root folder
4
+ * @returns the .elf path and its modification time, or undefined when there is none
5
+ */
6
+ export declare function findElf(root: string): Promise<{
7
+ path: string;
8
+ mtime: Date;
9
+ } | undefined>;
@@ -0,0 +1,19 @@
1
+ import { readdir, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ /**
4
+ * Finds the most recently built .elf under the project's build/ folder (project_build downloads it to build/<preset>/).
5
+ * @param root project root folder
6
+ * @returns the .elf path and its modification time, or undefined when there is none
7
+ */
8
+ export async function findElf(root) {
9
+ const dir = join(root, "build");
10
+ const names = await readdir(dir, { recursive: true }).catch(() => []);
11
+ let newest;
12
+ for (const name of names.filter((n) => n.endsWith(".elf"))) {
13
+ const path = join(dir, name);
14
+ const { mtime } = await stat(path);
15
+ if (!newest || mtime > newest.mtime)
16
+ newest = { path, mtime };
17
+ }
18
+ return newest;
19
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Hashes data with sha256.
3
+ * @param data the bytes or text to hash
4
+ * @returns the hex digest
5
+ */
6
+ export declare function sha256(data: string | Buffer): string;
7
+ /**
8
+ * Reads files and hashes their contents with sha256.
9
+ * @param root the folder the file names are relative to
10
+ * @param files file names relative to root
11
+ * @returns a map of each file name to its hex digest
12
+ */
13
+ export declare function sha256Files(root: string, files: string[]): Promise<Record<string, string>>;
14
+ /**
15
+ * Formats a file hash map as `sha256sum` output, the manifest the server's sync links take.
16
+ * @param manifest map of posix file names to their hex sha256
17
+ * @returns one `<sha256> <name>` line per file
18
+ */
19
+ export declare function toSha256sum(manifest: Record<string, string>): string;
@@ -0,0 +1,28 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ /**
5
+ * Hashes data with sha256.
6
+ * @param data the bytes or text to hash
7
+ * @returns the hex digest
8
+ */
9
+ export function sha256(data) {
10
+ return createHash('sha256').update(data).digest('hex');
11
+ }
12
+ /**
13
+ * Reads files and hashes their contents with sha256.
14
+ * @param root the folder the file names are relative to
15
+ * @param files file names relative to root
16
+ * @returns a map of each file name to its hex digest
17
+ */
18
+ export async function sha256Files(root, files) {
19
+ return Object.fromEntries(await Promise.all(files.map(async (name) => [name, sha256(await readFile(join(root, name)))])));
20
+ }
21
+ /**
22
+ * Formats a file hash map as `sha256sum` output, the manifest the server's sync links take.
23
+ * @param manifest map of posix file names to their hex sha256
24
+ * @returns one `<sha256> <name>` line per file
25
+ */
26
+ export function toSha256sum(manifest) {
27
+ return Object.entries(manifest).map(([name, hash]) => `${hash} ${name}\n`).join('');
28
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Lists the project files to push (posix relative paths): everything except build/, folders starting with a dot,
3
+ * .env files, .zip/.csv/.gz/.gzip/.rar files, .md files other than README.md, files over 10 MB and git-ignored files. Drivers/ is always listed, even when git-ignored.
4
+ * Only the files whose hash differs from the server's copy are uploaded, so the unchanged Drivers/ costs only its manifest entries.
5
+ * Files and folders in included_files of .turingcode/settings.json are synced despite these rules, except archives and files over 10 MB.
6
+ * Logs a warning when git is unavailable, as .gitignore is then not applied.
7
+ * ponytail: without git installed, .gitignore is not applied (only the fixed excludes); parse it here if that matters.
8
+ */
9
+ export declare function listSyncFiles(root: string): Promise<string[]>;